File: | tools/clang/lib/Sema/SemaDeclCXX.cpp |
Warning: | line 11848, column 26 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 132, __PRETTY_FUNCTION__)); | |||
133 | } | |||
134 | ||||
135 | Invalid |= Visit(E); | |||
136 | } | |||
137 | return Invalid; | |||
138 | } | |||
139 | ||||
140 | bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { | |||
141 | // C++11 [expr.lambda.prim]p13: | |||
142 | // A lambda-expression appearing in a default argument shall not | |||
143 | // implicitly or explicitly capture any entity. | |||
144 | if (Lambda->capture_begin() == Lambda->capture_end()) | |||
145 | return false; | |||
146 | ||||
147 | return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); | |||
148 | } | |||
149 | } | |||
150 | ||||
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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 177); | |||
178 | ||||
179 | // If this function can throw any exceptions, make a note of that. | |||
180 | case EST_MSAny: | |||
181 | case EST_None: | |||
182 | // FIXME: Whichever we see last of MSAny and None determines our result. | |||
183 | // We should make a consistent, order-independent choice here. | |||
184 | ClearExceptions(); | |||
185 | ComputedEST = EST; | |||
186 | return; | |||
187 | case EST_NoexceptFalse: | |||
188 | ClearExceptions(); | |||
189 | ComputedEST = EST_None; | |||
190 | return; | |||
191 | // FIXME: If the call to this decl is using any of its default arguments, we | |||
192 | // need to search them for potentially-throwing calls. | |||
193 | // If this function has a basic noexcept, it doesn't affect the outcome. | |||
194 | case EST_BasicNoexcept: | |||
195 | case EST_NoexceptTrue: | |||
196 | 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~svn373517/tools/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~svn373517/tools/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~svn373517/tools/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~svn373517/tools/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~svn373517/tools/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::CalledExpr(Expr *E) { | |||
221 | if (!E || 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(E)) | |||
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~svn373517/tools/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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 689, __PRETTY_FUNCTION__)); | |||
690 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); | |||
691 | ||||
692 | // The syntax only allows a decomposition declarator as a simple-declaration, | |||
693 | // a for-range-declaration, or a condition in Clang, but we parse it in more | |||
694 | // cases than that. | |||
695 | if (!D.mayHaveDecompositionDeclarator()) { | |||
696 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) | |||
697 | << Decomp.getSourceRange(); | |||
698 | return nullptr; | |||
699 | } | |||
700 | ||||
701 | if (!TemplateParamLists.empty()) { | |||
702 | // FIXME: There's no rule against this, but there are also no rules that | |||
703 | // would actually make it usable, so we reject it for now. | |||
704 | Diag(TemplateParamLists.front()->getTemplateLoc(), | |||
705 | diag::err_decomp_decl_template); | |||
706 | return nullptr; | |||
707 | } | |||
708 | ||||
709 | Diag(Decomp.getLSquareLoc(), | |||
710 | !getLangOpts().CPlusPlus17 | |||
711 | ? diag::ext_decomp_decl | |||
712 | : D.getContext() == DeclaratorContext::ConditionContext | |||
713 | ? diag::ext_decomp_decl_cond | |||
714 | : diag::warn_cxx14_compat_decomp_decl) | |||
715 | << Decomp.getSourceRange(); | |||
716 | ||||
717 | // The semantic context is always just the current context. | |||
718 | DeclContext *const DC = CurContext; | |||
719 | ||||
720 | // C++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 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
779 | QualType R = TInfo->getType(); | |||
780 | ||||
781 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | |||
782 | UPPC_DeclarationType)) | |||
783 | D.setInvalidType(); | |||
784 | ||||
785 | // The syntax only allows a single ref-qualifier prior to the decomposition | |||
786 | // declarator. No other declarator chunks are permitted. Also check the type | |||
787 | // specifier here. | |||
788 | if (DS.getTypeSpecType() != DeclSpec::TST_auto || | |||
789 | D.hasGroupingParens() || D.getNumTypeObjects() > 1 || | |||
790 | (D.getNumTypeObjects() == 1 && | |||
791 | D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { | |||
792 | Diag(Decomp.getLSquareLoc(), | |||
793 | (D.hasGroupingParens() || | |||
794 | (D.getNumTypeObjects() && | |||
795 | D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) | |||
796 | ? diag::err_decomp_decl_parens | |||
797 | : diag::err_decomp_decl_type) | |||
798 | << R; | |||
799 | ||||
800 | // In most cases, there's no actual problem with an explicitly-specified | |||
801 | // type, but a function type won't work here, and ActOnVariableDeclarator | |||
802 | // shouldn't be called for such a type. | |||
803 | if (R->isFunctionType()) | |||
804 | D.setInvalidType(); | |||
805 | } | |||
806 | ||||
807 | // Build the BindingDecls. | |||
808 | SmallVector<BindingDecl*, 8> Bindings; | |||
809 | ||||
810 | // Build the BindingDecls. | |||
811 | for (auto &B : D.getDecompositionDeclarator().bindings()) { | |||
812 | // Check for name conflicts. | |||
813 | DeclarationNameInfo NameInfo(B.Name, B.NameLoc); | |||
814 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
815 | ForVisibleRedeclaration); | |||
816 | LookupName(Previous, S, | |||
817 | /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); | |||
818 | ||||
819 | // It's not permitted to shadow a template parameter name. | |||
820 | if (Previous.isSingleResult() && | |||
821 | Previous.getFoundDecl()->isTemplateParameter()) { | |||
822 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), | |||
823 | Previous.getFoundDecl()); | |||
824 | Previous.clear(); | |||
825 | } | |||
826 | ||||
827 | bool ConsiderLinkage = DC->isFunctionOrMethod() && | |||
828 | DS.getStorageClassSpec() == DeclSpec::SCS_extern; | |||
829 | FilterLookupForScope(Previous, DC, S, ConsiderLinkage, | |||
830 | /*AllowInlineNamespace*/false); | |||
831 | if (!Previous.empty()) { | |||
832 | auto *Old = Previous.getRepresentativeDecl(); | |||
833 | Diag(B.NameLoc, diag::err_redefinition) << B.Name; | |||
834 | Diag(Old->getLocation(), diag::note_previous_definition); | |||
835 | } | |||
836 | ||||
837 | auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); | |||
838 | PushOnScopeChains(BD, S, true); | |||
839 | Bindings.push_back(BD); | |||
840 | ParsingInitForAutoVars.insert(BD); | |||
841 | } | |||
842 | ||||
843 | // There are no prior lookup results for the variable itself, because it | |||
844 | // is unnamed. | |||
845 | DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, | |||
846 | Decomp.getLSquareLoc()); | |||
847 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
848 | ForVisibleRedeclaration); | |||
849 | ||||
850 | // Build the variable that holds the non-decomposed object. | |||
851 | bool AddToScope = true; | |||
852 | NamedDecl *New = | |||
853 | ActOnVariableDeclarator(S, D, DC, TInfo, Previous, | |||
854 | MultiTemplateParamsArg(), AddToScope, Bindings); | |||
855 | if (AddToScope) { | |||
856 | S->AddDecl(New); | |||
857 | CurContext->addHiddenDecl(New); | |||
858 | } | |||
859 | ||||
860 | if (isInOpenMPDeclareTargetContext()) | |||
861 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); | |||
862 | ||||
863 | return New; | |||
864 | } | |||
865 | ||||
866 | static bool checkSimpleDecomposition( | |||
867 | Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, | |||
868 | QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, | |||
869 | llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { | |||
870 | if ((int64_t)Bindings.size() != NumElems) { | |||
871 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) | |||
872 | << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) | |||
873 | << (NumElems < Bindings.size()); | |||
874 | return true; | |||
875 | } | |||
876 | ||||
877 | unsigned I = 0; | |||
878 | for (auto *B : Bindings) { | |||
879 | SourceLocation Loc = B->getLocation(); | |||
880 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); | |||
881 | if (E.isInvalid()) | |||
882 | return true; | |||
883 | E = GetInit(Loc, E.get(), I++); | |||
884 | if (E.isInvalid()) | |||
885 | return true; | |||
886 | B->setBinding(ElemType, E.get()); | |||
887 | } | |||
888 | ||||
889 | return false; | |||
890 | } | |||
891 | ||||
892 | static bool checkArrayLikeDecomposition(Sema &S, | |||
893 | ArrayRef<BindingDecl *> Bindings, | |||
894 | ValueDecl *Src, QualType DecompType, | |||
895 | const llvm::APSInt &NumElems, | |||
896 | QualType ElemType) { | |||
897 | return checkSimpleDecomposition( | |||
898 | S, Bindings, Src, DecompType, NumElems, ElemType, | |||
899 | [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { | |||
900 | ExprResult E = S.ActOnIntegerConstant(Loc, I); | |||
901 | if (E.isInvalid()) | |||
902 | return ExprError(); | |||
903 | return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); | |||
904 | }); | |||
905 | } | |||
906 | ||||
907 | static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, | |||
908 | ValueDecl *Src, QualType DecompType, | |||
909 | const ConstantArrayType *CAT) { | |||
910 | return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, | |||
911 | llvm::APSInt(CAT->getSize()), | |||
912 | CAT->getElementType()); | |||
913 | } | |||
914 | ||||
915 | static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, | |||
916 | ValueDecl *Src, QualType DecompType, | |||
917 | const VectorType *VT) { | |||
918 | return checkArrayLikeDecomposition( | |||
919 | S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), | |||
920 | S.Context.getQualifiedType(VT->getElementType(), | |||
921 | DecompType.getQualifiers())); | |||
922 | } | |||
923 | ||||
924 | static bool checkComplexDecomposition(Sema &S, | |||
925 | ArrayRef<BindingDecl *> Bindings, | |||
926 | ValueDecl *Src, QualType DecompType, | |||
927 | const ComplexType *CT) { | |||
928 | return checkSimpleDecomposition( | |||
929 | S, Bindings, Src, DecompType, llvm::APSInt::get(2), | |||
930 | S.Context.getQualifiedType(CT->getElementType(), | |||
931 | DecompType.getQualifiers()), | |||
932 | [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { | |||
933 | return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); | |||
934 | }); | |||
935 | } | |||
936 | ||||
937 | static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, | |||
938 | TemplateArgumentListInfo &Args) { | |||
939 | SmallString<128> SS; | |||
940 | llvm::raw_svector_ostream OS(SS); | |||
941 | bool First = true; | |||
942 | for (auto &Arg : Args.arguments()) { | |||
943 | if (!First) | |||
944 | OS << ", "; | |||
945 | Arg.getArgument().print(PrintingPolicy, OS); | |||
946 | First = false; | |||
947 | } | |||
948 | return OS.str(); | |||
949 | } | |||
950 | ||||
951 | static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, | |||
952 | SourceLocation Loc, StringRef Trait, | |||
953 | TemplateArgumentListInfo &Args, | |||
954 | unsigned DiagID) { | |||
955 | auto DiagnoseMissing = [&] { | |||
956 | if (DiagID) | |||
957 | S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), | |||
958 | Args); | |||
959 | return true; | |||
960 | }; | |||
961 | ||||
962 | // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. | |||
963 | NamespaceDecl *Std = S.getStdNamespace(); | |||
964 | if (!Std) | |||
965 | return DiagnoseMissing(); | |||
966 | ||||
967 | // Look up the trait itself, within namespace std. We can diagnose various | |||
968 | // problems with this lookup even if we've been asked to not diagnose a | |||
969 | // missing specialization, because this can only fail if the user has been | |||
970 | // declaring their own names in namespace std or we don't support the | |||
971 | // standard library implementation in use. | |||
972 | LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), | |||
973 | Loc, Sema::LookupOrdinaryName); | |||
974 | if (!S.LookupQualifiedName(Result, Std)) | |||
975 | return DiagnoseMissing(); | |||
976 | if (Result.isAmbiguous()) | |||
977 | return true; | |||
978 | ||||
979 | ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); | |||
980 | if (!TraitTD) { | |||
981 | Result.suppressDiagnostics(); | |||
982 | NamedDecl *Found = *Result.begin(); | |||
983 | S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; | |||
984 | S.Diag(Found->getLocation(), diag::note_declared_at); | |||
985 | return true; | |||
986 | } | |||
987 | ||||
988 | // Build the template-id. | |||
989 | QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); | |||
990 | if (TraitTy.isNull()) | |||
991 | return true; | |||
992 | if (!S.isCompleteType(Loc, TraitTy)) { | |||
993 | if (DiagID) | |||
994 | S.RequireCompleteType( | |||
995 | Loc, TraitTy, DiagID, | |||
996 | printTemplateArgs(S.Context.getPrintingPolicy(), Args)); | |||
997 | return true; | |||
998 | } | |||
999 | ||||
1000 | CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); | |||
1001 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 1001, __PRETTY_FUNCTION__)); | |||
1002 | ||||
1003 | // Look up the member of the trait type. | |||
1004 | S.LookupQualifiedName(TraitMemberLookup, RD); | |||
1005 | return TraitMemberLookup.isAmbiguous(); | |||
1006 | } | |||
1007 | ||||
1008 | static TemplateArgumentLoc | |||
1009 | getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, | |||
1010 | uint64_t I) { | |||
1011 | TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); | |||
1012 | return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); | |||
1013 | } | |||
1014 | ||||
1015 | static TemplateArgumentLoc | |||
1016 | getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { | |||
1017 | return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); | |||
1018 | } | |||
1019 | ||||
1020 | namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } | |||
1021 | ||||
1022 | static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, | |||
1023 | llvm::APSInt &Size) { | |||
1024 | EnterExpressionEvaluationContext ContextRAII( | |||
1025 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); | |||
1026 | ||||
1027 | DeclarationName Value = S.PP.getIdentifierInfo("value"); | |||
1028 | LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); | |||
1029 | ||||
1030 | // Form template argument list for tuple_size<T>. | |||
1031 | TemplateArgumentListInfo Args(Loc, Loc); | |||
1032 | Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); | |||
1033 | ||||
1034 | // If there's no tuple_size specialization or the lookup of 'value' is empty, | |||
1035 | // it's not tuple-like. | |||
1036 | if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || | |||
1037 | R.empty()) | |||
1038 | return IsTupleLike::NotTupleLike; | |||
1039 | ||||
1040 | // If we get this far, we've committed to the tuple interpretation, but | |||
1041 | // we can still fail if there actually isn't a usable ::value. | |||
1042 | ||||
1043 | struct ICEDiagnoser : Sema::VerifyICEDiagnoser { | |||
1044 | LookupResult &R; | |||
1045 | TemplateArgumentListInfo &Args; | |||
1046 | ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) | |||
1047 | : R(R), Args(Args) {} | |||
1048 | void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { | |||
1049 | S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) | |||
1050 | << printTemplateArgs(S.Context.getPrintingPolicy(), Args); | |||
1051 | } | |||
1052 | } Diagnoser(R, Args); | |||
1053 | ||||
1054 | ExprResult E = | |||
1055 | S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); | |||
1056 | if (E.isInvalid()) | |||
1057 | return IsTupleLike::Error; | |||
1058 | ||||
1059 | E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); | |||
1060 | if (E.isInvalid()) | |||
1061 | return IsTupleLike::Error; | |||
1062 | ||||
1063 | return IsTupleLike::TupleLike; | |||
1064 | } | |||
1065 | ||||
1066 | /// \return std::tuple_element<I, T>::type. | |||
1067 | static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, | |||
1068 | unsigned I, QualType T) { | |||
1069 | // Form template argument list for tuple_element<I, T>. | |||
1070 | TemplateArgumentListInfo Args(Loc, Loc); | |||
1071 | Args.addArgument( | |||
1072 | getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); | |||
1073 | Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); | |||
1074 | ||||
1075 | DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); | |||
1076 | LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); | |||
1077 | if (lookupStdTypeTraitMember( | |||
1078 | S, R, Loc, "tuple_element", Args, | |||
1079 | diag::err_decomp_decl_std_tuple_element_not_specialized)) | |||
1080 | return QualType(); | |||
1081 | ||||
1082 | auto *TD = R.getAsSingle<TypeDecl>(); | |||
1083 | if (!TD) { | |||
1084 | R.suppressDiagnostics(); | |||
1085 | S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) | |||
1086 | << printTemplateArgs(S.Context.getPrintingPolicy(), Args); | |||
1087 | if (!R.empty()) | |||
1088 | S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); | |||
1089 | return QualType(); | |||
1090 | } | |||
1091 | ||||
1092 | return S.Context.getTypeDeclType(TD); | |||
1093 | } | |||
1094 | ||||
1095 | namespace { | |||
1096 | struct BindingDiagnosticTrap { | |||
1097 | Sema &S; | |||
1098 | DiagnosticErrorTrap Trap; | |||
1099 | BindingDecl *BD; | |||
1100 | ||||
1101 | BindingDiagnosticTrap(Sema &S, BindingDecl *BD) | |||
1102 | : S(S), Trap(S.Diags), BD(BD) {} | |||
1103 | ~BindingDiagnosticTrap() { | |||
1104 | if (Trap.hasErrorOccurred()) | |||
1105 | S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; | |||
1106 | } | |||
1107 | }; | |||
1108 | } | |||
1109 | ||||
1110 | static bool checkTupleLikeDecomposition(Sema &S, | |||
1111 | ArrayRef<BindingDecl *> Bindings, | |||
1112 | VarDecl *Src, QualType DecompType, | |||
1113 | const llvm::APSInt &TupleSize) { | |||
1114 | if ((int64_t)Bindings.size() != TupleSize) { | |||
1115 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) | |||
1116 | << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) | |||
1117 | << (TupleSize < Bindings.size()); | |||
1118 | return true; | |||
1119 | } | |||
1120 | ||||
1121 | if (Bindings.empty()) | |||
1122 | return false; | |||
1123 | ||||
1124 | DeclarationName GetDN = S.PP.getIdentifierInfo("get"); | |||
1125 | ||||
1126 | // [dcl.decomp]p3: | |||
1127 | // The unqualified-id get is looked up in the scope of E by class member | |||
1128 | // access lookup ... | |||
1129 | LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); | |||
1130 | bool UseMemberGet = false; | |||
1131 | if (S.isCompleteType(Src->getLocation(), DecompType)) { | |||
1132 | if (auto *RD = DecompType->getAsCXXRecordDecl()) | |||
1133 | S.LookupQualifiedName(MemberGet, RD); | |||
1134 | if (MemberGet.isAmbiguous()) | |||
1135 | return true; | |||
1136 | // ... and if that finds at least one declaration that is a function | |||
1137 | // template whose first template parameter is a non-type parameter ... | |||
1138 | for (NamedDecl *D : MemberGet) { | |||
1139 | if (FunctionTemplateDecl *FTD = | |||
1140 | dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { | |||
1141 | TemplateParameterList *TPL = FTD->getTemplateParameters(); | |||
1142 | if (TPL->size() != 0 && | |||
1143 | isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { | |||
1144 | // ... the initializer is e.get<i>(). | |||
1145 | UseMemberGet = true; | |||
1146 | break; | |||
1147 | } | |||
1148 | } | |||
1149 | } | |||
1150 | } | |||
1151 | ||||
1152 | unsigned I = 0; | |||
1153 | for (auto *B : Bindings) { | |||
1154 | BindingDiagnosticTrap Trap(S, B); | |||
1155 | SourceLocation Loc = B->getLocation(); | |||
1156 | ||||
1157 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); | |||
1158 | if (E.isInvalid()) | |||
1159 | return true; | |||
1160 | ||||
1161 | // e is an lvalue if the type of the entity is an lvalue reference and | |||
1162 | // an xvalue otherwise | |||
1163 | if (!Src->getType()->isLValueReferenceType()) | |||
1164 | E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, | |||
1165 | E.get(), nullptr, VK_XValue); | |||
1166 | ||||
1167 | TemplateArgumentListInfo Args(Loc, Loc); | |||
1168 | Args.addArgument( | |||
1169 | getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); | |||
1170 | ||||
1171 | if (UseMemberGet) { | |||
1172 | // if [lookup of member get] finds at least one declaration, the | |||
1173 | // initializer is e.get<i-1>(). | |||
1174 | E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, | |||
1175 | CXXScopeSpec(), SourceLocation(), nullptr, | |||
1176 | MemberGet, &Args, nullptr); | |||
1177 | if (E.isInvalid()) | |||
1178 | return true; | |||
1179 | ||||
1180 | E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); | |||
1181 | } else { | |||
1182 | // Otherwise, the initializer is get<i-1>(e), where get is looked up | |||
1183 | // in the associated namespaces. | |||
1184 | Expr *Get = UnresolvedLookupExpr::Create( | |||
1185 | S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), | |||
1186 | DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, | |||
1187 | UnresolvedSetIterator(), UnresolvedSetIterator()); | |||
1188 | ||||
1189 | Expr *Arg = E.get(); | |||
1190 | E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); | |||
1191 | } | |||
1192 | if (E.isInvalid()) | |||
1193 | return true; | |||
1194 | Expr *Init = E.get(); | |||
1195 | ||||
1196 | // Given the type T designated by std::tuple_element<i - 1, E>::type, | |||
1197 | QualType T = getTupleLikeElementType(S, Loc, I, DecompType); | |||
1198 | if (T.isNull()) | |||
1199 | return true; | |||
1200 | ||||
1201 | // each vi is a variable of type "reference to T" initialized with the | |||
1202 | // initializer, where the reference is an lvalue reference if the | |||
1203 | // initializer is an lvalue and an rvalue reference otherwise | |||
1204 | QualType RefType = | |||
1205 | S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); | |||
1206 | if (RefType.isNull()) | |||
1207 | return true; | |||
1208 | auto *RefVD = VarDecl::Create( | |||
1209 | S.Context, Src->getDeclContext(), Loc, Loc, | |||
1210 | B->getDeclName().getAsIdentifierInfo(), RefType, | |||
1211 | S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); | |||
1212 | RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); | |||
1213 | RefVD->setTSCSpec(Src->getTSCSpec()); | |||
1214 | RefVD->setImplicit(); | |||
1215 | if (Src->isInlineSpecified()) | |||
1216 | RefVD->setInlineSpecified(); | |||
1217 | RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); | |||
1218 | ||||
1219 | InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); | |||
1220 | InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); | |||
1221 | InitializationSequence Seq(S, Entity, Kind, Init); | |||
1222 | E = Seq.Perform(S, Entity, Kind, Init); | |||
1223 | if (E.isInvalid()) | |||
1224 | return true; | |||
1225 | E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); | |||
1226 | if (E.isInvalid()) | |||
1227 | return true; | |||
1228 | RefVD->setInit(E.get()); | |||
1229 | if (!E.get()->isValueDependent()) | |||
1230 | RefVD->checkInitIsICE(); | |||
1231 | ||||
1232 | E = S.BuildDeclarationNameExpr(CXXScopeSpec(), | |||
1233 | DeclarationNameInfo(B->getDeclName(), Loc), | |||
1234 | RefVD); | |||
1235 | if (E.isInvalid()) | |||
1236 | return true; | |||
1237 | ||||
1238 | B->setBinding(T, E.get()); | |||
1239 | I++; | |||
1240 | } | |||
1241 | ||||
1242 | return false; | |||
1243 | } | |||
1244 | ||||
1245 | /// Find the base class to decompose in a built-in decomposition of a class type. | |||
1246 | /// This base class search is, unfortunately, not quite like any other that we | |||
1247 | /// perform anywhere else in C++. | |||
1248 | static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, | |||
1249 | const CXXRecordDecl *RD, | |||
1250 | CXXCastPath &BasePath) { | |||
1251 | auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, | |||
1252 | CXXBasePath &Path) { | |||
1253 | return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); | |||
1254 | }; | |||
1255 | ||||
1256 | const CXXRecordDecl *ClassWithFields = nullptr; | |||
1257 | AccessSpecifier AS = AS_public; | |||
1258 | if (RD->hasDirectFields()) | |||
1259 | // [dcl.decomp]p4: | |||
1260 | // Otherwise, all of E's non-static data members shall be public direct | |||
1261 | // members of E ... | |||
1262 | ClassWithFields = RD; | |||
1263 | else { | |||
1264 | // ... or of ... | |||
1265 | CXXBasePaths Paths; | |||
1266 | Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); | |||
1267 | if (!RD->lookupInBases(BaseHasFields, Paths)) { | |||
1268 | // If no classes have fields, just decompose RD itself. (This will work | |||
1269 | // if and only if zero bindings were provided.) | |||
1270 | return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); | |||
1271 | } | |||
1272 | ||||
1273 | CXXBasePath *BestPath = nullptr; | |||
1274 | for (auto &P : Paths) { | |||
1275 | if (!BestPath) | |||
1276 | BestPath = &P; | |||
1277 | else if (!S.Context.hasSameType(P.back().Base->getType(), | |||
1278 | BestPath->back().Base->getType())) { | |||
1279 | // ... the same ... | |||
1280 | S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) | |||
1281 | << false << RD << BestPath->back().Base->getType() | |||
1282 | << P.back().Base->getType(); | |||
1283 | return DeclAccessPair(); | |||
1284 | } else if (P.Access < BestPath->Access) { | |||
1285 | BestPath = &P; | |||
1286 | } | |||
1287 | } | |||
1288 | ||||
1289 | // ... unambiguous ... | |||
1290 | QualType BaseType = BestPath->back().Base->getType(); | |||
1291 | if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { | |||
1292 | S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) | |||
1293 | << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); | |||
1294 | return DeclAccessPair(); | |||
1295 | } | |||
1296 | ||||
1297 | // ... [accessible, implied by other rules] base class of E. | |||
1298 | S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), | |||
1299 | *BestPath, diag::err_decomp_decl_inaccessible_base); | |||
1300 | AS = BestPath->Access; | |||
1301 | ||||
1302 | ClassWithFields = BaseType->getAsCXXRecordDecl(); | |||
1303 | S.BuildBasePathArray(Paths, BasePath); | |||
1304 | } | |||
1305 | ||||
1306 | // The above search did not check whether the selected class itself has base | |||
1307 | // classes with fields, so check that now. | |||
1308 | CXXBasePaths Paths; | |||
1309 | if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { | |||
1310 | S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) | |||
1311 | << (ClassWithFields == RD) << RD << ClassWithFields | |||
1312 | << Paths.front().back().Base->getType(); | |||
1313 | return DeclAccessPair(); | |||
1314 | } | |||
1315 | ||||
1316 | return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); | |||
1317 | } | |||
1318 | ||||
1319 | static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, | |||
1320 | ValueDecl *Src, QualType DecompType, | |||
1321 | const CXXRecordDecl *OrigRD) { | |||
1322 | if (S.RequireCompleteType(Src->getLocation(), DecompType, | |||
1323 | diag::err_incomplete_type)) | |||
1324 | return true; | |||
1325 | ||||
1326 | CXXCastPath BasePath; | |||
1327 | DeclAccessPair BasePair = | |||
1328 | findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); | |||
1329 | const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); | |||
1330 | if (!RD) | |||
1331 | return true; | |||
1332 | QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), | |||
1333 | DecompType.getQualifiers()); | |||
1334 | ||||
1335 | auto DiagnoseBadNumberOfBindings = [&]() -> bool { | |||
1336 | unsigned NumFields = | |||
1337 | std::count_if(RD->field_begin(), RD->field_end(), | |||
1338 | [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); | |||
1339 | assert(Bindings.size() != NumFields)((Bindings.size() != NumFields) ? static_cast<void> (0) : __assert_fail ("Bindings.size() != NumFields", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 1339, __PRETTY_FUNCTION__)); | |||
1340 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) | |||
1341 | << DecompType << (unsigned)Bindings.size() << NumFields | |||
1342 | << (NumFields < Bindings.size()); | |||
1343 | return true; | |||
1344 | }; | |||
1345 | ||||
1346 | // all of E's non-static data members shall be [...] well-formed | |||
1347 | // when named as e.name in the context of the structured binding, | |||
1348 | // E shall not have an anonymous union member, ... | |||
1349 | unsigned I = 0; | |||
1350 | for (auto *FD : RD->fields()) { | |||
1351 | if (FD->isUnnamedBitfield()) | |||
1352 | continue; | |||
1353 | ||||
1354 | if (FD->isAnonymousStructOrUnion()) { | |||
1355 | S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) | |||
1356 | << DecompType << FD->getType()->isUnionType(); | |||
1357 | S.Diag(FD->getLocation(), diag::note_declared_at); | |||
1358 | return true; | |||
1359 | } | |||
1360 | ||||
1361 | // We have a real field to bind. | |||
1362 | if (I >= Bindings.size()) | |||
1363 | return DiagnoseBadNumberOfBindings(); | |||
1364 | auto *B = Bindings[I++]; | |||
1365 | SourceLocation Loc = B->getLocation(); | |||
1366 | ||||
1367 | // The field must be accessible in the context of the structured binding. | |||
1368 | // We already checked that the base class is accessible. | |||
1369 | // FIXME: Add 'const' to AccessedEntity's classes so we can remove the | |||
1370 | // const_cast here. | |||
1371 | S.CheckStructuredBindingMemberAccess( | |||
1372 | Loc, const_cast<CXXRecordDecl *>(OrigRD), | |||
1373 | DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( | |||
1374 | BasePair.getAccess(), FD->getAccess()))); | |||
1375 | ||||
1376 | // Initialize the binding to Src.FD. | |||
1377 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); | |||
1378 | if (E.isInvalid()) | |||
1379 | return true; | |||
1380 | E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, | |||
1381 | VK_LValue, &BasePath); | |||
1382 | if (E.isInvalid()) | |||
1383 | return true; | |||
1384 | E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, | |||
1385 | CXXScopeSpec(), FD, | |||
1386 | DeclAccessPair::make(FD, FD->getAccess()), | |||
1387 | DeclarationNameInfo(FD->getDeclName(), Loc)); | |||
1388 | if (E.isInvalid()) | |||
1389 | return true; | |||
1390 | ||||
1391 | // If the type of the member is T, the referenced type is cv T, where cv is | |||
1392 | // the cv-qualification of the decomposition expression. | |||
1393 | // | |||
1394 | // FIXME: We resolve a defect here: if the field is mutable, we do not add | |||
1395 | // 'const' to the type of the field. | |||
1396 | Qualifiers Q = DecompType.getQualifiers(); | |||
1397 | if (FD->isMutable()) | |||
1398 | Q.removeConst(); | |||
1399 | B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); | |||
1400 | } | |||
1401 | ||||
1402 | if (I != Bindings.size()) | |||
1403 | return DiagnoseBadNumberOfBindings(); | |||
1404 | ||||
1405 | return false; | |||
1406 | } | |||
1407 | ||||
1408 | void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { | |||
1409 | QualType DecompType = DD->getType(); | |||
1410 | ||||
1411 | // If the type of the decomposition is dependent, then so is the type of | |||
1412 | // each binding. | |||
1413 | if (DecompType->isDependentType()) { | |||
1414 | for (auto *B : DD->bindings()) | |||
1415 | B->setType(Context.DependentTy); | |||
1416 | return; | |||
1417 | } | |||
1418 | ||||
1419 | DecompType = DecompType.getNonReferenceType(); | |||
1420 | ArrayRef<BindingDecl*> Bindings = DD->bindings(); | |||
1421 | ||||
1422 | // C++1z [dcl.decomp]/2: | |||
1423 | // If E is an array type [...] | |||
1424 | // As an extension, we also support decomposition of built-in complex and | |||
1425 | // vector types. | |||
1426 | if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { | |||
1427 | if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) | |||
1428 | DD->setInvalidDecl(); | |||
1429 | return; | |||
1430 | } | |||
1431 | if (auto *VT = DecompType->getAs<VectorType>()) { | |||
1432 | if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) | |||
1433 | DD->setInvalidDecl(); | |||
1434 | return; | |||
1435 | } | |||
1436 | if (auto *CT = DecompType->getAs<ComplexType>()) { | |||
1437 | if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) | |||
1438 | DD->setInvalidDecl(); | |||
1439 | return; | |||
1440 | } | |||
1441 | ||||
1442 | // C++1z [dcl.decomp]/3: | |||
1443 | // if the expression std::tuple_size<E>::value is a well-formed integral | |||
1444 | // constant expression, [...] | |||
1445 | llvm::APSInt TupleSize(32); | |||
1446 | switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { | |||
1447 | case IsTupleLike::Error: | |||
1448 | DD->setInvalidDecl(); | |||
1449 | return; | |||
1450 | ||||
1451 | case IsTupleLike::TupleLike: | |||
1452 | if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) | |||
1453 | DD->setInvalidDecl(); | |||
1454 | return; | |||
1455 | ||||
1456 | case IsTupleLike::NotTupleLike: | |||
1457 | break; | |||
1458 | } | |||
1459 | ||||
1460 | // C++1z [dcl.dcl]/8: | |||
1461 | // [E shall be of array or non-union class type] | |||
1462 | CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); | |||
1463 | if (!RD || RD->isUnion()) { | |||
1464 | Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) | |||
1465 | << DD << !RD << DecompType; | |||
1466 | DD->setInvalidDecl(); | |||
1467 | return; | |||
1468 | } | |||
1469 | ||||
1470 | // C++1z [dcl.decomp]/4: | |||
1471 | // all of E's non-static data members shall be [...] direct members of | |||
1472 | // E or of the same unambiguous public base class of E, ... | |||
1473 | if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) | |||
1474 | DD->setInvalidDecl(); | |||
1475 | } | |||
1476 | ||||
1477 | /// Merge the exception specifications of two variable declarations. | |||
1478 | /// | |||
1479 | /// This is called when there's a redeclaration of a VarDecl. The function | |||
1480 | /// checks if the redeclaration might have an exception specification and | |||
1481 | /// validates compatibility and merges the specs if necessary. | |||
1482 | void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { | |||
1483 | // Shortcut if exceptions are disabled. | |||
1484 | if (!getLangOpts().CXXExceptions) | |||
1485 | return; | |||
1486 | ||||
1487 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 1488, __PRETTY_FUNCTION__)) | |||
1488 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 1488, __PRETTY_FUNCTION__)); | |||
1489 | ||||
1490 | QualType NewType = New->getType(); | |||
1491 | QualType OldType = Old->getType(); | |||
1492 | ||||
1493 | // We're only interested in pointers and references to functions, as well | |||
1494 | // as pointers to member functions. | |||
1495 | if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { | |||
1496 | NewType = R->getPointeeType(); | |||
1497 | OldType = OldType->getAs<ReferenceType>()->getPointeeType(); | |||
1498 | } else if (const PointerType *P = NewType->getAs<PointerType>()) { | |||
1499 | NewType = P->getPointeeType(); | |||
1500 | OldType = OldType->getAs<PointerType>()->getPointeeType(); | |||
1501 | } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { | |||
1502 | NewType = M->getPointeeType(); | |||
1503 | OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); | |||
1504 | } | |||
1505 | ||||
1506 | if (!NewType->isFunctionProtoType()) | |||
1507 | return; | |||
1508 | ||||
1509 | // There's lots of special cases for functions. For function pointers, system | |||
1510 | // libraries are hopefully not as broken so that we don't need these | |||
1511 | // workarounds. | |||
1512 | if (CheckEquivalentExceptionSpec( | |||
1513 | OldType->getAs<FunctionProtoType>(), Old->getLocation(), | |||
1514 | NewType->getAs<FunctionProtoType>(), New->getLocation())) { | |||
1515 | New->setInvalidDecl(); | |||
1516 | } | |||
1517 | } | |||
1518 | ||||
1519 | /// CheckCXXDefaultArguments - Verify that the default arguments for a | |||
1520 | /// function declaration are well-formed according to C++ | |||
1521 | /// [dcl.fct.default]. | |||
1522 | void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { | |||
1523 | unsigned NumParams = FD->getNumParams(); | |||
1524 | unsigned p; | |||
1525 | ||||
1526 | // Find first parameter with a default argument | |||
1527 | for (p = 0; p < NumParams; ++p) { | |||
1528 | ParmVarDecl *Param = FD->getParamDecl(p); | |||
1529 | if (Param->hasDefaultArg()) | |||
1530 | break; | |||
1531 | } | |||
1532 | ||||
1533 | // C++11 [dcl.fct.default]p4: | |||
1534 | // In a given function declaration, each parameter subsequent to a parameter | |||
1535 | // with a default argument shall have a default argument supplied in this or | |||
1536 | // a previous declaration or shall be a function parameter pack. A default | |||
1537 | // argument shall not be redefined by a later declaration (not even to the | |||
1538 | // same value). | |||
1539 | unsigned LastMissingDefaultArg = 0; | |||
1540 | for (; p < NumParams; ++p) { | |||
1541 | ParmVarDecl *Param = FD->getParamDecl(p); | |||
1542 | if (!Param->hasDefaultArg() && !Param->isParameterPack()) { | |||
1543 | if (Param->isInvalidDecl()) | |||
1544 | /* We already complained about this parameter. */; | |||
1545 | else if (Param->getIdentifier()) | |||
1546 | Diag(Param->getLocation(), | |||
1547 | diag::err_param_default_argument_missing_name) | |||
1548 | << Param->getIdentifier(); | |||
1549 | else | |||
1550 | Diag(Param->getLocation(), | |||
1551 | diag::err_param_default_argument_missing); | |||
1552 | ||||
1553 | LastMissingDefaultArg = p; | |||
1554 | } | |||
1555 | } | |||
1556 | ||||
1557 | if (LastMissingDefaultArg > 0) { | |||
1558 | // Some default arguments were missing. Clear out all of the | |||
1559 | // default arguments up to (and including) the last missing | |||
1560 | // default argument, so that we leave the function parameters | |||
1561 | // in a semantically valid state. | |||
1562 | for (p = 0; p <= LastMissingDefaultArg; ++p) { | |||
1563 | ParmVarDecl *Param = FD->getParamDecl(p); | |||
1564 | if (Param->hasDefaultArg()) { | |||
1565 | Param->setDefaultArg(nullptr); | |||
1566 | } | |||
1567 | } | |||
1568 | } | |||
1569 | } | |||
1570 | ||||
1571 | /// Check that the given type is a literal type. Issue a diagnostic if not, | |||
1572 | /// if Kind is Diagnose. | |||
1573 | /// \return \c true if a problem has been found (and optionally diagnosed). | |||
1574 | template <typename... Ts> | |||
1575 | static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, | |||
1576 | SourceLocation Loc, QualType T, unsigned DiagID, | |||
1577 | Ts &&...DiagArgs) { | |||
1578 | if (T->isDependentType()) | |||
1579 | return false; | |||
1580 | ||||
1581 | switch (Kind) { | |||
1582 | case Sema::CheckConstexprKind::Diagnose: | |||
1583 | return SemaRef.RequireLiteralType(Loc, T, DiagID, | |||
1584 | std::forward<Ts>(DiagArgs)...); | |||
1585 | ||||
1586 | case Sema::CheckConstexprKind::CheckValid: | |||
1587 | return !T->isLiteralType(SemaRef.Context); | |||
1588 | } | |||
1589 | ||||
1590 | llvm_unreachable("unknown CheckConstexprKind")::llvm::llvm_unreachable_internal("unknown CheckConstexprKind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 1590); | |||
1591 | } | |||
1592 | ||||
1593 | /// Determine whether a destructor cannot be constexpr due to | |||
1594 | static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, | |||
1595 | const CXXDestructorDecl *DD, | |||
1596 | Sema::CheckConstexprKind Kind) { | |||
1597 | auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { | |||
1598 | const CXXRecordDecl *RD = | |||
1599 | T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | |||
1600 | if (!RD || RD->hasConstexprDestructor()) | |||
1601 | return true; | |||
1602 | ||||
1603 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | |||
1604 | SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) | |||
1605 | << DD->getConstexprKind() << !FD | |||
1606 | << (FD ? FD->getDeclName() : DeclarationName()) << T; | |||
1607 | SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) | |||
1608 | << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; | |||
1609 | } | |||
1610 | return false; | |||
1611 | }; | |||
1612 | ||||
1613 | const CXXRecordDecl *RD = DD->getParent(); | |||
1614 | for (const CXXBaseSpecifier &B : RD->bases()) | |||
1615 | if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) | |||
1616 | return false; | |||
1617 | for (const FieldDecl *FD : RD->fields()) | |||
1618 | if (!Check(FD->getLocation(), FD->getType(), FD)) | |||
1619 | return false; | |||
1620 | return true; | |||
1621 | } | |||
1622 | ||||
1623 | // CheckConstexprParameterTypes - Check whether a function's parameter types | |||
1624 | // are all literal types. If so, return true. If not, produce a suitable | |||
1625 | // diagnostic and return false. | |||
1626 | static bool CheckConstexprParameterTypes(Sema &SemaRef, | |||
1627 | const FunctionDecl *FD, | |||
1628 | Sema::CheckConstexprKind Kind) { | |||
1629 | unsigned ArgIndex = 0; | |||
1630 | const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); | |||
1631 | for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), | |||
1632 | e = FT->param_type_end(); | |||
1633 | i != e; ++i, ++ArgIndex) { | |||
1634 | const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); | |||
1635 | SourceLocation ParamLoc = PD->getLocation(); | |||
1636 | if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, | |||
1637 | diag::err_constexpr_non_literal_param, ArgIndex + 1, | |||
1638 | PD->getSourceRange(), isa<CXXConstructorDecl>(FD), | |||
1639 | FD->isConsteval())) | |||
1640 | return false; | |||
1641 | } | |||
1642 | return true; | |||
1643 | } | |||
1644 | ||||
1645 | /// Get diagnostic %select index for tag kind for | |||
1646 | /// record diagnostic message. | |||
1647 | /// WARNING: Indexes apply to particular diagnostics only! | |||
1648 | /// | |||
1649 | /// \returns diagnostic %select index. | |||
1650 | static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { | |||
1651 | switch (Tag) { | |||
1652 | case TTK_Struct: return 0; | |||
1653 | case TTK_Interface: return 1; | |||
1654 | case TTK_Class: return 2; | |||
1655 | default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 1655); | |||
1656 | } | |||
1657 | } | |||
1658 | ||||
1659 | static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, | |||
1660 | Stmt *Body, | |||
1661 | Sema::CheckConstexprKind Kind); | |||
1662 | ||||
1663 | // Check whether a function declaration satisfies the requirements of a | |||
1664 | // constexpr function definition or a constexpr constructor definition. If so, | |||
1665 | // return true. If not, produce appropriate diagnostics (unless asked not to by | |||
1666 | // Kind) and return false. | |||
1667 | // | |||
1668 | // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. | |||
1669 | bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, | |||
1670 | CheckConstexprKind Kind) { | |||
1671 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | |||
1672 | if (MD && MD->isInstance()) { | |||
1673 | // C++11 [dcl.constexpr]p4: | |||
1674 | // The definition of a constexpr constructor shall satisfy the following | |||
1675 | // constraints: | |||
1676 | // - the class shall not have any virtual base classes; | |||
1677 | // | |||
1678 | // FIXME: This only applies to constructors and destructors, not arbitrary | |||
1679 | // member functions. | |||
1680 | const CXXRecordDecl *RD = MD->getParent(); | |||
1681 | if (RD->getNumVBases()) { | |||
1682 | if (Kind == CheckConstexprKind::CheckValid) | |||
1683 | return false; | |||
1684 | ||||
1685 | Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) | |||
1686 | << isa<CXXConstructorDecl>(NewFD) | |||
1687 | << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); | |||
1688 | for (const auto &I : RD->vbases()) | |||
1689 | Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) | |||
1690 | << I.getSourceRange(); | |||
1691 | return false; | |||
1692 | } | |||
1693 | } | |||
1694 | ||||
1695 | if (!isa<CXXConstructorDecl>(NewFD)) { | |||
1696 | // C++11 [dcl.constexpr]p3: | |||
1697 | // The definition of a constexpr function shall satisfy the following | |||
1698 | // constraints: | |||
1699 | // - it shall not be virtual; (removed in C++20) | |||
1700 | const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); | |||
1701 | if (Method && Method->isVirtual()) { | |||
1702 | if (getLangOpts().CPlusPlus2a) { | |||
1703 | if (Kind == CheckConstexprKind::Diagnose) | |||
1704 | Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); | |||
1705 | } else { | |||
1706 | if (Kind == CheckConstexprKind::CheckValid) | |||
1707 | return false; | |||
1708 | ||||
1709 | Method = Method->getCanonicalDecl(); | |||
1710 | Diag(Method->getLocation(), diag::err_constexpr_virtual); | |||
1711 | ||||
1712 | // If it's not obvious why this function is virtual, find an overridden | |||
1713 | // function which uses the 'virtual' keyword. | |||
1714 | const CXXMethodDecl *WrittenVirtual = Method; | |||
1715 | while (!WrittenVirtual->isVirtualAsWritten()) | |||
1716 | WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); | |||
1717 | if (WrittenVirtual != Method) | |||
1718 | Diag(WrittenVirtual->getLocation(), | |||
1719 | diag::note_overridden_virtual_function); | |||
1720 | return false; | |||
1721 | } | |||
1722 | } | |||
1723 | ||||
1724 | // - its return type shall be a literal type; | |||
1725 | QualType RT = NewFD->getReturnType(); | |||
1726 | if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT, | |||
1727 | diag::err_constexpr_non_literal_return, | |||
1728 | NewFD->isConsteval())) | |||
1729 | return false; | |||
1730 | } | |||
1731 | ||||
1732 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { | |||
1733 | // A destructor can be constexpr only if the defaulted destructor could be; | |||
1734 | // we don't need to check the members and bases if we already know they all | |||
1735 | // have constexpr destructors. | |||
1736 | if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { | |||
1737 | if (Kind == CheckConstexprKind::CheckValid) | |||
1738 | return false; | |||
1739 | if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) | |||
1740 | return false; | |||
1741 | } | |||
1742 | } | |||
1743 | ||||
1744 | // - each of its parameter types shall be a literal type; | |||
1745 | if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) | |||
1746 | return false; | |||
1747 | ||||
1748 | Stmt *Body = NewFD->getBody(); | |||
1749 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 1750, __PRETTY_FUNCTION__)) | |||
1750 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 1750, __PRETTY_FUNCTION__)); | |||
1751 | return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); | |||
1752 | } | |||
1753 | ||||
1754 | /// Check the given declaration statement is legal within a constexpr function | |||
1755 | /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. | |||
1756 | /// | |||
1757 | /// \return true if the body is OK (maybe only as an extension), false if we | |||
1758 | /// have diagnosed a problem. | |||
1759 | static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, | |||
1760 | DeclStmt *DS, SourceLocation &Cxx1yLoc, | |||
1761 | Sema::CheckConstexprKind Kind) { | |||
1762 | // C++11 [dcl.constexpr]p3 and p4: | |||
1763 | // The definition of a constexpr function(p3) or constructor(p4) [...] shall | |||
1764 | // contain only | |||
1765 | for (const auto *DclIt : DS->decls()) { | |||
1766 | switch (DclIt->getKind()) { | |||
1767 | case Decl::StaticAssert: | |||
1768 | case Decl::Using: | |||
1769 | case Decl::UsingShadow: | |||
1770 | case Decl::UsingDirective: | |||
1771 | case Decl::UnresolvedUsingTypename: | |||
1772 | case Decl::UnresolvedUsingValue: | |||
1773 | // - static_assert-declarations | |||
1774 | // - using-declarations, | |||
1775 | // - using-directives, | |||
1776 | continue; | |||
1777 | ||||
1778 | case Decl::Typedef: | |||
1779 | case Decl::TypeAlias: { | |||
1780 | // - typedef declarations and alias-declarations that do not define | |||
1781 | // classes or enumerations, | |||
1782 | const auto *TN = cast<TypedefNameDecl>(DclIt); | |||
1783 | if (TN->getUnderlyingType()->isVariablyModifiedType()) { | |||
1784 | // Don't allow variably-modified types in constexpr functions. | |||
1785 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | |||
1786 | TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); | |||
1787 | SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) | |||
1788 | << TL.getSourceRange() << TL.getType() | |||
1789 | << isa<CXXConstructorDecl>(Dcl); | |||
1790 | } | |||
1791 | return false; | |||
1792 | } | |||
1793 | continue; | |||
1794 | } | |||
1795 | ||||
1796 | case Decl::Enum: | |||
1797 | case Decl::CXXRecord: | |||
1798 | // C++1y allows types to be defined, not just declared. | |||
1799 | if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { | |||
1800 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | |||
1801 | SemaRef.Diag(DS->getBeginLoc(), | |||
1802 | SemaRef.getLangOpts().CPlusPlus14 | |||
1803 | ? diag::warn_cxx11_compat_constexpr_type_definition | |||
1804 | : diag::ext_constexpr_type_definition) | |||
1805 | << isa<CXXConstructorDecl>(Dcl); | |||
1806 | } else if (!SemaRef.getLangOpts().CPlusPlus14) { | |||
1807 | return false; | |||
1808 | } | |||
1809 | } | |||
1810 | continue; | |||
1811 | ||||
1812 | case Decl::EnumConstant: | |||
1813 | case Decl::IndirectField: | |||
1814 | case Decl::ParmVar: | |||
1815 | // These can only appear with other declarations which are banned in | |||
1816 | // C++11 and permitted in C++1y, so ignore them. | |||
1817 | continue; | |||
1818 | ||||
1819 | case Decl::Var: | |||
1820 | case Decl::Decomposition: { | |||
1821 | // C++1y [dcl.constexpr]p3 allows anything except: | |||
1822 | // a definition of a variable of non-literal type or of static or | |||
1823 | // thread storage duration or [before C++2a] for which no | |||
1824 | // initialization is performed. | |||
1825 | const auto *VD = cast<VarDecl>(DclIt); | |||
1826 | if (VD->isThisDeclarationADefinition()) { | |||
1827 | if (VD->isStaticLocal()) { | |||
1828 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | |||
1829 | SemaRef.Diag(VD->getLocation(), | |||
1830 | diag::err_constexpr_local_var_static) | |||
1831 | << isa<CXXConstructorDecl>(Dcl) | |||
1832 | << (VD->getTLSKind() == VarDecl::TLS_Dynamic); | |||
1833 | } | |||
1834 | return false; | |||
1835 | } | |||
1836 | if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), | |||
1837 | diag::err_constexpr_local_var_non_literal_type, | |||
1838 | isa<CXXConstructorDecl>(Dcl))) | |||
1839 | return false; | |||
1840 | if (!VD->getType()->isDependentType() && | |||
1841 | !VD->hasInit() && !VD->isCXXForRangeDecl()) { | |||
1842 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | |||
1843 | SemaRef.Diag( | |||
1844 | VD->getLocation(), | |||
1845 | SemaRef.getLangOpts().CPlusPlus2a | |||
1846 | ? diag::warn_cxx17_compat_constexpr_local_var_no_init | |||
1847 | : diag::ext_constexpr_local_var_no_init) | |||
1848 | << isa<CXXConstructorDecl>(Dcl); | |||
1849 | } else if (!SemaRef.getLangOpts().CPlusPlus2a) { | |||
1850 | return false; | |||
1851 | } | |||
1852 | continue; | |||
1853 | } | |||
1854 | } | |||
1855 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | |||
1856 | SemaRef.Diag(VD->getLocation(), | |||
1857 | SemaRef.getLangOpts().CPlusPlus14 | |||
1858 | ? diag::warn_cxx11_compat_constexpr_local_var | |||
1859 | : diag::ext_constexpr_local_var) | |||
1860 | << isa<CXXConstructorDecl>(Dcl); | |||
1861 | } else if (!SemaRef.getLangOpts().CPlusPlus14) { | |||
1862 | return false; | |||
1863 | } | |||
1864 | continue; | |||
1865 | } | |||
1866 | ||||
1867 | case Decl::NamespaceAlias: | |||
1868 | case Decl::Function: | |||
1869 | // These are disallowed in C++11 and permitted in C++1y. Allow them | |||
1870 | // everywhere as an extension. | |||
1871 | if (!Cxx1yLoc.isValid()) | |||
1872 | Cxx1yLoc = DS->getBeginLoc(); | |||
1873 | continue; | |||
1874 | ||||
1875 | default: | |||
1876 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | |||
1877 | SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) | |||
1878 | << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); | |||
1879 | } | |||
1880 | return false; | |||
1881 | } | |||
1882 | } | |||
1883 | ||||
1884 | return true; | |||
1885 | } | |||
1886 | ||||
1887 | /// Check that the given field is initialized within a constexpr constructor. | |||
1888 | /// | |||
1889 | /// \param Dcl The constexpr constructor being checked. | |||
1890 | /// \param Field The field being checked. This may be a member of an anonymous | |||
1891 | /// struct or union nested within the class being checked. | |||
1892 | /// \param Inits All declarations, including anonymous struct/union members and | |||
1893 | /// indirect members, for which any initialization was provided. | |||
1894 | /// \param Diagnosed Whether we've emitted the error message yet. Used to attach | |||
1895 | /// multiple notes for different members to the same error. | |||
1896 | /// \param Kind Whether we're diagnosing a constructor as written or determining | |||
1897 | /// whether the formal requirements are satisfied. | |||
1898 | /// \return \c false if we're checking for validity and the constructor does | |||
1899 | /// not satisfy the requirements on a constexpr constructor. | |||
1900 | static bool CheckConstexprCtorInitializer(Sema &SemaRef, | |||
1901 | const FunctionDecl *Dcl, | |||
1902 | FieldDecl *Field, | |||
1903 | llvm::SmallSet<Decl*, 16> &Inits, | |||
1904 | bool &Diagnosed, | |||
1905 | Sema::CheckConstexprKind Kind) { | |||
1906 | // In C++20 onwards, there's nothing to check for validity. | |||
1907 | if (Kind == Sema::CheckConstexprKind::CheckValid && | |||
1908 | SemaRef.getLangOpts().CPlusPlus2a) | |||
1909 | return true; | |||
1910 | ||||
1911 | if (Field->isInvalidDecl()) | |||
1912 | return true; | |||
1913 | ||||
1914 | if (Field->isUnnamedBitfield()) | |||
1915 | return true; | |||
1916 | ||||
1917 | // Anonymous unions with no variant members and empty anonymous structs do not | |||
1918 | // need to be explicitly initialized. FIXME: Anonymous structs that contain no | |||
1919 | // indirect fields don't need initializing. | |||
1920 | if (Field->isAnonymousStructOrUnion() && | |||
1921 | (Field->getType()->isUnionType() | |||
1922 | ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() | |||
1923 | : Field->getType()->getAsCXXRecordDecl()->isEmpty())) | |||
1924 | return true; | |||
1925 | ||||
1926 | if (!Inits.count(Field)) { | |||
1927 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | |||
1928 | if (!Diagnosed) { | |||
1929 | SemaRef.Diag(Dcl->getLocation(), | |||
1930 | SemaRef.getLangOpts().CPlusPlus2a | |||
1931 | ? diag::warn_cxx17_compat_constexpr_ctor_missing_init | |||
1932 | : diag::ext_constexpr_ctor_missing_init); | |||
1933 | Diagnosed = true; | |||
1934 | } | |||
1935 | SemaRef.Diag(Field->getLocation(), | |||
1936 | diag::note_constexpr_ctor_missing_init); | |||
1937 | } else if (!SemaRef.getLangOpts().CPlusPlus2a) { | |||
1938 | return false; | |||
1939 | } | |||
1940 | } else if (Field->isAnonymousStructOrUnion()) { | |||
1941 | const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); | |||
1942 | for (auto *I : RD->fields()) | |||
1943 | // If an anonymous union contains an anonymous struct of which any member | |||
1944 | // is initialized, all members must be initialized. | |||
1945 | if (!RD->isUnion() || Inits.count(I)) | |||
1946 | if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, | |||
1947 | Kind)) | |||
1948 | return false; | |||
1949 | } | |||
1950 | return true; | |||
1951 | } | |||
1952 | ||||
1953 | /// Check the provided statement is allowed in a constexpr function | |||
1954 | /// definition. | |||
1955 | static bool | |||
1956 | CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, | |||
1957 | SmallVectorImpl<SourceLocation> &ReturnStmts, | |||
1958 | SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, | |||
1959 | Sema::CheckConstexprKind Kind) { | |||
1960 | // - its function-body shall be [...] a compound-statement that contains only | |||
1961 | switch (S->getStmtClass()) { | |||
1962 | case Stmt::NullStmtClass: | |||
1963 | // - null statements, | |||
1964 | return true; | |||
1965 | ||||
1966 | case Stmt::DeclStmtClass: | |||
1967 | // - static_assert-declarations | |||
1968 | // - using-declarations, | |||
1969 | // - using-directives, | |||
1970 | // - typedef declarations and alias-declarations that do not define | |||
1971 | // classes or enumerations, | |||
1972 | if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) | |||
1973 | return false; | |||
1974 | return true; | |||
1975 | ||||
1976 | case Stmt::ReturnStmtClass: | |||
1977 | // - and exactly one return statement; | |||
1978 | if (isa<CXXConstructorDecl>(Dcl)) { | |||
1979 | // C++1y allows return statements in constexpr constructors. | |||
1980 | if (!Cxx1yLoc.isValid()) | |||
1981 | Cxx1yLoc = S->getBeginLoc(); | |||
1982 | return true; | |||
1983 | } | |||
1984 | ||||
1985 | ReturnStmts.push_back(S->getBeginLoc()); | |||
1986 | return true; | |||
1987 | ||||
1988 | case Stmt::CompoundStmtClass: { | |||
1989 | // C++1y allows compound-statements. | |||
1990 | if (!Cxx1yLoc.isValid()) | |||
1991 | Cxx1yLoc = S->getBeginLoc(); | |||
1992 | ||||
1993 | CompoundStmt *CompStmt = cast<CompoundStmt>(S); | |||
1994 | for (auto *BodyIt : CompStmt->body()) { | |||
1995 | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, | |||
1996 | Cxx1yLoc, Cxx2aLoc, Kind)) | |||
1997 | return false; | |||
1998 | } | |||
1999 | return true; | |||
2000 | } | |||
2001 | ||||
2002 | case Stmt::AttributedStmtClass: | |||
2003 | if (!Cxx1yLoc.isValid()) | |||
2004 | Cxx1yLoc = S->getBeginLoc(); | |||
2005 | return true; | |||
2006 | ||||
2007 | case Stmt::IfStmtClass: { | |||
2008 | // C++1y allows if-statements. | |||
2009 | if (!Cxx1yLoc.isValid()) | |||
2010 | Cxx1yLoc = S->getBeginLoc(); | |||
2011 | ||||
2012 | IfStmt *If = cast<IfStmt>(S); | |||
2013 | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, | |||
2014 | Cxx1yLoc, Cxx2aLoc, Kind)) | |||
2015 | return false; | |||
2016 | if (If->getElse() && | |||
2017 | !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, | |||
2018 | Cxx1yLoc, Cxx2aLoc, Kind)) | |||
2019 | return false; | |||
2020 | return true; | |||
2021 | } | |||
2022 | ||||
2023 | case Stmt::WhileStmtClass: | |||
2024 | case Stmt::DoStmtClass: | |||
2025 | case Stmt::ForStmtClass: | |||
2026 | case Stmt::CXXForRangeStmtClass: | |||
2027 | case Stmt::ContinueStmtClass: | |||
2028 | // C++1y allows all of these. We don't allow them as extensions in C++11, | |||
2029 | // because they don't make sense without variable mutation. | |||
2030 | if (!SemaRef.getLangOpts().CPlusPlus14) | |||
2031 | break; | |||
2032 | if (!Cxx1yLoc.isValid()) | |||
2033 | Cxx1yLoc = S->getBeginLoc(); | |||
2034 | for (Stmt *SubStmt : S->children()) | |||
2035 | if (SubStmt && | |||
2036 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, | |||
2037 | Cxx1yLoc, Cxx2aLoc, Kind)) | |||
2038 | return false; | |||
2039 | return true; | |||
2040 | ||||
2041 | case Stmt::SwitchStmtClass: | |||
2042 | case Stmt::CaseStmtClass: | |||
2043 | case Stmt::DefaultStmtClass: | |||
2044 | case Stmt::BreakStmtClass: | |||
2045 | // C++1y allows switch-statements, and since they don't need variable | |||
2046 | // mutation, we can reasonably allow them in C++11 as an extension. | |||
2047 | if (!Cxx1yLoc.isValid()) | |||
2048 | Cxx1yLoc = S->getBeginLoc(); | |||
2049 | for (Stmt *SubStmt : S->children()) | |||
2050 | if (SubStmt && | |||
2051 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, | |||
2052 | Cxx1yLoc, Cxx2aLoc, Kind)) | |||
2053 | return false; | |||
2054 | return true; | |||
2055 | ||||
2056 | case Stmt::GCCAsmStmtClass: | |||
2057 | case Stmt::MSAsmStmtClass: | |||
2058 | // C++2a allows inline assembly statements. | |||
2059 | case Stmt::CXXTryStmtClass: | |||
2060 | if (Cxx2aLoc.isInvalid()) | |||
2061 | Cxx2aLoc = S->getBeginLoc(); | |||
2062 | for (Stmt *SubStmt : S->children()) { | |||
2063 | if (SubStmt && | |||
2064 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, | |||
2065 | Cxx1yLoc, Cxx2aLoc, Kind)) | |||
2066 | return false; | |||
2067 | } | |||
2068 | return true; | |||
2069 | ||||
2070 | case Stmt::CXXCatchStmtClass: | |||
2071 | // Do not bother checking the language mode (already covered by the | |||
2072 | // try block check). | |||
2073 | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, | |||
2074 | cast<CXXCatchStmt>(S)->getHandlerBlock(), | |||
2075 | ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) | |||
2076 | return false; | |||
2077 | return true; | |||
2078 | ||||
2079 | default: | |||
2080 | if (!isa<Expr>(S)) | |||
2081 | break; | |||
2082 | ||||
2083 | // C++1y allows expression-statements. | |||
2084 | if (!Cxx1yLoc.isValid()) | |||
2085 | Cxx1yLoc = S->getBeginLoc(); | |||
2086 | return true; | |||
2087 | } | |||
2088 | ||||
2089 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | |||
2090 | SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) | |||
2091 | << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); | |||
2092 | } | |||
2093 | return false; | |||
2094 | } | |||
2095 | ||||
2096 | /// Check the body for the given constexpr function declaration only contains | |||
2097 | /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. | |||
2098 | /// | |||
2099 | /// \return true if the body is OK, false if we have found or diagnosed a | |||
2100 | /// problem. | |||
2101 | static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, | |||
2102 | Stmt *Body, | |||
2103 | Sema::CheckConstexprKind Kind) { | |||
2104 | SmallVector<SourceLocation, 4> ReturnStmts; | |||
2105 | ||||
2106 | if (isa<CXXTryStmt>(Body)) { | |||
2107 | // C++11 [dcl.constexpr]p3: | |||
2108 | // The definition of a constexpr function shall satisfy the following | |||
2109 | // constraints: [...] | |||
2110 | // - its function-body shall be = delete, = default, or a | |||
2111 | // compound-statement | |||
2112 | // | |||
2113 | // C++11 [dcl.constexpr]p4: | |||
2114 | // In the definition of a constexpr constructor, [...] | |||
2115 | // - its function-body shall not be a function-try-block; | |||
2116 | // | |||
2117 | // This restriction is lifted in C++2a, as long as inner statements also | |||
2118 | // apply the general constexpr rules. | |||
2119 | switch (Kind) { | |||
2120 | case Sema::CheckConstexprKind::CheckValid: | |||
2121 | if (!SemaRef.getLangOpts().CPlusPlus2a) | |||
2122 | return false; | |||
2123 | break; | |||
2124 | ||||
2125 | case Sema::CheckConstexprKind::Diagnose: | |||
2126 | SemaRef.Diag(Body->getBeginLoc(), | |||
2127 | !SemaRef.getLangOpts().CPlusPlus2a | |||
2128 | ? diag::ext_constexpr_function_try_block_cxx2a | |||
2129 | : diag::warn_cxx17_compat_constexpr_function_try_block) | |||
2130 | << isa<CXXConstructorDecl>(Dcl); | |||
2131 | break; | |||
2132 | } | |||
2133 | } | |||
2134 | ||||
2135 | // - its function-body shall be [...] a compound-statement that contains only | |||
2136 | // [... list of cases ...] | |||
2137 | // | |||
2138 | // Note that walking the children here is enough to properly check for | |||
2139 | // CompoundStmt and CXXTryStmt body. | |||
2140 | SourceLocation Cxx1yLoc, Cxx2aLoc; | |||
2141 | for (Stmt *SubStmt : Body->children()) { | |||
2142 | if (SubStmt && | |||
2143 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, | |||
2144 | Cxx1yLoc, Cxx2aLoc, Kind)) | |||
2145 | return false; | |||
2146 | } | |||
2147 | ||||
2148 | if (Kind == Sema::CheckConstexprKind::CheckValid) { | |||
2149 | // If this is only valid as an extension, report that we don't satisfy the | |||
2150 | // constraints of the current language. | |||
2151 | if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) || | |||
2152 | (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) | |||
2153 | return false; | |||
2154 | } else if (Cxx2aLoc.isValid()) { | |||
2155 | SemaRef.Diag(Cxx2aLoc, | |||
2156 | SemaRef.getLangOpts().CPlusPlus2a | |||
2157 | ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt | |||
2158 | : diag::ext_constexpr_body_invalid_stmt_cxx2a) | |||
2159 | << isa<CXXConstructorDecl>(Dcl); | |||
2160 | } else if (Cxx1yLoc.isValid()) { | |||
2161 | SemaRef.Diag(Cxx1yLoc, | |||
2162 | SemaRef.getLangOpts().CPlusPlus14 | |||
2163 | ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt | |||
2164 | : diag::ext_constexpr_body_invalid_stmt) | |||
2165 | << isa<CXXConstructorDecl>(Dcl); | |||
2166 | } | |||
2167 | ||||
2168 | if (const CXXConstructorDecl *Constructor | |||
2169 | = dyn_cast<CXXConstructorDecl>(Dcl)) { | |||
2170 | const CXXRecordDecl *RD = Constructor->getParent(); | |||
2171 | // DR1359: | |||
2172 | // - every non-variant non-static data member and base class sub-object | |||
2173 | // shall be initialized; | |||
2174 | // DR1460: | |||
2175 | // - if the class is a union having variant members, exactly one of them | |||
2176 | // shall be initialized; | |||
2177 | if (RD->isUnion()) { | |||
2178 | if (Constructor->getNumCtorInitializers() == 0 && | |||
2179 | RD->hasVariantMembers()) { | |||
2180 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | |||
2181 | SemaRef.Diag( | |||
2182 | Dcl->getLocation(), | |||
2183 | SemaRef.getLangOpts().CPlusPlus2a | |||
2184 | ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init | |||
2185 | : diag::ext_constexpr_union_ctor_no_init); | |||
2186 | } else if (!SemaRef.getLangOpts().CPlusPlus2a) { | |||
2187 | return false; | |||
2188 | } | |||
2189 | } | |||
2190 | } else if (!Constructor->isDependentContext() && | |||
2191 | !Constructor->isDelegatingConstructor()) { | |||
2192 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2192, __PRETTY_FUNCTION__)); | |||
2193 | ||||
2194 | // Skip detailed checking if we have enough initializers, and we would | |||
2195 | // allow at most one initializer per member. | |||
2196 | bool AnyAnonStructUnionMembers = false; | |||
2197 | unsigned Fields = 0; | |||
2198 | for (CXXRecordDecl::field_iterator I = RD->field_begin(), | |||
2199 | E = RD->field_end(); I != E; ++I, ++Fields) { | |||
2200 | if (I->isAnonymousStructOrUnion()) { | |||
2201 | AnyAnonStructUnionMembers = true; | |||
2202 | break; | |||
2203 | } | |||
2204 | } | |||
2205 | // DR1460: | |||
2206 | // - if the class is a union-like class, but is not a union, for each of | |||
2207 | // its anonymous union members having variant members, exactly one of | |||
2208 | // them shall be initialized; | |||
2209 | if (AnyAnonStructUnionMembers || | |||
2210 | Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { | |||
2211 | // Check initialization of non-static data members. Base classes are | |||
2212 | // always initialized so do not need to be checked. Dependent bases | |||
2213 | // might not have initializers in the member initializer list. | |||
2214 | llvm::SmallSet<Decl*, 16> Inits; | |||
2215 | for (const auto *I: Constructor->inits()) { | |||
2216 | if (FieldDecl *FD = I->getMember()) | |||
2217 | Inits.insert(FD); | |||
2218 | else if (IndirectFieldDecl *ID = I->getIndirectMember()) | |||
2219 | Inits.insert(ID->chain_begin(), ID->chain_end()); | |||
2220 | } | |||
2221 | ||||
2222 | bool Diagnosed = false; | |||
2223 | for (auto *I : RD->fields()) | |||
2224 | if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, | |||
2225 | Kind)) | |||
2226 | return false; | |||
2227 | } | |||
2228 | } | |||
2229 | } else { | |||
2230 | if (ReturnStmts.empty()) { | |||
2231 | // C++1y doesn't require constexpr functions to contain a 'return' | |||
2232 | // statement. We still do, unless the return type might be void, because | |||
2233 | // otherwise if there's no return statement, the function cannot | |||
2234 | // be used in a core constant expression. | |||
2235 | bool OK = SemaRef.getLangOpts().CPlusPlus14 && | |||
2236 | (Dcl->getReturnType()->isVoidType() || | |||
2237 | Dcl->getReturnType()->isDependentType()); | |||
2238 | switch (Kind) { | |||
2239 | case Sema::CheckConstexprKind::Diagnose: | |||
2240 | SemaRef.Diag(Dcl->getLocation(), | |||
2241 | OK ? diag::warn_cxx11_compat_constexpr_body_no_return | |||
2242 | : diag::err_constexpr_body_no_return) | |||
2243 | << Dcl->isConsteval(); | |||
2244 | if (!OK) | |||
2245 | return false; | |||
2246 | break; | |||
2247 | ||||
2248 | case Sema::CheckConstexprKind::CheckValid: | |||
2249 | // The formal requirements don't include this rule in C++14, even | |||
2250 | // though the "must be able to produce a constant expression" rules | |||
2251 | // still imply it in some cases. | |||
2252 | if (!SemaRef.getLangOpts().CPlusPlus14) | |||
2253 | return false; | |||
2254 | break; | |||
2255 | } | |||
2256 | } else if (ReturnStmts.size() > 1) { | |||
2257 | switch (Kind) { | |||
2258 | case Sema::CheckConstexprKind::Diagnose: | |||
2259 | SemaRef.Diag( | |||
2260 | ReturnStmts.back(), | |||
2261 | SemaRef.getLangOpts().CPlusPlus14 | |||
2262 | ? diag::warn_cxx11_compat_constexpr_body_multiple_return | |||
2263 | : diag::ext_constexpr_body_multiple_return); | |||
2264 | for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) | |||
2265 | SemaRef.Diag(ReturnStmts[I], | |||
2266 | diag::note_constexpr_body_previous_return); | |||
2267 | break; | |||
2268 | ||||
2269 | case Sema::CheckConstexprKind::CheckValid: | |||
2270 | if (!SemaRef.getLangOpts().CPlusPlus14) | |||
2271 | return false; | |||
2272 | break; | |||
2273 | } | |||
2274 | } | |||
2275 | } | |||
2276 | ||||
2277 | // C++11 [dcl.constexpr]p5: | |||
2278 | // if no function argument values exist such that the function invocation | |||
2279 | // substitution would produce a constant expression, the program is | |||
2280 | // ill-formed; no diagnostic required. | |||
2281 | // C++11 [dcl.constexpr]p3: | |||
2282 | // - every constructor call and implicit conversion used in initializing the | |||
2283 | // return value shall be one of those allowed in a constant expression. | |||
2284 | // C++11 [dcl.constexpr]p4: | |||
2285 | // - every constructor involved in initializing non-static data members and | |||
2286 | // base class sub-objects shall be a constexpr constructor. | |||
2287 | // | |||
2288 | // Note that this rule is distinct from the "requirements for a constexpr | |||
2289 | // function", so is not checked in CheckValid mode. | |||
2290 | SmallVector<PartialDiagnosticAt, 8> Diags; | |||
2291 | if (Kind == Sema::CheckConstexprKind::Diagnose && | |||
2292 | !Expr::isPotentialConstantExpr(Dcl, Diags)) { | |||
2293 | SemaRef.Diag(Dcl->getLocation(), | |||
2294 | diag::ext_constexpr_function_never_constant_expr) | |||
2295 | << isa<CXXConstructorDecl>(Dcl); | |||
2296 | for (size_t I = 0, N = Diags.size(); I != N; ++I) | |||
2297 | SemaRef.Diag(Diags[I].first, Diags[I].second); | |||
2298 | // Don't return false here: we allow this for compatibility in | |||
2299 | // system headers. | |||
2300 | } | |||
2301 | ||||
2302 | return true; | |||
2303 | } | |||
2304 | ||||
2305 | /// Get the class that is directly named by the current context. This is the | |||
2306 | /// class for which an unqualified-id in this scope could name a constructor | |||
2307 | /// or destructor. | |||
2308 | /// | |||
2309 | /// If the scope specifier denotes a class, this will be that class. | |||
2310 | /// If the scope specifier is empty, this will be the class whose | |||
2311 | /// member-specification we are currently within. Otherwise, there | |||
2312 | /// is no such class. | |||
2313 | CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { | |||
2314 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2314, __PRETTY_FUNCTION__)); | |||
2315 | ||||
2316 | if (SS && SS->isInvalid()) | |||
2317 | return nullptr; | |||
2318 | ||||
2319 | if (SS && SS->isNotEmpty()) { | |||
2320 | DeclContext *DC = computeDeclContext(*SS, true); | |||
2321 | return dyn_cast_or_null<CXXRecordDecl>(DC); | |||
2322 | } | |||
2323 | ||||
2324 | return dyn_cast_or_null<CXXRecordDecl>(CurContext); | |||
2325 | } | |||
2326 | ||||
2327 | /// isCurrentClassName - Determine whether the identifier II is the | |||
2328 | /// name of the class type currently being defined. In the case of | |||
2329 | /// nested classes, this will only return true if II is the name of | |||
2330 | /// the innermost class. | |||
2331 | bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, | |||
2332 | const CXXScopeSpec *SS) { | |||
2333 | CXXRecordDecl *CurDecl = getCurrentClass(S, SS); | |||
2334 | return CurDecl && &II == CurDecl->getIdentifier(); | |||
2335 | } | |||
2336 | ||||
2337 | /// Determine whether the identifier II is a typo for the name of | |||
2338 | /// the class type currently being defined. If so, update it to the identifier | |||
2339 | /// that should have been used. | |||
2340 | bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { | |||
2341 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2341, __PRETTY_FUNCTION__)); | |||
2342 | ||||
2343 | if (!getLangOpts().SpellChecking) | |||
2344 | return false; | |||
2345 | ||||
2346 | CXXRecordDecl *CurDecl; | |||
2347 | if (SS && SS->isSet() && !SS->isInvalid()) { | |||
2348 | DeclContext *DC = computeDeclContext(*SS, true); | |||
2349 | CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); | |||
2350 | } else | |||
2351 | CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); | |||
2352 | ||||
2353 | if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && | |||
2354 | 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) | |||
2355 | < II->getLength()) { | |||
2356 | II = CurDecl->getIdentifier(); | |||
2357 | return true; | |||
2358 | } | |||
2359 | ||||
2360 | return false; | |||
2361 | } | |||
2362 | ||||
2363 | /// Determine whether the given class is a base class of the given | |||
2364 | /// class, including looking at dependent bases. | |||
2365 | static bool findCircularInheritance(const CXXRecordDecl *Class, | |||
2366 | const CXXRecordDecl *Current) { | |||
2367 | SmallVector<const CXXRecordDecl*, 8> Queue; | |||
2368 | ||||
2369 | Class = Class->getCanonicalDecl(); | |||
2370 | while (true) { | |||
2371 | for (const auto &I : Current->bases()) { | |||
2372 | CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); | |||
2373 | if (!Base) | |||
2374 | continue; | |||
2375 | ||||
2376 | Base = Base->getDefinition(); | |||
2377 | if (!Base) | |||
2378 | continue; | |||
2379 | ||||
2380 | if (Base->getCanonicalDecl() == Class) | |||
2381 | return true; | |||
2382 | ||||
2383 | Queue.push_back(Base); | |||
2384 | } | |||
2385 | ||||
2386 | if (Queue.empty()) | |||
2387 | return false; | |||
2388 | ||||
2389 | Current = Queue.pop_back_val(); | |||
2390 | } | |||
2391 | ||||
2392 | return false; | |||
2393 | } | |||
2394 | ||||
2395 | /// Check the validity of a C++ base class specifier. | |||
2396 | /// | |||
2397 | /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics | |||
2398 | /// and returns NULL otherwise. | |||
2399 | CXXBaseSpecifier * | |||
2400 | Sema::CheckBaseSpecifier(CXXRecordDecl *Class, | |||
2401 | SourceRange SpecifierRange, | |||
2402 | bool Virtual, AccessSpecifier Access, | |||
2403 | TypeSourceInfo *TInfo, | |||
2404 | SourceLocation EllipsisLoc) { | |||
2405 | QualType BaseType = TInfo->getType(); | |||
2406 | ||||
2407 | // C++ [class.union]p1: | |||
2408 | // A union shall not have base classes. | |||
2409 | if (Class->isUnion()) { | |||
2410 | Diag(Class->getLocation(), diag::err_base_clause_on_union) | |||
2411 | << SpecifierRange; | |||
2412 | return nullptr; | |||
2413 | } | |||
2414 | ||||
2415 | if (EllipsisLoc.isValid() && | |||
2416 | !TInfo->getType()->containsUnexpandedParameterPack()) { | |||
2417 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) | |||
2418 | << TInfo->getTypeLoc().getSourceRange(); | |||
2419 | EllipsisLoc = SourceLocation(); | |||
2420 | } | |||
2421 | ||||
2422 | SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); | |||
2423 | ||||
2424 | if (BaseType->isDependentType()) { | |||
2425 | // Make sure that we don't have circular inheritance among our dependent | |||
2426 | // bases. For non-dependent bases, the check for completeness below handles | |||
2427 | // this. | |||
2428 | if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { | |||
2429 | if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || | |||
2430 | ((BaseDecl = BaseDecl->getDefinition()) && | |||
2431 | findCircularInheritance(Class, BaseDecl))) { | |||
2432 | Diag(BaseLoc, diag::err_circular_inheritance) | |||
2433 | << BaseType << Context.getTypeDeclType(Class); | |||
2434 | ||||
2435 | if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) | |||
2436 | Diag(BaseDecl->getLocation(), diag::note_previous_decl) | |||
2437 | << BaseType; | |||
2438 | ||||
2439 | return nullptr; | |||
2440 | } | |||
2441 | } | |||
2442 | ||||
2443 | return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, | |||
2444 | Class->getTagKind() == TTK_Class, | |||
2445 | Access, TInfo, EllipsisLoc); | |||
2446 | } | |||
2447 | ||||
2448 | // Base specifiers must be record types. | |||
2449 | if (!BaseType->isRecordType()) { | |||
2450 | Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; | |||
2451 | return nullptr; | |||
2452 | } | |||
2453 | ||||
2454 | // C++ [class.union]p1: | |||
2455 | // A union shall not be used as a base class. | |||
2456 | if (BaseType->isUnionType()) { | |||
2457 | Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; | |||
2458 | return nullptr; | |||
2459 | } | |||
2460 | ||||
2461 | // For the MS ABI, propagate DLL attributes to base class templates. | |||
2462 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
2463 | if (Attr *ClassAttr = getDLLAttr(Class)) { | |||
2464 | if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( | |||
2465 | BaseType->getAsCXXRecordDecl())) { | |||
2466 | propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, | |||
2467 | BaseLoc); | |||
2468 | } | |||
2469 | } | |||
2470 | } | |||
2471 | ||||
2472 | // C++ [class.derived]p2: | |||
2473 | // The class-name in a base-specifier shall not be an incompletely | |||
2474 | // defined class. | |||
2475 | if (RequireCompleteType(BaseLoc, BaseType, | |||
2476 | diag::err_incomplete_base_class, SpecifierRange)) { | |||
2477 | Class->setInvalidDecl(); | |||
2478 | return nullptr; | |||
2479 | } | |||
2480 | ||||
2481 | // If the base class is polymorphic or isn't empty, the new one is/isn't, too. | |||
2482 | RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); | |||
2483 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2483, __PRETTY_FUNCTION__)); | |||
2484 | BaseDecl = BaseDecl->getDefinition(); | |||
2485 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2485, __PRETTY_FUNCTION__)); | |||
2486 | CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); | |||
2487 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2487, __PRETTY_FUNCTION__)); | |||
2488 | ||||
2489 | // Microsoft docs say: | |||
2490 | // "If a base-class has a code_seg attribute, derived classes must have the | |||
2491 | // same attribute." | |||
2492 | const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); | |||
2493 | const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); | |||
2494 | if ((DerivedCSA || BaseCSA) && | |||
2495 | (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { | |||
2496 | Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); | |||
2497 | Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) | |||
2498 | << CXXBaseDecl; | |||
2499 | return nullptr; | |||
2500 | } | |||
2501 | ||||
2502 | // A class which contains a flexible array member is not suitable for use as a | |||
2503 | // base class: | |||
2504 | // - If the layout determines that a base comes before another base, | |||
2505 | // the flexible array member would index into the subsequent base. | |||
2506 | // - If the layout determines that base comes before the derived class, | |||
2507 | // the flexible array member would index into the derived class. | |||
2508 | if (CXXBaseDecl->hasFlexibleArrayMember()) { | |||
2509 | Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) | |||
2510 | << CXXBaseDecl->getDeclName(); | |||
2511 | return nullptr; | |||
2512 | } | |||
2513 | ||||
2514 | // C++ [class]p3: | |||
2515 | // If a class is marked final and it appears as a base-type-specifier in | |||
2516 | // base-clause, the program is ill-formed. | |||
2517 | if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { | |||
2518 | Diag(BaseLoc, diag::err_class_marked_final_used_as_base) | |||
2519 | << CXXBaseDecl->getDeclName() | |||
2520 | << FA->isSpelledAsSealed(); | |||
2521 | Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) | |||
2522 | << CXXBaseDecl->getDeclName() << FA->getRange(); | |||
2523 | return nullptr; | |||
2524 | } | |||
2525 | ||||
2526 | if (BaseDecl->isInvalidDecl()) | |||
2527 | Class->setInvalidDecl(); | |||
2528 | ||||
2529 | // Create the base specifier. | |||
2530 | return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, | |||
2531 | Class->getTagKind() == TTK_Class, | |||
2532 | Access, TInfo, EllipsisLoc); | |||
2533 | } | |||
2534 | ||||
2535 | /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is | |||
2536 | /// one entry in the base class list of a class specifier, for | |||
2537 | /// example: | |||
2538 | /// class foo : public bar, virtual private baz { | |||
2539 | /// 'public bar' and 'virtual private baz' are each base-specifiers. | |||
2540 | BaseResult | |||
2541 | Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, | |||
2542 | ParsedAttributes &Attributes, | |||
2543 | bool Virtual, AccessSpecifier Access, | |||
2544 | ParsedType basetype, SourceLocation BaseLoc, | |||
2545 | SourceLocation EllipsisLoc) { | |||
2546 | if (!classdecl) | |||
2547 | return true; | |||
2548 | ||||
2549 | AdjustDeclIfTemplate(classdecl); | |||
2550 | CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); | |||
2551 | if (!Class) | |||
2552 | return true; | |||
2553 | ||||
2554 | // We haven't yet attached the base specifiers. | |||
2555 | Class->setIsParsingBaseSpecifiers(); | |||
2556 | ||||
2557 | // We do not support any C++11 attributes on base-specifiers yet. | |||
2558 | // Diagnose any attributes we see. | |||
2559 | for (const ParsedAttr &AL : Attributes) { | |||
2560 | if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) | |||
2561 | continue; | |||
2562 | Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute | |||
2563 | ? (unsigned)diag::warn_unknown_attribute_ignored | |||
2564 | : (unsigned)diag::err_base_specifier_attribute) | |||
2565 | << AL; | |||
2566 | } | |||
2567 | ||||
2568 | TypeSourceInfo *TInfo = nullptr; | |||
2569 | GetTypeFromParser(basetype, &TInfo); | |||
2570 | ||||
2571 | if (EllipsisLoc.isInvalid() && | |||
2572 | DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, | |||
2573 | UPPC_BaseType)) | |||
2574 | return true; | |||
2575 | ||||
2576 | if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, | |||
2577 | Virtual, Access, TInfo, | |||
2578 | EllipsisLoc)) | |||
2579 | return BaseSpec; | |||
2580 | else | |||
2581 | Class->setInvalidDecl(); | |||
2582 | ||||
2583 | return true; | |||
2584 | } | |||
2585 | ||||
2586 | /// Use small set to collect indirect bases. As this is only used | |||
2587 | /// locally, there's no need to abstract the small size parameter. | |||
2588 | typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; | |||
2589 | ||||
2590 | /// Recursively add the bases of Type. Don't add Type itself. | |||
2591 | static void | |||
2592 | NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, | |||
2593 | const QualType &Type) | |||
2594 | { | |||
2595 | // Even though the incoming type is a base, it might not be | |||
2596 | // a class -- it could be a template parm, for instance. | |||
2597 | if (auto Rec = Type->getAs<RecordType>()) { | |||
2598 | auto Decl = Rec->getAsCXXRecordDecl(); | |||
2599 | ||||
2600 | // Iterate over its bases. | |||
2601 | for (const auto &BaseSpec : Decl->bases()) { | |||
2602 | QualType Base = Context.getCanonicalType(BaseSpec.getType()) | |||
2603 | .getUnqualifiedType(); | |||
2604 | if (Set.insert(Base).second) | |||
2605 | // If we've not already seen it, recurse. | |||
2606 | NoteIndirectBases(Context, Set, Base); | |||
2607 | } | |||
2608 | } | |||
2609 | } | |||
2610 | ||||
2611 | /// Performs the actual work of attaching the given base class | |||
2612 | /// specifiers to a C++ class. | |||
2613 | bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, | |||
2614 | MutableArrayRef<CXXBaseSpecifier *> Bases) { | |||
2615 | if (Bases.empty()) | |||
2616 | return false; | |||
2617 | ||||
2618 | // Used to keep track of which base types we have already seen, so | |||
2619 | // that we can properly diagnose redundant direct base types. Note | |||
2620 | // that the key is always the unqualified canonical type of the base | |||
2621 | // class. | |||
2622 | std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; | |||
2623 | ||||
2624 | // Used to track indirect bases so we can see if a direct base is | |||
2625 | // ambiguous. | |||
2626 | IndirectBaseSet IndirectBaseTypes; | |||
2627 | ||||
2628 | // Copy non-redundant base specifiers into permanent storage. | |||
2629 | unsigned NumGoodBases = 0; | |||
2630 | bool Invalid = false; | |||
2631 | for (unsigned idx = 0; idx < Bases.size(); ++idx) { | |||
2632 | QualType NewBaseType | |||
2633 | = Context.getCanonicalType(Bases[idx]->getType()); | |||
2634 | NewBaseType = NewBaseType.getLocalUnqualifiedType(); | |||
2635 | ||||
2636 | CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; | |||
2637 | if (KnownBase) { | |||
2638 | // C++ [class.mi]p3: | |||
2639 | // A class shall not be specified as a direct base class of a | |||
2640 | // derived class more than once. | |||
2641 | Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) | |||
2642 | << KnownBase->getType() << Bases[idx]->getSourceRange(); | |||
2643 | ||||
2644 | // Delete the duplicate base class specifier; we're going to | |||
2645 | // overwrite its pointer later. | |||
2646 | Context.Deallocate(Bases[idx]); | |||
2647 | ||||
2648 | Invalid = true; | |||
2649 | } else { | |||
2650 | // Okay, add this new base class. | |||
2651 | KnownBase = Bases[idx]; | |||
2652 | Bases[NumGoodBases++] = Bases[idx]; | |||
2653 | ||||
2654 | // Note this base's direct & indirect bases, if there could be ambiguity. | |||
2655 | if (Bases.size() > 1) | |||
2656 | NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); | |||
2657 | ||||
2658 | if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { | |||
2659 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); | |||
2660 | if (Class->isInterface() && | |||
2661 | (!RD->isInterfaceLike() || | |||
2662 | KnownBase->getAccessSpecifier() != AS_public)) { | |||
2663 | // The Microsoft extension __interface does not permit bases that | |||
2664 | // are not themselves public interfaces. | |||
2665 | Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) | |||
2666 | << getRecordDiagFromTagKind(RD->getTagKind()) << RD | |||
2667 | << RD->getSourceRange(); | |||
2668 | Invalid = true; | |||
2669 | } | |||
2670 | if (RD->hasAttr<WeakAttr>()) | |||
2671 | Class->addAttr(WeakAttr::CreateImplicit(Context)); | |||
2672 | } | |||
2673 | } | |||
2674 | } | |||
2675 | ||||
2676 | // Attach the remaining base class specifiers to the derived class. | |||
2677 | Class->setBases(Bases.data(), NumGoodBases); | |||
2678 | ||||
2679 | // Check that the only base classes that are duplicate are virtual. | |||
2680 | for (unsigned idx = 0; idx < NumGoodBases; ++idx) { | |||
2681 | // Check whether this direct base is inaccessible due to ambiguity. | |||
2682 | QualType BaseType = Bases[idx]->getType(); | |||
2683 | ||||
2684 | // Skip all dependent types in templates being used as base specifiers. | |||
2685 | // Checks below assume that the base specifier is a CXXRecord. | |||
2686 | if (BaseType->isDependentType()) | |||
2687 | continue; | |||
2688 | ||||
2689 | CanQualType CanonicalBase = Context.getCanonicalType(BaseType) | |||
2690 | .getUnqualifiedType(); | |||
2691 | ||||
2692 | if (IndirectBaseTypes.count(CanonicalBase)) { | |||
2693 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | |||
2694 | /*DetectVirtual=*/true); | |||
2695 | bool found | |||
2696 | = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); | |||
2697 | assert(found)((found) ? static_cast<void> (0) : __assert_fail ("found" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2697, __PRETTY_FUNCTION__)); | |||
2698 | (void)found; | |||
2699 | ||||
2700 | if (Paths.isAmbiguous(CanonicalBase)) | |||
2701 | Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) | |||
2702 | << BaseType << getAmbiguousPathsDisplayString(Paths) | |||
2703 | << Bases[idx]->getSourceRange(); | |||
2704 | else | |||
2705 | assert(Bases[idx]->isVirtual())((Bases[idx]->isVirtual()) ? static_cast<void> (0) : __assert_fail ("Bases[idx]->isVirtual()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2705, __PRETTY_FUNCTION__)); | |||
2706 | } | |||
2707 | ||||
2708 | // Delete the base class specifier, since its data has been copied | |||
2709 | // into the CXXRecordDecl. | |||
2710 | Context.Deallocate(Bases[idx]); | |||
2711 | } | |||
2712 | ||||
2713 | return Invalid; | |||
2714 | } | |||
2715 | ||||
2716 | /// ActOnBaseSpecifiers - Attach the given base specifiers to the | |||
2717 | /// class, after checking whether there are any duplicate base | |||
2718 | /// classes. | |||
2719 | void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, | |||
2720 | MutableArrayRef<CXXBaseSpecifier *> Bases) { | |||
2721 | if (!ClassDecl || Bases.empty()) | |||
2722 | return; | |||
2723 | ||||
2724 | AdjustDeclIfTemplate(ClassDecl); | |||
2725 | AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); | |||
2726 | } | |||
2727 | ||||
2728 | /// Determine whether the type \p Derived is a C++ class that is | |||
2729 | /// derived from the type \p Base. | |||
2730 | bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { | |||
2731 | if (!getLangOpts().CPlusPlus) | |||
2732 | return false; | |||
2733 | ||||
2734 | CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); | |||
2735 | if (!DerivedRD) | |||
2736 | return false; | |||
2737 | ||||
2738 | CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); | |||
2739 | if (!BaseRD) | |||
2740 | return false; | |||
2741 | ||||
2742 | // If either the base or the derived type is invalid, don't try to | |||
2743 | // check whether one is derived from the other. | |||
2744 | if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) | |||
2745 | return false; | |||
2746 | ||||
2747 | // FIXME: In a modules build, do we need the entire path to be visible for us | |||
2748 | // to be able to use the inheritance relationship? | |||
2749 | if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) | |||
2750 | return false; | |||
2751 | ||||
2752 | return DerivedRD->isDerivedFrom(BaseRD); | |||
2753 | } | |||
2754 | ||||
2755 | /// Determine whether the type \p Derived is a C++ class that is | |||
2756 | /// derived from the type \p Base. | |||
2757 | bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, | |||
2758 | CXXBasePaths &Paths) { | |||
2759 | if (!getLangOpts().CPlusPlus) | |||
2760 | return false; | |||
2761 | ||||
2762 | CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); | |||
2763 | if (!DerivedRD) | |||
2764 | return false; | |||
2765 | ||||
2766 | CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); | |||
2767 | if (!BaseRD) | |||
2768 | return false; | |||
2769 | ||||
2770 | if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) | |||
2771 | return false; | |||
2772 | ||||
2773 | return DerivedRD->isDerivedFrom(BaseRD, Paths); | |||
2774 | } | |||
2775 | ||||
2776 | static void BuildBasePathArray(const CXXBasePath &Path, | |||
2777 | CXXCastPath &BasePathArray) { | |||
2778 | // We first go backward and check if we have a virtual base. | |||
2779 | // FIXME: It would be better if CXXBasePath had the base specifier for | |||
2780 | // the nearest virtual base. | |||
2781 | unsigned Start = 0; | |||
2782 | for (unsigned I = Path.size(); I != 0; --I) { | |||
2783 | if (Path[I - 1].Base->isVirtual()) { | |||
2784 | Start = I - 1; | |||
2785 | break; | |||
2786 | } | |||
2787 | } | |||
2788 | ||||
2789 | // Now add all bases. | |||
2790 | for (unsigned I = Start, E = Path.size(); I != E; ++I) | |||
2791 | BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); | |||
2792 | } | |||
2793 | ||||
2794 | ||||
2795 | void Sema::BuildBasePathArray(const CXXBasePaths &Paths, | |||
2796 | CXXCastPath &BasePathArray) { | |||
2797 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2797, __PRETTY_FUNCTION__)); | |||
2798 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2798, __PRETTY_FUNCTION__)); | |||
2799 | return ::BuildBasePathArray(Paths.front(), BasePathArray); | |||
2800 | } | |||
2801 | /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base | |||
2802 | /// conversion (where Derived and Base are class types) is | |||
2803 | /// well-formed, meaning that the conversion is unambiguous (and | |||
2804 | /// that all of the base classes are accessible). Returns true | |||
2805 | /// and emits a diagnostic if the code is ill-formed, returns false | |||
2806 | /// otherwise. Loc is the location where this routine should point to | |||
2807 | /// if there is an error, and Range is the source range to highlight | |||
2808 | /// if there is an error. | |||
2809 | /// | |||
2810 | /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the | |||
2811 | /// diagnostic for the respective type of error will be suppressed, but the | |||
2812 | /// check for ill-formed code will still be performed. | |||
2813 | bool | |||
2814 | Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, | |||
2815 | unsigned InaccessibleBaseID, | |||
2816 | unsigned AmbigiousBaseConvID, | |||
2817 | SourceLocation Loc, SourceRange Range, | |||
2818 | DeclarationName Name, | |||
2819 | CXXCastPath *BasePath, | |||
2820 | bool IgnoreAccess) { | |||
2821 | // First, determine whether the path from Derived to Base is | |||
2822 | // ambiguous. This is slightly more expensive than checking whether | |||
2823 | // the Derived to Base conversion exists, because here we need to | |||
2824 | // explore multiple paths to determine if there is an ambiguity. | |||
2825 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | |||
2826 | /*DetectVirtual=*/false); | |||
2827 | bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); | |||
2828 | if (!DerivationOkay) | |||
2829 | return true; | |||
2830 | ||||
2831 | const CXXBasePath *Path = nullptr; | |||
2832 | if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) | |||
2833 | Path = &Paths.front(); | |||
2834 | ||||
2835 | // For MSVC compatibility, check if Derived directly inherits from Base. Clang | |||
2836 | // warns about this hierarchy under -Winaccessible-base, but MSVC allows the | |||
2837 | // user to access such bases. | |||
2838 | if (!Path && getLangOpts().MSVCCompat) { | |||
2839 | for (const CXXBasePath &PossiblePath : Paths) { | |||
2840 | if (PossiblePath.size() == 1) { | |||
2841 | Path = &PossiblePath; | |||
2842 | if (AmbigiousBaseConvID) | |||
2843 | Diag(Loc, diag::ext_ms_ambiguous_direct_base) | |||
2844 | << Base << Derived << Range; | |||
2845 | break; | |||
2846 | } | |||
2847 | } | |||
2848 | } | |||
2849 | ||||
2850 | if (Path) { | |||
2851 | if (!IgnoreAccess) { | |||
2852 | // Check that the base class can be accessed. | |||
2853 | switch ( | |||
2854 | CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { | |||
2855 | case AR_inaccessible: | |||
2856 | return true; | |||
2857 | case AR_accessible: | |||
2858 | case AR_dependent: | |||
2859 | case AR_delayed: | |||
2860 | break; | |||
2861 | } | |||
2862 | } | |||
2863 | ||||
2864 | // Build a base path if necessary. | |||
2865 | if (BasePath) | |||
2866 | ::BuildBasePathArray(*Path, *BasePath); | |||
2867 | return false; | |||
2868 | } | |||
2869 | ||||
2870 | if (AmbigiousBaseConvID) { | |||
2871 | // We know that the derived-to-base conversion is ambiguous, and | |||
2872 | // we're going to produce a diagnostic. Perform the derived-to-base | |||
2873 | // search just one more time to compute all of the possible paths so | |||
2874 | // that we can print them out. This is more expensive than any of | |||
2875 | // the previous derived-to-base checks we've done, but at this point | |||
2876 | // performance isn't as much of an issue. | |||
2877 | Paths.clear(); | |||
2878 | Paths.setRecordingPaths(true); | |||
2879 | bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); | |||
2880 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2880, __PRETTY_FUNCTION__)); | |||
2881 | (void)StillOkay; | |||
2882 | ||||
2883 | // Build up a textual representation of the ambiguous paths, e.g., | |||
2884 | // D -> B -> A, that will be used to illustrate the ambiguous | |||
2885 | // conversions in the diagnostic. We only print one of the paths | |||
2886 | // to each base class subobject. | |||
2887 | std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); | |||
2888 | ||||
2889 | Diag(Loc, AmbigiousBaseConvID) | |||
2890 | << Derived << Base << PathDisplayStr << Range << Name; | |||
2891 | } | |||
2892 | return true; | |||
2893 | } | |||
2894 | ||||
2895 | bool | |||
2896 | Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, | |||
2897 | SourceLocation Loc, SourceRange Range, | |||
2898 | CXXCastPath *BasePath, | |||
2899 | bool IgnoreAccess) { | |||
2900 | return CheckDerivedToBaseConversion( | |||
2901 | Derived, Base, diag::err_upcast_to_inaccessible_base, | |||
2902 | diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), | |||
2903 | BasePath, IgnoreAccess); | |||
2904 | } | |||
2905 | ||||
2906 | ||||
2907 | /// Builds a string representing ambiguous paths from a | |||
2908 | /// specific derived class to different subobjects of the same base | |||
2909 | /// class. | |||
2910 | /// | |||
2911 | /// This function builds a string that can be used in error messages | |||
2912 | /// to show the different paths that one can take through the | |||
2913 | /// inheritance hierarchy to go from the derived class to different | |||
2914 | /// subobjects of a base class. The result looks something like this: | |||
2915 | /// @code | |||
2916 | /// struct D -> struct B -> struct A | |||
2917 | /// struct D -> struct C -> struct A | |||
2918 | /// @endcode | |||
2919 | std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { | |||
2920 | std::string PathDisplayStr; | |||
2921 | std::set<unsigned> DisplayedPaths; | |||
2922 | for (CXXBasePaths::paths_iterator Path = Paths.begin(); | |||
2923 | Path != Paths.end(); ++Path) { | |||
2924 | if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { | |||
2925 | // We haven't displayed a path to this particular base | |||
2926 | // class subobject yet. | |||
2927 | PathDisplayStr += "\n "; | |||
2928 | PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); | |||
2929 | for (CXXBasePath::const_iterator Element = Path->begin(); | |||
2930 | Element != Path->end(); ++Element) | |||
2931 | PathDisplayStr += " -> " + Element->Base->getType().getAsString(); | |||
2932 | } | |||
2933 | } | |||
2934 | ||||
2935 | return PathDisplayStr; | |||
2936 | } | |||
2937 | ||||
2938 | //===----------------------------------------------------------------------===// | |||
2939 | // C++ class member Handling | |||
2940 | //===----------------------------------------------------------------------===// | |||
2941 | ||||
2942 | /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. | |||
2943 | bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, | |||
2944 | SourceLocation ColonLoc, | |||
2945 | const ParsedAttributesView &Attrs) { | |||
2946 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 2946, __PRETTY_FUNCTION__)); | |||
2947 | AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, | |||
2948 | ASLoc, ColonLoc); | |||
2949 | CurContext->addHiddenDecl(ASDecl); | |||
2950 | return ProcessAccessDeclAttributeList(ASDecl, Attrs); | |||
2951 | } | |||
2952 | ||||
2953 | /// CheckOverrideControl - Check C++11 override control semantics. | |||
2954 | void Sema::CheckOverrideControl(NamedDecl *D) { | |||
2955 | if (D->isInvalidDecl()) | |||
2956 | return; | |||
2957 | ||||
2958 | // We only care about "override" and "final" declarations. | |||
2959 | if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) | |||
2960 | return; | |||
2961 | ||||
2962 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); | |||
2963 | ||||
2964 | // We can't check dependent instance methods. | |||
2965 | if (MD && MD->isInstance() && | |||
2966 | (MD->getParent()->hasAnyDependentBases() || | |||
2967 | MD->getType()->isDependentType())) | |||
2968 | return; | |||
2969 | ||||
2970 | if (MD && !MD->isVirtual()) { | |||
2971 | // If we have a non-virtual method, check if if hides a virtual method. | |||
2972 | // (In that case, it's most likely the method has the wrong type.) | |||
2973 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; | |||
2974 | FindHiddenVirtualMethods(MD, OverloadedMethods); | |||
2975 | ||||
2976 | if (!OverloadedMethods.empty()) { | |||
2977 | if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { | |||
2978 | Diag(OA->getLocation(), | |||
2979 | diag::override_keyword_hides_virtual_member_function) | |||
2980 | << "override" << (OverloadedMethods.size() > 1); | |||
2981 | } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { | |||
2982 | Diag(FA->getLocation(), | |||
2983 | diag::override_keyword_hides_virtual_member_function) | |||
2984 | << (FA->isSpelledAsSealed() ? "sealed" : "final") | |||
2985 | << (OverloadedMethods.size() > 1); | |||
2986 | } | |||
2987 | NoteHiddenVirtualMethods(MD, OverloadedMethods); | |||
2988 | MD->setInvalidDecl(); | |||
2989 | return; | |||
2990 | } | |||
2991 | // Fall through into the general case diagnostic. | |||
2992 | // FIXME: We might want to attempt typo correction here. | |||
2993 | } | |||
2994 | ||||
2995 | if (!MD || !MD->isVirtual()) { | |||
2996 | if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { | |||
2997 | Diag(OA->getLocation(), | |||
2998 | diag::override_keyword_only_allowed_on_virtual_member_functions) | |||
2999 | << "override" << FixItHint::CreateRemoval(OA->getLocation()); | |||
3000 | D->dropAttr<OverrideAttr>(); | |||
3001 | } | |||
3002 | if (FinalAttr *FA = D->getAttr<FinalAttr>()) { | |||
3003 | Diag(FA->getLocation(), | |||
3004 | diag::override_keyword_only_allowed_on_virtual_member_functions) | |||
3005 | << (FA->isSpelledAsSealed() ? "sealed" : "final") | |||
3006 | << FixItHint::CreateRemoval(FA->getLocation()); | |||
3007 | D->dropAttr<FinalAttr>(); | |||
3008 | } | |||
3009 | return; | |||
3010 | } | |||
3011 | ||||
3012 | // C++11 [class.virtual]p5: | |||
3013 | // If a function is marked with the virt-specifier override and | |||
3014 | // does not override a member function of a base class, the program is | |||
3015 | // ill-formed. | |||
3016 | bool HasOverriddenMethods = MD->size_overridden_methods() != 0; | |||
3017 | if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) | |||
3018 | Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) | |||
3019 | << MD->getDeclName(); | |||
3020 | } | |||
3021 | ||||
3022 | void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { | |||
3023 | if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) | |||
3024 | return; | |||
3025 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); | |||
3026 | if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) | |||
3027 | return; | |||
3028 | ||||
3029 | SourceLocation Loc = MD->getLocation(); | |||
3030 | SourceLocation SpellingLoc = Loc; | |||
3031 | if (getSourceManager().isMacroArgExpansion(Loc)) | |||
3032 | SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); | |||
3033 | SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); | |||
3034 | if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) | |||
3035 | return; | |||
3036 | ||||
3037 | if (MD->size_overridden_methods() > 0) { | |||
3038 | unsigned DiagID = isa<CXXDestructorDecl>(MD) | |||
3039 | ? diag::warn_destructor_marked_not_override_overriding | |||
3040 | : diag::warn_function_marked_not_override_overriding; | |||
3041 | Diag(MD->getLocation(), DiagID) << MD->getDeclName(); | |||
3042 | const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); | |||
3043 | Diag(OMD->getLocation(), diag::note_overridden_virtual_function); | |||
3044 | } | |||
3045 | } | |||
3046 | ||||
3047 | /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member | |||
3048 | /// function overrides a virtual member function marked 'final', according to | |||
3049 | /// C++11 [class.virtual]p4. | |||
3050 | bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, | |||
3051 | const CXXMethodDecl *Old) { | |||
3052 | FinalAttr *FA = Old->getAttr<FinalAttr>(); | |||
3053 | if (!FA) | |||
3054 | return false; | |||
3055 | ||||
3056 | Diag(New->getLocation(), diag::err_final_function_overridden) | |||
3057 | << New->getDeclName() | |||
3058 | << FA->isSpelledAsSealed(); | |||
3059 | Diag(Old->getLocation(), diag::note_overridden_virtual_function); | |||
3060 | return true; | |||
3061 | } | |||
3062 | ||||
3063 | static bool InitializationHasSideEffects(const FieldDecl &FD) { | |||
3064 | const Type *T = FD.getType()->getBaseElementTypeUnsafe(); | |||
3065 | // FIXME: Destruction of ObjC lifetime types has side-effects. | |||
3066 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | |||
3067 | return !RD->isCompleteDefinition() || | |||
3068 | !RD->hasTrivialDefaultConstructor() || | |||
3069 | !RD->hasTrivialDestructor(); | |||
3070 | return false; | |||
3071 | } | |||
3072 | ||||
3073 | static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { | |||
3074 | ParsedAttributesView::const_iterator Itr = | |||
3075 | llvm::find_if(list, [](const ParsedAttr &AL) { | |||
3076 | return AL.isDeclspecPropertyAttribute(); | |||
3077 | }); | |||
3078 | if (Itr != list.end()) | |||
3079 | return &*Itr; | |||
3080 | return nullptr; | |||
3081 | } | |||
3082 | ||||
3083 | // Check if there is a field shadowing. | |||
3084 | void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, | |||
3085 | DeclarationName FieldName, | |||
3086 | const CXXRecordDecl *RD, | |||
3087 | bool DeclIsField) { | |||
3088 | if (Diags.isIgnored(diag::warn_shadow_field, Loc)) | |||
3089 | return; | |||
3090 | ||||
3091 | // To record a shadowed field in a base | |||
3092 | std::map<CXXRecordDecl*, NamedDecl*> Bases; | |||
3093 | auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, | |||
3094 | CXXBasePath &Path) { | |||
3095 | const auto Base = Specifier->getType()->getAsCXXRecordDecl(); | |||
3096 | // Record an ambiguous path directly | |||
3097 | if (Bases.find(Base) != Bases.end()) | |||
3098 | return true; | |||
3099 | for (const auto Field : Base->lookup(FieldName)) { | |||
3100 | if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && | |||
3101 | Field->getAccess() != AS_private) { | |||
3102 | assert(Field->getAccess() != AS_none)((Field->getAccess() != AS_none) ? static_cast<void> (0) : __assert_fail ("Field->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3102, __PRETTY_FUNCTION__)); | |||
3103 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3103, __PRETTY_FUNCTION__)); | |||
3104 | Bases[Base] = Field; | |||
3105 | return true; | |||
3106 | } | |||
3107 | } | |||
3108 | return false; | |||
3109 | }; | |||
3110 | ||||
3111 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | |||
3112 | /*DetectVirtual=*/true); | |||
3113 | if (!RD->lookupInBases(FieldShadowed, Paths)) | |||
3114 | return; | |||
3115 | ||||
3116 | for (const auto &P : Paths) { | |||
3117 | auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); | |||
3118 | auto It = Bases.find(Base); | |||
3119 | // Skip duplicated bases | |||
3120 | if (It == Bases.end()) | |||
3121 | continue; | |||
3122 | auto BaseField = It->second; | |||
3123 | assert(BaseField->getAccess() != AS_private)((BaseField->getAccess() != AS_private) ? static_cast<void > (0) : __assert_fail ("BaseField->getAccess() != AS_private" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3123, __PRETTY_FUNCTION__)); | |||
3124 | if (AS_none != | |||
3125 | CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { | |||
3126 | Diag(Loc, diag::warn_shadow_field) | |||
3127 | << FieldName << RD << Base << DeclIsField; | |||
3128 | Diag(BaseField->getLocation(), diag::note_shadow_field); | |||
3129 | Bases.erase(It); | |||
3130 | } | |||
3131 | } | |||
3132 | } | |||
3133 | ||||
3134 | /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member | |||
3135 | /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the | |||
3136 | /// bitfield width if there is one, 'InitExpr' specifies the initializer if | |||
3137 | /// one has been parsed, and 'InitStyle' is set if an in-class initializer is | |||
3138 | /// present (but parsing it has been deferred). | |||
3139 | NamedDecl * | |||
3140 | Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, | |||
3141 | MultiTemplateParamsArg TemplateParameterLists, | |||
3142 | Expr *BW, const VirtSpecifiers &VS, | |||
3143 | InClassInitStyle InitStyle) { | |||
3144 | const DeclSpec &DS = D.getDeclSpec(); | |||
3145 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | |||
3146 | DeclarationName Name = NameInfo.getName(); | |||
3147 | SourceLocation Loc = NameInfo.getLoc(); | |||
3148 | ||||
3149 | // For anonymous bitfields, the location should point to the type. | |||
3150 | if (Loc.isInvalid()) | |||
3151 | Loc = D.getBeginLoc(); | |||
3152 | ||||
3153 | Expr *BitWidth = static_cast<Expr*>(BW); | |||
3154 | ||||
3155 | assert(isa<CXXRecordDecl>(CurContext))((isa<CXXRecordDecl>(CurContext)) ? static_cast<void > (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3155, __PRETTY_FUNCTION__)); | |||
3156 | assert(!DS.isFriendSpecified())((!DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail ("!DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3156, __PRETTY_FUNCTION__)); | |||
3157 | ||||
3158 | bool isFunc = D.isDeclarationOfFunction(); | |||
3159 | const ParsedAttr *MSPropertyAttr = | |||
3160 | getMSPropertyAttr(D.getDeclSpec().getAttributes()); | |||
3161 | ||||
3162 | if (cast<CXXRecordDecl>(CurContext)->isInterface()) { | |||
3163 | // The Microsoft extension __interface only permits public member functions | |||
3164 | // and prohibits constructors, destructors, operators, non-public member | |||
3165 | // functions, static methods and data members. | |||
3166 | unsigned InvalidDecl; | |||
3167 | bool ShowDeclName = true; | |||
3168 | if (!isFunc && | |||
3169 | (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) | |||
3170 | InvalidDecl = 0; | |||
3171 | else if (!isFunc) | |||
3172 | InvalidDecl = 1; | |||
3173 | else if (AS != AS_public) | |||
3174 | InvalidDecl = 2; | |||
3175 | else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) | |||
3176 | InvalidDecl = 3; | |||
3177 | else switch (Name.getNameKind()) { | |||
3178 | case DeclarationName::CXXConstructorName: | |||
3179 | InvalidDecl = 4; | |||
3180 | ShowDeclName = false; | |||
3181 | break; | |||
3182 | ||||
3183 | case DeclarationName::CXXDestructorName: | |||
3184 | InvalidDecl = 5; | |||
3185 | ShowDeclName = false; | |||
3186 | break; | |||
3187 | ||||
3188 | case DeclarationName::CXXOperatorName: | |||
3189 | case DeclarationName::CXXConversionFunctionName: | |||
3190 | InvalidDecl = 6; | |||
3191 | break; | |||
3192 | ||||
3193 | default: | |||
3194 | InvalidDecl = 0; | |||
3195 | break; | |||
3196 | } | |||
3197 | ||||
3198 | if (InvalidDecl) { | |||
3199 | if (ShowDeclName) | |||
3200 | Diag(Loc, diag::err_invalid_member_in_interface) | |||
3201 | << (InvalidDecl-1) << Name; | |||
3202 | else | |||
3203 | Diag(Loc, diag::err_invalid_member_in_interface) | |||
3204 | << (InvalidDecl-1) << ""; | |||
3205 | return nullptr; | |||
3206 | } | |||
3207 | } | |||
3208 | ||||
3209 | // C++ 9.2p6: A member shall not be declared to have automatic storage | |||
3210 | // duration (auto, register) or with the extern storage-class-specifier. | |||
3211 | // C++ 7.1.1p8: The mutable specifier can be applied only to names of class | |||
3212 | // data members and cannot be applied to names declared const or static, | |||
3213 | // and cannot be applied to reference members. | |||
3214 | switch (DS.getStorageClassSpec()) { | |||
3215 | case DeclSpec::SCS_unspecified: | |||
3216 | case DeclSpec::SCS_typedef: | |||
3217 | case DeclSpec::SCS_static: | |||
3218 | break; | |||
3219 | case DeclSpec::SCS_mutable: | |||
3220 | if (isFunc) { | |||
3221 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); | |||
3222 | ||||
3223 | // FIXME: It would be nicer if the keyword was ignored only for this | |||
3224 | // declarator. Otherwise we could get follow-up errors. | |||
3225 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | |||
3226 | } | |||
3227 | break; | |||
3228 | default: | |||
3229 | Diag(DS.getStorageClassSpecLoc(), | |||
3230 | diag::err_storageclass_invalid_for_member); | |||
3231 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | |||
3232 | break; | |||
3233 | } | |||
3234 | ||||
3235 | bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || | |||
3236 | DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && | |||
3237 | !isFunc); | |||
3238 | ||||
3239 | if (DS.hasConstexprSpecifier() && isInstField) { | |||
3240 | SemaDiagnosticBuilder B = | |||
3241 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); | |||
3242 | SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); | |||
3243 | if (InitStyle == ICIS_NoInit) { | |||
3244 | B << 0 << 0; | |||
3245 | if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) | |||
3246 | B << FixItHint::CreateRemoval(ConstexprLoc); | |||
3247 | else { | |||
3248 | B << FixItHint::CreateReplacement(ConstexprLoc, "const"); | |||
3249 | D.getMutableDeclSpec().ClearConstexprSpec(); | |||
3250 | const char *PrevSpec; | |||
3251 | unsigned DiagID; | |||
3252 | bool Failed = D.getMutableDeclSpec().SetTypeQual( | |||
3253 | DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); | |||
3254 | (void)Failed; | |||
3255 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3255, __PRETTY_FUNCTION__)); | |||
3256 | } | |||
3257 | } else { | |||
3258 | B << 1; | |||
3259 | const char *PrevSpec; | |||
3260 | unsigned DiagID; | |||
3261 | if (D.getMutableDeclSpec().SetStorageClassSpec( | |||
3262 | *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, | |||
3263 | Context.getPrintingPolicy())) { | |||
3264 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3265, __PRETTY_FUNCTION__)) | |||
3265 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3265, __PRETTY_FUNCTION__)); | |||
3266 | B << 1; | |||
3267 | } else { | |||
3268 | B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); | |||
3269 | isInstField = false; | |||
3270 | } | |||
3271 | } | |||
3272 | } | |||
3273 | ||||
3274 | NamedDecl *Member; | |||
3275 | if (isInstField) { | |||
3276 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | |||
3277 | ||||
3278 | // Data members must have identifiers for names. | |||
3279 | if (!Name.isIdentifier()) { | |||
3280 | Diag(Loc, diag::err_bad_variable_name) | |||
3281 | << Name; | |||
3282 | return nullptr; | |||
3283 | } | |||
3284 | ||||
3285 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | |||
3286 | ||||
3287 | // Member field could not be with "template" keyword. | |||
3288 | // So TemplateParameterLists should be empty in this case. | |||
3289 | if (TemplateParameterLists.size()) { | |||
3290 | TemplateParameterList* TemplateParams = TemplateParameterLists[0]; | |||
3291 | if (TemplateParams->size()) { | |||
3292 | // There is no such thing as a member field template. | |||
3293 | Diag(D.getIdentifierLoc(), diag::err_template_member) | |||
3294 | << II | |||
3295 | << SourceRange(TemplateParams->getTemplateLoc(), | |||
3296 | TemplateParams->getRAngleLoc()); | |||
3297 | } else { | |||
3298 | // There is an extraneous 'template<>' for this member. | |||
3299 | Diag(TemplateParams->getTemplateLoc(), | |||
3300 | diag::err_template_member_noparams) | |||
3301 | << II | |||
3302 | << SourceRange(TemplateParams->getTemplateLoc(), | |||
3303 | TemplateParams->getRAngleLoc()); | |||
3304 | } | |||
3305 | return nullptr; | |||
3306 | } | |||
3307 | ||||
3308 | if (SS.isSet() && !SS.isInvalid()) { | |||
3309 | // The user provided a superfluous scope specifier inside a class | |||
3310 | // definition: | |||
3311 | // | |||
3312 | // class X { | |||
3313 | // int X::member; | |||
3314 | // }; | |||
3315 | if (DeclContext *DC = computeDeclContext(SS, false)) | |||
3316 | diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), | |||
3317 | D.getName().getKind() == | |||
3318 | UnqualifiedIdKind::IK_TemplateId); | |||
3319 | else | |||
3320 | Diag(D.getIdentifierLoc(), diag::err_member_qualification) | |||
3321 | << Name << SS.getRange(); | |||
3322 | ||||
3323 | SS.clear(); | |||
3324 | } | |||
3325 | ||||
3326 | if (MSPropertyAttr) { | |||
3327 | Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, | |||
3328 | BitWidth, InitStyle, AS, *MSPropertyAttr); | |||
3329 | if (!Member) | |||
3330 | return nullptr; | |||
3331 | isInstField = false; | |||
3332 | } else { | |||
3333 | Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, | |||
3334 | BitWidth, InitStyle, AS); | |||
3335 | if (!Member) | |||
3336 | return nullptr; | |||
3337 | } | |||
3338 | ||||
3339 | CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); | |||
3340 | } else { | |||
3341 | Member = HandleDeclarator(S, D, TemplateParameterLists); | |||
3342 | if (!Member) | |||
3343 | return nullptr; | |||
3344 | ||||
3345 | // Non-instance-fields can't have a bitfield. | |||
3346 | if (BitWidth) { | |||
3347 | if (Member->isInvalidDecl()) { | |||
3348 | // don't emit another diagnostic. | |||
3349 | } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { | |||
3350 | // C++ 9.6p3: A bit-field shall not be a static member. | |||
3351 | // "static member 'A' cannot be a bit-field" | |||
3352 | Diag(Loc, diag::err_static_not_bitfield) | |||
3353 | << Name << BitWidth->getSourceRange(); | |||
3354 | } else if (isa<TypedefDecl>(Member)) { | |||
3355 | // "typedef member 'x' cannot be a bit-field" | |||
3356 | Diag(Loc, diag::err_typedef_not_bitfield) | |||
3357 | << Name << BitWidth->getSourceRange(); | |||
3358 | } else { | |||
3359 | // A function typedef ("typedef int f(); f a;"). | |||
3360 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. | |||
3361 | Diag(Loc, diag::err_not_integral_type_bitfield) | |||
3362 | << Name << cast<ValueDecl>(Member)->getType() | |||
3363 | << BitWidth->getSourceRange(); | |||
3364 | } | |||
3365 | ||||
3366 | BitWidth = nullptr; | |||
3367 | Member->setInvalidDecl(); | |||
3368 | } | |||
3369 | ||||
3370 | NamedDecl *NonTemplateMember = Member; | |||
3371 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) | |||
3372 | NonTemplateMember = FunTmpl->getTemplatedDecl(); | |||
3373 | else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) | |||
3374 | NonTemplateMember = VarTmpl->getTemplatedDecl(); | |||
3375 | ||||
3376 | Member->setAccess(AS); | |||
3377 | ||||
3378 | // If we have declared a member function template or static data member | |||
3379 | // template, set the access of the templated declaration as well. | |||
3380 | if (NonTemplateMember != Member) | |||
3381 | NonTemplateMember->setAccess(AS); | |||
3382 | ||||
3383 | // C++ [temp.deduct.guide]p3: | |||
3384 | // A deduction guide [...] for a member class template [shall be | |||
3385 | // declared] with the same access [as the template]. | |||
3386 | if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { | |||
3387 | auto *TD = DG->getDeducedTemplate(); | |||
3388 | // Access specifiers are only meaningful if both the template and the | |||
3389 | // deduction guide are from the same scope. | |||
3390 | if (AS != TD->getAccess() && | |||
3391 | TD->getDeclContext()->getRedeclContext()->Equals( | |||
3392 | DG->getDeclContext()->getRedeclContext())) { | |||
3393 | Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); | |||
3394 | Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) | |||
3395 | << TD->getAccess(); | |||
3396 | const AccessSpecDecl *LastAccessSpec = nullptr; | |||
3397 | for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { | |||
3398 | if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) | |||
3399 | LastAccessSpec = AccessSpec; | |||
3400 | } | |||
3401 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3401, __PRETTY_FUNCTION__)); | |||
3402 | Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) | |||
3403 | << AS; | |||
3404 | } | |||
3405 | } | |||
3406 | } | |||
3407 | ||||
3408 | if (VS.isOverrideSpecified()) | |||
3409 | Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), | |||
3410 | AttributeCommonInfo::AS_Keyword)); | |||
3411 | if (VS.isFinalSpecified()) | |||
3412 | Member->addAttr(FinalAttr::Create( | |||
3413 | Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, | |||
3414 | static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); | |||
3415 | ||||
3416 | if (VS.getLastLocation().isValid()) { | |||
3417 | // Update the end location of a method that has a virt-specifiers. | |||
3418 | if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) | |||
3419 | MD->setRangeEnd(VS.getLastLocation()); | |||
3420 | } | |||
3421 | ||||
3422 | CheckOverrideControl(Member); | |||
3423 | ||||
3424 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3424, __PRETTY_FUNCTION__)); | |||
3425 | ||||
3426 | if (isInstField) { | |||
3427 | FieldDecl *FD = cast<FieldDecl>(Member); | |||
3428 | FieldCollector->Add(FD); | |||
3429 | ||||
3430 | if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { | |||
3431 | // Remember all explicit private FieldDecls that have a name, no side | |||
3432 | // effects and are not part of a dependent type declaration. | |||
3433 | if (!FD->isImplicit() && FD->getDeclName() && | |||
3434 | FD->getAccess() == AS_private && | |||
3435 | !FD->hasAttr<UnusedAttr>() && | |||
3436 | !FD->getParent()->isDependentContext() && | |||
3437 | !InitializationHasSideEffects(*FD)) | |||
3438 | UnusedPrivateFields.insert(FD); | |||
3439 | } | |||
3440 | } | |||
3441 | ||||
3442 | return Member; | |||
3443 | } | |||
3444 | ||||
3445 | namespace { | |||
3446 | class UninitializedFieldVisitor | |||
3447 | : public EvaluatedExprVisitor<UninitializedFieldVisitor> { | |||
3448 | Sema &S; | |||
3449 | // List of Decls to generate a warning on. Also remove Decls that become | |||
3450 | // initialized. | |||
3451 | llvm::SmallPtrSetImpl<ValueDecl*> &Decls; | |||
3452 | // List of base classes of the record. Classes are removed after their | |||
3453 | // initializers. | |||
3454 | llvm::SmallPtrSetImpl<QualType> &BaseClasses; | |||
3455 | // Vector of decls to be removed from the Decl set prior to visiting the | |||
3456 | // nodes. These Decls may have been initialized in the prior initializer. | |||
3457 | llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; | |||
3458 | // If non-null, add a note to the warning pointing back to the constructor. | |||
3459 | const CXXConstructorDecl *Constructor; | |||
3460 | // Variables to hold state when processing an initializer list. When | |||
3461 | // InitList is true, special case initialization of FieldDecls matching | |||
3462 | // InitListFieldDecl. | |||
3463 | bool InitList; | |||
3464 | FieldDecl *InitListFieldDecl; | |||
3465 | llvm::SmallVector<unsigned, 4> InitFieldIndex; | |||
3466 | ||||
3467 | public: | |||
3468 | typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; | |||
3469 | UninitializedFieldVisitor(Sema &S, | |||
3470 | llvm::SmallPtrSetImpl<ValueDecl*> &Decls, | |||
3471 | llvm::SmallPtrSetImpl<QualType> &BaseClasses) | |||
3472 | : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), | |||
3473 | Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} | |||
3474 | ||||
3475 | // Returns true if the use of ME is not an uninitialized use. | |||
3476 | bool IsInitListMemberExprInitialized(MemberExpr *ME, | |||
3477 | bool CheckReferenceOnly) { | |||
3478 | llvm::SmallVector<FieldDecl*, 4> Fields; | |||
3479 | bool ReferenceField = false; | |||
3480 | while (ME) { | |||
3481 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | |||
3482 | if (!FD) | |||
3483 | return false; | |||
3484 | Fields.push_back(FD); | |||
3485 | if (FD->getType()->isReferenceType()) | |||
3486 | ReferenceField = true; | |||
3487 | ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); | |||
3488 | } | |||
3489 | ||||
3490 | // Binding a reference to an uninitialized field is not an | |||
3491 | // uninitialized use. | |||
3492 | if (CheckReferenceOnly && !ReferenceField) | |||
3493 | return true; | |||
3494 | ||||
3495 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; | |||
3496 | // Discard the first field since it is the field decl that is being | |||
3497 | // initialized. | |||
3498 | for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { | |||
3499 | UsedFieldIndex.push_back((*I)->getFieldIndex()); | |||
3500 | } | |||
3501 | ||||
3502 | for (auto UsedIter = UsedFieldIndex.begin(), | |||
3503 | UsedEnd = UsedFieldIndex.end(), | |||
3504 | OrigIter = InitFieldIndex.begin(), | |||
3505 | OrigEnd = InitFieldIndex.end(); | |||
3506 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { | |||
3507 | if (*UsedIter < *OrigIter) | |||
3508 | return true; | |||
3509 | if (*UsedIter > *OrigIter) | |||
3510 | break; | |||
3511 | } | |||
3512 | ||||
3513 | return false; | |||
3514 | } | |||
3515 | ||||
3516 | void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, | |||
3517 | bool AddressOf) { | |||
3518 | if (isa<EnumConstantDecl>(ME->getMemberDecl())) | |||
3519 | return; | |||
3520 | ||||
3521 | // FieldME is the inner-most MemberExpr that is not an anonymous struct | |||
3522 | // or union. | |||
3523 | MemberExpr *FieldME = ME; | |||
3524 | ||||
3525 | bool AllPODFields = FieldME->getType().isPODType(S.Context); | |||
3526 | ||||
3527 | Expr *Base = ME; | |||
3528 | while (MemberExpr *SubME = | |||
3529 | dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { | |||
3530 | ||||
3531 | if (isa<VarDecl>(SubME->getMemberDecl())) | |||
3532 | return; | |||
3533 | ||||
3534 | if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) | |||
3535 | if (!FD->isAnonymousStructOrUnion()) | |||
3536 | FieldME = SubME; | |||
3537 | ||||
3538 | if (!FieldME->getType().isPODType(S.Context)) | |||
3539 | AllPODFields = false; | |||
3540 | ||||
3541 | Base = SubME->getBase(); | |||
3542 | } | |||
3543 | ||||
3544 | if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) | |||
3545 | return; | |||
3546 | ||||
3547 | if (AddressOf && AllPODFields) | |||
3548 | return; | |||
3549 | ||||
3550 | ValueDecl* FoundVD = FieldME->getMemberDecl(); | |||
3551 | ||||
3552 | if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { | |||
3553 | while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { | |||
3554 | BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); | |||
3555 | } | |||
3556 | ||||
3557 | if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { | |||
3558 | QualType T = BaseCast->getType(); | |||
3559 | if (T->isPointerType() && | |||
3560 | BaseClasses.count(T->getPointeeType())) { | |||
3561 | S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) | |||
3562 | << T->getPointeeType() << FoundVD; | |||
3563 | } | |||
3564 | } | |||
3565 | } | |||
3566 | ||||
3567 | if (!Decls.count(FoundVD)) | |||
3568 | return; | |||
3569 | ||||
3570 | const bool IsReference = FoundVD->getType()->isReferenceType(); | |||
3571 | ||||
3572 | if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { | |||
3573 | // Special checking for initializer lists. | |||
3574 | if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { | |||
3575 | return; | |||
3576 | } | |||
3577 | } else { | |||
3578 | // Prevent double warnings on use of unbounded references. | |||
3579 | if (CheckReferenceOnly && !IsReference) | |||
3580 | return; | |||
3581 | } | |||
3582 | ||||
3583 | unsigned diag = IsReference | |||
3584 | ? diag::warn_reference_field_is_uninit | |||
3585 | : diag::warn_field_is_uninit; | |||
3586 | S.Diag(FieldME->getExprLoc(), diag) << FoundVD; | |||
3587 | if (Constructor) | |||
3588 | S.Diag(Constructor->getLocation(), | |||
3589 | diag::note_uninit_in_this_constructor) | |||
3590 | << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); | |||
3591 | ||||
3592 | } | |||
3593 | ||||
3594 | void HandleValue(Expr *E, bool AddressOf) { | |||
3595 | E = E->IgnoreParens(); | |||
3596 | ||||
3597 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | |||
3598 | HandleMemberExpr(ME, false /*CheckReferenceOnly*/, | |||
3599 | AddressOf /*AddressOf*/); | |||
3600 | return; | |||
3601 | } | |||
3602 | ||||
3603 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { | |||
3604 | Visit(CO->getCond()); | |||
3605 | HandleValue(CO->getTrueExpr(), AddressOf); | |||
3606 | HandleValue(CO->getFalseExpr(), AddressOf); | |||
3607 | return; | |||
3608 | } | |||
3609 | ||||
3610 | if (BinaryConditionalOperator *BCO = | |||
3611 | dyn_cast<BinaryConditionalOperator>(E)) { | |||
3612 | Visit(BCO->getCond()); | |||
3613 | HandleValue(BCO->getFalseExpr(), AddressOf); | |||
3614 | return; | |||
3615 | } | |||
3616 | ||||
3617 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | |||
3618 | HandleValue(OVE->getSourceExpr(), AddressOf); | |||
3619 | return; | |||
3620 | } | |||
3621 | ||||
3622 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
3623 | switch (BO->getOpcode()) { | |||
3624 | default: | |||
3625 | break; | |||
3626 | case(BO_PtrMemD): | |||
3627 | case(BO_PtrMemI): | |||
3628 | HandleValue(BO->getLHS(), AddressOf); | |||
3629 | Visit(BO->getRHS()); | |||
3630 | return; | |||
3631 | case(BO_Comma): | |||
3632 | Visit(BO->getLHS()); | |||
3633 | HandleValue(BO->getRHS(), AddressOf); | |||
3634 | return; | |||
3635 | } | |||
3636 | } | |||
3637 | ||||
3638 | Visit(E); | |||
3639 | } | |||
3640 | ||||
3641 | void CheckInitListExpr(InitListExpr *ILE) { | |||
3642 | InitFieldIndex.push_back(0); | |||
3643 | for (auto Child : ILE->children()) { | |||
3644 | if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { | |||
3645 | CheckInitListExpr(SubList); | |||
3646 | } else { | |||
3647 | Visit(Child); | |||
3648 | } | |||
3649 | ++InitFieldIndex.back(); | |||
3650 | } | |||
3651 | InitFieldIndex.pop_back(); | |||
3652 | } | |||
3653 | ||||
3654 | void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, | |||
3655 | FieldDecl *Field, const Type *BaseClass) { | |||
3656 | // Remove Decls that may have been initialized in the previous | |||
3657 | // initializer. | |||
3658 | for (ValueDecl* VD : DeclsToRemove) | |||
3659 | Decls.erase(VD); | |||
3660 | DeclsToRemove.clear(); | |||
3661 | ||||
3662 | Constructor = FieldConstructor; | |||
3663 | InitListExpr *ILE = dyn_cast<InitListExpr>(E); | |||
3664 | ||||
3665 | if (ILE && Field) { | |||
3666 | InitList = true; | |||
3667 | InitListFieldDecl = Field; | |||
3668 | InitFieldIndex.clear(); | |||
3669 | CheckInitListExpr(ILE); | |||
3670 | } else { | |||
3671 | InitList = false; | |||
3672 | Visit(E); | |||
3673 | } | |||
3674 | ||||
3675 | if (Field) | |||
3676 | Decls.erase(Field); | |||
3677 | if (BaseClass) | |||
3678 | BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); | |||
3679 | } | |||
3680 | ||||
3681 | void VisitMemberExpr(MemberExpr *ME) { | |||
3682 | // All uses of unbounded reference fields will warn. | |||
3683 | HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); | |||
3684 | } | |||
3685 | ||||
3686 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { | |||
3687 | if (E->getCastKind() == CK_LValueToRValue) { | |||
3688 | HandleValue(E->getSubExpr(), false /*AddressOf*/); | |||
3689 | return; | |||
3690 | } | |||
3691 | ||||
3692 | Inherited::VisitImplicitCastExpr(E); | |||
3693 | } | |||
3694 | ||||
3695 | void VisitCXXConstructExpr(CXXConstructExpr *E) { | |||
3696 | if (E->getConstructor()->isCopyConstructor()) { | |||
3697 | Expr *ArgExpr = E->getArg(0); | |||
3698 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) | |||
3699 | if (ILE->getNumInits() == 1) | |||
3700 | ArgExpr = ILE->getInit(0); | |||
3701 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) | |||
3702 | if (ICE->getCastKind() == CK_NoOp) | |||
3703 | ArgExpr = ICE->getSubExpr(); | |||
3704 | HandleValue(ArgExpr, false /*AddressOf*/); | |||
3705 | return; | |||
3706 | } | |||
3707 | Inherited::VisitCXXConstructExpr(E); | |||
3708 | } | |||
3709 | ||||
3710 | void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { | |||
3711 | Expr *Callee = E->getCallee(); | |||
3712 | if (isa<MemberExpr>(Callee)) { | |||
3713 | HandleValue(Callee, false /*AddressOf*/); | |||
3714 | for (auto Arg : E->arguments()) | |||
3715 | Visit(Arg); | |||
3716 | return; | |||
3717 | } | |||
3718 | ||||
3719 | Inherited::VisitCXXMemberCallExpr(E); | |||
3720 | } | |||
3721 | ||||
3722 | void VisitCallExpr(CallExpr *E) { | |||
3723 | // Treat std::move as a use. | |||
3724 | if (E->isCallToStdMove()) { | |||
3725 | HandleValue(E->getArg(0), /*AddressOf=*/false); | |||
3726 | return; | |||
3727 | } | |||
3728 | ||||
3729 | Inherited::VisitCallExpr(E); | |||
3730 | } | |||
3731 | ||||
3732 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | |||
3733 | Expr *Callee = E->getCallee(); | |||
3734 | ||||
3735 | if (isa<UnresolvedLookupExpr>(Callee)) | |||
3736 | return Inherited::VisitCXXOperatorCallExpr(E); | |||
3737 | ||||
3738 | Visit(Callee); | |||
3739 | for (auto Arg : E->arguments()) | |||
3740 | HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); | |||
3741 | } | |||
3742 | ||||
3743 | void VisitBinaryOperator(BinaryOperator *E) { | |||
3744 | // If a field assignment is detected, remove the field from the | |||
3745 | // uninitiailized field set. | |||
3746 | if (E->getOpcode() == BO_Assign) | |||
3747 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) | |||
3748 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) | |||
3749 | if (!FD->getType()->isReferenceType()) | |||
3750 | DeclsToRemove.push_back(FD); | |||
3751 | ||||
3752 | if (E->isCompoundAssignmentOp()) { | |||
3753 | HandleValue(E->getLHS(), false /*AddressOf*/); | |||
3754 | Visit(E->getRHS()); | |||
3755 | return; | |||
3756 | } | |||
3757 | ||||
3758 | Inherited::VisitBinaryOperator(E); | |||
3759 | } | |||
3760 | ||||
3761 | void VisitUnaryOperator(UnaryOperator *E) { | |||
3762 | if (E->isIncrementDecrementOp()) { | |||
3763 | HandleValue(E->getSubExpr(), false /*AddressOf*/); | |||
3764 | return; | |||
3765 | } | |||
3766 | if (E->getOpcode() == UO_AddrOf) { | |||
3767 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { | |||
3768 | HandleValue(ME->getBase(), true /*AddressOf*/); | |||
3769 | return; | |||
3770 | } | |||
3771 | } | |||
3772 | ||||
3773 | Inherited::VisitUnaryOperator(E); | |||
3774 | } | |||
3775 | }; | |||
3776 | ||||
3777 | // Diagnose value-uses of fields to initialize themselves, e.g. | |||
3778 | // foo(foo) | |||
3779 | // where foo is not also a parameter to the constructor. | |||
3780 | // Also diagnose across field uninitialized use such as | |||
3781 | // x(y), y(x) | |||
3782 | // TODO: implement -Wuninitialized and fold this into that framework. | |||
3783 | static void DiagnoseUninitializedFields( | |||
3784 | Sema &SemaRef, const CXXConstructorDecl *Constructor) { | |||
3785 | ||||
3786 | if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, | |||
3787 | Constructor->getLocation())) { | |||
3788 | return; | |||
3789 | } | |||
3790 | ||||
3791 | if (Constructor->isInvalidDecl()) | |||
3792 | return; | |||
3793 | ||||
3794 | const CXXRecordDecl *RD = Constructor->getParent(); | |||
3795 | ||||
3796 | if (RD->getDescribedClassTemplate()) | |||
3797 | return; | |||
3798 | ||||
3799 | // Holds fields that are uninitialized. | |||
3800 | llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; | |||
3801 | ||||
3802 | // At the beginning, all fields are uninitialized. | |||
3803 | for (auto *I : RD->decls()) { | |||
3804 | if (auto *FD = dyn_cast<FieldDecl>(I)) { | |||
3805 | UninitializedFields.insert(FD); | |||
3806 | } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { | |||
3807 | UninitializedFields.insert(IFD->getAnonField()); | |||
3808 | } | |||
3809 | } | |||
3810 | ||||
3811 | llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; | |||
3812 | for (auto I : RD->bases()) | |||
3813 | UninitializedBaseClasses.insert(I.getType().getCanonicalType()); | |||
3814 | ||||
3815 | if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) | |||
3816 | return; | |||
3817 | ||||
3818 | UninitializedFieldVisitor UninitializedChecker(SemaRef, | |||
3819 | UninitializedFields, | |||
3820 | UninitializedBaseClasses); | |||
3821 | ||||
3822 | for (const auto *FieldInit : Constructor->inits()) { | |||
3823 | if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) | |||
3824 | break; | |||
3825 | ||||
3826 | Expr *InitExpr = FieldInit->getInit(); | |||
3827 | if (!InitExpr) | |||
3828 | continue; | |||
3829 | ||||
3830 | if (CXXDefaultInitExpr *Default = | |||
3831 | dyn_cast<CXXDefaultInitExpr>(InitExpr)) { | |||
3832 | InitExpr = Default->getExpr(); | |||
3833 | if (!InitExpr) | |||
3834 | continue; | |||
3835 | // In class initializers will point to the constructor. | |||
3836 | UninitializedChecker.CheckInitializer(InitExpr, Constructor, | |||
3837 | FieldInit->getAnyMember(), | |||
3838 | FieldInit->getBaseClass()); | |||
3839 | } else { | |||
3840 | UninitializedChecker.CheckInitializer(InitExpr, nullptr, | |||
3841 | FieldInit->getAnyMember(), | |||
3842 | FieldInit->getBaseClass()); | |||
3843 | } | |||
3844 | } | |||
3845 | } | |||
3846 | } // namespace | |||
3847 | ||||
3848 | /// Enter a new C++ default initializer scope. After calling this, the | |||
3849 | /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if | |||
3850 | /// parsing or instantiating the initializer failed. | |||
3851 | void Sema::ActOnStartCXXInClassMemberInitializer() { | |||
3852 | // Create a synthetic function scope to represent the call to the constructor | |||
3853 | // that notionally surrounds a use of this initializer. | |||
3854 | PushFunctionScope(); | |||
3855 | } | |||
3856 | ||||
3857 | /// This is invoked after parsing an in-class initializer for a | |||
3858 | /// non-static C++ class member, and after instantiating an in-class initializer | |||
3859 | /// in a class template. Such actions are deferred until the class is complete. | |||
3860 | void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, | |||
3861 | SourceLocation InitLoc, | |||
3862 | Expr *InitExpr) { | |||
3863 | // Pop the notional constructor scope we created earlier. | |||
3864 | PopFunctionScopeInfo(nullptr, D); | |||
3865 | ||||
3866 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | |||
3867 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3868, __PRETTY_FUNCTION__)) | |||
3868 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 3868, __PRETTY_FUNCTION__)); | |||
3869 | ||||
3870 | if (!InitExpr) { | |||
3871 | D->setInvalidDecl(); | |||
3872 | if (FD) | |||
3873 | FD->removeInClassInitializer(); | |||
3874 | return; | |||
3875 | } | |||
3876 | ||||
3877 | if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { | |||
3878 | FD->setInvalidDecl(); | |||
3879 | FD->removeInClassInitializer(); | |||
3880 | return; | |||
3881 | } | |||
3882 | ||||
3883 | ExprResult Init = InitExpr; | |||
3884 | if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { | |||
3885 | InitializedEntity Entity = | |||
3886 | InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); | |||
3887 | InitializationKind Kind = | |||
3888 | FD->getInClassInitStyle() == ICIS_ListInit | |||
3889 | ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), | |||
3890 | InitExpr->getBeginLoc(), | |||
3891 | InitExpr->getEndLoc()) | |||
3892 | : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); | |||
3893 | InitializationSequence Seq(*this, Entity, Kind, InitExpr); | |||
3894 | Init = Seq.Perform(*this, Entity, Kind, InitExpr); | |||
3895 | if (Init.isInvalid()) { | |||
3896 | FD->setInvalidDecl(); | |||
3897 | return; | |||
3898 | } | |||
3899 | } | |||
3900 | ||||
3901 | // C++11 [class.base.init]p7: | |||
3902 | // The initialization of each base and member constitutes a | |||
3903 | // full-expression. | |||
3904 | Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); | |||
3905 | if (Init.isInvalid()) { | |||
3906 | FD->setInvalidDecl(); | |||
3907 | return; | |||
3908 | } | |||
3909 | ||||
3910 | InitExpr = Init.get(); | |||
3911 | ||||
3912 | FD->setInClassInitializer(InitExpr); | |||
3913 | } | |||
3914 | ||||
3915 | /// Find the direct and/or virtual base specifiers that | |||
3916 | /// correspond to the given base type, for use in base initialization | |||
3917 | /// within a constructor. | |||
3918 | static bool FindBaseInitializer(Sema &SemaRef, | |||
3919 | CXXRecordDecl *ClassDecl, | |||
3920 | QualType BaseType, | |||
3921 | const CXXBaseSpecifier *&DirectBaseSpec, | |||
3922 | const CXXBaseSpecifier *&VirtualBaseSpec) { | |||
3923 | // First, check for a direct base class. | |||
3924 | DirectBaseSpec = nullptr; | |||
3925 | for (const auto &Base : ClassDecl->bases()) { | |||
3926 | if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { | |||
3927 | // We found a direct base of this type. That's what we're | |||
3928 | // initializing. | |||
3929 | DirectBaseSpec = &Base; | |||
3930 | break; | |||
3931 | } | |||
3932 | } | |||
3933 | ||||
3934 | // Check for a virtual base class. | |||
3935 | // FIXME: We might be able to short-circuit this if we know in advance that | |||
3936 | // there are no virtual bases. | |||
3937 | VirtualBaseSpec = nullptr; | |||
3938 | if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { | |||
3939 | // We haven't found a base yet; search the class hierarchy for a | |||
3940 | // virtual base class. | |||
3941 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | |||
3942 | /*DetectVirtual=*/false); | |||
3943 | if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), | |||
3944 | SemaRef.Context.getTypeDeclType(ClassDecl), | |||
3945 | BaseType, Paths)) { | |||
3946 | for (CXXBasePaths::paths_iterator Path = Paths.begin(); | |||
3947 | Path != Paths.end(); ++Path) { | |||
3948 | if (Path->back().Base->isVirtual()) { | |||
3949 | VirtualBaseSpec = Path->back().Base; | |||
3950 | break; | |||
3951 | } | |||
3952 | } | |||
3953 | } | |||
3954 | } | |||
3955 | ||||
3956 | return DirectBaseSpec || VirtualBaseSpec; | |||
3957 | } | |||
3958 | ||||
3959 | /// Handle a C++ member initializer using braced-init-list syntax. | |||
3960 | MemInitResult | |||
3961 | Sema::ActOnMemInitializer(Decl *ConstructorD, | |||
3962 | Scope *S, | |||
3963 | CXXScopeSpec &SS, | |||
3964 | IdentifierInfo *MemberOrBase, | |||
3965 | ParsedType TemplateTypeTy, | |||
3966 | const DeclSpec &DS, | |||
3967 | SourceLocation IdLoc, | |||
3968 | Expr *InitList, | |||
3969 | SourceLocation EllipsisLoc) { | |||
3970 | return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, | |||
3971 | DS, IdLoc, InitList, | |||
3972 | EllipsisLoc); | |||
3973 | } | |||
3974 | ||||
3975 | /// Handle a C++ member initializer using parentheses syntax. | |||
3976 | MemInitResult | |||
3977 | Sema::ActOnMemInitializer(Decl *ConstructorD, | |||
3978 | Scope *S, | |||
3979 | CXXScopeSpec &SS, | |||
3980 | IdentifierInfo *MemberOrBase, | |||
3981 | ParsedType TemplateTypeTy, | |||
3982 | const DeclSpec &DS, | |||
3983 | SourceLocation IdLoc, | |||
3984 | SourceLocation LParenLoc, | |||
3985 | ArrayRef<Expr *> Args, | |||
3986 | SourceLocation RParenLoc, | |||
3987 | SourceLocation EllipsisLoc) { | |||
3988 | Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); | |||
3989 | return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, | |||
3990 | DS, IdLoc, List, EllipsisLoc); | |||
3991 | } | |||
3992 | ||||
3993 | namespace { | |||
3994 | ||||
3995 | // Callback to only accept typo corrections that can be a valid C++ member | |||
3996 | // intializer: either a non-static field member or a base class. | |||
3997 | class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { | |||
3998 | public: | |||
3999 | explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) | |||
4000 | : ClassDecl(ClassDecl) {} | |||
4001 | ||||
4002 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
4003 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { | |||
4004 | if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) | |||
4005 | return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); | |||
4006 | return isa<TypeDecl>(ND); | |||
4007 | } | |||
4008 | return false; | |||
4009 | } | |||
4010 | ||||
4011 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
4012 | return std::make_unique<MemInitializerValidatorCCC>(*this); | |||
4013 | } | |||
4014 | ||||
4015 | private: | |||
4016 | CXXRecordDecl *ClassDecl; | |||
4017 | }; | |||
4018 | ||||
4019 | } | |||
4020 | ||||
4021 | ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, | |||
4022 | CXXScopeSpec &SS, | |||
4023 | ParsedType TemplateTypeTy, | |||
4024 | IdentifierInfo *MemberOrBase) { | |||
4025 | if (SS.getScopeRep() || TemplateTypeTy) | |||
4026 | return nullptr; | |||
4027 | DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); | |||
4028 | if (Result.empty()) | |||
4029 | return nullptr; | |||
4030 | ValueDecl *Member; | |||
4031 | if ((Member = dyn_cast<FieldDecl>(Result.front())) || | |||
4032 | (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) | |||
4033 | return Member; | |||
4034 | return nullptr; | |||
4035 | } | |||
4036 | ||||
4037 | /// Handle a C++ member initializer. | |||
4038 | MemInitResult | |||
4039 | Sema::BuildMemInitializer(Decl *ConstructorD, | |||
4040 | Scope *S, | |||
4041 | CXXScopeSpec &SS, | |||
4042 | IdentifierInfo *MemberOrBase, | |||
4043 | ParsedType TemplateTypeTy, | |||
4044 | const DeclSpec &DS, | |||
4045 | SourceLocation IdLoc, | |||
4046 | Expr *Init, | |||
4047 | SourceLocation EllipsisLoc) { | |||
4048 | ExprResult Res = CorrectDelayedTyposInExpr(Init); | |||
4049 | if (!Res.isUsable()) | |||
4050 | return true; | |||
4051 | Init = Res.get(); | |||
4052 | ||||
4053 | if (!ConstructorD) | |||
4054 | return true; | |||
4055 | ||||
4056 | AdjustDeclIfTemplate(ConstructorD); | |||
4057 | ||||
4058 | CXXConstructorDecl *Constructor | |||
4059 | = dyn_cast<CXXConstructorDecl>(ConstructorD); | |||
4060 | if (!Constructor) { | |||
4061 | // The user wrote a constructor initializer on a function that is | |||
4062 | // not a C++ constructor. Ignore the error for now, because we may | |||
4063 | // have more member initializers coming; we'll diagnose it just | |||
4064 | // once in ActOnMemInitializers. | |||
4065 | return true; | |||
4066 | } | |||
4067 | ||||
4068 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
4069 | ||||
4070 | // C++ [class.base.init]p2: | |||
4071 | // Names in a mem-initializer-id are looked up in the scope of the | |||
4072 | // constructor's class and, if not found in that scope, are looked | |||
4073 | // up in the scope containing the constructor's definition. | |||
4074 | // [Note: if the constructor's class contains a member with the | |||
4075 | // same name as a direct or virtual base class of the class, a | |||
4076 | // mem-initializer-id naming the member or base class and composed | |||
4077 | // of a single identifier refers to the class member. A | |||
4078 | // mem-initializer-id for the hidden base class may be specified | |||
4079 | // using a qualified name. ] | |||
4080 | ||||
4081 | // Look for a member, first. | |||
4082 | if (ValueDecl *Member = tryLookupCtorInitMemberDecl( | |||
4083 | ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { | |||
4084 | if (EllipsisLoc.isValid()) | |||
4085 | Diag(EllipsisLoc, diag::err_pack_expansion_member_init) | |||
4086 | << MemberOrBase | |||
4087 | << SourceRange(IdLoc, Init->getSourceRange().getEnd()); | |||
4088 | ||||
4089 | return BuildMemberInitializer(Member, Init, IdLoc); | |||
4090 | } | |||
4091 | // It didn't name a member, so see if it names a class. | |||
4092 | QualType BaseType; | |||
4093 | TypeSourceInfo *TInfo = nullptr; | |||
4094 | ||||
4095 | if (TemplateTypeTy) { | |||
4096 | BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); | |||
4097 | if (BaseType.isNull()) | |||
4098 | return true; | |||
4099 | } else if (DS.getTypeSpecType() == TST_decltype) { | |||
4100 | BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); | |||
4101 | } else if (DS.getTypeSpecType() == TST_decltype_auto) { | |||
4102 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); | |||
4103 | return true; | |||
4104 | } else { | |||
4105 | LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); | |||
4106 | LookupParsedName(R, S, &SS); | |||
4107 | ||||
4108 | TypeDecl *TyD = R.getAsSingle<TypeDecl>(); | |||
4109 | if (!TyD) { | |||
4110 | if (R.isAmbiguous()) return true; | |||
4111 | ||||
4112 | // We don't want access-control diagnostics here. | |||
4113 | R.suppressDiagnostics(); | |||
4114 | ||||
4115 | if (SS.isSet() && isDependentScopeSpecifier(SS)) { | |||
4116 | bool NotUnknownSpecialization = false; | |||
4117 | DeclContext *DC = computeDeclContext(SS, false); | |||
4118 | if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) | |||
4119 | NotUnknownSpecialization = !Record->hasAnyDependentBases(); | |||
4120 | ||||
4121 | if (!NotUnknownSpecialization) { | |||
4122 | // When the scope specifier can refer to a member of an unknown | |||
4123 | // specialization, we take it as a type name. | |||
4124 | BaseType = CheckTypenameType(ETK_None, SourceLocation(), | |||
4125 | SS.getWithLocInContext(Context), | |||
4126 | *MemberOrBase, IdLoc); | |||
4127 | if (BaseType.isNull()) | |||
4128 | return true; | |||
4129 | ||||
4130 | TInfo = Context.CreateTypeSourceInfo(BaseType); | |||
4131 | DependentNameTypeLoc TL = | |||
4132 | TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); | |||
4133 | if (!TL.isNull()) { | |||
4134 | TL.setNameLoc(IdLoc); | |||
4135 | TL.setElaboratedKeywordLoc(SourceLocation()); | |||
4136 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
4137 | } | |||
4138 | ||||
4139 | R.clear(); | |||
4140 | R.setLookupName(MemberOrBase); | |||
4141 | } | |||
4142 | } | |||
4143 | ||||
4144 | // If no results were found, try to correct typos. | |||
4145 | TypoCorrection Corr; | |||
4146 | MemInitializerValidatorCCC CCC(ClassDecl); | |||
4147 | if (R.empty() && BaseType.isNull() && | |||
4148 | (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, | |||
4149 | CCC, CTK_ErrorRecovery, ClassDecl))) { | |||
4150 | if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { | |||
4151 | // We have found a non-static data member with a similar | |||
4152 | // name to what was typed; complain and initialize that | |||
4153 | // member. | |||
4154 | diagnoseTypo(Corr, | |||
4155 | PDiag(diag::err_mem_init_not_member_or_class_suggest) | |||
4156 | << MemberOrBase << true); | |||
4157 | return BuildMemberInitializer(Member, Init, IdLoc); | |||
4158 | } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { | |||
4159 | const CXXBaseSpecifier *DirectBaseSpec; | |||
4160 | const CXXBaseSpecifier *VirtualBaseSpec; | |||
4161 | if (FindBaseInitializer(*this, ClassDecl, | |||
4162 | Context.getTypeDeclType(Type), | |||
4163 | DirectBaseSpec, VirtualBaseSpec)) { | |||
4164 | // We have found a direct or virtual base class with a | |||
4165 | // similar name to what was typed; complain and initialize | |||
4166 | // that base class. | |||
4167 | diagnoseTypo(Corr, | |||
4168 | PDiag(diag::err_mem_init_not_member_or_class_suggest) | |||
4169 | << MemberOrBase << false, | |||
4170 | PDiag() /*Suppress note, we provide our own.*/); | |||
4171 | ||||
4172 | const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec | |||
4173 | : VirtualBaseSpec; | |||
4174 | Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) | |||
4175 | << BaseSpec->getType() << BaseSpec->getSourceRange(); | |||
4176 | ||||
4177 | TyD = Type; | |||
4178 | } | |||
4179 | } | |||
4180 | } | |||
4181 | ||||
4182 | if (!TyD && BaseType.isNull()) { | |||
4183 | Diag(IdLoc, diag::err_mem_init_not_member_or_class) | |||
4184 | << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); | |||
4185 | return true; | |||
4186 | } | |||
4187 | } | |||
4188 | ||||
4189 | if (BaseType.isNull()) { | |||
4190 | BaseType = Context.getTypeDeclType(TyD); | |||
4191 | MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); | |||
4192 | if (SS.isSet()) { | |||
4193 | BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), | |||
4194 | BaseType); | |||
4195 | TInfo = Context.CreateTypeSourceInfo(BaseType); | |||
4196 | ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); | |||
4197 | TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); | |||
4198 | TL.setElaboratedKeywordLoc(SourceLocation()); | |||
4199 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
4200 | } | |||
4201 | } | |||
4202 | } | |||
4203 | ||||
4204 | if (!TInfo) | |||
4205 | TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); | |||
4206 | ||||
4207 | return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); | |||
4208 | } | |||
4209 | ||||
4210 | MemInitResult | |||
4211 | Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, | |||
4212 | SourceLocation IdLoc) { | |||
4213 | FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); | |||
4214 | IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); | |||
4215 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4216, __PRETTY_FUNCTION__)) | |||
4216 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4216, __PRETTY_FUNCTION__)); | |||
4217 | ||||
4218 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) | |||
4219 | return true; | |||
4220 | ||||
4221 | if (Member->isInvalidDecl()) | |||
4222 | return true; | |||
4223 | ||||
4224 | MultiExprArg Args; | |||
4225 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { | |||
4226 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); | |||
4227 | } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { | |||
4228 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); | |||
4229 | } else { | |||
4230 | // Template instantiation doesn't reconstruct ParenListExprs for us. | |||
4231 | Args = Init; | |||
4232 | } | |||
4233 | ||||
4234 | SourceRange InitRange = Init->getSourceRange(); | |||
4235 | ||||
4236 | if (Member->getType()->isDependentType() || Init->isTypeDependent()) { | |||
4237 | // Can't check initialization for a member of dependent type or when | |||
4238 | // any of the arguments are type-dependent expressions. | |||
4239 | DiscardCleanupsInEvaluationContext(); | |||
4240 | } else { | |||
4241 | bool InitList = false; | |||
4242 | if (isa<InitListExpr>(Init)) { | |||
4243 | InitList = true; | |||
4244 | Args = Init; | |||
4245 | } | |||
4246 | ||||
4247 | // Initialize the member. | |||
4248 | InitializedEntity MemberEntity = | |||
4249 | DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) | |||
4250 | : InitializedEntity::InitializeMember(IndirectMember, | |||
4251 | nullptr); | |||
4252 | InitializationKind Kind = | |||
4253 | InitList ? InitializationKind::CreateDirectList( | |||
4254 | IdLoc, Init->getBeginLoc(), Init->getEndLoc()) | |||
4255 | : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), | |||
4256 | InitRange.getEnd()); | |||
4257 | ||||
4258 | InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); | |||
4259 | ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, | |||
4260 | nullptr); | |||
4261 | if (MemberInit.isInvalid()) | |||
4262 | return true; | |||
4263 | ||||
4264 | // C++11 [class.base.init]p7: | |||
4265 | // The initialization of each base and member constitutes a | |||
4266 | // full-expression. | |||
4267 | MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), | |||
4268 | /*DiscardedValue*/ false); | |||
4269 | if (MemberInit.isInvalid()) | |||
4270 | return true; | |||
4271 | ||||
4272 | Init = MemberInit.get(); | |||
4273 | } | |||
4274 | ||||
4275 | if (DirectMember) { | |||
4276 | return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, | |||
4277 | InitRange.getBegin(), Init, | |||
4278 | InitRange.getEnd()); | |||
4279 | } else { | |||
4280 | return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, | |||
4281 | InitRange.getBegin(), Init, | |||
4282 | InitRange.getEnd()); | |||
4283 | } | |||
4284 | } | |||
4285 | ||||
4286 | MemInitResult | |||
4287 | Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, | |||
4288 | CXXRecordDecl *ClassDecl) { | |||
4289 | SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); | |||
4290 | if (!LangOpts.CPlusPlus11) | |||
4291 | return Diag(NameLoc, diag::err_delegating_ctor) | |||
4292 | << TInfo->getTypeLoc().getLocalSourceRange(); | |||
4293 | Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); | |||
4294 | ||||
4295 | bool InitList = true; | |||
4296 | MultiExprArg Args = Init; | |||
4297 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { | |||
4298 | InitList = false; | |||
4299 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); | |||
4300 | } | |||
4301 | ||||
4302 | SourceRange InitRange = Init->getSourceRange(); | |||
4303 | // Initialize the object. | |||
4304 | InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( | |||
4305 | QualType(ClassDecl->getTypeForDecl(), 0)); | |||
4306 | InitializationKind Kind = | |||
4307 | InitList ? InitializationKind::CreateDirectList( | |||
4308 | NameLoc, Init->getBeginLoc(), Init->getEndLoc()) | |||
4309 | : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), | |||
4310 | InitRange.getEnd()); | |||
4311 | InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); | |||
4312 | ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, | |||
4313 | Args, nullptr); | |||
4314 | if (DelegationInit.isInvalid()) | |||
4315 | return true; | |||
4316 | ||||
4317 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4318, __PRETTY_FUNCTION__)) | |||
4318 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4318, __PRETTY_FUNCTION__)); | |||
4319 | ||||
4320 | // C++11 [class.base.init]p7: | |||
4321 | // The initialization of each base and member constitutes a | |||
4322 | // full-expression. | |||
4323 | DelegationInit = ActOnFinishFullExpr( | |||
4324 | DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); | |||
4325 | if (DelegationInit.isInvalid()) | |||
4326 | return true; | |||
4327 | ||||
4328 | // If we are in a dependent context, template instantiation will | |||
4329 | // perform this type-checking again. Just save the arguments that we | |||
4330 | // received in a ParenListExpr. | |||
4331 | // FIXME: This isn't quite ideal, since our ASTs don't capture all | |||
4332 | // of the information that we have about the base | |||
4333 | // initializer. However, deconstructing the ASTs is a dicey process, | |||
4334 | // and this approach is far more likely to get the corner cases right. | |||
4335 | if (CurContext->isDependentContext()) | |||
4336 | DelegationInit = Init; | |||
4337 | ||||
4338 | return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), | |||
4339 | DelegationInit.getAs<Expr>(), | |||
4340 | InitRange.getEnd()); | |||
4341 | } | |||
4342 | ||||
4343 | MemInitResult | |||
4344 | Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, | |||
4345 | Expr *Init, CXXRecordDecl *ClassDecl, | |||
4346 | SourceLocation EllipsisLoc) { | |||
4347 | SourceLocation BaseLoc | |||
4348 | = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); | |||
4349 | ||||
4350 | if (!BaseType->isDependentType() && !BaseType->isRecordType()) | |||
4351 | return Diag(BaseLoc, diag::err_base_init_does_not_name_class) | |||
4352 | << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); | |||
4353 | ||||
4354 | // C++ [class.base.init]p2: | |||
4355 | // [...] Unless the mem-initializer-id names a nonstatic data | |||
4356 | // member of the constructor's class or a direct or virtual base | |||
4357 | // of that class, the mem-initializer is ill-formed. A | |||
4358 | // mem-initializer-list can initialize a base class using any | |||
4359 | // name that denotes that base class type. | |||
4360 | bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); | |||
4361 | ||||
4362 | SourceRange InitRange = Init->getSourceRange(); | |||
4363 | if (EllipsisLoc.isValid()) { | |||
4364 | // This is a pack expansion. | |||
4365 | if (!BaseType->containsUnexpandedParameterPack()) { | |||
4366 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) | |||
4367 | << SourceRange(BaseLoc, InitRange.getEnd()); | |||
4368 | ||||
4369 | EllipsisLoc = SourceLocation(); | |||
4370 | } | |||
4371 | } else { | |||
4372 | // Check for any unexpanded parameter packs. | |||
4373 | if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) | |||
4374 | return true; | |||
4375 | ||||
4376 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) | |||
4377 | return true; | |||
4378 | } | |||
4379 | ||||
4380 | // Check for direct and virtual base classes. | |||
4381 | const CXXBaseSpecifier *DirectBaseSpec = nullptr; | |||
4382 | const CXXBaseSpecifier *VirtualBaseSpec = nullptr; | |||
4383 | if (!Dependent) { | |||
4384 | if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), | |||
4385 | BaseType)) | |||
4386 | return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); | |||
4387 | ||||
4388 | FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, | |||
4389 | VirtualBaseSpec); | |||
4390 | ||||
4391 | // C++ [base.class.init]p2: | |||
4392 | // Unless the mem-initializer-id names a nonstatic data member of the | |||
4393 | // constructor's class or a direct or virtual base of that class, the | |||
4394 | // mem-initializer is ill-formed. | |||
4395 | if (!DirectBaseSpec && !VirtualBaseSpec) { | |||
4396 | // If the class has any dependent bases, then it's possible that | |||
4397 | // one of those types will resolve to the same type as | |||
4398 | // BaseType. Therefore, just treat this as a dependent base | |||
4399 | // class initialization. FIXME: Should we try to check the | |||
4400 | // initialization anyway? It seems odd. | |||
4401 | if (ClassDecl->hasAnyDependentBases()) | |||
4402 | Dependent = true; | |||
4403 | else | |||
4404 | return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) | |||
4405 | << BaseType << Context.getTypeDeclType(ClassDecl) | |||
4406 | << BaseTInfo->getTypeLoc().getLocalSourceRange(); | |||
4407 | } | |||
4408 | } | |||
4409 | ||||
4410 | if (Dependent) { | |||
4411 | DiscardCleanupsInEvaluationContext(); | |||
4412 | ||||
4413 | return new (Context) CXXCtorInitializer(Context, BaseTInfo, | |||
4414 | /*IsVirtual=*/false, | |||
4415 | InitRange.getBegin(), Init, | |||
4416 | InitRange.getEnd(), EllipsisLoc); | |||
4417 | } | |||
4418 | ||||
4419 | // C++ [base.class.init]p2: | |||
4420 | // If a mem-initializer-id is ambiguous because it designates both | |||
4421 | // a direct non-virtual base class and an inherited virtual base | |||
4422 | // class, the mem-initializer is ill-formed. | |||
4423 | if (DirectBaseSpec && VirtualBaseSpec) | |||
4424 | return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) | |||
4425 | << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); | |||
4426 | ||||
4427 | const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; | |||
4428 | if (!BaseSpec) | |||
4429 | BaseSpec = VirtualBaseSpec; | |||
4430 | ||||
4431 | // Initialize the base. | |||
4432 | bool InitList = true; | |||
4433 | MultiExprArg Args = Init; | |||
4434 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { | |||
4435 | InitList = false; | |||
4436 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); | |||
4437 | } | |||
4438 | ||||
4439 | InitializedEntity BaseEntity = | |||
4440 | InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); | |||
4441 | InitializationKind Kind = | |||
4442 | InitList ? InitializationKind::CreateDirectList(BaseLoc) | |||
4443 | : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), | |||
4444 | InitRange.getEnd()); | |||
4445 | InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); | |||
4446 | ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); | |||
4447 | if (BaseInit.isInvalid()) | |||
4448 | return true; | |||
4449 | ||||
4450 | // C++11 [class.base.init]p7: | |||
4451 | // The initialization of each base and member constitutes a | |||
4452 | // full-expression. | |||
4453 | BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), | |||
4454 | /*DiscardedValue*/ false); | |||
4455 | if (BaseInit.isInvalid()) | |||
4456 | return true; | |||
4457 | ||||
4458 | // If we are in a dependent context, template instantiation will | |||
4459 | // perform this type-checking again. Just save the arguments that we | |||
4460 | // received in a ParenListExpr. | |||
4461 | // FIXME: This isn't quite ideal, since our ASTs don't capture all | |||
4462 | // of the information that we have about the base | |||
4463 | // initializer. However, deconstructing the ASTs is a dicey process, | |||
4464 | // and this approach is far more likely to get the corner cases right. | |||
4465 | if (CurContext->isDependentContext()) | |||
4466 | BaseInit = Init; | |||
4467 | ||||
4468 | return new (Context) CXXCtorInitializer(Context, BaseTInfo, | |||
4469 | BaseSpec->isVirtual(), | |||
4470 | InitRange.getBegin(), | |||
4471 | BaseInit.getAs<Expr>(), | |||
4472 | InitRange.getEnd(), EllipsisLoc); | |||
4473 | } | |||
4474 | ||||
4475 | // Create a static_cast\<T&&>(expr). | |||
4476 | static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { | |||
4477 | if (T.isNull()) T = E->getType(); | |||
4478 | QualType TargetType = SemaRef.BuildReferenceType( | |||
4479 | T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); | |||
4480 | SourceLocation ExprLoc = E->getBeginLoc(); | |||
4481 | TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( | |||
4482 | TargetType, ExprLoc); | |||
4483 | ||||
4484 | return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, | |||
4485 | SourceRange(ExprLoc, ExprLoc), | |||
4486 | E->getSourceRange()).get(); | |||
4487 | } | |||
4488 | ||||
4489 | /// ImplicitInitializerKind - How an implicit base or member initializer should | |||
4490 | /// initialize its base or member. | |||
4491 | enum ImplicitInitializerKind { | |||
4492 | IIK_Default, | |||
4493 | IIK_Copy, | |||
4494 | IIK_Move, | |||
4495 | IIK_Inherit | |||
4496 | }; | |||
4497 | ||||
4498 | static bool | |||
4499 | BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, | |||
4500 | ImplicitInitializerKind ImplicitInitKind, | |||
4501 | CXXBaseSpecifier *BaseSpec, | |||
4502 | bool IsInheritedVirtualBase, | |||
4503 | CXXCtorInitializer *&CXXBaseInit) { | |||
4504 | InitializedEntity InitEntity | |||
4505 | = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, | |||
4506 | IsInheritedVirtualBase); | |||
4507 | ||||
4508 | ExprResult BaseInit; | |||
4509 | ||||
4510 | switch (ImplicitInitKind) { | |||
4511 | case IIK_Inherit: | |||
4512 | case IIK_Default: { | |||
4513 | InitializationKind InitKind | |||
4514 | = InitializationKind::CreateDefault(Constructor->getLocation()); | |||
4515 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); | |||
4516 | BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); | |||
4517 | break; | |||
4518 | } | |||
4519 | ||||
4520 | case IIK_Move: | |||
4521 | case IIK_Copy: { | |||
4522 | bool Moving = ImplicitInitKind == IIK_Move; | |||
4523 | ParmVarDecl *Param = Constructor->getParamDecl(0); | |||
4524 | QualType ParamType = Param->getType().getNonReferenceType(); | |||
4525 | ||||
4526 | Expr *CopyCtorArg = | |||
4527 | DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), | |||
4528 | SourceLocation(), Param, false, | |||
4529 | Constructor->getLocation(), ParamType, | |||
4530 | VK_LValue, nullptr); | |||
4531 | ||||
4532 | SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); | |||
4533 | ||||
4534 | // Cast to the base class to avoid ambiguities. | |||
4535 | QualType ArgTy = | |||
4536 | SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), | |||
4537 | ParamType.getQualifiers()); | |||
4538 | ||||
4539 | if (Moving) { | |||
4540 | CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); | |||
4541 | } | |||
4542 | ||||
4543 | CXXCastPath BasePath; | |||
4544 | BasePath.push_back(BaseSpec); | |||
4545 | CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, | |||
4546 | CK_UncheckedDerivedToBase, | |||
4547 | Moving ? VK_XValue : VK_LValue, | |||
4548 | &BasePath).get(); | |||
4549 | ||||
4550 | InitializationKind InitKind | |||
4551 | = InitializationKind::CreateDirect(Constructor->getLocation(), | |||
4552 | SourceLocation(), SourceLocation()); | |||
4553 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); | |||
4554 | BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); | |||
4555 | break; | |||
4556 | } | |||
4557 | } | |||
4558 | ||||
4559 | BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); | |||
4560 | if (BaseInit.isInvalid()) | |||
4561 | return true; | |||
4562 | ||||
4563 | CXXBaseInit = | |||
4564 | new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, | |||
4565 | SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), | |||
4566 | SourceLocation()), | |||
4567 | BaseSpec->isVirtual(), | |||
4568 | SourceLocation(), | |||
4569 | BaseInit.getAs<Expr>(), | |||
4570 | SourceLocation(), | |||
4571 | SourceLocation()); | |||
4572 | ||||
4573 | return false; | |||
4574 | } | |||
4575 | ||||
4576 | static bool RefersToRValueRef(Expr *MemRef) { | |||
4577 | ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); | |||
4578 | return Referenced->getType()->isRValueReferenceType(); | |||
4579 | } | |||
4580 | ||||
4581 | static bool | |||
4582 | BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, | |||
4583 | ImplicitInitializerKind ImplicitInitKind, | |||
4584 | FieldDecl *Field, IndirectFieldDecl *Indirect, | |||
4585 | CXXCtorInitializer *&CXXMemberInit) { | |||
4586 | if (Field->isInvalidDecl()) | |||
4587 | return true; | |||
4588 | ||||
4589 | SourceLocation Loc = Constructor->getLocation(); | |||
4590 | ||||
4591 | if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { | |||
4592 | bool Moving = ImplicitInitKind == IIK_Move; | |||
4593 | ParmVarDecl *Param = Constructor->getParamDecl(0); | |||
4594 | QualType ParamType = Param->getType().getNonReferenceType(); | |||
4595 | ||||
4596 | // Suppress copying zero-width bitfields. | |||
4597 | if (Field->isZeroLengthBitField(SemaRef.Context)) | |||
4598 | return false; | |||
4599 | ||||
4600 | Expr *MemberExprBase = | |||
4601 | DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), | |||
4602 | SourceLocation(), Param, false, | |||
4603 | Loc, ParamType, VK_LValue, nullptr); | |||
4604 | ||||
4605 | SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); | |||
4606 | ||||
4607 | if (Moving) { | |||
4608 | MemberExprBase = CastForMoving(SemaRef, MemberExprBase); | |||
4609 | } | |||
4610 | ||||
4611 | // Build a reference to this field within the parameter. | |||
4612 | CXXScopeSpec SS; | |||
4613 | LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, | |||
4614 | Sema::LookupMemberName); | |||
4615 | MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) | |||
4616 | : cast<ValueDecl>(Field), AS_public); | |||
4617 | MemberLookup.resolveKind(); | |||
4618 | ExprResult CtorArg | |||
4619 | = SemaRef.BuildMemberReferenceExpr(MemberExprBase, | |||
4620 | ParamType, Loc, | |||
4621 | /*IsArrow=*/false, | |||
4622 | SS, | |||
4623 | /*TemplateKWLoc=*/SourceLocation(), | |||
4624 | /*FirstQualifierInScope=*/nullptr, | |||
4625 | MemberLookup, | |||
4626 | /*TemplateArgs=*/nullptr, | |||
4627 | /*S*/nullptr); | |||
4628 | if (CtorArg.isInvalid()) | |||
4629 | return true; | |||
4630 | ||||
4631 | // C++11 [class.copy]p15: | |||
4632 | // - if a member m has rvalue reference type T&&, it is direct-initialized | |||
4633 | // with static_cast<T&&>(x.m); | |||
4634 | if (RefersToRValueRef(CtorArg.get())) { | |||
4635 | CtorArg = CastForMoving(SemaRef, CtorArg.get()); | |||
4636 | } | |||
4637 | ||||
4638 | InitializedEntity Entity = | |||
4639 | Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, | |||
4640 | /*Implicit*/ true) | |||
4641 | : InitializedEntity::InitializeMember(Field, nullptr, | |||
4642 | /*Implicit*/ true); | |||
4643 | ||||
4644 | // Direct-initialize to use the copy constructor. | |||
4645 | InitializationKind InitKind = | |||
4646 | InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); | |||
4647 | ||||
4648 | Expr *CtorArgE = CtorArg.getAs<Expr>(); | |||
4649 | InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); | |||
4650 | ExprResult MemberInit = | |||
4651 | InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); | |||
4652 | MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); | |||
4653 | if (MemberInit.isInvalid()) | |||
4654 | return true; | |||
4655 | ||||
4656 | if (Indirect) | |||
4657 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( | |||
4658 | SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); | |||
4659 | else | |||
4660 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( | |||
4661 | SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); | |||
4662 | return false; | |||
4663 | } | |||
4664 | ||||
4665 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4666, __PRETTY_FUNCTION__)) | |||
4666 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4666, __PRETTY_FUNCTION__)); | |||
4667 | ||||
4668 | QualType FieldBaseElementType = | |||
4669 | SemaRef.Context.getBaseElementType(Field->getType()); | |||
4670 | ||||
4671 | if (FieldBaseElementType->isRecordType()) { | |||
4672 | InitializedEntity InitEntity = | |||
4673 | Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, | |||
4674 | /*Implicit*/ true) | |||
4675 | : InitializedEntity::InitializeMember(Field, nullptr, | |||
4676 | /*Implicit*/ true); | |||
4677 | InitializationKind InitKind = | |||
4678 | InitializationKind::CreateDefault(Loc); | |||
4679 | ||||
4680 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); | |||
4681 | ExprResult MemberInit = | |||
4682 | InitSeq.Perform(SemaRef, InitEntity, InitKind, None); | |||
4683 | ||||
4684 | MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); | |||
4685 | if (MemberInit.isInvalid()) | |||
4686 | return true; | |||
4687 | ||||
4688 | if (Indirect) | |||
4689 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, | |||
4690 | Indirect, Loc, | |||
4691 | Loc, | |||
4692 | MemberInit.get(), | |||
4693 | Loc); | |||
4694 | else | |||
4695 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, | |||
4696 | Field, Loc, Loc, | |||
4697 | MemberInit.get(), | |||
4698 | Loc); | |||
4699 | return false; | |||
4700 | } | |||
4701 | ||||
4702 | if (!Field->getParent()->isUnion()) { | |||
4703 | if (FieldBaseElementType->isReferenceType()) { | |||
4704 | SemaRef.Diag(Constructor->getLocation(), | |||
4705 | diag::err_uninitialized_member_in_ctor) | |||
4706 | << (int)Constructor->isImplicit() | |||
4707 | << SemaRef.Context.getTagDeclType(Constructor->getParent()) | |||
4708 | << 0 << Field->getDeclName(); | |||
4709 | SemaRef.Diag(Field->getLocation(), diag::note_declared_at); | |||
4710 | return true; | |||
4711 | } | |||
4712 | ||||
4713 | if (FieldBaseElementType.isConstQualified()) { | |||
4714 | SemaRef.Diag(Constructor->getLocation(), | |||
4715 | diag::err_uninitialized_member_in_ctor) | |||
4716 | << (int)Constructor->isImplicit() | |||
4717 | << SemaRef.Context.getTagDeclType(Constructor->getParent()) | |||
4718 | << 1 << Field->getDeclName(); | |||
4719 | SemaRef.Diag(Field->getLocation(), diag::note_declared_at); | |||
4720 | return true; | |||
4721 | } | |||
4722 | } | |||
4723 | ||||
4724 | if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { | |||
4725 | // ARC and Weak: | |||
4726 | // Default-initialize Objective-C pointers to NULL. | |||
4727 | CXXMemberInit | |||
4728 | = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, | |||
4729 | Loc, Loc, | |||
4730 | new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), | |||
4731 | Loc); | |||
4732 | return false; | |||
4733 | } | |||
4734 | ||||
4735 | // Nothing to initialize. | |||
4736 | CXXMemberInit = nullptr; | |||
4737 | return false; | |||
4738 | } | |||
4739 | ||||
4740 | namespace { | |||
4741 | struct BaseAndFieldInfo { | |||
4742 | Sema &S; | |||
4743 | CXXConstructorDecl *Ctor; | |||
4744 | bool AnyErrorsInInits; | |||
4745 | ImplicitInitializerKind IIK; | |||
4746 | llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; | |||
4747 | SmallVector<CXXCtorInitializer*, 8> AllToInit; | |||
4748 | llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; | |||
4749 | ||||
4750 | BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) | |||
4751 | : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { | |||
4752 | bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); | |||
4753 | if (Ctor->getInheritedConstructor()) | |||
4754 | IIK = IIK_Inherit; | |||
4755 | else if (Generated && Ctor->isCopyConstructor()) | |||
4756 | IIK = IIK_Copy; | |||
4757 | else if (Generated && Ctor->isMoveConstructor()) | |||
4758 | IIK = IIK_Move; | |||
4759 | else | |||
4760 | IIK = IIK_Default; | |||
4761 | } | |||
4762 | ||||
4763 | bool isImplicitCopyOrMove() const { | |||
4764 | switch (IIK) { | |||
4765 | case IIK_Copy: | |||
4766 | case IIK_Move: | |||
4767 | return true; | |||
4768 | ||||
4769 | case IIK_Default: | |||
4770 | case IIK_Inherit: | |||
4771 | return false; | |||
4772 | } | |||
4773 | ||||
4774 | llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4774); | |||
4775 | } | |||
4776 | ||||
4777 | bool addFieldInitializer(CXXCtorInitializer *Init) { | |||
4778 | AllToInit.push_back(Init); | |||
4779 | ||||
4780 | // Check whether this initializer makes the field "used". | |||
4781 | if (Init->getInit()->HasSideEffects(S.Context)) | |||
4782 | S.UnusedPrivateFields.remove(Init->getAnyMember()); | |||
4783 | ||||
4784 | return false; | |||
4785 | } | |||
4786 | ||||
4787 | bool isInactiveUnionMember(FieldDecl *Field) { | |||
4788 | RecordDecl *Record = Field->getParent(); | |||
4789 | if (!Record->isUnion()) | |||
4790 | return false; | |||
4791 | ||||
4792 | if (FieldDecl *Active = | |||
4793 | ActiveUnionMember.lookup(Record->getCanonicalDecl())) | |||
4794 | return Active != Field->getCanonicalDecl(); | |||
4795 | ||||
4796 | // In an implicit copy or move constructor, ignore any in-class initializer. | |||
4797 | if (isImplicitCopyOrMove()) | |||
4798 | return true; | |||
4799 | ||||
4800 | // If there's no explicit initialization, the field is active only if it | |||
4801 | // has an in-class initializer... | |||
4802 | if (Field->hasInClassInitializer()) | |||
4803 | return false; | |||
4804 | // ... or it's an anonymous struct or union whose class has an in-class | |||
4805 | // initializer. | |||
4806 | if (!Field->isAnonymousStructOrUnion()) | |||
4807 | return true; | |||
4808 | CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); | |||
4809 | return !FieldRD->hasInClassInitializer(); | |||
4810 | } | |||
4811 | ||||
4812 | /// Determine whether the given field is, or is within, a union member | |||
4813 | /// that is inactive (because there was an initializer given for a different | |||
4814 | /// member of the union, or because the union was not initialized at all). | |||
4815 | bool isWithinInactiveUnionMember(FieldDecl *Field, | |||
4816 | IndirectFieldDecl *Indirect) { | |||
4817 | if (!Indirect) | |||
4818 | return isInactiveUnionMember(Field); | |||
4819 | ||||
4820 | for (auto *C : Indirect->chain()) { | |||
4821 | FieldDecl *Field = dyn_cast<FieldDecl>(C); | |||
4822 | if (Field && isInactiveUnionMember(Field)) | |||
4823 | return true; | |||
4824 | } | |||
4825 | return false; | |||
4826 | } | |||
4827 | }; | |||
4828 | } | |||
4829 | ||||
4830 | /// Determine whether the given type is an incomplete or zero-lenfgth | |||
4831 | /// array type. | |||
4832 | static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { | |||
4833 | if (T->isIncompleteArrayType()) | |||
4834 | return true; | |||
4835 | ||||
4836 | while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { | |||
4837 | if (!ArrayT->getSize()) | |||
4838 | return true; | |||
4839 | ||||
4840 | T = ArrayT->getElementType(); | |||
4841 | } | |||
4842 | ||||
4843 | return false; | |||
4844 | } | |||
4845 | ||||
4846 | static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, | |||
4847 | FieldDecl *Field, | |||
4848 | IndirectFieldDecl *Indirect = nullptr) { | |||
4849 | if (Field->isInvalidDecl()) | |||
4850 | return false; | |||
4851 | ||||
4852 | // Overwhelmingly common case: we have a direct initializer for this field. | |||
4853 | if (CXXCtorInitializer *Init = | |||
4854 | Info.AllBaseFields.lookup(Field->getCanonicalDecl())) | |||
4855 | return Info.addFieldInitializer(Init); | |||
4856 | ||||
4857 | // C++11 [class.base.init]p8: | |||
4858 | // if the entity is a non-static data member that has a | |||
4859 | // brace-or-equal-initializer and either | |||
4860 | // -- the constructor's class is a union and no other variant member of that | |||
4861 | // union is designated by a mem-initializer-id or | |||
4862 | // -- the constructor's class is not a union, and, if the entity is a member | |||
4863 | // of an anonymous union, no other member of that union is designated by | |||
4864 | // a mem-initializer-id, | |||
4865 | // the entity is initialized as specified in [dcl.init]. | |||
4866 | // | |||
4867 | // We also apply the same rules to handle anonymous structs within anonymous | |||
4868 | // unions. | |||
4869 | if (Info.isWithinInactiveUnionMember(Field, Indirect)) | |||
4870 | return false; | |||
4871 | ||||
4872 | if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { | |||
4873 | ExprResult DIE = | |||
4874 | SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); | |||
4875 | if (DIE.isInvalid()) | |||
4876 | return true; | |||
4877 | ||||
4878 | auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); | |||
4879 | SemaRef.checkInitializerLifetime(Entity, DIE.get()); | |||
4880 | ||||
4881 | CXXCtorInitializer *Init; | |||
4882 | if (Indirect) | |||
4883 | Init = new (SemaRef.Context) | |||
4884 | CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), | |||
4885 | SourceLocation(), DIE.get(), SourceLocation()); | |||
4886 | else | |||
4887 | Init = new (SemaRef.Context) | |||
4888 | CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), | |||
4889 | SourceLocation(), DIE.get(), SourceLocation()); | |||
4890 | return Info.addFieldInitializer(Init); | |||
4891 | } | |||
4892 | ||||
4893 | // Don't initialize incomplete or zero-length arrays. | |||
4894 | if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) | |||
4895 | return false; | |||
4896 | ||||
4897 | // Don't try to build an implicit initializer if there were semantic | |||
4898 | // errors in any of the initializers (and therefore we might be | |||
4899 | // missing some that the user actually wrote). | |||
4900 | if (Info.AnyErrorsInInits) | |||
4901 | return false; | |||
4902 | ||||
4903 | CXXCtorInitializer *Init = nullptr; | |||
4904 | if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, | |||
4905 | Indirect, Init)) | |||
4906 | return true; | |||
4907 | ||||
4908 | if (!Init) | |||
4909 | return false; | |||
4910 | ||||
4911 | return Info.addFieldInitializer(Init); | |||
4912 | } | |||
4913 | ||||
4914 | bool | |||
4915 | Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, | |||
4916 | CXXCtorInitializer *Initializer) { | |||
4917 | assert(Initializer->isDelegatingInitializer())((Initializer->isDelegatingInitializer()) ? static_cast< void> (0) : __assert_fail ("Initializer->isDelegatingInitializer()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 4917, __PRETTY_FUNCTION__)); | |||
4918 | Constructor->setNumCtorInitializers(1); | |||
4919 | CXXCtorInitializer **initializer = | |||
4920 | new (Context) CXXCtorInitializer*[1]; | |||
4921 | memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); | |||
4922 | Constructor->setCtorInitializers(initializer); | |||
4923 | ||||
4924 | if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { | |||
4925 | MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); | |||
4926 | DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); | |||
4927 | } | |||
4928 | ||||
4929 | DelegatingCtorDecls.push_back(Constructor); | |||
4930 | ||||
4931 | DiagnoseUninitializedFields(*this, Constructor); | |||
4932 | ||||
4933 | return false; | |||
4934 | } | |||
4935 | ||||
4936 | bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, | |||
4937 | ArrayRef<CXXCtorInitializer *> Initializers) { | |||
4938 | if (Constructor->isDependentContext()) { | |||
4939 | // Just store the initializers as written, they will be checked during | |||
4940 | // instantiation. | |||
4941 | if (!Initializers.empty()) { | |||
4942 | Constructor->setNumCtorInitializers(Initializers.size()); | |||
4943 | CXXCtorInitializer **baseOrMemberInitializers = | |||
4944 | new (Context) CXXCtorInitializer*[Initializers.size()]; | |||
4945 | memcpy(baseOrMemberInitializers, Initializers.data(), | |||
4946 | Initializers.size() * sizeof(CXXCtorInitializer*)); | |||
4947 | Constructor->setCtorInitializers(baseOrMemberInitializers); | |||
4948 | } | |||
4949 | ||||
4950 | // Let template instantiation know whether we had errors. | |||
4951 | if (AnyErrors) | |||
4952 | Constructor->setInvalidDecl(); | |||
4953 | ||||
4954 | return false; | |||
4955 | } | |||
4956 | ||||
4957 | BaseAndFieldInfo Info(*this, Constructor, AnyErrors); | |||
4958 | ||||
4959 | // We need to build the initializer AST according to order of construction | |||
4960 | // and not what user specified in the Initializers list. | |||
4961 | CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); | |||
4962 | if (!ClassDecl) | |||
4963 | return true; | |||
4964 | ||||
4965 | bool HadError = false; | |||
4966 | ||||
4967 | for (unsigned i = 0; i < Initializers.size(); i++) { | |||
4968 | CXXCtorInitializer *Member = Initializers[i]; | |||
4969 | ||||
4970 | if (Member->isBaseInitializer()) | |||
4971 | Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; | |||
4972 | else { | |||
4973 | Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; | |||
4974 | ||||
4975 | if (IndirectFieldDecl *F = Member->getIndirectMember()) { | |||
4976 | for (auto *C : F->chain()) { | |||
4977 | FieldDecl *FD = dyn_cast<FieldDecl>(C); | |||
4978 | if (FD && FD->getParent()->isUnion()) | |||
4979 | Info.ActiveUnionMember.insert(std::make_pair( | |||
4980 | FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); | |||
4981 | } | |||
4982 | } else if (FieldDecl *FD = Member->getMember()) { | |||
4983 | if (FD->getParent()->isUnion()) | |||
4984 | Info.ActiveUnionMember.insert(std::make_pair( | |||
4985 | FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); | |||
4986 | } | |||
4987 | } | |||
4988 | } | |||
4989 | ||||
4990 | // Keep track of the direct virtual bases. | |||
4991 | llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; | |||
4992 | for (auto &I : ClassDecl->bases()) { | |||
4993 | if (I.isVirtual()) | |||
4994 | DirectVBases.insert(&I); | |||
4995 | } | |||
4996 | ||||
4997 | // Push virtual bases before others. | |||
4998 | for (auto &VBase : ClassDecl->vbases()) { | |||
4999 | if (CXXCtorInitializer *Value | |||
5000 | = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { | |||
5001 | // [class.base.init]p7, per DR257: | |||
5002 | // A mem-initializer where the mem-initializer-id names a virtual base | |||
5003 | // class is ignored during execution of a constructor of any class that | |||
5004 | // is not the most derived class. | |||
5005 | if (ClassDecl->isAbstract()) { | |||
5006 | // FIXME: Provide a fixit to remove the base specifier. This requires | |||
5007 | // tracking the location of the associated comma for a base specifier. | |||
5008 | Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) | |||
5009 | << VBase.getType() << ClassDecl; | |||
5010 | DiagnoseAbstractType(ClassDecl); | |||
5011 | } | |||
5012 | ||||
5013 | Info.AllToInit.push_back(Value); | |||
5014 | } else if (!AnyErrors && !ClassDecl->isAbstract()) { | |||
5015 | // [class.base.init]p8, per DR257: | |||
5016 | // If a given [...] base class is not named by a mem-initializer-id | |||
5017 | // [...] and the entity is not a virtual base class of an abstract | |||
5018 | // class, then [...] the entity is default-initialized. | |||
5019 | bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); | |||
5020 | CXXCtorInitializer *CXXBaseInit; | |||
5021 | if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, | |||
5022 | &VBase, IsInheritedVirtualBase, | |||
5023 | CXXBaseInit)) { | |||
5024 | HadError = true; | |||
5025 | continue; | |||
5026 | } | |||
5027 | ||||
5028 | Info.AllToInit.push_back(CXXBaseInit); | |||
5029 | } | |||
5030 | } | |||
5031 | ||||
5032 | // Non-virtual bases. | |||
5033 | for (auto &Base : ClassDecl->bases()) { | |||
5034 | // Virtuals are in the virtual base list and already constructed. | |||
5035 | if (Base.isVirtual()) | |||
5036 | continue; | |||
5037 | ||||
5038 | if (CXXCtorInitializer *Value | |||
5039 | = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { | |||
5040 | Info.AllToInit.push_back(Value); | |||
5041 | } else if (!AnyErrors) { | |||
5042 | CXXCtorInitializer *CXXBaseInit; | |||
5043 | if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, | |||
5044 | &Base, /*IsInheritedVirtualBase=*/false, | |||
5045 | CXXBaseInit)) { | |||
5046 | HadError = true; | |||
5047 | continue; | |||
5048 | } | |||
5049 | ||||
5050 | Info.AllToInit.push_back(CXXBaseInit); | |||
5051 | } | |||
5052 | } | |||
5053 | ||||
5054 | // Fields. | |||
5055 | for (auto *Mem : ClassDecl->decls()) { | |||
5056 | if (auto *F = dyn_cast<FieldDecl>(Mem)) { | |||
5057 | // C++ [class.bit]p2: | |||
5058 | // A declaration for a bit-field that omits the identifier declares an | |||
5059 | // unnamed bit-field. Unnamed bit-fields are not members and cannot be | |||
5060 | // initialized. | |||
5061 | if (F->isUnnamedBitfield()) | |||
5062 | continue; | |||
5063 | ||||
5064 | // If we're not generating the implicit copy/move constructor, then we'll | |||
5065 | // handle anonymous struct/union fields based on their individual | |||
5066 | // indirect fields. | |||
5067 | if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) | |||
5068 | continue; | |||
5069 | ||||
5070 | if (CollectFieldInitializer(*this, Info, F)) | |||
5071 | HadError = true; | |||
5072 | continue; | |||
5073 | } | |||
5074 | ||||
5075 | // Beyond this point, we only consider default initialization. | |||
5076 | if (Info.isImplicitCopyOrMove()) | |||
5077 | continue; | |||
5078 | ||||
5079 | if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { | |||
5080 | if (F->getType()->isIncompleteArrayType()) { | |||
5081 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5082, __PRETTY_FUNCTION__)) | |||
5082 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5082, __PRETTY_FUNCTION__)); | |||
5083 | continue; | |||
5084 | } | |||
5085 | ||||
5086 | // Initialize each field of an anonymous struct individually. | |||
5087 | if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) | |||
5088 | HadError = true; | |||
5089 | ||||
5090 | continue; | |||
5091 | } | |||
5092 | } | |||
5093 | ||||
5094 | unsigned NumInitializers = Info.AllToInit.size(); | |||
5095 | if (NumInitializers > 0) { | |||
5096 | Constructor->setNumCtorInitializers(NumInitializers); | |||
5097 | CXXCtorInitializer **baseOrMemberInitializers = | |||
5098 | new (Context) CXXCtorInitializer*[NumInitializers]; | |||
5099 | memcpy(baseOrMemberInitializers, Info.AllToInit.data(), | |||
5100 | NumInitializers * sizeof(CXXCtorInitializer*)); | |||
5101 | Constructor->setCtorInitializers(baseOrMemberInitializers); | |||
5102 | ||||
5103 | // Constructors implicitly reference the base and member | |||
5104 | // destructors. | |||
5105 | MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), | |||
5106 | Constructor->getParent()); | |||
5107 | } | |||
5108 | ||||
5109 | return HadError; | |||
5110 | } | |||
5111 | ||||
5112 | static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { | |||
5113 | if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { | |||
5114 | const RecordDecl *RD = RT->getDecl(); | |||
5115 | if (RD->isAnonymousStructOrUnion()) { | |||
5116 | for (auto *Field : RD->fields()) | |||
5117 | PopulateKeysForFields(Field, IdealInits); | |||
5118 | return; | |||
5119 | } | |||
5120 | } | |||
5121 | IdealInits.push_back(Field->getCanonicalDecl()); | |||
5122 | } | |||
5123 | ||||
5124 | static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { | |||
5125 | return Context.getCanonicalType(BaseType).getTypePtr(); | |||
5126 | } | |||
5127 | ||||
5128 | static const void *GetKeyForMember(ASTContext &Context, | |||
5129 | CXXCtorInitializer *Member) { | |||
5130 | if (!Member->isAnyMemberInitializer()) | |||
5131 | return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); | |||
5132 | ||||
5133 | return Member->getAnyMember()->getCanonicalDecl(); | |||
5134 | } | |||
5135 | ||||
5136 | static void DiagnoseBaseOrMemInitializerOrder( | |||
5137 | Sema &SemaRef, const CXXConstructorDecl *Constructor, | |||
5138 | ArrayRef<CXXCtorInitializer *> Inits) { | |||
5139 | if (Constructor->getDeclContext()->isDependentContext()) | |||
5140 | return; | |||
5141 | ||||
5142 | // Don't check initializers order unless the warning is enabled at the | |||
5143 | // location of at least one initializer. | |||
5144 | bool ShouldCheckOrder = false; | |||
5145 | for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { | |||
5146 | CXXCtorInitializer *Init = Inits[InitIndex]; | |||
5147 | if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, | |||
5148 | Init->getSourceLocation())) { | |||
5149 | ShouldCheckOrder = true; | |||
5150 | break; | |||
5151 | } | |||
5152 | } | |||
5153 | if (!ShouldCheckOrder) | |||
5154 | return; | |||
5155 | ||||
5156 | // Build the list of bases and members in the order that they'll | |||
5157 | // actually be initialized. The explicit initializers should be in | |||
5158 | // this same order but may be missing things. | |||
5159 | SmallVector<const void*, 32> IdealInitKeys; | |||
5160 | ||||
5161 | const CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
5162 | ||||
5163 | // 1. Virtual bases. | |||
5164 | for (const auto &VBase : ClassDecl->vbases()) | |||
5165 | IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); | |||
5166 | ||||
5167 | // 2. Non-virtual bases. | |||
5168 | for (const auto &Base : ClassDecl->bases()) { | |||
5169 | if (Base.isVirtual()) | |||
5170 | continue; | |||
5171 | IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); | |||
5172 | } | |||
5173 | ||||
5174 | // 3. Direct fields. | |||
5175 | for (auto *Field : ClassDecl->fields()) { | |||
5176 | if (Field->isUnnamedBitfield()) | |||
5177 | continue; | |||
5178 | ||||
5179 | PopulateKeysForFields(Field, IdealInitKeys); | |||
5180 | } | |||
5181 | ||||
5182 | unsigned NumIdealInits = IdealInitKeys.size(); | |||
5183 | unsigned IdealIndex = 0; | |||
5184 | ||||
5185 | CXXCtorInitializer *PrevInit = nullptr; | |||
5186 | for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { | |||
5187 | CXXCtorInitializer *Init = Inits[InitIndex]; | |||
5188 | const void *InitKey = GetKeyForMember(SemaRef.Context, Init); | |||
5189 | ||||
5190 | // Scan forward to try to find this initializer in the idealized | |||
5191 | // initializers list. | |||
5192 | for (; IdealIndex != NumIdealInits; ++IdealIndex) | |||
5193 | if (InitKey == IdealInitKeys[IdealIndex]) | |||
5194 | break; | |||
5195 | ||||
5196 | // If we didn't find this initializer, it must be because we | |||
5197 | // scanned past it on a previous iteration. That can only | |||
5198 | // happen if we're out of order; emit a warning. | |||
5199 | if (IdealIndex == NumIdealInits && PrevInit) { | |||
5200 | Sema::SemaDiagnosticBuilder D = | |||
5201 | SemaRef.Diag(PrevInit->getSourceLocation(), | |||
5202 | diag::warn_initializer_out_of_order); | |||
5203 | ||||
5204 | if (PrevInit->isAnyMemberInitializer()) | |||
5205 | D << 0 << PrevInit->getAnyMember()->getDeclName(); | |||
5206 | else | |||
5207 | D << 1 << PrevInit->getTypeSourceInfo()->getType(); | |||
5208 | ||||
5209 | if (Init->isAnyMemberInitializer()) | |||
5210 | D << 0 << Init->getAnyMember()->getDeclName(); | |||
5211 | else | |||
5212 | D << 1 << Init->getTypeSourceInfo()->getType(); | |||
5213 | ||||
5214 | // Move back to the initializer's location in the ideal list. | |||
5215 | for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) | |||
5216 | if (InitKey == IdealInitKeys[IdealIndex]) | |||
5217 | break; | |||
5218 | ||||
5219 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5220, __PRETTY_FUNCTION__)) | |||
5220 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5220, __PRETTY_FUNCTION__)); | |||
5221 | } | |||
5222 | ||||
5223 | PrevInit = Init; | |||
5224 | } | |||
5225 | } | |||
5226 | ||||
5227 | namespace { | |||
5228 | bool CheckRedundantInit(Sema &S, | |||
5229 | CXXCtorInitializer *Init, | |||
5230 | CXXCtorInitializer *&PrevInit) { | |||
5231 | if (!PrevInit) { | |||
5232 | PrevInit = Init; | |||
5233 | return false; | |||
5234 | } | |||
5235 | ||||
5236 | if (FieldDecl *Field = Init->getAnyMember()) | |||
5237 | S.Diag(Init->getSourceLocation(), | |||
5238 | diag::err_multiple_mem_initialization) | |||
5239 | << Field->getDeclName() | |||
5240 | << Init->getSourceRange(); | |||
5241 | else { | |||
5242 | const Type *BaseClass = Init->getBaseClass(); | |||
5243 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5243, __PRETTY_FUNCTION__)); | |||
5244 | S.Diag(Init->getSourceLocation(), | |||
5245 | diag::err_multiple_base_initialization) | |||
5246 | << QualType(BaseClass, 0) | |||
5247 | << Init->getSourceRange(); | |||
5248 | } | |||
5249 | S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) | |||
5250 | << 0 << PrevInit->getSourceRange(); | |||
5251 | ||||
5252 | return true; | |||
5253 | } | |||
5254 | ||||
5255 | typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; | |||
5256 | typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; | |||
5257 | ||||
5258 | bool CheckRedundantUnionInit(Sema &S, | |||
5259 | CXXCtorInitializer *Init, | |||
5260 | RedundantUnionMap &Unions) { | |||
5261 | FieldDecl *Field = Init->getAnyMember(); | |||
5262 | RecordDecl *Parent = Field->getParent(); | |||
5263 | NamedDecl *Child = Field; | |||
5264 | ||||
5265 | while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { | |||
5266 | if (Parent->isUnion()) { | |||
5267 | UnionEntry &En = Unions[Parent]; | |||
5268 | if (En.first && En.first != Child) { | |||
5269 | S.Diag(Init->getSourceLocation(), | |||
5270 | diag::err_multiple_mem_union_initialization) | |||
5271 | << Field->getDeclName() | |||
5272 | << Init->getSourceRange(); | |||
5273 | S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) | |||
5274 | << 0 << En.second->getSourceRange(); | |||
5275 | return true; | |||
5276 | } | |||
5277 | if (!En.first) { | |||
5278 | En.first = Child; | |||
5279 | En.second = Init; | |||
5280 | } | |||
5281 | if (!Parent->isAnonymousStructOrUnion()) | |||
5282 | return false; | |||
5283 | } | |||
5284 | ||||
5285 | Child = Parent; | |||
5286 | Parent = cast<RecordDecl>(Parent->getDeclContext()); | |||
5287 | } | |||
5288 | ||||
5289 | return false; | |||
5290 | } | |||
5291 | } | |||
5292 | ||||
5293 | /// ActOnMemInitializers - Handle the member initializers for a constructor. | |||
5294 | void Sema::ActOnMemInitializers(Decl *ConstructorDecl, | |||
5295 | SourceLocation ColonLoc, | |||
5296 | ArrayRef<CXXCtorInitializer*> MemInits, | |||
5297 | bool AnyErrors) { | |||
5298 | if (!ConstructorDecl) | |||
5299 | return; | |||
5300 | ||||
5301 | AdjustDeclIfTemplate(ConstructorDecl); | |||
5302 | ||||
5303 | CXXConstructorDecl *Constructor | |||
5304 | = dyn_cast<CXXConstructorDecl>(ConstructorDecl); | |||
5305 | ||||
5306 | if (!Constructor) { | |||
5307 | Diag(ColonLoc, diag::err_only_constructors_take_base_inits); | |||
5308 | return; | |||
5309 | } | |||
5310 | ||||
5311 | // Mapping for the duplicate initializers check. | |||
5312 | // For member initializers, this is keyed with a FieldDecl*. | |||
5313 | // For base initializers, this is keyed with a Type*. | |||
5314 | llvm::DenseMap<const void *, CXXCtorInitializer *> Members; | |||
5315 | ||||
5316 | // Mapping for the inconsistent anonymous-union initializers check. | |||
5317 | RedundantUnionMap MemberUnions; | |||
5318 | ||||
5319 | bool HadError = false; | |||
5320 | for (unsigned i = 0; i < MemInits.size(); i++) { | |||
5321 | CXXCtorInitializer *Init = MemInits[i]; | |||
5322 | ||||
5323 | // Set the source order index. | |||
5324 | Init->setSourceOrder(i); | |||
5325 | ||||
5326 | if (Init->isAnyMemberInitializer()) { | |||
5327 | const void *Key = GetKeyForMember(Context, Init); | |||
5328 | if (CheckRedundantInit(*this, Init, Members[Key]) || | |||
5329 | CheckRedundantUnionInit(*this, Init, MemberUnions)) | |||
5330 | HadError = true; | |||
5331 | } else if (Init->isBaseInitializer()) { | |||
5332 | const void *Key = GetKeyForMember(Context, Init); | |||
5333 | if (CheckRedundantInit(*this, Init, Members[Key])) | |||
5334 | HadError = true; | |||
5335 | } else { | |||
5336 | assert(Init->isDelegatingInitializer())((Init->isDelegatingInitializer()) ? static_cast<void> (0) : __assert_fail ("Init->isDelegatingInitializer()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5336, __PRETTY_FUNCTION__)); | |||
5337 | // This must be the only initializer | |||
5338 | if (MemInits.size() != 1) { | |||
5339 | Diag(Init->getSourceLocation(), | |||
5340 | diag::err_delegating_initializer_alone) | |||
5341 | << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); | |||
5342 | // We will treat this as being the only initializer. | |||
5343 | } | |||
5344 | SetDelegatingInitializer(Constructor, MemInits[i]); | |||
5345 | // Return immediately as the initializer is set. | |||
5346 | return; | |||
5347 | } | |||
5348 | } | |||
5349 | ||||
5350 | if (HadError) | |||
5351 | return; | |||
5352 | ||||
5353 | DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); | |||
5354 | ||||
5355 | SetCtorInitializers(Constructor, AnyErrors, MemInits); | |||
5356 | ||||
5357 | DiagnoseUninitializedFields(*this, Constructor); | |||
5358 | } | |||
5359 | ||||
5360 | void | |||
5361 | Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, | |||
5362 | CXXRecordDecl *ClassDecl) { | |||
5363 | // Ignore dependent contexts. Also ignore unions, since their members never | |||
5364 | // have destructors implicitly called. | |||
5365 | if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) | |||
5366 | return; | |||
5367 | ||||
5368 | // FIXME: all the access-control diagnostics are positioned on the | |||
5369 | // field/base declaration. That's probably good; that said, the | |||
5370 | // user might reasonably want to know why the destructor is being | |||
5371 | // emitted, and we currently don't say. | |||
5372 | ||||
5373 | // Non-static data members. | |||
5374 | for (auto *Field : ClassDecl->fields()) { | |||
5375 | if (Field->isInvalidDecl()) | |||
5376 | continue; | |||
5377 | ||||
5378 | // Don't destroy incomplete or zero-length arrays. | |||
5379 | if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) | |||
5380 | continue; | |||
5381 | ||||
5382 | QualType FieldType = Context.getBaseElementType(Field->getType()); | |||
5383 | ||||
5384 | const RecordType* RT = FieldType->getAs<RecordType>(); | |||
5385 | if (!RT) | |||
5386 | continue; | |||
5387 | ||||
5388 | CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
5389 | if (FieldClassDecl->isInvalidDecl()) | |||
5390 | continue; | |||
5391 | if (FieldClassDecl->hasIrrelevantDestructor()) | |||
5392 | continue; | |||
5393 | // The destructor for an implicit anonymous union member is never invoked. | |||
5394 | if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) | |||
5395 | continue; | |||
5396 | ||||
5397 | CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); | |||
5398 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5398, __PRETTY_FUNCTION__)); | |||
5399 | CheckDestructorAccess(Field->getLocation(), Dtor, | |||
5400 | PDiag(diag::err_access_dtor_field) | |||
5401 | << Field->getDeclName() | |||
5402 | << FieldType); | |||
5403 | ||||
5404 | MarkFunctionReferenced(Location, Dtor); | |||
5405 | DiagnoseUseOfDecl(Dtor, Location); | |||
5406 | } | |||
5407 | ||||
5408 | // We only potentially invoke the destructors of potentially constructed | |||
5409 | // subobjects. | |||
5410 | bool VisitVirtualBases = !ClassDecl->isAbstract(); | |||
5411 | ||||
5412 | llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; | |||
5413 | ||||
5414 | // Bases. | |||
5415 | for (const auto &Base : ClassDecl->bases()) { | |||
5416 | // Bases are always records in a well-formed non-dependent class. | |||
5417 | const RecordType *RT = Base.getType()->getAs<RecordType>(); | |||
5418 | ||||
5419 | // Remember direct virtual bases. | |||
5420 | if (Base.isVirtual()) { | |||
5421 | if (!VisitVirtualBases) | |||
5422 | continue; | |||
5423 | DirectVirtualBases.insert(RT); | |||
5424 | } | |||
5425 | ||||
5426 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
5427 | // If our base class is invalid, we probably can't get its dtor anyway. | |||
5428 | if (BaseClassDecl->isInvalidDecl()) | |||
5429 | continue; | |||
5430 | if (BaseClassDecl->hasIrrelevantDestructor()) | |||
5431 | continue; | |||
5432 | ||||
5433 | CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); | |||
5434 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5434, __PRETTY_FUNCTION__)); | |||
5435 | ||||
5436 | // FIXME: caret should be on the start of the class name | |||
5437 | CheckDestructorAccess(Base.getBeginLoc(), Dtor, | |||
5438 | PDiag(diag::err_access_dtor_base) | |||
5439 | << Base.getType() << Base.getSourceRange(), | |||
5440 | Context.getTypeDeclType(ClassDecl)); | |||
5441 | ||||
5442 | MarkFunctionReferenced(Location, Dtor); | |||
5443 | DiagnoseUseOfDecl(Dtor, Location); | |||
5444 | } | |||
5445 | ||||
5446 | if (!VisitVirtualBases) | |||
5447 | return; | |||
5448 | ||||
5449 | // Virtual bases. | |||
5450 | for (const auto &VBase : ClassDecl->vbases()) { | |||
5451 | // Bases are always records in a well-formed non-dependent class. | |||
5452 | const RecordType *RT = VBase.getType()->castAs<RecordType>(); | |||
5453 | ||||
5454 | // Ignore direct virtual bases. | |||
5455 | if (DirectVirtualBases.count(RT)) | |||
5456 | continue; | |||
5457 | ||||
5458 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
5459 | // If our base class is invalid, we probably can't get its dtor anyway. | |||
5460 | if (BaseClassDecl->isInvalidDecl()) | |||
5461 | continue; | |||
5462 | if (BaseClassDecl->hasIrrelevantDestructor()) | |||
5463 | continue; | |||
5464 | ||||
5465 | CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); | |||
5466 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5466, __PRETTY_FUNCTION__)); | |||
5467 | if (CheckDestructorAccess( | |||
5468 | ClassDecl->getLocation(), Dtor, | |||
5469 | PDiag(diag::err_access_dtor_vbase) | |||
5470 | << Context.getTypeDeclType(ClassDecl) << VBase.getType(), | |||
5471 | Context.getTypeDeclType(ClassDecl)) == | |||
5472 | AR_accessible) { | |||
5473 | CheckDerivedToBaseConversion( | |||
5474 | Context.getTypeDeclType(ClassDecl), VBase.getType(), | |||
5475 | diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), | |||
5476 | SourceRange(), DeclarationName(), nullptr); | |||
5477 | } | |||
5478 | ||||
5479 | MarkFunctionReferenced(Location, Dtor); | |||
5480 | DiagnoseUseOfDecl(Dtor, Location); | |||
5481 | } | |||
5482 | } | |||
5483 | ||||
5484 | void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { | |||
5485 | if (!CDtorDecl) | |||
5486 | return; | |||
5487 | ||||
5488 | if (CXXConstructorDecl *Constructor | |||
5489 | = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { | |||
5490 | SetCtorInitializers(Constructor, /*AnyErrors=*/false); | |||
5491 | DiagnoseUninitializedFields(*this, Constructor); | |||
5492 | } | |||
5493 | } | |||
5494 | ||||
5495 | bool Sema::isAbstractType(SourceLocation Loc, QualType T) { | |||
5496 | if (!getLangOpts().CPlusPlus) | |||
5497 | return false; | |||
5498 | ||||
5499 | const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); | |||
5500 | if (!RD) | |||
5501 | return false; | |||
5502 | ||||
5503 | // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a | |||
5504 | // class template specialization here, but doing so breaks a lot of code. | |||
5505 | ||||
5506 | // We can't answer whether something is abstract until it has a | |||
5507 | // definition. If it's currently being defined, we'll walk back | |||
5508 | // over all the declarations when we have a full definition. | |||
5509 | const CXXRecordDecl *Def = RD->getDefinition(); | |||
5510 | if (!Def || Def->isBeingDefined()) | |||
5511 | return false; | |||
5512 | ||||
5513 | return RD->isAbstract(); | |||
5514 | } | |||
5515 | ||||
5516 | bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, | |||
5517 | TypeDiagnoser &Diagnoser) { | |||
5518 | if (!isAbstractType(Loc, T)) | |||
5519 | return false; | |||
5520 | ||||
5521 | T = Context.getBaseElementType(T); | |||
5522 | Diagnoser.diagnose(*this, Loc, T); | |||
5523 | DiagnoseAbstractType(T->getAsCXXRecordDecl()); | |||
5524 | return true; | |||
5525 | } | |||
5526 | ||||
5527 | void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { | |||
5528 | // Check if we've already emitted the list of pure virtual functions | |||
5529 | // for this class. | |||
5530 | if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) | |||
5531 | return; | |||
5532 | ||||
5533 | // If the diagnostic is suppressed, don't emit the notes. We're only | |||
5534 | // going to emit them once, so try to attach them to a diagnostic we're | |||
5535 | // actually going to show. | |||
5536 | if (Diags.isLastDiagnosticIgnored()) | |||
5537 | return; | |||
5538 | ||||
5539 | CXXFinalOverriderMap FinalOverriders; | |||
5540 | RD->getFinalOverriders(FinalOverriders); | |||
5541 | ||||
5542 | // Keep a set of seen pure methods so we won't diagnose the same method | |||
5543 | // more than once. | |||
5544 | llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; | |||
5545 | ||||
5546 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), | |||
5547 | MEnd = FinalOverriders.end(); | |||
5548 | M != MEnd; | |||
5549 | ++M) { | |||
5550 | for (OverridingMethods::iterator SO = M->second.begin(), | |||
5551 | SOEnd = M->second.end(); | |||
5552 | SO != SOEnd; ++SO) { | |||
5553 | // C++ [class.abstract]p4: | |||
5554 | // A class is abstract if it contains or inherits at least one | |||
5555 | // pure virtual function for which the final overrider is pure | |||
5556 | // virtual. | |||
5557 | ||||
5558 | // | |||
5559 | if (SO->second.size() != 1) | |||
5560 | continue; | |||
5561 | ||||
5562 | if (!SO->second.front().Method->isPure()) | |||
5563 | continue; | |||
5564 | ||||
5565 | if (!SeenPureMethods.insert(SO->second.front().Method).second) | |||
5566 | continue; | |||
5567 | ||||
5568 | Diag(SO->second.front().Method->getLocation(), | |||
5569 | diag::note_pure_virtual_function) | |||
5570 | << SO->second.front().Method->getDeclName() << RD->getDeclName(); | |||
5571 | } | |||
5572 | } | |||
5573 | ||||
5574 | if (!PureVirtualClassDiagSet) | |||
5575 | PureVirtualClassDiagSet.reset(new RecordDeclSetTy); | |||
5576 | PureVirtualClassDiagSet->insert(RD); | |||
5577 | } | |||
5578 | ||||
5579 | namespace { | |||
5580 | struct AbstractUsageInfo { | |||
5581 | Sema &S; | |||
5582 | CXXRecordDecl *Record; | |||
5583 | CanQualType AbstractType; | |||
5584 | bool Invalid; | |||
5585 | ||||
5586 | AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) | |||
5587 | : S(S), Record(Record), | |||
5588 | AbstractType(S.Context.getCanonicalType( | |||
5589 | S.Context.getTypeDeclType(Record))), | |||
5590 | Invalid(false) {} | |||
5591 | ||||
5592 | void DiagnoseAbstractType() { | |||
5593 | if (Invalid) return; | |||
5594 | S.DiagnoseAbstractType(Record); | |||
5595 | Invalid = true; | |||
5596 | } | |||
5597 | ||||
5598 | void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); | |||
5599 | }; | |||
5600 | ||||
5601 | struct CheckAbstractUsage { | |||
5602 | AbstractUsageInfo &Info; | |||
5603 | const NamedDecl *Ctx; | |||
5604 | ||||
5605 | CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) | |||
5606 | : Info(Info), Ctx(Ctx) {} | |||
5607 | ||||
5608 | void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5609 | switch (TL.getTypeLocClass()) { | |||
5610 | #define ABSTRACT_TYPELOC(CLASS, PARENT) | |||
5611 | #define TYPELOC(CLASS, PARENT) \ | |||
5612 | case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; | |||
5613 | #include "clang/AST/TypeLocNodes.def" | |||
5614 | } | |||
5615 | } | |||
5616 | ||||
5617 | void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5618 | Visit(TL.getReturnLoc(), Sema::AbstractReturnType); | |||
5619 | for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { | |||
5620 | if (!TL.getParam(I)) | |||
5621 | continue; | |||
5622 | ||||
5623 | TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); | |||
5624 | if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); | |||
5625 | } | |||
5626 | } | |||
5627 | ||||
5628 | void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5629 | Visit(TL.getElementLoc(), Sema::AbstractArrayType); | |||
5630 | } | |||
5631 | ||||
5632 | void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5633 | // Visit the type parameters from a permissive context. | |||
5634 | for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { | |||
5635 | TemplateArgumentLoc TAL = TL.getArgLoc(I); | |||
5636 | if (TAL.getArgument().getKind() == TemplateArgument::Type) | |||
5637 | if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) | |||
5638 | Visit(TSI->getTypeLoc(), Sema::AbstractNone); | |||
5639 | // TODO: other template argument types? | |||
5640 | } | |||
5641 | } | |||
5642 | ||||
5643 | // Visit pointee types from a permissive context. | |||
5644 | #define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc (), Sema::AbstractNone); } \ | |||
5645 | void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ | |||
5646 | Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ | |||
5647 | } | |||
5648 | CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit (TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5649 | CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5650 | CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel ) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5651 | CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel ) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5652 | CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit (TL.getNextTypeLoc(), Sema::AbstractNone); } | |||
5653 | ||||
5654 | /// Handle all the types we haven't given a more specific | |||
5655 | /// implementation for above. | |||
5656 | void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { | |||
5657 | // Every other kind of type that we haven't called out already | |||
5658 | // that has an inner type is either (1) sugar or (2) contains that | |||
5659 | // inner type in some way as a subobject. | |||
5660 | if (TypeLoc Next = TL.getNextTypeLoc()) | |||
5661 | return Visit(Next, Sel); | |||
5662 | ||||
5663 | // If there's no inner type and we're in a permissive context, | |||
5664 | // don't diagnose. | |||
5665 | if (Sel == Sema::AbstractNone) return; | |||
5666 | ||||
5667 | // Check whether the type matches the abstract type. | |||
5668 | QualType T = TL.getType(); | |||
5669 | if (T->isArrayType()) { | |||
5670 | Sel = Sema::AbstractArrayType; | |||
5671 | T = Info.S.Context.getBaseElementType(T); | |||
5672 | } | |||
5673 | CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); | |||
5674 | if (CT != Info.AbstractType) return; | |||
5675 | ||||
5676 | // It matched; do some magic. | |||
5677 | if (Sel == Sema::AbstractArrayType) { | |||
5678 | Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) | |||
5679 | << T << TL.getSourceRange(); | |||
5680 | } else { | |||
5681 | Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) | |||
5682 | << Sel << T << TL.getSourceRange(); | |||
5683 | } | |||
5684 | Info.DiagnoseAbstractType(); | |||
5685 | } | |||
5686 | }; | |||
5687 | ||||
5688 | void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, | |||
5689 | Sema::AbstractDiagSelID Sel) { | |||
5690 | CheckAbstractUsage(*this, D).Visit(TL, Sel); | |||
5691 | } | |||
5692 | ||||
5693 | } | |||
5694 | ||||
5695 | /// Check for invalid uses of an abstract type in a method declaration. | |||
5696 | static void CheckAbstractClassUsage(AbstractUsageInfo &Info, | |||
5697 | CXXMethodDecl *MD) { | |||
5698 | // No need to do the check on definitions, which require that | |||
5699 | // the return/param types be complete. | |||
5700 | if (MD->doesThisDeclarationHaveABody()) | |||
5701 | return; | |||
5702 | ||||
5703 | // For safety's sake, just ignore it if we don't have type source | |||
5704 | // information. This should never happen for non-implicit methods, | |||
5705 | // but... | |||
5706 | if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) | |||
5707 | Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); | |||
5708 | } | |||
5709 | ||||
5710 | /// Check for invalid uses of an abstract type within a class definition. | |||
5711 | static void CheckAbstractClassUsage(AbstractUsageInfo &Info, | |||
5712 | CXXRecordDecl *RD) { | |||
5713 | for (auto *D : RD->decls()) { | |||
5714 | if (D->isImplicit()) continue; | |||
5715 | ||||
5716 | // Methods and method templates. | |||
5717 | if (isa<CXXMethodDecl>(D)) { | |||
5718 | CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); | |||
5719 | } else if (isa<FunctionTemplateDecl>(D)) { | |||
5720 | FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); | |||
5721 | CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); | |||
5722 | ||||
5723 | // Fields and static variables. | |||
5724 | } else if (isa<FieldDecl>(D)) { | |||
5725 | FieldDecl *FD = cast<FieldDecl>(D); | |||
5726 | if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) | |||
5727 | Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); | |||
5728 | } else if (isa<VarDecl>(D)) { | |||
5729 | VarDecl *VD = cast<VarDecl>(D); | |||
5730 | if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) | |||
5731 | Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); | |||
5732 | ||||
5733 | // Nested classes and class templates. | |||
5734 | } else if (isa<CXXRecordDecl>(D)) { | |||
5735 | CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); | |||
5736 | } else if (isa<ClassTemplateDecl>(D)) { | |||
5737 | CheckAbstractClassUsage(Info, | |||
5738 | cast<ClassTemplateDecl>(D)->getTemplatedDecl()); | |||
5739 | } | |||
5740 | } | |||
5741 | } | |||
5742 | ||||
5743 | static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { | |||
5744 | Attr *ClassAttr = getDLLAttr(Class); | |||
5745 | if (!ClassAttr) | |||
5746 | return; | |||
5747 | ||||
5748 | assert(ClassAttr->getKind() == attr::DLLExport)((ClassAttr->getKind() == attr::DLLExport) ? static_cast< void> (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 5748, __PRETTY_FUNCTION__)); | |||
5749 | ||||
5750 | TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); | |||
5751 | ||||
5752 | if (TSK == TSK_ExplicitInstantiationDeclaration) | |||
5753 | // Don't go any further if this is just an explicit instantiation | |||
5754 | // declaration. | |||
5755 | return; | |||
5756 | ||||
5757 | if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) | |||
5758 | S.MarkVTableUsed(Class->getLocation(), Class, true); | |||
5759 | ||||
5760 | for (Decl *Member : Class->decls()) { | |||
5761 | // Defined static variables that are members of an exported base | |||
5762 | // class must be marked export too. | |||
5763 | auto *VD = dyn_cast<VarDecl>(Member); | |||
5764 | if (VD && Member->getAttr<DLLExportAttr>() && | |||
5765 | VD->getStorageClass() == SC_Static && | |||
5766 | TSK == TSK_ImplicitInstantiation) | |||
5767 | S.MarkVariableReferenced(VD->getLocation(), VD); | |||
5768 | ||||
5769 | auto *MD = dyn_cast<CXXMethodDecl>(Member); | |||
5770 | if (!MD) | |||
5771 | continue; | |||
5772 | ||||
5773 | if (Member->getAttr<DLLExportAttr>()) { | |||
5774 | if (MD->isUserProvided()) { | |||
5775 | // Instantiate non-default class member functions ... | |||
5776 | ||||
5777 | // .. except for certain kinds of template specializations. | |||
5778 | if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) | |||
5779 | continue; | |||
5780 | ||||
5781 | S.MarkFunctionReferenced(Class->getLocation(), MD); | |||
5782 | ||||
5783 | // The function will be passed to the consumer when its definition is | |||
5784 | // encountered. | |||
5785 | } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || | |||
5786 | MD->isCopyAssignmentOperator() || | |||
5787 | MD->isMoveAssignmentOperator()) { | |||
5788 | // Synthesize and instantiate non-trivial implicit methods, explicitly | |||
5789 | // defaulted methods, and the copy and move assignment operators. The | |||
5790 | // latter are exported even if they are trivial, because the address of | |||
5791 | // an operator can be taken and should compare equal across libraries. | |||
5792 | DiagnosticErrorTrap Trap(S.Diags); | |||
5793 | S.MarkFunctionReferenced(Class->getLocation(), MD); | |||
5794 | if (Trap.hasErrorOccurred()) { | |||
5795 | S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) | |||
5796 | << Class << !S.getLangOpts().CPlusPlus11; | |||
5797 | break; | |||
5798 | } | |||
5799 | ||||
5800 | // There is no later point when we will see the definition of this | |||
5801 | // function, so pass it to the consumer now. | |||
5802 | S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); | |||
5803 | } | |||
5804 | } | |||
5805 | } | |||
5806 | } | |||
5807 | ||||
5808 | static void checkForMultipleExportedDefaultConstructors(Sema &S, | |||
5809 | CXXRecordDecl *Class) { | |||
5810 | // Only the MS ABI has default constructor closures, so we don't need to do | |||
5811 | // this semantic checking anywhere else. | |||
5812 | if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) | |||
5813 | return; | |||
5814 | ||||
5815 | CXXConstructorDecl *LastExportedDefaultCtor = nullptr; | |||
5816 | for (Decl *Member : Class->decls()) { | |||
5817 | // Look for exported default constructors. | |||
5818 | auto *CD = dyn_cast<CXXConstructorDecl>(Member); | |||
5819 | if (!CD || !CD->isDefaultConstructor()) | |||
5820 | continue; | |||
5821 | auto *Attr = CD->getAttr<DLLExportAttr>(); | |||
5822 | if (!Attr) | |||
5823 | continue; | |||
5824 | ||||
5825 | // If the class is non-dependent, mark the default arguments as ODR-used so | |||
5826 | // that we can properly codegen the constructor closure. | |||
5827 | if (!Class->isDependentContext()) { | |||
5828 | for (ParmVarDecl *PD : CD->parameters()) { | |||
5829 | (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); | |||
5830 | S.DiscardCleanupsInEvaluationContext(); | |||
5831 | } | |||
5832 | } | |||
5833 | ||||
5834 | if (LastExportedDefaultCtor) { | |||
5835 | S.Diag(LastExportedDefaultCtor->getLocation(), | |||
5836 | diag::err_attribute_dll_ambiguous_default_ctor) | |||
5837 | << Class; | |||
5838 | S.Diag(CD->getLocation(), diag::note_entity_declared_at) | |||
5839 | << CD->getDeclName(); | |||
5840 | return; | |||
5841 | } | |||
5842 | LastExportedDefaultCtor = CD; | |||
5843 | } | |||
5844 | } | |||
5845 | ||||
5846 | void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { | |||
5847 | // Mark any compiler-generated routines with the implicit code_seg attribute. | |||
5848 | for (auto *Method : Class->methods()) { | |||
5849 | if (Method->isUserProvided()) | |||
5850 | continue; | |||
5851 | if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) | |||
5852 | Method->addAttr(A); | |||
5853 | } | |||
5854 | } | |||
5855 | ||||
5856 | /// Check class-level dllimport/dllexport attribute. | |||
5857 | void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { | |||
5858 | Attr *ClassAttr = getDLLAttr(Class); | |||
5859 | ||||
5860 | // MSVC inherits DLL attributes to partial class template specializations. | |||
5861 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { | |||
5862 | if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { | |||
5863 | if (Attr *TemplateAttr = | |||
5864 | getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { | |||
5865 | auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); | |||
5866 | A->setInherited(true); | |||
5867 | ClassAttr = A; | |||
5868 | } | |||
5869 | } | |||
5870 | } | |||
5871 | ||||
5872 | if (!ClassAttr) | |||
5873 | return; | |||
5874 | ||||
5875 | if (!Class->isExternallyVisible()) { | |||
5876 | Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) | |||
5877 | << Class << ClassAttr; | |||
5878 | return; | |||
5879 | } | |||
5880 | ||||
5881 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | |||
5882 | !ClassAttr->isInherited()) { | |||
5883 | // Diagnose dll attributes on members of class with dll attribute. | |||
5884 | for (Decl *Member : Class->decls()) { | |||
5885 | if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) | |||
5886 | continue; | |||
5887 | InheritableAttr *MemberAttr = getDLLAttr(Member); | |||
5888 | if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) | |||
5889 | continue; | |||
5890 | ||||
5891 | Diag(MemberAttr->getLocation(), | |||
5892 | diag::err_attribute_dll_member_of_dll_class) | |||
5893 | << MemberAttr << ClassAttr; | |||
5894 | Diag(ClassAttr->getLocation(), diag::note_previous_attribute); | |||
5895 | Member->setInvalidDecl(); | |||
5896 | } | |||
5897 | } | |||
5898 | ||||
5899 | if (Class->getDescribedClassTemplate()) | |||
5900 | // Don't inherit dll attribute until the template is instantiated. | |||
5901 | return; | |||
5902 | ||||
5903 | // The class is either imported or exported. | |||
5904 | const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; | |||
5905 | ||||
5906 | // Check if this was a dllimport attribute propagated from a derived class to | |||
5907 | // a base class template specialization. We don't apply these attributes to | |||
5908 | // static data members. | |||
5909 | const bool PropagatedImport = | |||
5910 | !ClassExported && | |||
5911 | cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); | |||
5912 | ||||
5913 | TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); | |||
5914 | ||||
5915 | // Ignore explicit dllexport on explicit class template instantiation | |||
5916 | // declarations, except in MinGW mode. | |||
5917 | if (ClassExported && !ClassAttr->isInherited() && | |||
5918 | TSK == TSK_ExplicitInstantiationDeclaration && | |||
5919 | !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { | |||
5920 | Class->dropAttr<DLLExportAttr>(); | |||
5921 | return; | |||
5922 | } | |||
5923 | ||||
5924 | // Force declaration of implicit members so they can inherit the attribute. | |||
5925 | ForceDeclarationOfImplicitMembers(Class); | |||
5926 | ||||
5927 | // FIXME: MSVC's docs say all bases must be exportable, but this doesn't | |||
5928 | // seem to be true in practice? | |||
5929 | ||||
5930 | for (Decl *Member : Class->decls()) { | |||
5931 | VarDecl *VD = dyn_cast<VarDecl>(Member); | |||
5932 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); | |||
5933 | ||||
5934 | // Only methods and static fields inherit the attributes. | |||
5935 | if (!VD && !MD) | |||
5936 | continue; | |||
5937 | ||||
5938 | if (MD) { | |||
5939 | // Don't process deleted methods. | |||
5940 | if (MD->isDeleted()) | |||
5941 | continue; | |||
5942 | ||||
5943 | if (MD->isInlined()) { | |||
5944 | // MinGW does not import or export inline methods. But do it for | |||
5945 | // template instantiations. | |||
5946 | if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && | |||
5947 | !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && | |||
5948 | TSK != TSK_ExplicitInstantiationDeclaration && | |||
5949 | TSK != TSK_ExplicitInstantiationDefinition) | |||
5950 | continue; | |||
5951 | ||||
5952 | // MSVC versions before 2015 don't export the move assignment operators | |||
5953 | // and move constructor, so don't attempt to import/export them if | |||
5954 | // we have a definition. | |||
5955 | auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); | |||
5956 | if ((MD->isMoveAssignmentOperator() || | |||
5957 | (Ctor && Ctor->isMoveConstructor())) && | |||
5958 | !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) | |||
5959 | continue; | |||
5960 | ||||
5961 | // MSVC2015 doesn't export trivial defaulted x-tor but copy assign | |||
5962 | // operator is exported anyway. | |||
5963 | if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | |||
5964 | (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) | |||
5965 | continue; | |||
5966 | } | |||
5967 | } | |||
5968 | ||||
5969 | // Don't apply dllimport attributes to static data members of class template | |||
5970 | // instantiations when the attribute is propagated from a derived class. | |||
5971 | if (VD && PropagatedImport) | |||
5972 | continue; | |||
5973 | ||||
5974 | if (!cast<NamedDecl>(Member)->isExternallyVisible()) | |||
5975 | continue; | |||
5976 | ||||
5977 | if (!getDLLAttr(Member)) { | |||
5978 | InheritableAttr *NewAttr = nullptr; | |||
5979 | ||||
5980 | // Do not export/import inline function when -fno-dllexport-inlines is | |||
5981 | // passed. But add attribute for later local static var check. | |||
5982 | if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && | |||
5983 | TSK != TSK_ExplicitInstantiationDeclaration && | |||
5984 | TSK != TSK_ExplicitInstantiationDefinition) { | |||
5985 | if (ClassExported) { | |||
5986 | NewAttr = ::new (getASTContext()) | |||
5987 | DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); | |||
5988 | } else { | |||
5989 | NewAttr = ::new (getASTContext()) | |||
5990 | DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); | |||
5991 | } | |||
5992 | } else { | |||
5993 | NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); | |||
5994 | } | |||
5995 | ||||
5996 | NewAttr->setInherited(true); | |||
5997 | Member->addAttr(NewAttr); | |||
5998 | ||||
5999 | if (MD) { | |||
6000 | // Propagate DLLAttr to friend re-declarations of MD that have already | |||
6001 | // been constructed. | |||
6002 | for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; | |||
6003 | FD = FD->getPreviousDecl()) { | |||
6004 | if (FD->getFriendObjectKind() == Decl::FOK_None) | |||
6005 | continue; | |||
6006 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6007, __PRETTY_FUNCTION__)) | |||
6007 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6007, __PRETTY_FUNCTION__)); | |||
6008 | NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); | |||
6009 | NewAttr->setInherited(true); | |||
6010 | FD->addAttr(NewAttr); | |||
6011 | } | |||
6012 | } | |||
6013 | } | |||
6014 | } | |||
6015 | ||||
6016 | if (ClassExported) | |||
6017 | DelayedDllExportClasses.push_back(Class); | |||
6018 | } | |||
6019 | ||||
6020 | /// Perform propagation of DLL attributes from a derived class to a | |||
6021 | /// templated base class for MS compatibility. | |||
6022 | void Sema::propagateDLLAttrToBaseClassTemplate( | |||
6023 | CXXRecordDecl *Class, Attr *ClassAttr, | |||
6024 | ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { | |||
6025 | if (getDLLAttr( | |||
6026 | BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { | |||
6027 | // If the base class template has a DLL attribute, don't try to change it. | |||
6028 | return; | |||
6029 | } | |||
6030 | ||||
6031 | auto TSK = BaseTemplateSpec->getSpecializationKind(); | |||
6032 | if (!getDLLAttr(BaseTemplateSpec) && | |||
6033 | (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || | |||
6034 | TSK == TSK_ImplicitInstantiation)) { | |||
6035 | // The template hasn't been instantiated yet (or it has, but only as an | |||
6036 | // explicit instantiation declaration or implicit instantiation, which means | |||
6037 | // we haven't codegenned any members yet), so propagate the attribute. | |||
6038 | auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); | |||
6039 | NewAttr->setInherited(true); | |||
6040 | BaseTemplateSpec->addAttr(NewAttr); | |||
6041 | ||||
6042 | // If this was an import, mark that we propagated it from a derived class to | |||
6043 | // a base class template specialization. | |||
6044 | if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) | |||
6045 | ImportAttr->setPropagatedToBaseTemplate(); | |||
6046 | ||||
6047 | // If the template is already instantiated, checkDLLAttributeRedeclaration() | |||
6048 | // needs to be run again to work see the new attribute. Otherwise this will | |||
6049 | // get run whenever the template is instantiated. | |||
6050 | if (TSK != TSK_Undeclared) | |||
6051 | checkClassLevelDLLAttribute(BaseTemplateSpec); | |||
6052 | ||||
6053 | return; | |||
6054 | } | |||
6055 | ||||
6056 | if (getDLLAttr(BaseTemplateSpec)) { | |||
6057 | // The template has already been specialized or instantiated with an | |||
6058 | // attribute, explicitly or through propagation. We should not try to change | |||
6059 | // it. | |||
6060 | return; | |||
6061 | } | |||
6062 | ||||
6063 | // The template was previously instantiated or explicitly specialized without | |||
6064 | // a dll attribute, It's too late for us to add an attribute, so warn that | |||
6065 | // this is unsupported. | |||
6066 | Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) | |||
6067 | << BaseTemplateSpec->isExplicitSpecialization(); | |||
6068 | Diag(ClassAttr->getLocation(), diag::note_attribute); | |||
6069 | if (BaseTemplateSpec->isExplicitSpecialization()) { | |||
6070 | Diag(BaseTemplateSpec->getLocation(), | |||
6071 | diag::note_template_class_explicit_specialization_was_here) | |||
6072 | << BaseTemplateSpec; | |||
6073 | } else { | |||
6074 | Diag(BaseTemplateSpec->getPointOfInstantiation(), | |||
6075 | diag::note_template_class_instantiation_was_here) | |||
6076 | << BaseTemplateSpec; | |||
6077 | } | |||
6078 | } | |||
6079 | ||||
6080 | static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, | |||
6081 | SourceLocation DefaultLoc) { | |||
6082 | switch (S.getSpecialMember(MD)) { | |||
6083 | case Sema::CXXDefaultConstructor: | |||
6084 | S.DefineImplicitDefaultConstructor(DefaultLoc, | |||
6085 | cast<CXXConstructorDecl>(MD)); | |||
6086 | break; | |||
6087 | case Sema::CXXCopyConstructor: | |||
6088 | S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); | |||
6089 | break; | |||
6090 | case Sema::CXXCopyAssignment: | |||
6091 | S.DefineImplicitCopyAssignment(DefaultLoc, MD); | |||
6092 | break; | |||
6093 | case Sema::CXXDestructor: | |||
6094 | S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); | |||
6095 | break; | |||
6096 | case Sema::CXXMoveConstructor: | |||
6097 | S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); | |||
6098 | break; | |||
6099 | case Sema::CXXMoveAssignment: | |||
6100 | S.DefineImplicitMoveAssignment(DefaultLoc, MD); | |||
6101 | break; | |||
6102 | case Sema::CXXInvalid: | |||
6103 | llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6103); | |||
6104 | } | |||
6105 | } | |||
6106 | ||||
6107 | /// Determine whether a type is permitted to be passed or returned in | |||
6108 | /// registers, per C++ [class.temporary]p3. | |||
6109 | static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, | |||
6110 | TargetInfo::CallingConvKind CCK) { | |||
6111 | if (D->isDependentType() || D->isInvalidDecl()) | |||
6112 | return false; | |||
6113 | ||||
6114 | // Clang <= 4 used the pre-C++11 rule, which ignores move operations. | |||
6115 | // The PS4 platform ABI follows the behavior of Clang 3.2. | |||
6116 | if (CCK == TargetInfo::CCK_ClangABI4OrPS4) | |||
6117 | return !D->hasNonTrivialDestructorForCall() && | |||
6118 | !D->hasNonTrivialCopyConstructorForCall(); | |||
6119 | ||||
6120 | if (CCK == TargetInfo::CCK_MicrosoftWin64) { | |||
6121 | bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; | |||
6122 | bool DtorIsTrivialForCall = false; | |||
6123 | ||||
6124 | // If a class has at least one non-deleted, trivial copy constructor, it | |||
6125 | // is passed according to the C ABI. Otherwise, it is passed indirectly. | |||
6126 | // | |||
6127 | // Note: This permits classes with non-trivial copy or move ctors to be | |||
6128 | // passed in registers, so long as they *also* have a trivial copy ctor, | |||
6129 | // which is non-conforming. | |||
6130 | if (D->needsImplicitCopyConstructor()) { | |||
6131 | if (!D->defaultedCopyConstructorIsDeleted()) { | |||
6132 | if (D->hasTrivialCopyConstructor()) | |||
6133 | CopyCtorIsTrivial = true; | |||
6134 | if (D->hasTrivialCopyConstructorForCall()) | |||
6135 | CopyCtorIsTrivialForCall = true; | |||
6136 | } | |||
6137 | } else { | |||
6138 | for (const CXXConstructorDecl *CD : D->ctors()) { | |||
6139 | if (CD->isCopyConstructor() && !CD->isDeleted()) { | |||
6140 | if (CD->isTrivial()) | |||
6141 | CopyCtorIsTrivial = true; | |||
6142 | if (CD->isTrivialForCall()) | |||
6143 | CopyCtorIsTrivialForCall = true; | |||
6144 | } | |||
6145 | } | |||
6146 | } | |||
6147 | ||||
6148 | if (D->needsImplicitDestructor()) { | |||
6149 | if (!D->defaultedDestructorIsDeleted() && | |||
6150 | D->hasTrivialDestructorForCall()) | |||
6151 | DtorIsTrivialForCall = true; | |||
6152 | } else if (const auto *DD = D->getDestructor()) { | |||
6153 | if (!DD->isDeleted() && DD->isTrivialForCall()) | |||
6154 | DtorIsTrivialForCall = true; | |||
6155 | } | |||
6156 | ||||
6157 | // If the copy ctor and dtor are both trivial-for-calls, pass direct. | |||
6158 | if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) | |||
6159 | return true; | |||
6160 | ||||
6161 | // If a class has a destructor, we'd really like to pass it indirectly | |||
6162 | // because it allows us to elide copies. Unfortunately, MSVC makes that | |||
6163 | // impossible for small types, which it will pass in a single register or | |||
6164 | // stack slot. Most objects with dtors are large-ish, so handle that early. | |||
6165 | // We can't call out all large objects as being indirect because there are | |||
6166 | // multiple x64 calling conventions and the C++ ABI code shouldn't dictate | |||
6167 | // how we pass large POD types. | |||
6168 | ||||
6169 | // Note: This permits small classes with nontrivial destructors to be | |||
6170 | // passed in registers, which is non-conforming. | |||
6171 | bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); | |||
6172 | uint64_t TypeSize = isAArch64 ? 128 : 64; | |||
6173 | ||||
6174 | if (CopyCtorIsTrivial && | |||
6175 | S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) | |||
6176 | return true; | |||
6177 | return false; | |||
6178 | } | |||
6179 | ||||
6180 | // Per C++ [class.temporary]p3, the relevant condition is: | |||
6181 | // each copy constructor, move constructor, and destructor of X is | |||
6182 | // either trivial or deleted, and X has at least one non-deleted copy | |||
6183 | // or move constructor | |||
6184 | bool HasNonDeletedCopyOrMove = false; | |||
6185 | ||||
6186 | if (D->needsImplicitCopyConstructor() && | |||
6187 | !D->defaultedCopyConstructorIsDeleted()) { | |||
6188 | if (!D->hasTrivialCopyConstructorForCall()) | |||
6189 | return false; | |||
6190 | HasNonDeletedCopyOrMove = true; | |||
6191 | } | |||
6192 | ||||
6193 | if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && | |||
6194 | !D->defaultedMoveConstructorIsDeleted()) { | |||
6195 | if (!D->hasTrivialMoveConstructorForCall()) | |||
6196 | return false; | |||
6197 | HasNonDeletedCopyOrMove = true; | |||
6198 | } | |||
6199 | ||||
6200 | if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && | |||
6201 | !D->hasTrivialDestructorForCall()) | |||
6202 | return false; | |||
6203 | ||||
6204 | for (const CXXMethodDecl *MD : D->methods()) { | |||
6205 | if (MD->isDeleted()) | |||
6206 | continue; | |||
6207 | ||||
6208 | auto *CD = dyn_cast<CXXConstructorDecl>(MD); | |||
6209 | if (CD && CD->isCopyOrMoveConstructor()) | |||
6210 | HasNonDeletedCopyOrMove = true; | |||
6211 | else if (!isa<CXXDestructorDecl>(MD)) | |||
6212 | continue; | |||
6213 | ||||
6214 | if (!MD->isTrivialForCall()) | |||
6215 | return false; | |||
6216 | } | |||
6217 | ||||
6218 | return HasNonDeletedCopyOrMove; | |||
6219 | } | |||
6220 | ||||
6221 | /// Perform semantic checks on a class definition that has been | |||
6222 | /// completing, introducing implicitly-declared members, checking for | |||
6223 | /// abstract types, etc. | |||
6224 | void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { | |||
6225 | if (!Record) | |||
6226 | return; | |||
6227 | ||||
6228 | if (Record->isAbstract() && !Record->isInvalidDecl()) { | |||
6229 | AbstractUsageInfo Info(*this, Record); | |||
6230 | CheckAbstractClassUsage(Info, Record); | |||
6231 | } | |||
6232 | ||||
6233 | // If this is not an aggregate type and has no user-declared constructor, | |||
6234 | // complain about any non-static data members of reference or const scalar | |||
6235 | // type, since they will never get initializers. | |||
6236 | if (!Record->isInvalidDecl() && !Record->isDependentType() && | |||
6237 | !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && | |||
6238 | !Record->isLambda()) { | |||
6239 | bool Complained = false; | |||
6240 | for (const auto *F : Record->fields()) { | |||
6241 | if (F->hasInClassInitializer() || F->isUnnamedBitfield()) | |||
6242 | continue; | |||
6243 | ||||
6244 | if (F->getType()->isReferenceType() || | |||
6245 | (F->getType().isConstQualified() && F->getType()->isScalarType())) { | |||
6246 | if (!Complained) { | |||
6247 | Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) | |||
6248 | << Record->getTagKind() << Record; | |||
6249 | Complained = true; | |||
6250 | } | |||
6251 | ||||
6252 | Diag(F->getLocation(), diag::note_refconst_member_not_initialized) | |||
6253 | << F->getType()->isReferenceType() | |||
6254 | << F->getDeclName(); | |||
6255 | } | |||
6256 | } | |||
6257 | } | |||
6258 | ||||
6259 | if (Record->getIdentifier()) { | |||
6260 | // C++ [class.mem]p13: | |||
6261 | // If T is the name of a class, then each of the following shall have a | |||
6262 | // name different from T: | |||
6263 | // - every member of every anonymous union that is a member of class T. | |||
6264 | // | |||
6265 | // C++ [class.mem]p14: | |||
6266 | // In addition, if class T has a user-declared constructor (12.1), every | |||
6267 | // non-static data member of class T shall have a name different from T. | |||
6268 | DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); | |||
6269 | for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; | |||
6270 | ++I) { | |||
6271 | NamedDecl *D = (*I)->getUnderlyingDecl(); | |||
6272 | if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && | |||
6273 | Record->hasUserDeclaredConstructor()) || | |||
6274 | isa<IndirectFieldDecl>(D)) { | |||
6275 | Diag((*I)->getLocation(), diag::err_member_name_of_class) | |||
6276 | << D->getDeclName(); | |||
6277 | break; | |||
6278 | } | |||
6279 | } | |||
6280 | } | |||
6281 | ||||
6282 | // Warn if the class has virtual methods but non-virtual public destructor. | |||
6283 | if (Record->isPolymorphic() && !Record->isDependentType()) { | |||
6284 | CXXDestructorDecl *dtor = Record->getDestructor(); | |||
6285 | if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && | |||
6286 | !Record->hasAttr<FinalAttr>()) | |||
6287 | Diag(dtor ? dtor->getLocation() : Record->getLocation(), | |||
6288 | diag::warn_non_virtual_dtor) << Context.getRecordType(Record); | |||
6289 | } | |||
6290 | ||||
6291 | if (Record->isAbstract()) { | |||
6292 | if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { | |||
6293 | Diag(Record->getLocation(), diag::warn_abstract_final_class) | |||
6294 | << FA->isSpelledAsSealed(); | |||
6295 | DiagnoseAbstractType(Record); | |||
6296 | } | |||
6297 | } | |||
6298 | ||||
6299 | // Warn if the class has a final destructor but is not itself marked final. | |||
6300 | if (!Record->hasAttr<FinalAttr>()) { | |||
6301 | if (const CXXDestructorDecl *dtor = Record->getDestructor()) { | |||
6302 | if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { | |||
6303 | Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) | |||
6304 | << FA->isSpelledAsSealed() | |||
6305 | << FixItHint::CreateInsertion( | |||
6306 | getLocForEndOfToken(Record->getLocation()), | |||
6307 | (FA->isSpelledAsSealed() ? " sealed" : " final")); | |||
6308 | Diag(Record->getLocation(), | |||
6309 | diag::note_final_dtor_non_final_class_silence) | |||
6310 | << Context.getRecordType(Record) << FA->isSpelledAsSealed(); | |||
6311 | } | |||
6312 | } | |||
6313 | } | |||
6314 | ||||
6315 | // See if trivial_abi has to be dropped. | |||
6316 | if (Record->hasAttr<TrivialABIAttr>()) | |||
6317 | checkIllFormedTrivialABIStruct(*Record); | |||
6318 | ||||
6319 | // Set HasTrivialSpecialMemberForCall if the record has attribute | |||
6320 | // "trivial_abi". | |||
6321 | bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); | |||
6322 | ||||
6323 | if (HasTrivialABI) | |||
6324 | Record->setHasTrivialSpecialMemberForCall(); | |||
6325 | ||||
6326 | auto CompleteMemberFunction = [&](CXXMethodDecl *M) { | |||
6327 | // Check whether the explicitly-defaulted special members are valid. | |||
6328 | if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) | |||
6329 | CheckExplicitlyDefaultedSpecialMember(M); | |||
6330 | ||||
6331 | // For an explicitly defaulted or deleted special member, we defer | |||
6332 | // determining triviality until the class is complete. That time is now! | |||
6333 | CXXSpecialMember CSM = getSpecialMember(M); | |||
6334 | if (!M->isImplicit() && !M->isUserProvided()) { | |||
6335 | if (CSM != CXXInvalid) { | |||
6336 | M->setTrivial(SpecialMemberIsTrivial(M, CSM)); | |||
6337 | // Inform the class that we've finished declaring this member. | |||
6338 | Record->finishedDefaultedOrDeletedMember(M); | |||
6339 | M->setTrivialForCall( | |||
6340 | HasTrivialABI || | |||
6341 | SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); | |||
6342 | Record->setTrivialForCallFlags(M); | |||
6343 | } | |||
6344 | } | |||
6345 | ||||
6346 | // Set triviality for the purpose of calls if this is a user-provided | |||
6347 | // copy/move constructor or destructor. | |||
6348 | if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || | |||
6349 | CSM == CXXDestructor) && M->isUserProvided()) { | |||
6350 | M->setTrivialForCall(HasTrivialABI); | |||
6351 | Record->setTrivialForCallFlags(M); | |||
6352 | } | |||
6353 | ||||
6354 | if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && | |||
6355 | M->hasAttr<DLLExportAttr>()) { | |||
6356 | if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | |||
6357 | M->isTrivial() && | |||
6358 | (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || | |||
6359 | CSM == CXXDestructor)) | |||
6360 | M->dropAttr<DLLExportAttr>(); | |||
6361 | ||||
6362 | if (M->hasAttr<DLLExportAttr>()) { | |||
6363 | // Define after any fields with in-class initializers have been parsed. | |||
6364 | DelayedDllExportMemberFunctions.push_back(M); | |||
6365 | } | |||
6366 | } | |||
6367 | ||||
6368 | // Define defaulted constexpr virtual functions that override a base class | |||
6369 | // function right away. | |||
6370 | // FIXME: We can defer doing this until the vtable is marked as used. | |||
6371 | if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) | |||
6372 | DefineImplicitSpecialMember(*this, M, M->getLocation()); | |||
6373 | }; | |||
6374 | ||||
6375 | bool HasMethodWithOverrideControl = false, | |||
6376 | HasOverridingMethodWithoutOverrideControl = false; | |||
6377 | if (!Record->isDependentType()) { | |||
6378 | // Check the destructor before any other member function. We need to | |||
6379 | // determine whether it's trivial in order to determine whether the claas | |||
6380 | // type is a literal type, which is a prerequisite for determining whether | |||
6381 | // other special member functions are valid and whether they're implicitly | |||
6382 | // 'constexpr'. | |||
6383 | if (CXXDestructorDecl *Dtor = Record->getDestructor()) | |||
6384 | CompleteMemberFunction(Dtor); | |||
6385 | ||||
6386 | for (auto *M : Record->methods()) { | |||
6387 | // See if a method overloads virtual methods in a base | |||
6388 | // class without overriding any. | |||
6389 | if (!M->isStatic()) | |||
6390 | DiagnoseHiddenVirtualMethods(M); | |||
6391 | if (M->hasAttr<OverrideAttr>()) | |||
6392 | HasMethodWithOverrideControl = true; | |||
6393 | else if (M->size_overridden_methods() > 0) | |||
6394 | HasOverridingMethodWithoutOverrideControl = true; | |||
6395 | ||||
6396 | if (!isa<CXXDestructorDecl>(M)) | |||
6397 | CompleteMemberFunction(M); | |||
6398 | } | |||
6399 | } | |||
6400 | ||||
6401 | if (HasMethodWithOverrideControl && | |||
6402 | HasOverridingMethodWithoutOverrideControl) { | |||
6403 | // At least one method has the 'override' control declared. | |||
6404 | // Diagnose all other overridden methods which do not have 'override' specified on them. | |||
6405 | for (auto *M : Record->methods()) | |||
6406 | DiagnoseAbsenceOfOverrideControl(M); | |||
6407 | } | |||
6408 | ||||
6409 | // ms_struct is a request to use the same ABI rules as MSVC. Check | |||
6410 | // whether this class uses any C++ features that are implemented | |||
6411 | // completely differently in MSVC, and if so, emit a diagnostic. | |||
6412 | // That diagnostic defaults to an error, but we allow projects to | |||
6413 | // map it down to a warning (or ignore it). It's a fairly common | |||
6414 | // practice among users of the ms_struct pragma to mass-annotate | |||
6415 | // headers, sweeping up a bunch of types that the project doesn't | |||
6416 | // really rely on MSVC-compatible layout for. We must therefore | |||
6417 | // support "ms_struct except for C++ stuff" as a secondary ABI. | |||
6418 | if (Record->isMsStruct(Context) && | |||
6419 | (Record->isPolymorphic() || Record->getNumBases())) { | |||
6420 | Diag(Record->getLocation(), diag::warn_cxx_ms_struct); | |||
6421 | } | |||
6422 | ||||
6423 | checkClassLevelDLLAttribute(Record); | |||
6424 | checkClassLevelCodeSegAttribute(Record); | |||
6425 | ||||
6426 | bool ClangABICompat4 = | |||
6427 | Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; | |||
6428 | TargetInfo::CallingConvKind CCK = | |||
6429 | Context.getTargetInfo().getCallingConvKind(ClangABICompat4); | |||
6430 | bool CanPass = canPassInRegisters(*this, Record, CCK); | |||
6431 | ||||
6432 | // Do not change ArgPassingRestrictions if it has already been set to | |||
6433 | // APK_CanNeverPassInRegs. | |||
6434 | if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) | |||
6435 | Record->setArgPassingRestrictions(CanPass | |||
6436 | ? RecordDecl::APK_CanPassInRegs | |||
6437 | : RecordDecl::APK_CannotPassInRegs); | |||
6438 | ||||
6439 | // If canPassInRegisters returns true despite the record having a non-trivial | |||
6440 | // destructor, the record is destructed in the callee. This happens only when | |||
6441 | // the record or one of its subobjects has a field annotated with trivial_abi | |||
6442 | // or a field qualified with ObjC __strong/__weak. | |||
6443 | if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) | |||
6444 | Record->setParamDestroyedInCallee(true); | |||
6445 | else if (Record->hasNonTrivialDestructor()) | |||
6446 | Record->setParamDestroyedInCallee(CanPass); | |||
6447 | ||||
6448 | if (getLangOpts().ForceEmitVTables) { | |||
6449 | // If we want to emit all the vtables, we need to mark it as used. This | |||
6450 | // is especially required for cases like vtable assumption loads. | |||
6451 | MarkVTableUsed(Record->getInnerLocStart(), Record); | |||
6452 | } | |||
6453 | } | |||
6454 | ||||
6455 | /// Look up the special member function that would be called by a special | |||
6456 | /// member function for a subobject of class type. | |||
6457 | /// | |||
6458 | /// \param Class The class type of the subobject. | |||
6459 | /// \param CSM The kind of special member function. | |||
6460 | /// \param FieldQuals If the subobject is a field, its cv-qualifiers. | |||
6461 | /// \param ConstRHS True if this is a copy operation with a const object | |||
6462 | /// on its RHS, that is, if the argument to the outer special member | |||
6463 | /// function is 'const' and this is not a field marked 'mutable'. | |||
6464 | static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( | |||
6465 | Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, | |||
6466 | unsigned FieldQuals, bool ConstRHS) { | |||
6467 | unsigned LHSQuals = 0; | |||
6468 | if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) | |||
6469 | LHSQuals = FieldQuals; | |||
6470 | ||||
6471 | unsigned RHSQuals = FieldQuals; | |||
6472 | if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) | |||
6473 | RHSQuals = 0; | |||
6474 | else if (ConstRHS) | |||
6475 | RHSQuals |= Qualifiers::Const; | |||
6476 | ||||
6477 | return S.LookupSpecialMember(Class, CSM, | |||
6478 | RHSQuals & Qualifiers::Const, | |||
6479 | RHSQuals & Qualifiers::Volatile, | |||
6480 | false, | |||
6481 | LHSQuals & Qualifiers::Const, | |||
6482 | LHSQuals & Qualifiers::Volatile); | |||
6483 | } | |||
6484 | ||||
6485 | class Sema::InheritedConstructorInfo { | |||
6486 | Sema &S; | |||
6487 | SourceLocation UseLoc; | |||
6488 | ||||
6489 | /// A mapping from the base classes through which the constructor was | |||
6490 | /// inherited to the using shadow declaration in that base class (or a null | |||
6491 | /// pointer if the constructor was declared in that base class). | |||
6492 | llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> | |||
6493 | InheritedFromBases; | |||
6494 | ||||
6495 | public: | |||
6496 | InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, | |||
6497 | ConstructorUsingShadowDecl *Shadow) | |||
6498 | : S(S), UseLoc(UseLoc) { | |||
6499 | bool DiagnosedMultipleConstructedBases = false; | |||
6500 | CXXRecordDecl *ConstructedBase = nullptr; | |||
6501 | UsingDecl *ConstructedBaseUsing = nullptr; | |||
6502 | ||||
6503 | // Find the set of such base class subobjects and check that there's a | |||
6504 | // unique constructed subobject. | |||
6505 | for (auto *D : Shadow->redecls()) { | |||
6506 | auto *DShadow = cast<ConstructorUsingShadowDecl>(D); | |||
6507 | auto *DNominatedBase = DShadow->getNominatedBaseClass(); | |||
6508 | auto *DConstructedBase = DShadow->getConstructedBaseClass(); | |||
6509 | ||||
6510 | InheritedFromBases.insert( | |||
6511 | std::make_pair(DNominatedBase->getCanonicalDecl(), | |||
6512 | DShadow->getNominatedBaseClassShadowDecl())); | |||
6513 | if (DShadow->constructsVirtualBase()) | |||
6514 | InheritedFromBases.insert( | |||
6515 | std::make_pair(DConstructedBase->getCanonicalDecl(), | |||
6516 | DShadow->getConstructedBaseClassShadowDecl())); | |||
6517 | else | |||
6518 | assert(DNominatedBase == DConstructedBase)((DNominatedBase == DConstructedBase) ? static_cast<void> (0) : __assert_fail ("DNominatedBase == DConstructedBase", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6518, __PRETTY_FUNCTION__)); | |||
6519 | ||||
6520 | // [class.inhctor.init]p2: | |||
6521 | // If the constructor was inherited from multiple base class subobjects | |||
6522 | // of type B, the program is ill-formed. | |||
6523 | if (!ConstructedBase) { | |||
6524 | ConstructedBase = DConstructedBase; | |||
6525 | ConstructedBaseUsing = D->getUsingDecl(); | |||
6526 | } else if (ConstructedBase != DConstructedBase && | |||
6527 | !Shadow->isInvalidDecl()) { | |||
6528 | if (!DiagnosedMultipleConstructedBases) { | |||
6529 | S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) | |||
6530 | << Shadow->getTargetDecl(); | |||
6531 | S.Diag(ConstructedBaseUsing->getLocation(), | |||
6532 | diag::note_ambiguous_inherited_constructor_using) | |||
6533 | << ConstructedBase; | |||
6534 | DiagnosedMultipleConstructedBases = true; | |||
6535 | } | |||
6536 | S.Diag(D->getUsingDecl()->getLocation(), | |||
6537 | diag::note_ambiguous_inherited_constructor_using) | |||
6538 | << DConstructedBase; | |||
6539 | } | |||
6540 | } | |||
6541 | ||||
6542 | if (DiagnosedMultipleConstructedBases) | |||
6543 | Shadow->setInvalidDecl(); | |||
6544 | } | |||
6545 | ||||
6546 | /// Find the constructor to use for inherited construction of a base class, | |||
6547 | /// and whether that base class constructor inherits the constructor from a | |||
6548 | /// virtual base class (in which case it won't actually invoke it). | |||
6549 | std::pair<CXXConstructorDecl *, bool> | |||
6550 | findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { | |||
6551 | auto It = InheritedFromBases.find(Base->getCanonicalDecl()); | |||
6552 | if (It == InheritedFromBases.end()) | |||
6553 | return std::make_pair(nullptr, false); | |||
6554 | ||||
6555 | // This is an intermediary class. | |||
6556 | if (It->second) | |||
6557 | return std::make_pair( | |||
6558 | S.findInheritingConstructor(UseLoc, Ctor, It->second), | |||
6559 | It->second->constructsVirtualBase()); | |||
6560 | ||||
6561 | // This is the base class from which the constructor was inherited. | |||
6562 | return std::make_pair(Ctor, false); | |||
6563 | } | |||
6564 | }; | |||
6565 | ||||
6566 | /// Is the special member function which would be selected to perform the | |||
6567 | /// specified operation on the specified class type a constexpr constructor? | |||
6568 | static bool | |||
6569 | specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, | |||
6570 | Sema::CXXSpecialMember CSM, unsigned Quals, | |||
6571 | bool ConstRHS, | |||
6572 | CXXConstructorDecl *InheritedCtor = nullptr, | |||
6573 | Sema::InheritedConstructorInfo *Inherited = nullptr) { | |||
6574 | // If we're inheriting a constructor, see if we need to call it for this base | |||
6575 | // class. | |||
6576 | if (InheritedCtor) { | |||
6577 | assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void> (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6577, __PRETTY_FUNCTION__)); | |||
6578 | auto BaseCtor = | |||
6579 | Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; | |||
6580 | if (BaseCtor) | |||
6581 | return BaseCtor->isConstexpr(); | |||
6582 | } | |||
6583 | ||||
6584 | if (CSM == Sema::CXXDefaultConstructor) | |||
6585 | return ClassDecl->hasConstexprDefaultConstructor(); | |||
6586 | if (CSM == Sema::CXXDestructor) | |||
6587 | return ClassDecl->hasConstexprDestructor(); | |||
6588 | ||||
6589 | Sema::SpecialMemberOverloadResult SMOR = | |||
6590 | lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); | |||
6591 | if (!SMOR.getMethod()) | |||
6592 | // A constructor we wouldn't select can't be "involved in initializing" | |||
6593 | // anything. | |||
6594 | return true; | |||
6595 | return SMOR.getMethod()->isConstexpr(); | |||
6596 | } | |||
6597 | ||||
6598 | /// Determine whether the specified special member function would be constexpr | |||
6599 | /// if it were implicitly defined. | |||
6600 | static bool defaultedSpecialMemberIsConstexpr( | |||
6601 | Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, | |||
6602 | bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, | |||
6603 | Sema::InheritedConstructorInfo *Inherited = nullptr) { | |||
6604 | if (!S.getLangOpts().CPlusPlus11) | |||
6605 | return false; | |||
6606 | ||||
6607 | // C++11 [dcl.constexpr]p4: | |||
6608 | // In the definition of a constexpr constructor [...] | |||
6609 | bool Ctor = true; | |||
6610 | switch (CSM) { | |||
6611 | case Sema::CXXDefaultConstructor: | |||
6612 | if (Inherited) | |||
6613 | break; | |||
6614 | // Since default constructor lookup is essentially trivial (and cannot | |||
6615 | // involve, for instance, template instantiation), we compute whether a | |||
6616 | // defaulted default constructor is constexpr directly within CXXRecordDecl. | |||
6617 | // | |||
6618 | // This is important for performance; we need to know whether the default | |||
6619 | // constructor is constexpr to determine whether the type is a literal type. | |||
6620 | return ClassDecl->defaultedDefaultConstructorIsConstexpr(); | |||
6621 | ||||
6622 | case Sema::CXXCopyConstructor: | |||
6623 | case Sema::CXXMoveConstructor: | |||
6624 | // For copy or move constructors, we need to perform overload resolution. | |||
6625 | break; | |||
6626 | ||||
6627 | case Sema::CXXCopyAssignment: | |||
6628 | case Sema::CXXMoveAssignment: | |||
6629 | if (!S.getLangOpts().CPlusPlus14) | |||
6630 | return false; | |||
6631 | // In C++1y, we need to perform overload resolution. | |||
6632 | Ctor = false; | |||
6633 | break; | |||
6634 | ||||
6635 | case Sema::CXXDestructor: | |||
6636 | return ClassDecl->defaultedDestructorIsConstexpr(); | |||
6637 | ||||
6638 | case Sema::CXXInvalid: | |||
6639 | return false; | |||
6640 | } | |||
6641 | ||||
6642 | // -- if the class is a non-empty union, or for each non-empty anonymous | |||
6643 | // union member of a non-union class, exactly one non-static data member | |||
6644 | // shall be initialized; [DR1359] | |||
6645 | // | |||
6646 | // If we squint, this is guaranteed, since exactly one non-static data member | |||
6647 | // will be initialized (if the constructor isn't deleted), we just don't know | |||
6648 | // which one. | |||
6649 | if (Ctor && ClassDecl->isUnion()) | |||
6650 | return CSM == Sema::CXXDefaultConstructor | |||
6651 | ? ClassDecl->hasInClassInitializer() || | |||
6652 | !ClassDecl->hasVariantMembers() | |||
6653 | : true; | |||
6654 | ||||
6655 | // -- the class shall not have any virtual base classes; | |||
6656 | if (Ctor && ClassDecl->getNumVBases()) | |||
6657 | return false; | |||
6658 | ||||
6659 | // C++1y [class.copy]p26: | |||
6660 | // -- [the class] is a literal type, and | |||
6661 | if (!Ctor && !ClassDecl->isLiteral()) | |||
6662 | return false; | |||
6663 | ||||
6664 | // -- every constructor involved in initializing [...] base class | |||
6665 | // sub-objects shall be a constexpr constructor; | |||
6666 | // -- the assignment operator selected to copy/move each direct base | |||
6667 | // class is a constexpr function, and | |||
6668 | for (const auto &B : ClassDecl->bases()) { | |||
6669 | const RecordType *BaseType = B.getType()->getAs<RecordType>(); | |||
6670 | if (!BaseType) continue; | |||
6671 | ||||
6672 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); | |||
6673 | if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, | |||
6674 | InheritedCtor, Inherited)) | |||
6675 | return false; | |||
6676 | } | |||
6677 | ||||
6678 | // -- every constructor involved in initializing non-static data members | |||
6679 | // [...] shall be a constexpr constructor; | |||
6680 | // -- every non-static data member and base class sub-object shall be | |||
6681 | // initialized | |||
6682 | // -- for each non-static data member of X that is of class type (or array | |||
6683 | // thereof), the assignment operator selected to copy/move that member is | |||
6684 | // a constexpr function | |||
6685 | for (const auto *F : ClassDecl->fields()) { | |||
6686 | if (F->isInvalidDecl()) | |||
6687 | continue; | |||
6688 | if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) | |||
6689 | continue; | |||
6690 | QualType BaseType = S.Context.getBaseElementType(F->getType()); | |||
6691 | if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { | |||
6692 | CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); | |||
6693 | if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, | |||
6694 | BaseType.getCVRQualifiers(), | |||
6695 | ConstArg && !F->isMutable())) | |||
6696 | return false; | |||
6697 | } else if (CSM == Sema::CXXDefaultConstructor) { | |||
6698 | return false; | |||
6699 | } | |||
6700 | } | |||
6701 | ||||
6702 | // All OK, it's constexpr! | |||
6703 | return true; | |||
6704 | } | |||
6705 | ||||
6706 | static Sema::ImplicitExceptionSpecification | |||
6707 | ComputeDefaultedSpecialMemberExceptionSpec( | |||
6708 | Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, | |||
6709 | Sema::InheritedConstructorInfo *ICI); | |||
6710 | ||||
6711 | static Sema::ImplicitExceptionSpecification | |||
6712 | computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { | |||
6713 | auto CSM = S.getSpecialMember(MD); | |||
6714 | if (CSM != Sema::CXXInvalid) | |||
6715 | return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); | |||
6716 | ||||
6717 | auto *CD = cast<CXXConstructorDecl>(MD); | |||
6718 | assert(CD->getInheritedConstructor() &&((CD->getInheritedConstructor() && "only special members have implicit exception specs" ) ? static_cast<void> (0) : __assert_fail ("CD->getInheritedConstructor() && \"only special members have implicit exception specs\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6719, __PRETTY_FUNCTION__)) | |||
6719 | "only special members have implicit exception specs")((CD->getInheritedConstructor() && "only special members have implicit exception specs" ) ? static_cast<void> (0) : __assert_fail ("CD->getInheritedConstructor() && \"only special members have implicit exception specs\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6719, __PRETTY_FUNCTION__)); | |||
6720 | Sema::InheritedConstructorInfo ICI( | |||
6721 | S, Loc, CD->getInheritedConstructor().getShadowDecl()); | |||
6722 | return ComputeDefaultedSpecialMemberExceptionSpec( | |||
6723 | S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); | |||
6724 | } | |||
6725 | ||||
6726 | static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, | |||
6727 | CXXMethodDecl *MD) { | |||
6728 | FunctionProtoType::ExtProtoInfo EPI; | |||
6729 | ||||
6730 | // Build an exception specification pointing back at this member. | |||
6731 | EPI.ExceptionSpec.Type = EST_Unevaluated; | |||
6732 | EPI.ExceptionSpec.SourceDecl = MD; | |||
6733 | ||||
6734 | // Set the calling convention to the default for C++ instance methods. | |||
6735 | EPI.ExtInfo = EPI.ExtInfo.withCallingConv( | |||
6736 | S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, | |||
6737 | /*IsCXXMethod=*/true)); | |||
6738 | return EPI; | |||
6739 | } | |||
6740 | ||||
6741 | void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { | |||
6742 | const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); | |||
6743 | if (FPT->getExceptionSpecType() != EST_Unevaluated) | |||
6744 | return; | |||
6745 | ||||
6746 | // Evaluate the exception specification. | |||
6747 | auto IES = computeImplicitExceptionSpec(*this, Loc, MD); | |||
6748 | auto ESI = IES.getExceptionSpec(); | |||
6749 | ||||
6750 | // Update the type of the special member to use it. | |||
6751 | UpdateExceptionSpec(MD, ESI); | |||
6752 | ||||
6753 | // A user-provided destructor can be defined outside the class. When that | |||
6754 | // happens, be sure to update the exception specification on both | |||
6755 | // declarations. | |||
6756 | const FunctionProtoType *CanonicalFPT = | |||
6757 | MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); | |||
6758 | if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) | |||
6759 | UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); | |||
6760 | } | |||
6761 | ||||
6762 | void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { | |||
6763 | CXXRecordDecl *RD = MD->getParent(); | |||
6764 | CXXSpecialMember CSM = getSpecialMember(MD); | |||
6765 | ||||
6766 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6767, __PRETTY_FUNCTION__)) | |||
6767 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6767, __PRETTY_FUNCTION__)); | |||
6768 | ||||
6769 | // Whether this was the first-declared instance of the constructor. | |||
6770 | // This affects whether we implicitly add an exception spec and constexpr. | |||
6771 | bool First = MD == MD->getCanonicalDecl(); | |||
6772 | ||||
6773 | bool HadError = false; | |||
6774 | ||||
6775 | // C++11 [dcl.fct.def.default]p1: | |||
6776 | // A function that is explicitly defaulted shall | |||
6777 | // -- be a special member function (checked elsewhere), | |||
6778 | // -- have the same type (except for ref-qualifiers, and except that a | |||
6779 | // copy operation can take a non-const reference) as an implicit | |||
6780 | // declaration, and | |||
6781 | // -- not have default arguments. | |||
6782 | // C++2a changes the second bullet to instead delete the function if it's | |||
6783 | // defaulted on its first declaration, unless it's "an assignment operator, | |||
6784 | // and its return type differs or its parameter type is not a reference". | |||
6785 | bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; | |||
6786 | bool ShouldDeleteForTypeMismatch = false; | |||
6787 | unsigned ExpectedParams = 1; | |||
6788 | if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) | |||
6789 | ExpectedParams = 0; | |||
6790 | if (MD->getNumParams() != ExpectedParams) { | |||
6791 | // This checks for default arguments: a copy or move constructor with a | |||
6792 | // default argument is classified as a default constructor, and assignment | |||
6793 | // operations and destructors can't have default arguments. | |||
6794 | Diag(MD->getLocation(), diag::err_defaulted_special_member_params) | |||
6795 | << CSM << MD->getSourceRange(); | |||
6796 | HadError = true; | |||
6797 | } else if (MD->isVariadic()) { | |||
6798 | if (DeleteOnTypeMismatch) | |||
6799 | ShouldDeleteForTypeMismatch = true; | |||
6800 | else { | |||
6801 | Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) | |||
6802 | << CSM << MD->getSourceRange(); | |||
6803 | HadError = true; | |||
6804 | } | |||
6805 | } | |||
6806 | ||||
6807 | const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); | |||
6808 | ||||
6809 | bool CanHaveConstParam = false; | |||
6810 | if (CSM == CXXCopyConstructor) | |||
6811 | CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); | |||
6812 | else if (CSM == CXXCopyAssignment) | |||
6813 | CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); | |||
6814 | ||||
6815 | QualType ReturnType = Context.VoidTy; | |||
6816 | if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { | |||
6817 | // Check for return type matching. | |||
6818 | ReturnType = Type->getReturnType(); | |||
6819 | ||||
6820 | QualType DeclType = Context.getTypeDeclType(RD); | |||
6821 | DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); | |||
6822 | QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); | |||
6823 | ||||
6824 | if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { | |||
6825 | Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) | |||
6826 | << (CSM == CXXMoveAssignment) << ExpectedReturnType; | |||
6827 | HadError = true; | |||
6828 | } | |||
6829 | ||||
6830 | // A defaulted special member cannot have cv-qualifiers. | |||
6831 | if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { | |||
6832 | if (DeleteOnTypeMismatch) | |||
6833 | ShouldDeleteForTypeMismatch = true; | |||
6834 | else { | |||
6835 | Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) | |||
6836 | << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; | |||
6837 | HadError = true; | |||
6838 | } | |||
6839 | } | |||
6840 | } | |||
6841 | ||||
6842 | // Check for parameter type matching. | |||
6843 | QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); | |||
6844 | bool HasConstParam = false; | |||
6845 | if (ExpectedParams && ArgType->isReferenceType()) { | |||
6846 | // Argument must be reference to possibly-const T. | |||
6847 | QualType ReferentType = ArgType->getPointeeType(); | |||
6848 | HasConstParam = ReferentType.isConstQualified(); | |||
6849 | ||||
6850 | if (ReferentType.isVolatileQualified()) { | |||
6851 | if (DeleteOnTypeMismatch) | |||
6852 | ShouldDeleteForTypeMismatch = true; | |||
6853 | else { | |||
6854 | Diag(MD->getLocation(), | |||
6855 | diag::err_defaulted_special_member_volatile_param) << CSM; | |||
6856 | HadError = true; | |||
6857 | } | |||
6858 | } | |||
6859 | ||||
6860 | if (HasConstParam && !CanHaveConstParam) { | |||
6861 | if (DeleteOnTypeMismatch) | |||
6862 | ShouldDeleteForTypeMismatch = true; | |||
6863 | else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { | |||
6864 | Diag(MD->getLocation(), | |||
6865 | diag::err_defaulted_special_member_copy_const_param) | |||
6866 | << (CSM == CXXCopyAssignment); | |||
6867 | // FIXME: Explain why this special member can't be const. | |||
6868 | HadError = true; | |||
6869 | } else { | |||
6870 | Diag(MD->getLocation(), | |||
6871 | diag::err_defaulted_special_member_move_const_param) | |||
6872 | << (CSM == CXXMoveAssignment); | |||
6873 | HadError = true; | |||
6874 | } | |||
6875 | } | |||
6876 | } else if (ExpectedParams) { | |||
6877 | // A copy assignment operator can take its argument by value, but a | |||
6878 | // defaulted one cannot. | |||
6879 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6879, __PRETTY_FUNCTION__)); | |||
6880 | Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); | |||
6881 | HadError = true; | |||
6882 | } | |||
6883 | ||||
6884 | // C++11 [dcl.fct.def.default]p2: | |||
6885 | // An explicitly-defaulted function may be declared constexpr only if it | |||
6886 | // would have been implicitly declared as constexpr, | |||
6887 | // Do not apply this rule to members of class templates, since core issue 1358 | |||
6888 | // makes such functions always instantiate to constexpr functions. For | |||
6889 | // functions which cannot be constexpr (for non-constructors in C++11 and for | |||
6890 | // destructors in C++14 and C++17), this is checked elsewhere. | |||
6891 | // | |||
6892 | // FIXME: This should not apply if the member is deleted. | |||
6893 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, | |||
6894 | HasConstParam); | |||
6895 | if ((getLangOpts().CPlusPlus2a || | |||
6896 | (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) | |||
6897 | : isa<CXXConstructorDecl>(MD))) && | |||
6898 | MD->isConstexpr() && !Constexpr && | |||
6899 | MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { | |||
6900 | Diag(MD->getBeginLoc(), MD->isConsteval() | |||
6901 | ? diag::err_incorrect_defaulted_consteval | |||
6902 | : diag::err_incorrect_defaulted_constexpr) | |||
6903 | << CSM; | |||
6904 | // FIXME: Explain why the special member can't be constexpr. | |||
6905 | HadError = true; | |||
6906 | } | |||
6907 | ||||
6908 | if (First) { | |||
6909 | // C++2a [dcl.fct.def.default]p3: | |||
6910 | // If a function is explicitly defaulted on its first declaration, it is | |||
6911 | // implicitly considered to be constexpr if the implicit declaration | |||
6912 | // would be. | |||
6913 | MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified); | |||
6914 | ||||
6915 | if (!Type->hasExceptionSpec()) { | |||
6916 | // C++2a [except.spec]p3: | |||
6917 | // If a declaration of a function does not have a noexcept-specifier | |||
6918 | // [and] is defaulted on its first declaration, [...] the exception | |||
6919 | // specification is as specified below | |||
6920 | FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); | |||
6921 | EPI.ExceptionSpec.Type = EST_Unevaluated; | |||
6922 | EPI.ExceptionSpec.SourceDecl = MD; | |||
6923 | MD->setType(Context.getFunctionType(ReturnType, | |||
6924 | llvm::makeArrayRef(&ArgType, | |||
6925 | ExpectedParams), | |||
6926 | EPI)); | |||
6927 | } | |||
6928 | } | |||
6929 | ||||
6930 | if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { | |||
6931 | if (First) { | |||
6932 | SetDeclDeleted(MD, MD->getLocation()); | |||
6933 | if (!inTemplateInstantiation() && !HadError) { | |||
6934 | Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; | |||
6935 | if (ShouldDeleteForTypeMismatch) { | |||
6936 | Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; | |||
6937 | } else { | |||
6938 | ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); | |||
6939 | } | |||
6940 | } | |||
6941 | if (ShouldDeleteForTypeMismatch && !HadError) { | |||
6942 | Diag(MD->getLocation(), | |||
6943 | diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; | |||
6944 | } | |||
6945 | } else { | |||
6946 | // C++11 [dcl.fct.def.default]p4: | |||
6947 | // [For a] user-provided explicitly-defaulted function [...] if such a | |||
6948 | // function is implicitly defined as deleted, the program is ill-formed. | |||
6949 | Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; | |||
6950 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 6950, __PRETTY_FUNCTION__)); | |||
6951 | ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); | |||
6952 | HadError = true; | |||
6953 | } | |||
6954 | } | |||
6955 | ||||
6956 | if (HadError) | |||
6957 | MD->setInvalidDecl(); | |||
6958 | } | |||
6959 | ||||
6960 | void Sema::CheckDelayedMemberExceptionSpecs() { | |||
6961 | decltype(DelayedOverridingExceptionSpecChecks) Overriding; | |||
6962 | decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; | |||
6963 | ||||
6964 | std::swap(Overriding, DelayedOverridingExceptionSpecChecks); | |||
6965 | std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); | |||
6966 | ||||
6967 | // Perform any deferred checking of exception specifications for virtual | |||
6968 | // destructors. | |||
6969 | for (auto &Check : Overriding) | |||
6970 | CheckOverridingFunctionExceptionSpec(Check.first, Check.second); | |||
6971 | ||||
6972 | // Perform any deferred checking of exception specifications for befriended | |||
6973 | // special members. | |||
6974 | for (auto &Check : Equivalent) | |||
6975 | CheckEquivalentExceptionSpec(Check.second, Check.first); | |||
6976 | } | |||
6977 | ||||
6978 | namespace { | |||
6979 | /// CRTP base class for visiting operations performed by a special member | |||
6980 | /// function (or inherited constructor). | |||
6981 | template<typename Derived> | |||
6982 | struct SpecialMemberVisitor { | |||
6983 | Sema &S; | |||
6984 | CXXMethodDecl *MD; | |||
6985 | Sema::CXXSpecialMember CSM; | |||
6986 | Sema::InheritedConstructorInfo *ICI; | |||
6987 | ||||
6988 | // Properties of the special member, computed for convenience. | |||
6989 | bool IsConstructor = false, IsAssignment = false, ConstArg = false; | |||
6990 | ||||
6991 | SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, | |||
6992 | Sema::InheritedConstructorInfo *ICI) | |||
6993 | : S(S), MD(MD), CSM(CSM), ICI(ICI) { | |||
6994 | switch (CSM) { | |||
6995 | case Sema::CXXDefaultConstructor: | |||
6996 | case Sema::CXXCopyConstructor: | |||
6997 | case Sema::CXXMoveConstructor: | |||
6998 | IsConstructor = true; | |||
6999 | break; | |||
7000 | case Sema::CXXCopyAssignment: | |||
7001 | case Sema::CXXMoveAssignment: | |||
7002 | IsAssignment = true; | |||
7003 | break; | |||
7004 | case Sema::CXXDestructor: | |||
7005 | break; | |||
7006 | case Sema::CXXInvalid: | |||
7007 | llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7007); | |||
7008 | } | |||
7009 | ||||
7010 | if (MD->getNumParams()) { | |||
7011 | if (const ReferenceType *RT = | |||
7012 | MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) | |||
7013 | ConstArg = RT->getPointeeType().isConstQualified(); | |||
7014 | } | |||
7015 | } | |||
7016 | ||||
7017 | Derived &getDerived() { return static_cast<Derived&>(*this); } | |||
7018 | ||||
7019 | /// Is this a "move" special member? | |||
7020 | bool isMove() const { | |||
7021 | return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; | |||
7022 | } | |||
7023 | ||||
7024 | /// Look up the corresponding special member in the given class. | |||
7025 | Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, | |||
7026 | unsigned Quals, bool IsMutable) { | |||
7027 | return lookupCallFromSpecialMember(S, Class, CSM, Quals, | |||
7028 | ConstArg && !IsMutable); | |||
7029 | } | |||
7030 | ||||
7031 | /// Look up the constructor for the specified base class to see if it's | |||
7032 | /// overridden due to this being an inherited constructor. | |||
7033 | Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { | |||
7034 | if (!ICI) | |||
7035 | return {}; | |||
7036 | assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void> (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7036, __PRETTY_FUNCTION__)); | |||
7037 | auto *BaseCtor = | |||
7038 | cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); | |||
7039 | if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) | |||
7040 | return MD; | |||
7041 | return {}; | |||
7042 | } | |||
7043 | ||||
7044 | /// A base or member subobject. | |||
7045 | typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; | |||
7046 | ||||
7047 | /// Get the location to use for a subobject in diagnostics. | |||
7048 | static SourceLocation getSubobjectLoc(Subobject Subobj) { | |||
7049 | // FIXME: For an indirect virtual base, the direct base leading to | |||
7050 | // the indirect virtual base would be a more useful choice. | |||
7051 | if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) | |||
7052 | return B->getBaseTypeLoc(); | |||
7053 | else | |||
7054 | return Subobj.get<FieldDecl*>()->getLocation(); | |||
7055 | } | |||
7056 | ||||
7057 | enum BasesToVisit { | |||
7058 | /// Visit all non-virtual (direct) bases. | |||
7059 | VisitNonVirtualBases, | |||
7060 | /// Visit all direct bases, virtual or not. | |||
7061 | VisitDirectBases, | |||
7062 | /// Visit all non-virtual bases, and all virtual bases if the class | |||
7063 | /// is not abstract. | |||
7064 | VisitPotentiallyConstructedBases, | |||
7065 | /// Visit all direct or virtual bases. | |||
7066 | VisitAllBases | |||
7067 | }; | |||
7068 | ||||
7069 | // Visit the bases and members of the class. | |||
7070 | bool visit(BasesToVisit Bases) { | |||
7071 | CXXRecordDecl *RD = MD->getParent(); | |||
7072 | ||||
7073 | if (Bases == VisitPotentiallyConstructedBases) | |||
7074 | Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; | |||
7075 | ||||
7076 | for (auto &B : RD->bases()) | |||
7077 | if ((Bases == VisitDirectBases || !B.isVirtual()) && | |||
7078 | getDerived().visitBase(&B)) | |||
7079 | return true; | |||
7080 | ||||
7081 | if (Bases == VisitAllBases) | |||
7082 | for (auto &B : RD->vbases()) | |||
7083 | if (getDerived().visitBase(&B)) | |||
7084 | return true; | |||
7085 | ||||
7086 | for (auto *F : RD->fields()) | |||
7087 | if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && | |||
7088 | getDerived().visitField(F)) | |||
7089 | return true; | |||
7090 | ||||
7091 | return false; | |||
7092 | } | |||
7093 | }; | |||
7094 | } | |||
7095 | ||||
7096 | namespace { | |||
7097 | struct SpecialMemberDeletionInfo | |||
7098 | : SpecialMemberVisitor<SpecialMemberDeletionInfo> { | |||
7099 | bool Diagnose; | |||
7100 | ||||
7101 | SourceLocation Loc; | |||
7102 | ||||
7103 | bool AllFieldsAreConst; | |||
7104 | ||||
7105 | SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, | |||
7106 | Sema::CXXSpecialMember CSM, | |||
7107 | Sema::InheritedConstructorInfo *ICI, bool Diagnose) | |||
7108 | : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), | |||
7109 | Loc(MD->getLocation()), AllFieldsAreConst(true) {} | |||
7110 | ||||
7111 | bool inUnion() const { return MD->getParent()->isUnion(); } | |||
7112 | ||||
7113 | Sema::CXXSpecialMember getEffectiveCSM() { | |||
7114 | return ICI ? Sema::CXXInvalid : CSM; | |||
7115 | } | |||
7116 | ||||
7117 | bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); | |||
7118 | ||||
7119 | bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } | |||
7120 | bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } | |||
7121 | ||||
7122 | bool shouldDeleteForBase(CXXBaseSpecifier *Base); | |||
7123 | bool shouldDeleteForField(FieldDecl *FD); | |||
7124 | bool shouldDeleteForAllConstMembers(); | |||
7125 | ||||
7126 | bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, | |||
7127 | unsigned Quals); | |||
7128 | bool shouldDeleteForSubobjectCall(Subobject Subobj, | |||
7129 | Sema::SpecialMemberOverloadResult SMOR, | |||
7130 | bool IsDtorCallInCtor); | |||
7131 | ||||
7132 | bool isAccessible(Subobject Subobj, CXXMethodDecl *D); | |||
7133 | }; | |||
7134 | } | |||
7135 | ||||
7136 | /// Is the given special member inaccessible when used on the given | |||
7137 | /// sub-object. | |||
7138 | bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, | |||
7139 | CXXMethodDecl *target) { | |||
7140 | /// If we're operating on a base class, the object type is the | |||
7141 | /// type of this special member. | |||
7142 | QualType objectTy; | |||
7143 | AccessSpecifier access = target->getAccess(); | |||
7144 | if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { | |||
7145 | objectTy = S.Context.getTypeDeclType(MD->getParent()); | |||
7146 | access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); | |||
7147 | ||||
7148 | // If we're operating on a field, the object type is the type of the field. | |||
7149 | } else { | |||
7150 | objectTy = S.Context.getTypeDeclType(target->getParent()); | |||
7151 | } | |||
7152 | ||||
7153 | return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); | |||
7154 | } | |||
7155 | ||||
7156 | /// Check whether we should delete a special member due to the implicit | |||
7157 | /// definition containing a call to a special member of a subobject. | |||
7158 | bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( | |||
7159 | Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, | |||
7160 | bool IsDtorCallInCtor) { | |||
7161 | CXXMethodDecl *Decl = SMOR.getMethod(); | |||
7162 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); | |||
7163 | ||||
7164 | int DiagKind = -1; | |||
7165 | ||||
7166 | if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) | |||
7167 | DiagKind = !Decl ? 0 : 1; | |||
7168 | else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) | |||
7169 | DiagKind = 2; | |||
7170 | else if (!isAccessible(Subobj, Decl)) | |||
7171 | DiagKind = 3; | |||
7172 | else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && | |||
7173 | !Decl->isTrivial()) { | |||
7174 | // A member of a union must have a trivial corresponding special member. | |||
7175 | // As a weird special case, a destructor call from a union's constructor | |||
7176 | // must be accessible and non-deleted, but need not be trivial. Such a | |||
7177 | // destructor is never actually called, but is semantically checked as | |||
7178 | // if it were. | |||
7179 | DiagKind = 4; | |||
7180 | } | |||
7181 | ||||
7182 | if (DiagKind == -1) | |||
7183 | return false; | |||
7184 | ||||
7185 | if (Diagnose) { | |||
7186 | if (Field) { | |||
7187 | S.Diag(Field->getLocation(), | |||
7188 | diag::note_deleted_special_member_class_subobject) | |||
7189 | << getEffectiveCSM() << MD->getParent() << /*IsField*/true | |||
7190 | << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; | |||
7191 | } else { | |||
7192 | CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); | |||
7193 | S.Diag(Base->getBeginLoc(), | |||
7194 | diag::note_deleted_special_member_class_subobject) | |||
7195 | << getEffectiveCSM() << MD->getParent() << /*IsField*/ false | |||
7196 | << Base->getType() << DiagKind << IsDtorCallInCtor | |||
7197 | << /*IsObjCPtr*/false; | |||
7198 | } | |||
7199 | ||||
7200 | if (DiagKind == 1) | |||
7201 | S.NoteDeletedFunction(Decl); | |||
7202 | // FIXME: Explain inaccessibility if DiagKind == 3. | |||
7203 | } | |||
7204 | ||||
7205 | return true; | |||
7206 | } | |||
7207 | ||||
7208 | /// Check whether we should delete a special member function due to having a | |||
7209 | /// direct or virtual base class or non-static data member of class type M. | |||
7210 | bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( | |||
7211 | CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { | |||
7212 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); | |||
7213 | bool IsMutable = Field && Field->isMutable(); | |||
7214 | ||||
7215 | // C++11 [class.ctor]p5: | |||
7216 | // -- any direct or virtual base class, or non-static data member with no | |||
7217 | // brace-or-equal-initializer, has class type M (or array thereof) and | |||
7218 | // either M has no default constructor or overload resolution as applied | |||
7219 | // to M's default constructor results in an ambiguity or in a function | |||
7220 | // that is deleted or inaccessible | |||
7221 | // C++11 [class.copy]p11, C++11 [class.copy]p23: | |||
7222 | // -- a direct or virtual base class B that cannot be copied/moved because | |||
7223 | // overload resolution, as applied to B's corresponding special member, | |||
7224 | // results in an ambiguity or a function that is deleted or inaccessible | |||
7225 | // from the defaulted special member | |||
7226 | // C++11 [class.dtor]p5: | |||
7227 | // -- any direct or virtual base class [...] has a type with a destructor | |||
7228 | // that is deleted or inaccessible | |||
7229 | if (!(CSM == Sema::CXXDefaultConstructor && | |||
7230 | Field && Field->hasInClassInitializer()) && | |||
7231 | shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), | |||
7232 | false)) | |||
7233 | return true; | |||
7234 | ||||
7235 | // C++11 [class.ctor]p5, C++11 [class.copy]p11: | |||
7236 | // -- any direct or virtual base class or non-static data member has a | |||
7237 | // type with a destructor that is deleted or inaccessible | |||
7238 | if (IsConstructor) { | |||
7239 | Sema::SpecialMemberOverloadResult SMOR = | |||
7240 | S.LookupSpecialMember(Class, Sema::CXXDestructor, | |||
7241 | false, false, false, false, false); | |||
7242 | if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) | |||
7243 | return true; | |||
7244 | } | |||
7245 | ||||
7246 | return false; | |||
7247 | } | |||
7248 | ||||
7249 | bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( | |||
7250 | FieldDecl *FD, QualType FieldType) { | |||
7251 | // The defaulted special functions are defined as deleted if this is a variant | |||
7252 | // member with a non-trivial ownership type, e.g., ObjC __strong or __weak | |||
7253 | // type under ARC. | |||
7254 | if (!FieldType.hasNonTrivialObjCLifetime()) | |||
7255 | return false; | |||
7256 | ||||
7257 | // Don't make the defaulted default constructor defined as deleted if the | |||
7258 | // member has an in-class initializer. | |||
7259 | if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) | |||
7260 | return false; | |||
7261 | ||||
7262 | if (Diagnose) { | |||
7263 | auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); | |||
7264 | S.Diag(FD->getLocation(), | |||
7265 | diag::note_deleted_special_member_class_subobject) | |||
7266 | << getEffectiveCSM() << ParentClass << /*IsField*/true | |||
7267 | << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; | |||
7268 | } | |||
7269 | ||||
7270 | return true; | |||
7271 | } | |||
7272 | ||||
7273 | /// Check whether we should delete a special member function due to the class | |||
7274 | /// having a particular direct or virtual base class. | |||
7275 | bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { | |||
7276 | CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); | |||
7277 | // If program is correct, BaseClass cannot be null, but if it is, the error | |||
7278 | // must be reported elsewhere. | |||
7279 | if (!BaseClass) | |||
7280 | return false; | |||
7281 | // If we have an inheriting constructor, check whether we're calling an | |||
7282 | // inherited constructor instead of a default constructor. | |||
7283 | Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); | |||
7284 | if (auto *BaseCtor = SMOR.getMethod()) { | |||
7285 | // Note that we do not check access along this path; other than that, | |||
7286 | // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); | |||
7287 | // FIXME: Check that the base has a usable destructor! Sink this into | |||
7288 | // shouldDeleteForClassSubobject. | |||
7289 | if (BaseCtor->isDeleted() && Diagnose) { | |||
7290 | S.Diag(Base->getBeginLoc(), | |||
7291 | diag::note_deleted_special_member_class_subobject) | |||
7292 | << getEffectiveCSM() << MD->getParent() << /*IsField*/ false | |||
7293 | << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false | |||
7294 | << /*IsObjCPtr*/false; | |||
7295 | S.NoteDeletedFunction(BaseCtor); | |||
7296 | } | |||
7297 | return BaseCtor->isDeleted(); | |||
7298 | } | |||
7299 | return shouldDeleteForClassSubobject(BaseClass, Base, 0); | |||
7300 | } | |||
7301 | ||||
7302 | /// Check whether we should delete a special member function due to the class | |||
7303 | /// having a particular non-static data member. | |||
7304 | bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { | |||
7305 | QualType FieldType = S.Context.getBaseElementType(FD->getType()); | |||
7306 | CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); | |||
7307 | ||||
7308 | if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) | |||
7309 | return true; | |||
7310 | ||||
7311 | if (CSM == Sema::CXXDefaultConstructor) { | |||
7312 | // For a default constructor, all references must be initialized in-class | |||
7313 | // and, if a union, it must have a non-const member. | |||
7314 | if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { | |||
7315 | if (Diagnose) | |||
7316 | S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) | |||
7317 | << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; | |||
7318 | return true; | |||
7319 | } | |||
7320 | // C++11 [class.ctor]p5: any non-variant non-static data member of | |||
7321 | // const-qualified type (or array thereof) with no | |||
7322 | // brace-or-equal-initializer does not have a user-provided default | |||
7323 | // constructor. | |||
7324 | if (!inUnion() && FieldType.isConstQualified() && | |||
7325 | !FD->hasInClassInitializer() && | |||
7326 | (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { | |||
7327 | if (Diagnose) | |||
7328 | S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) | |||
7329 | << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; | |||
7330 | return true; | |||
7331 | } | |||
7332 | ||||
7333 | if (inUnion() && !FieldType.isConstQualified()) | |||
7334 | AllFieldsAreConst = false; | |||
7335 | } else if (CSM == Sema::CXXCopyConstructor) { | |||
7336 | // For a copy constructor, data members must not be of rvalue reference | |||
7337 | // type. | |||
7338 | if (FieldType->isRValueReferenceType()) { | |||
7339 | if (Diagnose) | |||
7340 | S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) | |||
7341 | << MD->getParent() << FD << FieldType; | |||
7342 | return true; | |||
7343 | } | |||
7344 | } else if (IsAssignment) { | |||
7345 | // For an assignment operator, data members must not be of reference type. | |||
7346 | if (FieldType->isReferenceType()) { | |||
7347 | if (Diagnose) | |||
7348 | S.Diag(FD->getLocation(), diag::note_deleted_assign_field) | |||
7349 | << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; | |||
7350 | return true; | |||
7351 | } | |||
7352 | if (!FieldRecord && FieldType.isConstQualified()) { | |||
7353 | // C++11 [class.copy]p23: | |||
7354 | // -- a non-static data member of const non-class type (or array thereof) | |||
7355 | if (Diagnose) | |||
7356 | S.Diag(FD->getLocation(), diag::note_deleted_assign_field) | |||
7357 | << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; | |||
7358 | return true; | |||
7359 | } | |||
7360 | } | |||
7361 | ||||
7362 | if (FieldRecord) { | |||
7363 | // Some additional restrictions exist on the variant members. | |||
7364 | if (!inUnion() && FieldRecord->isUnion() && | |||
7365 | FieldRecord->isAnonymousStructOrUnion()) { | |||
7366 | bool AllVariantFieldsAreConst = true; | |||
7367 | ||||
7368 | // FIXME: Handle anonymous unions declared within anonymous unions. | |||
7369 | for (auto *UI : FieldRecord->fields()) { | |||
7370 | QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); | |||
7371 | ||||
7372 | if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) | |||
7373 | return true; | |||
7374 | ||||
7375 | if (!UnionFieldType.isConstQualified()) | |||
7376 | AllVariantFieldsAreConst = false; | |||
7377 | ||||
7378 | CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); | |||
7379 | if (UnionFieldRecord && | |||
7380 | shouldDeleteForClassSubobject(UnionFieldRecord, UI, | |||
7381 | UnionFieldType.getCVRQualifiers())) | |||
7382 | return true; | |||
7383 | } | |||
7384 | ||||
7385 | // At least one member in each anonymous union must be non-const | |||
7386 | if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && | |||
7387 | !FieldRecord->field_empty()) { | |||
7388 | if (Diagnose) | |||
7389 | S.Diag(FieldRecord->getLocation(), | |||
7390 | diag::note_deleted_default_ctor_all_const) | |||
7391 | << !!ICI << MD->getParent() << /*anonymous union*/1; | |||
7392 | return true; | |||
7393 | } | |||
7394 | ||||
7395 | // Don't check the implicit member of the anonymous union type. | |||
7396 | // This is technically non-conformant, but sanity demands it. | |||
7397 | return false; | |||
7398 | } | |||
7399 | ||||
7400 | if (shouldDeleteForClassSubobject(FieldRecord, FD, | |||
7401 | FieldType.getCVRQualifiers())) | |||
7402 | return true; | |||
7403 | } | |||
7404 | ||||
7405 | return false; | |||
7406 | } | |||
7407 | ||||
7408 | /// C++11 [class.ctor] p5: | |||
7409 | /// A defaulted default constructor for a class X is defined as deleted if | |||
7410 | /// X is a union and all of its variant members are of const-qualified type. | |||
7411 | bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { | |||
7412 | // This is a silly definition, because it gives an empty union a deleted | |||
7413 | // default constructor. Don't do that. | |||
7414 | if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { | |||
7415 | bool AnyFields = false; | |||
7416 | for (auto *F : MD->getParent()->fields()) | |||
7417 | if ((AnyFields = !F->isUnnamedBitfield())) | |||
7418 | break; | |||
7419 | if (!AnyFields) | |||
7420 | return false; | |||
7421 | if (Diagnose) | |||
7422 | S.Diag(MD->getParent()->getLocation(), | |||
7423 | diag::note_deleted_default_ctor_all_const) | |||
7424 | << !!ICI << MD->getParent() << /*not anonymous union*/0; | |||
7425 | return true; | |||
7426 | } | |||
7427 | return false; | |||
7428 | } | |||
7429 | ||||
7430 | /// Determine whether a defaulted special member function should be defined as | |||
7431 | /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, | |||
7432 | /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. | |||
7433 | bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, | |||
7434 | InheritedConstructorInfo *ICI, | |||
7435 | bool Diagnose) { | |||
7436 | if (MD->isInvalidDecl()) | |||
7437 | return false; | |||
7438 | CXXRecordDecl *RD = MD->getParent(); | |||
7439 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7439, __PRETTY_FUNCTION__)); | |||
7440 | if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) | |||
7441 | return false; | |||
7442 | ||||
7443 | // C++11 [expr.lambda.prim]p19: | |||
7444 | // The closure type associated with a lambda-expression has a | |||
7445 | // deleted (8.4.3) default constructor and a deleted copy | |||
7446 | // assignment operator. | |||
7447 | // C++2a adds back these operators if the lambda has no lambda-capture. | |||
7448 | if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && | |||
7449 | (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { | |||
7450 | if (Diagnose) | |||
7451 | Diag(RD->getLocation(), diag::note_lambda_decl); | |||
7452 | return true; | |||
7453 | } | |||
7454 | ||||
7455 | // For an anonymous struct or union, the copy and assignment special members | |||
7456 | // will never be used, so skip the check. For an anonymous union declared at | |||
7457 | // namespace scope, the constructor and destructor are used. | |||
7458 | if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && | |||
7459 | RD->isAnonymousStructOrUnion()) | |||
7460 | return false; | |||
7461 | ||||
7462 | // C++11 [class.copy]p7, p18: | |||
7463 | // If the class definition declares a move constructor or move assignment | |||
7464 | // operator, an implicitly declared copy constructor or copy assignment | |||
7465 | // operator is defined as deleted. | |||
7466 | if (MD->isImplicit() && | |||
7467 | (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { | |||
7468 | CXXMethodDecl *UserDeclaredMove = nullptr; | |||
7469 | ||||
7470 | // In Microsoft mode up to MSVC 2013, a user-declared move only causes the | |||
7471 | // deletion of the corresponding copy operation, not both copy operations. | |||
7472 | // MSVC 2015 has adopted the standards conforming behavior. | |||
7473 | bool DeletesOnlyMatchingCopy = | |||
7474 | getLangOpts().MSVCCompat && | |||
7475 | !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); | |||
7476 | ||||
7477 | if (RD->hasUserDeclaredMoveConstructor() && | |||
7478 | (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { | |||
7479 | if (!Diagnose) return true; | |||
7480 | ||||
7481 | // Find any user-declared move constructor. | |||
7482 | for (auto *I : RD->ctors()) { | |||
7483 | if (I->isMoveConstructor()) { | |||
7484 | UserDeclaredMove = I; | |||
7485 | break; | |||
7486 | } | |||
7487 | } | |||
7488 | assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail ("UserDeclaredMove", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7488, __PRETTY_FUNCTION__)); | |||
7489 | } else if (RD->hasUserDeclaredMoveAssignment() && | |||
7490 | (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { | |||
7491 | if (!Diagnose) return true; | |||
7492 | ||||
7493 | // Find any user-declared move assignment operator. | |||
7494 | for (auto *I : RD->methods()) { | |||
7495 | if (I->isMoveAssignmentOperator()) { | |||
7496 | UserDeclaredMove = I; | |||
7497 | break; | |||
7498 | } | |||
7499 | } | |||
7500 | assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail ("UserDeclaredMove", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7500, __PRETTY_FUNCTION__)); | |||
7501 | } | |||
7502 | ||||
7503 | if (UserDeclaredMove) { | |||
7504 | Diag(UserDeclaredMove->getLocation(), | |||
7505 | diag::note_deleted_copy_user_declared_move) | |||
7506 | << (CSM == CXXCopyAssignment) << RD | |||
7507 | << UserDeclaredMove->isMoveAssignmentOperator(); | |||
7508 | return true; | |||
7509 | } | |||
7510 | } | |||
7511 | ||||
7512 | // Do access control from the special member function | |||
7513 | ContextRAII MethodContext(*this, MD); | |||
7514 | ||||
7515 | // C++11 [class.dtor]p5: | |||
7516 | // -- for a virtual destructor, lookup of the non-array deallocation function | |||
7517 | // results in an ambiguity or in a function that is deleted or inaccessible | |||
7518 | if (CSM == CXXDestructor && MD->isVirtual()) { | |||
7519 | FunctionDecl *OperatorDelete = nullptr; | |||
7520 | DeclarationName Name = | |||
7521 | Context.DeclarationNames.getCXXOperatorName(OO_Delete); | |||
7522 | if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, | |||
7523 | OperatorDelete, /*Diagnose*/false)) { | |||
7524 | if (Diagnose) | |||
7525 | Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); | |||
7526 | return true; | |||
7527 | } | |||
7528 | } | |||
7529 | ||||
7530 | SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); | |||
7531 | ||||
7532 | // Per DR1611, do not consider virtual bases of constructors of abstract | |||
7533 | // classes, since we are not going to construct them. | |||
7534 | // Per DR1658, do not consider virtual bases of destructors of abstract | |||
7535 | // classes either. | |||
7536 | // Per DR2180, for assignment operators we only assign (and thus only | |||
7537 | // consider) direct bases. | |||
7538 | if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases | |||
7539 | : SMI.VisitPotentiallyConstructedBases)) | |||
7540 | return true; | |||
7541 | ||||
7542 | if (SMI.shouldDeleteForAllConstMembers()) | |||
7543 | return true; | |||
7544 | ||||
7545 | if (getLangOpts().CUDA) { | |||
7546 | // We should delete the special member in CUDA mode if target inference | |||
7547 | // failed. | |||
7548 | // For inherited constructors (non-null ICI), CSM may be passed so that MD | |||
7549 | // is treated as certain special member, which may not reflect what special | |||
7550 | // member MD really is. However inferCUDATargetForImplicitSpecialMember | |||
7551 | // expects CSM to match MD, therefore recalculate CSM. | |||
7552 | assert(ICI || CSM == getSpecialMember(MD))((ICI || CSM == getSpecialMember(MD)) ? static_cast<void> (0) : __assert_fail ("ICI || CSM == getSpecialMember(MD)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7552, __PRETTY_FUNCTION__)); | |||
7553 | auto RealCSM = CSM; | |||
7554 | if (ICI) | |||
7555 | RealCSM = getSpecialMember(MD); | |||
7556 | ||||
7557 | return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, | |||
7558 | SMI.ConstArg, Diagnose); | |||
7559 | } | |||
7560 | ||||
7561 | return false; | |||
7562 | } | |||
7563 | ||||
7564 | /// Perform lookup for a special member of the specified kind, and determine | |||
7565 | /// whether it is trivial. If the triviality can be determined without the | |||
7566 | /// lookup, skip it. This is intended for use when determining whether a | |||
7567 | /// special member of a containing object is trivial, and thus does not ever | |||
7568 | /// perform overload resolution for default constructors. | |||
7569 | /// | |||
7570 | /// If \p Selected is not \c NULL, \c *Selected will be filled in with the | |||
7571 | /// member that was most likely to be intended to be trivial, if any. | |||
7572 | /// | |||
7573 | /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to | |||
7574 | /// determine whether the special member is trivial. | |||
7575 | static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, | |||
7576 | Sema::CXXSpecialMember CSM, unsigned Quals, | |||
7577 | bool ConstRHS, | |||
7578 | Sema::TrivialABIHandling TAH, | |||
7579 | CXXMethodDecl **Selected) { | |||
7580 | if (Selected) | |||
7581 | *Selected = nullptr; | |||
7582 | ||||
7583 | switch (CSM) { | |||
7584 | case Sema::CXXInvalid: | |||
7585 | llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7585); | |||
7586 | ||||
7587 | case Sema::CXXDefaultConstructor: | |||
7588 | // C++11 [class.ctor]p5: | |||
7589 | // A default constructor is trivial if: | |||
7590 | // - all the [direct subobjects] have trivial default constructors | |||
7591 | // | |||
7592 | // Note, no overload resolution is performed in this case. | |||
7593 | if (RD->hasTrivialDefaultConstructor()) | |||
7594 | return true; | |||
7595 | ||||
7596 | if (Selected) { | |||
7597 | // If there's a default constructor which could have been trivial, dig it | |||
7598 | // out. Otherwise, if there's any user-provided default constructor, point | |||
7599 | // to that as an example of why there's not a trivial one. | |||
7600 | CXXConstructorDecl *DefCtor = nullptr; | |||
7601 | if (RD->needsImplicitDefaultConstructor()) | |||
7602 | S.DeclareImplicitDefaultConstructor(RD); | |||
7603 | for (auto *CI : RD->ctors()) { | |||
7604 | if (!CI->isDefaultConstructor()) | |||
7605 | continue; | |||
7606 | DefCtor = CI; | |||
7607 | if (!DefCtor->isUserProvided()) | |||
7608 | break; | |||
7609 | } | |||
7610 | ||||
7611 | *Selected = DefCtor; | |||
7612 | } | |||
7613 | ||||
7614 | return false; | |||
7615 | ||||
7616 | case Sema::CXXDestructor: | |||
7617 | // C++11 [class.dtor]p5: | |||
7618 | // A destructor is trivial if: | |||
7619 | // - all the direct [subobjects] have trivial destructors | |||
7620 | if (RD->hasTrivialDestructor() || | |||
7621 | (TAH == Sema::TAH_ConsiderTrivialABI && | |||
7622 | RD->hasTrivialDestructorForCall())) | |||
7623 | return true; | |||
7624 | ||||
7625 | if (Selected) { | |||
7626 | if (RD->needsImplicitDestructor()) | |||
7627 | S.DeclareImplicitDestructor(RD); | |||
7628 | *Selected = RD->getDestructor(); | |||
7629 | } | |||
7630 | ||||
7631 | return false; | |||
7632 | ||||
7633 | case Sema::CXXCopyConstructor: | |||
7634 | // C++11 [class.copy]p12: | |||
7635 | // A copy constructor is trivial if: | |||
7636 | // - the constructor selected to copy each direct [subobject] is trivial | |||
7637 | if (RD->hasTrivialCopyConstructor() || | |||
7638 | (TAH == Sema::TAH_ConsiderTrivialABI && | |||
7639 | RD->hasTrivialCopyConstructorForCall())) { | |||
7640 | if (Quals == Qualifiers::Const) | |||
7641 | // We must either select the trivial copy constructor or reach an | |||
7642 | // ambiguity; no need to actually perform overload resolution. | |||
7643 | return true; | |||
7644 | } else if (!Selected) { | |||
7645 | return false; | |||
7646 | } | |||
7647 | // In C++98, we are not supposed to perform overload resolution here, but we | |||
7648 | // treat that as a language defect, as suggested on cxx-abi-dev, to treat | |||
7649 | // cases like B as having a non-trivial copy constructor: | |||
7650 | // struct A { template<typename T> A(T&); }; | |||
7651 | // struct B { mutable A a; }; | |||
7652 | goto NeedOverloadResolution; | |||
7653 | ||||
7654 | case Sema::CXXCopyAssignment: | |||
7655 | // C++11 [class.copy]p25: | |||
7656 | // A copy assignment operator is trivial if: | |||
7657 | // - the assignment operator selected to copy each direct [subobject] is | |||
7658 | // trivial | |||
7659 | if (RD->hasTrivialCopyAssignment()) { | |||
7660 | if (Quals == Qualifiers::Const) | |||
7661 | return true; | |||
7662 | } else if (!Selected) { | |||
7663 | return false; | |||
7664 | } | |||
7665 | // In C++98, we are not supposed to perform overload resolution here, but we | |||
7666 | // treat that as a language defect. | |||
7667 | goto NeedOverloadResolution; | |||
7668 | ||||
7669 | case Sema::CXXMoveConstructor: | |||
7670 | case Sema::CXXMoveAssignment: | |||
7671 | NeedOverloadResolution: | |||
7672 | Sema::SpecialMemberOverloadResult SMOR = | |||
7673 | lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); | |||
7674 | ||||
7675 | // The standard doesn't describe how to behave if the lookup is ambiguous. | |||
7676 | // We treat it as not making the member non-trivial, just like the standard | |||
7677 | // mandates for the default constructor. This should rarely matter, because | |||
7678 | // the member will also be deleted. | |||
7679 | if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) | |||
7680 | return true; | |||
7681 | ||||
7682 | if (!SMOR.getMethod()) { | |||
7683 | assert(SMOR.getKind() ==((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted ) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7684, __PRETTY_FUNCTION__)) | |||
7684 | Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted ) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7684, __PRETTY_FUNCTION__)); | |||
7685 | return false; | |||
7686 | } | |||
7687 | ||||
7688 | // We deliberately don't check if we found a deleted special member. We're | |||
7689 | // not supposed to! | |||
7690 | if (Selected) | |||
7691 | *Selected = SMOR.getMethod(); | |||
7692 | ||||
7693 | if (TAH == Sema::TAH_ConsiderTrivialABI && | |||
7694 | (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) | |||
7695 | return SMOR.getMethod()->isTrivialForCall(); | |||
7696 | return SMOR.getMethod()->isTrivial(); | |||
7697 | } | |||
7698 | ||||
7699 | llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7699); | |||
7700 | } | |||
7701 | ||||
7702 | static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { | |||
7703 | for (auto *CI : RD->ctors()) | |||
7704 | if (!CI->isImplicit()) | |||
7705 | return CI; | |||
7706 | ||||
7707 | // Look for constructor templates. | |||
7708 | typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; | |||
7709 | for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { | |||
7710 | if (CXXConstructorDecl *CD = | |||
7711 | dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) | |||
7712 | return CD; | |||
7713 | } | |||
7714 | ||||
7715 | return nullptr; | |||
7716 | } | |||
7717 | ||||
7718 | /// The kind of subobject we are checking for triviality. The values of this | |||
7719 | /// enumeration are used in diagnostics. | |||
7720 | enum TrivialSubobjectKind { | |||
7721 | /// The subobject is a base class. | |||
7722 | TSK_BaseClass, | |||
7723 | /// The subobject is a non-static data member. | |||
7724 | TSK_Field, | |||
7725 | /// The object is actually the complete object. | |||
7726 | TSK_CompleteObject | |||
7727 | }; | |||
7728 | ||||
7729 | /// Check whether the special member selected for a given type would be trivial. | |||
7730 | static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, | |||
7731 | QualType SubType, bool ConstRHS, | |||
7732 | Sema::CXXSpecialMember CSM, | |||
7733 | TrivialSubobjectKind Kind, | |||
7734 | Sema::TrivialABIHandling TAH, bool Diagnose) { | |||
7735 | CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); | |||
7736 | if (!SubRD) | |||
7737 | return true; | |||
7738 | ||||
7739 | CXXMethodDecl *Selected; | |||
7740 | if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), | |||
7741 | ConstRHS, TAH, Diagnose ? &Selected : nullptr)) | |||
7742 | return true; | |||
7743 | ||||
7744 | if (Diagnose) { | |||
7745 | if (ConstRHS) | |||
7746 | SubType.addConst(); | |||
7747 | ||||
7748 | if (!Selected && CSM == Sema::CXXDefaultConstructor) { | |||
7749 | S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) | |||
7750 | << Kind << SubType.getUnqualifiedType(); | |||
7751 | if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) | |||
7752 | S.Diag(CD->getLocation(), diag::note_user_declared_ctor); | |||
7753 | } else if (!Selected) | |||
7754 | S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) | |||
7755 | << Kind << SubType.getUnqualifiedType() << CSM << SubType; | |||
7756 | else if (Selected->isUserProvided()) { | |||
7757 | if (Kind == TSK_CompleteObject) | |||
7758 | S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) | |||
7759 | << Kind << SubType.getUnqualifiedType() << CSM; | |||
7760 | else { | |||
7761 | S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) | |||
7762 | << Kind << SubType.getUnqualifiedType() << CSM; | |||
7763 | S.Diag(Selected->getLocation(), diag::note_declared_at); | |||
7764 | } | |||
7765 | } else { | |||
7766 | if (Kind != TSK_CompleteObject) | |||
7767 | S.Diag(SubobjLoc, diag::note_nontrivial_subobject) | |||
7768 | << Kind << SubType.getUnqualifiedType() << CSM; | |||
7769 | ||||
7770 | // Explain why the defaulted or deleted special member isn't trivial. | |||
7771 | S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, | |||
7772 | Diagnose); | |||
7773 | } | |||
7774 | } | |||
7775 | ||||
7776 | return false; | |||
7777 | } | |||
7778 | ||||
7779 | /// Check whether the members of a class type allow a special member to be | |||
7780 | /// trivial. | |||
7781 | static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, | |||
7782 | Sema::CXXSpecialMember CSM, | |||
7783 | bool ConstArg, | |||
7784 | Sema::TrivialABIHandling TAH, | |||
7785 | bool Diagnose) { | |||
7786 | for (const auto *FI : RD->fields()) { | |||
7787 | if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) | |||
7788 | continue; | |||
7789 | ||||
7790 | QualType FieldType = S.Context.getBaseElementType(FI->getType()); | |||
7791 | ||||
7792 | // Pretend anonymous struct or union members are members of this class. | |||
7793 | if (FI->isAnonymousStructOrUnion()) { | |||
7794 | if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), | |||
7795 | CSM, ConstArg, TAH, Diagnose)) | |||
7796 | return false; | |||
7797 | continue; | |||
7798 | } | |||
7799 | ||||
7800 | // C++11 [class.ctor]p5: | |||
7801 | // A default constructor is trivial if [...] | |||
7802 | // -- no non-static data member of its class has a | |||
7803 | // brace-or-equal-initializer | |||
7804 | if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { | |||
7805 | if (Diagnose) | |||
7806 | S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; | |||
7807 | return false; | |||
7808 | } | |||
7809 | ||||
7810 | // Objective C ARC 4.3.5: | |||
7811 | // [...] nontrivally ownership-qualified types are [...] not trivially | |||
7812 | // default constructible, copy constructible, move constructible, copy | |||
7813 | // assignable, move assignable, or destructible [...] | |||
7814 | if (FieldType.hasNonTrivialObjCLifetime()) { | |||
7815 | if (Diagnose) | |||
7816 | S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) | |||
7817 | << RD << FieldType.getObjCLifetime(); | |||
7818 | return false; | |||
7819 | } | |||
7820 | ||||
7821 | bool ConstRHS = ConstArg && !FI->isMutable(); | |||
7822 | if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, | |||
7823 | CSM, TSK_Field, TAH, Diagnose)) | |||
7824 | return false; | |||
7825 | } | |||
7826 | ||||
7827 | return true; | |||
7828 | } | |||
7829 | ||||
7830 | /// Diagnose why the specified class does not have a trivial special member of | |||
7831 | /// the given kind. | |||
7832 | void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { | |||
7833 | QualType Ty = Context.getRecordType(RD); | |||
7834 | ||||
7835 | bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); | |||
7836 | checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, | |||
7837 | TSK_CompleteObject, TAH_IgnoreTrivialABI, | |||
7838 | /*Diagnose*/true); | |||
7839 | } | |||
7840 | ||||
7841 | /// Determine whether a defaulted or deleted special member function is trivial, | |||
7842 | /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, | |||
7843 | /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. | |||
7844 | bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, | |||
7845 | TrivialABIHandling TAH, bool Diagnose) { | |||
7846 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7846, __PRETTY_FUNCTION__)); | |||
7847 | ||||
7848 | CXXRecordDecl *RD = MD->getParent(); | |||
7849 | ||||
7850 | bool ConstArg = false; | |||
7851 | ||||
7852 | // C++11 [class.copy]p12, p25: [DR1593] | |||
7853 | // A [special member] is trivial if [...] its parameter-type-list is | |||
7854 | // equivalent to the parameter-type-list of an implicit declaration [...] | |||
7855 | switch (CSM) { | |||
7856 | case CXXDefaultConstructor: | |||
7857 | case CXXDestructor: | |||
7858 | // Trivial default constructors and destructors cannot have parameters. | |||
7859 | break; | |||
7860 | ||||
7861 | case CXXCopyConstructor: | |||
7862 | case CXXCopyAssignment: { | |||
7863 | // Trivial copy operations always have const, non-volatile parameter types. | |||
7864 | ConstArg = true; | |||
7865 | const ParmVarDecl *Param0 = MD->getParamDecl(0); | |||
7866 | const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); | |||
7867 | if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { | |||
7868 | if (Diagnose) | |||
7869 | Diag(Param0->getLocation(), diag::note_nontrivial_param_type) | |||
7870 | << Param0->getSourceRange() << Param0->getType() | |||
7871 | << Context.getLValueReferenceType( | |||
7872 | Context.getRecordType(RD).withConst()); | |||
7873 | return false; | |||
7874 | } | |||
7875 | break; | |||
7876 | } | |||
7877 | ||||
7878 | case CXXMoveConstructor: | |||
7879 | case CXXMoveAssignment: { | |||
7880 | // Trivial move operations always have non-cv-qualified parameters. | |||
7881 | const ParmVarDecl *Param0 = MD->getParamDecl(0); | |||
7882 | const RValueReferenceType *RT = | |||
7883 | Param0->getType()->getAs<RValueReferenceType>(); | |||
7884 | if (!RT || RT->getPointeeType().getCVRQualifiers()) { | |||
7885 | if (Diagnose) | |||
7886 | Diag(Param0->getLocation(), diag::note_nontrivial_param_type) | |||
7887 | << Param0->getSourceRange() << Param0->getType() | |||
7888 | << Context.getRValueReferenceType(Context.getRecordType(RD)); | |||
7889 | return false; | |||
7890 | } | |||
7891 | break; | |||
7892 | } | |||
7893 | ||||
7894 | case CXXInvalid: | |||
7895 | llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7895); | |||
7896 | } | |||
7897 | ||||
7898 | if (MD->getMinRequiredArguments() < MD->getNumParams()) { | |||
7899 | if (Diagnose) | |||
7900 | Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), | |||
7901 | diag::note_nontrivial_default_arg) | |||
7902 | << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); | |||
7903 | return false; | |||
7904 | } | |||
7905 | if (MD->isVariadic()) { | |||
7906 | if (Diagnose) | |||
7907 | Diag(MD->getLocation(), diag::note_nontrivial_variadic); | |||
7908 | return false; | |||
7909 | } | |||
7910 | ||||
7911 | // C++11 [class.ctor]p5, C++11 [class.dtor]p5: | |||
7912 | // A copy/move [constructor or assignment operator] is trivial if | |||
7913 | // -- the [member] selected to copy/move each direct base class subobject | |||
7914 | // is trivial | |||
7915 | // | |||
7916 | // C++11 [class.copy]p12, C++11 [class.copy]p25: | |||
7917 | // A [default constructor or destructor] is trivial if | |||
7918 | // -- all the direct base classes have trivial [default constructors or | |||
7919 | // destructors] | |||
7920 | for (const auto &BI : RD->bases()) | |||
7921 | if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), | |||
7922 | ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) | |||
7923 | return false; | |||
7924 | ||||
7925 | // C++11 [class.ctor]p5, C++11 [class.dtor]p5: | |||
7926 | // A copy/move [constructor or assignment operator] for a class X is | |||
7927 | // trivial if | |||
7928 | // -- for each non-static data member of X that is of class type (or array | |||
7929 | // thereof), the constructor selected to copy/move that member is | |||
7930 | // trivial | |||
7931 | // | |||
7932 | // C++11 [class.copy]p12, C++11 [class.copy]p25: | |||
7933 | // A [default constructor or destructor] is trivial if | |||
7934 | // -- for all of the non-static data members of its class that are of class | |||
7935 | // type (or array thereof), each such class has a trivial [default | |||
7936 | // constructor or destructor] | |||
7937 | if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) | |||
7938 | return false; | |||
7939 | ||||
7940 | // C++11 [class.dtor]p5: | |||
7941 | // A destructor is trivial if [...] | |||
7942 | // -- the destructor is not virtual | |||
7943 | if (CSM == CXXDestructor && MD->isVirtual()) { | |||
7944 | if (Diagnose) | |||
7945 | Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; | |||
7946 | return false; | |||
7947 | } | |||
7948 | ||||
7949 | // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: | |||
7950 | // A [special member] for class X is trivial if [...] | |||
7951 | // -- class X has no virtual functions and no virtual base classes | |||
7952 | if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { | |||
7953 | if (!Diagnose) | |||
7954 | return false; | |||
7955 | ||||
7956 | if (RD->getNumVBases()) { | |||
7957 | // Check for virtual bases. We already know that the corresponding | |||
7958 | // member in all bases is trivial, so vbases must all be direct. | |||
7959 | CXXBaseSpecifier &BS = *RD->vbases_begin(); | |||
7960 | assert(BS.isVirtual())((BS.isVirtual()) ? static_cast<void> (0) : __assert_fail ("BS.isVirtual()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7960, __PRETTY_FUNCTION__)); | |||
7961 | Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; | |||
7962 | return false; | |||
7963 | } | |||
7964 | ||||
7965 | // Must have a virtual method. | |||
7966 | for (const auto *MI : RD->methods()) { | |||
7967 | if (MI->isVirtual()) { | |||
7968 | SourceLocation MLoc = MI->getBeginLoc(); | |||
7969 | Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; | |||
7970 | return false; | |||
7971 | } | |||
7972 | } | |||
7973 | ||||
7974 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 7974); | |||
7975 | } | |||
7976 | ||||
7977 | // Looks like it's trivial! | |||
7978 | return true; | |||
7979 | } | |||
7980 | ||||
7981 | namespace { | |||
7982 | struct FindHiddenVirtualMethod { | |||
7983 | Sema *S; | |||
7984 | CXXMethodDecl *Method; | |||
7985 | llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; | |||
7986 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; | |||
7987 | ||||
7988 | private: | |||
7989 | /// Check whether any most overridden method from MD in Methods | |||
7990 | static bool CheckMostOverridenMethods( | |||
7991 | const CXXMethodDecl *MD, | |||
7992 | const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { | |||
7993 | if (MD->size_overridden_methods() == 0) | |||
7994 | return Methods.count(MD->getCanonicalDecl()); | |||
7995 | for (const CXXMethodDecl *O : MD->overridden_methods()) | |||
7996 | if (CheckMostOverridenMethods(O, Methods)) | |||
7997 | return true; | |||
7998 | return false; | |||
7999 | } | |||
8000 | ||||
8001 | public: | |||
8002 | /// Member lookup function that determines whether a given C++ | |||
8003 | /// method overloads virtual methods in a base class without overriding any, | |||
8004 | /// to be used with CXXRecordDecl::lookupInBases(). | |||
8005 | bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { | |||
8006 | RecordDecl *BaseRecord = | |||
8007 | Specifier->getType()->getAs<RecordType>()->getDecl(); | |||
8008 | ||||
8009 | DeclarationName Name = Method->getDeclName(); | |||
8010 | assert(Name.getNameKind() == DeclarationName::Identifier)((Name.getNameKind() == DeclarationName::Identifier) ? static_cast <void> (0) : __assert_fail ("Name.getNameKind() == DeclarationName::Identifier" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8010, __PRETTY_FUNCTION__)); | |||
8011 | ||||
8012 | bool foundSameNameMethod = false; | |||
8013 | SmallVector<CXXMethodDecl *, 8> overloadedMethods; | |||
8014 | for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); | |||
8015 | Path.Decls = Path.Decls.slice(1)) { | |||
8016 | NamedDecl *D = Path.Decls.front(); | |||
8017 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { | |||
8018 | MD = MD->getCanonicalDecl(); | |||
8019 | foundSameNameMethod = true; | |||
8020 | // Interested only in hidden virtual methods. | |||
8021 | if (!MD->isVirtual()) | |||
8022 | continue; | |||
8023 | // If the method we are checking overrides a method from its base | |||
8024 | // don't warn about the other overloaded methods. Clang deviates from | |||
8025 | // GCC by only diagnosing overloads of inherited virtual functions that | |||
8026 | // do not override any other virtual functions in the base. GCC's | |||
8027 | // -Woverloaded-virtual diagnoses any derived function hiding a virtual | |||
8028 | // function from a base class. These cases may be better served by a | |||
8029 | // warning (not specific to virtual functions) on call sites when the | |||
8030 | // call would select a different function from the base class, were it | |||
8031 | // visible. | |||
8032 | // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. | |||
8033 | if (!S->IsOverload(Method, MD, false)) | |||
8034 | return true; | |||
8035 | // Collect the overload only if its hidden. | |||
8036 | if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) | |||
8037 | overloadedMethods.push_back(MD); | |||
8038 | } | |||
8039 | } | |||
8040 | ||||
8041 | if (foundSameNameMethod) | |||
8042 | OverloadedMethods.append(overloadedMethods.begin(), | |||
8043 | overloadedMethods.end()); | |||
8044 | return foundSameNameMethod; | |||
8045 | } | |||
8046 | }; | |||
8047 | } // end anonymous namespace | |||
8048 | ||||
8049 | /// Add the most overriden methods from MD to Methods | |||
8050 | static void AddMostOverridenMethods(const CXXMethodDecl *MD, | |||
8051 | llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { | |||
8052 | if (MD->size_overridden_methods() == 0) | |||
8053 | Methods.insert(MD->getCanonicalDecl()); | |||
8054 | else | |||
8055 | for (const CXXMethodDecl *O : MD->overridden_methods()) | |||
8056 | AddMostOverridenMethods(O, Methods); | |||
8057 | } | |||
8058 | ||||
8059 | /// Check if a method overloads virtual methods in a base class without | |||
8060 | /// overriding any. | |||
8061 | void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, | |||
8062 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { | |||
8063 | if (!MD->getDeclName().isIdentifier()) | |||
8064 | return; | |||
8065 | ||||
8066 | CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. | |||
8067 | /*bool RecordPaths=*/false, | |||
8068 | /*bool DetectVirtual=*/false); | |||
8069 | FindHiddenVirtualMethod FHVM; | |||
8070 | FHVM.Method = MD; | |||
8071 | FHVM.S = this; | |||
8072 | ||||
8073 | // Keep the base methods that were overridden or introduced in the subclass | |||
8074 | // by 'using' in a set. A base method not in this set is hidden. | |||
8075 | CXXRecordDecl *DC = MD->getParent(); | |||
8076 | DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); | |||
8077 | for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { | |||
8078 | NamedDecl *ND = *I; | |||
8079 | if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) | |||
8080 | ND = shad->getTargetDecl(); | |||
8081 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) | |||
8082 | AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); | |||
8083 | } | |||
8084 | ||||
8085 | if (DC->lookupInBases(FHVM, Paths)) | |||
8086 | OverloadedMethods = FHVM.OverloadedMethods; | |||
8087 | } | |||
8088 | ||||
8089 | void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, | |||
8090 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { | |||
8091 | for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { | |||
8092 | CXXMethodDecl *overloadedMD = OverloadedMethods[i]; | |||
8093 | PartialDiagnostic PD = PDiag( | |||
8094 | diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; | |||
8095 | HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); | |||
8096 | Diag(overloadedMD->getLocation(), PD); | |||
8097 | } | |||
8098 | } | |||
8099 | ||||
8100 | /// Diagnose methods which overload virtual methods in a base class | |||
8101 | /// without overriding any. | |||
8102 | void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { | |||
8103 | if (MD->isInvalidDecl()) | |||
8104 | return; | |||
8105 | ||||
8106 | if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) | |||
8107 | return; | |||
8108 | ||||
8109 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; | |||
8110 | FindHiddenVirtualMethods(MD, OverloadedMethods); | |||
8111 | if (!OverloadedMethods.empty()) { | |||
8112 | Diag(MD->getLocation(), diag::warn_overloaded_virtual) | |||
8113 | << MD << (OverloadedMethods.size() > 1); | |||
8114 | ||||
8115 | NoteHiddenVirtualMethods(MD, OverloadedMethods); | |||
8116 | } | |||
8117 | } | |||
8118 | ||||
8119 | void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { | |||
8120 | auto PrintDiagAndRemoveAttr = [&]() { | |||
8121 | // No diagnostics if this is a template instantiation. | |||
8122 | if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) | |||
8123 | Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), | |||
8124 | diag::ext_cannot_use_trivial_abi) << &RD; | |||
8125 | RD.dropAttr<TrivialABIAttr>(); | |||
8126 | }; | |||
8127 | ||||
8128 | // Ill-formed if the struct has virtual functions. | |||
8129 | if (RD.isPolymorphic()) { | |||
8130 | PrintDiagAndRemoveAttr(); | |||
8131 | return; | |||
8132 | } | |||
8133 | ||||
8134 | for (const auto &B : RD.bases()) { | |||
8135 | // Ill-formed if the base class is non-trivial for the purpose of calls or a | |||
8136 | // virtual base. | |||
8137 | if ((!B.getType()->isDependentType() && | |||
8138 | !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || | |||
8139 | B.isVirtual()) { | |||
8140 | PrintDiagAndRemoveAttr(); | |||
8141 | return; | |||
8142 | } | |||
8143 | } | |||
8144 | ||||
8145 | for (const auto *FD : RD.fields()) { | |||
8146 | // Ill-formed if the field is an ObjectiveC pointer or of a type that is | |||
8147 | // non-trivial for the purpose of calls. | |||
8148 | QualType FT = FD->getType(); | |||
8149 | if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { | |||
8150 | PrintDiagAndRemoveAttr(); | |||
8151 | return; | |||
8152 | } | |||
8153 | ||||
8154 | if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) | |||
8155 | if (!RT->isDependentType() && | |||
8156 | !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { | |||
8157 | PrintDiagAndRemoveAttr(); | |||
8158 | return; | |||
8159 | } | |||
8160 | } | |||
8161 | } | |||
8162 | ||||
8163 | void Sema::ActOnFinishCXXMemberSpecification( | |||
8164 | Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, | |||
8165 | SourceLocation RBrac, const ParsedAttributesView &AttrList) { | |||
8166 | if (!TagDecl) | |||
8167 | return; | |||
8168 | ||||
8169 | AdjustDeclIfTemplate(TagDecl); | |||
8170 | ||||
8171 | for (const ParsedAttr &AL : AttrList) { | |||
8172 | if (AL.getKind() != ParsedAttr::AT_Visibility) | |||
8173 | continue; | |||
8174 | AL.setInvalid(); | |||
8175 | Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; | |||
8176 | } | |||
8177 | ||||
8178 | ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( | |||
8179 | // strict aliasing violation! | |||
8180 | reinterpret_cast<Decl**>(FieldCollector->getCurFields()), | |||
8181 | FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); | |||
8182 | ||||
8183 | CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl)); | |||
8184 | } | |||
8185 | ||||
8186 | /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared | |||
8187 | /// special functions, such as the default constructor, copy | |||
8188 | /// constructor, or destructor, to the given C++ class (C++ | |||
8189 | /// [special]p1). This routine can only be executed just before the | |||
8190 | /// definition of the class is complete. | |||
8191 | void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { | |||
8192 | if (ClassDecl->needsImplicitDefaultConstructor()) { | |||
8193 | ++getASTContext().NumImplicitDefaultConstructors; | |||
8194 | ||||
8195 | if (ClassDecl->hasInheritedConstructor()) | |||
8196 | DeclareImplicitDefaultConstructor(ClassDecl); | |||
8197 | } | |||
8198 | ||||
8199 | if (ClassDecl->needsImplicitCopyConstructor()) { | |||
8200 | ++getASTContext().NumImplicitCopyConstructors; | |||
8201 | ||||
8202 | // If the properties or semantics of the copy constructor couldn't be | |||
8203 | // determined while the class was being declared, force a declaration | |||
8204 | // of it now. | |||
8205 | if (ClassDecl->needsOverloadResolutionForCopyConstructor() || | |||
8206 | ClassDecl->hasInheritedConstructor()) | |||
8207 | DeclareImplicitCopyConstructor(ClassDecl); | |||
8208 | // For the MS ABI we need to know whether the copy ctor is deleted. A | |||
8209 | // prerequisite for deleting the implicit copy ctor is that the class has a | |||
8210 | // move ctor or move assignment that is either user-declared or whose | |||
8211 | // semantics are inherited from a subobject. FIXME: We should provide a more | |||
8212 | // direct way for CodeGen to ask whether the constructor was deleted. | |||
8213 | else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | |||
8214 | (ClassDecl->hasUserDeclaredMoveConstructor() || | |||
8215 | ClassDecl->needsOverloadResolutionForMoveConstructor() || | |||
8216 | ClassDecl->hasUserDeclaredMoveAssignment() || | |||
8217 | ClassDecl->needsOverloadResolutionForMoveAssignment())) | |||
8218 | DeclareImplicitCopyConstructor(ClassDecl); | |||
8219 | } | |||
8220 | ||||
8221 | if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { | |||
8222 | ++getASTContext().NumImplicitMoveConstructors; | |||
8223 | ||||
8224 | if (ClassDecl->needsOverloadResolutionForMoveConstructor() || | |||
8225 | ClassDecl->hasInheritedConstructor()) | |||
8226 | DeclareImplicitMoveConstructor(ClassDecl); | |||
8227 | } | |||
8228 | ||||
8229 | if (ClassDecl->needsImplicitCopyAssignment()) { | |||
8230 | ++getASTContext().NumImplicitCopyAssignmentOperators; | |||
8231 | ||||
8232 | // If we have a dynamic class, then the copy assignment operator may be | |||
8233 | // virtual, so we have to declare it immediately. This ensures that, e.g., | |||
8234 | // it shows up in the right place in the vtable and that we diagnose | |||
8235 | // problems with the implicit exception specification. | |||
8236 | if (ClassDecl->isDynamicClass() || | |||
8237 | ClassDecl->needsOverloadResolutionForCopyAssignment() || | |||
8238 | ClassDecl->hasInheritedAssignment()) | |||
8239 | DeclareImplicitCopyAssignment(ClassDecl); | |||
8240 | } | |||
8241 | ||||
8242 | if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { | |||
8243 | ++getASTContext().NumImplicitMoveAssignmentOperators; | |||
8244 | ||||
8245 | // Likewise for the move assignment operator. | |||
8246 | if (ClassDecl->isDynamicClass() || | |||
8247 | ClassDecl->needsOverloadResolutionForMoveAssignment() || | |||
8248 | ClassDecl->hasInheritedAssignment()) | |||
8249 | DeclareImplicitMoveAssignment(ClassDecl); | |||
8250 | } | |||
8251 | ||||
8252 | if (ClassDecl->needsImplicitDestructor()) { | |||
8253 | ++getASTContext().NumImplicitDestructors; | |||
8254 | ||||
8255 | // If we have a dynamic class, then the destructor may be virtual, so we | |||
8256 | // have to declare the destructor immediately. This ensures that, e.g., it | |||
8257 | // shows up in the right place in the vtable and that we diagnose problems | |||
8258 | // with the implicit exception specification. | |||
8259 | if (ClassDecl->isDynamicClass() || | |||
8260 | ClassDecl->needsOverloadResolutionForDestructor()) | |||
8261 | DeclareImplicitDestructor(ClassDecl); | |||
8262 | } | |||
8263 | } | |||
8264 | ||||
8265 | unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { | |||
8266 | if (!D) | |||
8267 | return 0; | |||
8268 | ||||
8269 | // The order of template parameters is not important here. All names | |||
8270 | // get added to the same scope. | |||
8271 | SmallVector<TemplateParameterList *, 4> ParameterLists; | |||
8272 | ||||
8273 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) | |||
8274 | D = TD->getTemplatedDecl(); | |||
8275 | ||||
8276 | if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) | |||
8277 | ParameterLists.push_back(PSD->getTemplateParameters()); | |||
8278 | ||||
8279 | if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { | |||
8280 | for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) | |||
8281 | ParameterLists.push_back(DD->getTemplateParameterList(i)); | |||
8282 | ||||
8283 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
8284 | if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) | |||
8285 | ParameterLists.push_back(FTD->getTemplateParameters()); | |||
8286 | } | |||
8287 | } | |||
8288 | ||||
8289 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) { | |||
8290 | for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) | |||
8291 | ParameterLists.push_back(TD->getTemplateParameterList(i)); | |||
8292 | ||||
8293 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { | |||
8294 | if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) | |||
8295 | ParameterLists.push_back(CTD->getTemplateParameters()); | |||
8296 | } | |||
8297 | } | |||
8298 | ||||
8299 | unsigned Count = 0; | |||
8300 | for (TemplateParameterList *Params : ParameterLists) { | |||
8301 | if (Params->size() > 0) | |||
8302 | // Ignore explicit specializations; they don't contribute to the template | |||
8303 | // depth. | |||
8304 | ++Count; | |||
8305 | for (NamedDecl *Param : *Params) { | |||
8306 | if (Param->getDeclName()) { | |||
8307 | S->AddDecl(Param); | |||
8308 | IdResolver.AddDecl(Param); | |||
8309 | } | |||
8310 | } | |||
8311 | } | |||
8312 | ||||
8313 | return Count; | |||
8314 | } | |||
8315 | ||||
8316 | void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { | |||
8317 | if (!RecordD) return; | |||
8318 | AdjustDeclIfTemplate(RecordD); | |||
8319 | CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); | |||
8320 | PushDeclContext(S, Record); | |||
8321 | } | |||
8322 | ||||
8323 | void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { | |||
8324 | if (!RecordD) return; | |||
8325 | PopDeclContext(); | |||
8326 | } | |||
8327 | ||||
8328 | /// This is used to implement the constant expression evaluation part of the | |||
8329 | /// attribute enable_if extension. There is nothing in standard C++ which would | |||
8330 | /// require reentering parameters. | |||
8331 | void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { | |||
8332 | if (!Param) | |||
8333 | return; | |||
8334 | ||||
8335 | S->AddDecl(Param); | |||
8336 | if (Param->getDeclName()) | |||
8337 | IdResolver.AddDecl(Param); | |||
8338 | } | |||
8339 | ||||
8340 | /// ActOnStartDelayedCXXMethodDeclaration - We have completed | |||
8341 | /// parsing a top-level (non-nested) C++ class, and we are now | |||
8342 | /// parsing those parts of the given Method declaration that could | |||
8343 | /// not be parsed earlier (C++ [class.mem]p2), such as default | |||
8344 | /// arguments. This action should enter the scope of the given | |||
8345 | /// Method declaration as if we had just parsed the qualified method | |||
8346 | /// name. However, it should not bring the parameters into scope; | |||
8347 | /// that will be performed by ActOnDelayedCXXMethodParameter. | |||
8348 | void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { | |||
8349 | } | |||
8350 | ||||
8351 | /// ActOnDelayedCXXMethodParameter - We've already started a delayed | |||
8352 | /// C++ method declaration. We're (re-)introducing the given | |||
8353 | /// function parameter into scope for use in parsing later parts of | |||
8354 | /// the method declaration. For example, we could see an | |||
8355 | /// ActOnParamDefaultArgument event for this parameter. | |||
8356 | void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { | |||
8357 | if (!ParamD) | |||
8358 | return; | |||
8359 | ||||
8360 | ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); | |||
8361 | ||||
8362 | // If this parameter has an unparsed default argument, clear it out | |||
8363 | // to make way for the parsed default argument. | |||
8364 | if (Param->hasUnparsedDefaultArg()) | |||
8365 | Param->setDefaultArg(nullptr); | |||
8366 | ||||
8367 | S->AddDecl(Param); | |||
8368 | if (Param->getDeclName()) | |||
8369 | IdResolver.AddDecl(Param); | |||
8370 | } | |||
8371 | ||||
8372 | /// ActOnFinishDelayedCXXMethodDeclaration - We have finished | |||
8373 | /// processing the delayed method declaration for Method. The method | |||
8374 | /// declaration is now considered finished. There may be a separate | |||
8375 | /// ActOnStartOfFunctionDef action later (not necessarily | |||
8376 | /// immediately!) for this method, if it was also defined inside the | |||
8377 | /// class body. | |||
8378 | void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { | |||
8379 | if (!MethodD) | |||
8380 | return; | |||
8381 | ||||
8382 | AdjustDeclIfTemplate(MethodD); | |||
8383 | ||||
8384 | FunctionDecl *Method = cast<FunctionDecl>(MethodD); | |||
8385 | ||||
8386 | // Now that we have our default arguments, check the constructor | |||
8387 | // again. It could produce additional diagnostics or affect whether | |||
8388 | // the class has implicitly-declared destructors, among other | |||
8389 | // things. | |||
8390 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) | |||
8391 | CheckConstructor(Constructor); | |||
8392 | ||||
8393 | // Check the default arguments, which we may have added. | |||
8394 | if (!Method->isInvalidDecl()) | |||
8395 | CheckCXXDefaultArguments(Method); | |||
8396 | } | |||
8397 | ||||
8398 | // Emit the given diagnostic for each non-address-space qualifier. | |||
8399 | // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. | |||
8400 | static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { | |||
8401 | const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | |||
8402 | if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { | |||
8403 | bool DiagOccured = false; | |||
8404 | FTI.MethodQualifiers->forEachQualifier( | |||
8405 | [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, | |||
8406 | SourceLocation SL) { | |||
8407 | // This diagnostic should be emitted on any qualifier except an addr | |||
8408 | // space qualifier. However, forEachQualifier currently doesn't visit | |||
8409 | // addr space qualifiers, so there's no way to write this condition | |||
8410 | // right now; we just diagnose on everything. | |||
8411 | S.Diag(SL, DiagID) << QualName << SourceRange(SL); | |||
8412 | DiagOccured = true; | |||
8413 | }); | |||
8414 | if (DiagOccured) | |||
8415 | D.setInvalidType(); | |||
8416 | } | |||
8417 | } | |||
8418 | ||||
8419 | /// CheckConstructorDeclarator - Called by ActOnDeclarator to check | |||
8420 | /// the well-formedness of the constructor declarator @p D with type @p | |||
8421 | /// R. If there are any errors in the declarator, this routine will | |||
8422 | /// emit diagnostics and set the invalid bit to true. In any case, the type | |||
8423 | /// will be updated to reflect a well-formed type for the constructor and | |||
8424 | /// returned. | |||
8425 | QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, | |||
8426 | StorageClass &SC) { | |||
8427 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); | |||
8428 | ||||
8429 | // C++ [class.ctor]p3: | |||
8430 | // A constructor shall not be virtual (10.3) or static (9.4). A | |||
8431 | // constructor can be invoked for a const, volatile or const | |||
8432 | // volatile object. A constructor shall not be declared const, | |||
8433 | // volatile, or const volatile (9.3.2). | |||
8434 | if (isVirtual) { | |||
8435 | if (!D.isInvalidType()) | |||
8436 | Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) | |||
8437 | << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) | |||
8438 | << SourceRange(D.getIdentifierLoc()); | |||
8439 | D.setInvalidType(); | |||
8440 | } | |||
8441 | if (SC == SC_Static) { | |||
8442 | if (!D.isInvalidType()) | |||
8443 | Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) | |||
8444 | << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) | |||
8445 | << SourceRange(D.getIdentifierLoc()); | |||
8446 | D.setInvalidType(); | |||
8447 | SC = SC_None; | |||
8448 | } | |||
8449 | ||||
8450 | if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { | |||
8451 | diagnoseIgnoredQualifiers( | |||
8452 | diag::err_constructor_return_type, TypeQuals, SourceLocation(), | |||
8453 | D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), | |||
8454 | D.getDeclSpec().getRestrictSpecLoc(), | |||
8455 | D.getDeclSpec().getAtomicSpecLoc()); | |||
8456 | D.setInvalidType(); | |||
8457 | } | |||
8458 | ||||
8459 | checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); | |||
8460 | ||||
8461 | // C++0x [class.ctor]p4: | |||
8462 | // A constructor shall not be declared with a ref-qualifier. | |||
8463 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | |||
8464 | if (FTI.hasRefQualifier()) { | |||
8465 | Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) | |||
8466 | << FTI.RefQualifierIsLValueRef | |||
8467 | << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); | |||
8468 | D.setInvalidType(); | |||
8469 | } | |||
8470 | ||||
8471 | // Rebuild the function type "R" without any type qualifiers (in | |||
8472 | // case any of the errors above fired) and with "void" as the | |||
8473 | // return type, since constructors don't have return types. | |||
8474 | const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); | |||
8475 | if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) | |||
8476 | return R; | |||
8477 | ||||
8478 | FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); | |||
8479 | EPI.TypeQuals = Qualifiers(); | |||
8480 | EPI.RefQualifier = RQ_None; | |||
8481 | ||||
8482 | return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); | |||
8483 | } | |||
8484 | ||||
8485 | /// CheckConstructor - Checks a fully-formed constructor for | |||
8486 | /// well-formedness, issuing any diagnostics required. Returns true if | |||
8487 | /// the constructor declarator is invalid. | |||
8488 | void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { | |||
8489 | CXXRecordDecl *ClassDecl | |||
8490 | = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); | |||
8491 | if (!ClassDecl) | |||
8492 | return Constructor->setInvalidDecl(); | |||
8493 | ||||
8494 | // C++ [class.copy]p3: | |||
8495 | // A declaration of a constructor for a class X is ill-formed if | |||
8496 | // its first parameter is of type (optionally cv-qualified) X and | |||
8497 | // either there are no other parameters or else all other | |||
8498 | // parameters have default arguments. | |||
8499 | if (!Constructor->isInvalidDecl() && | |||
8500 | ((Constructor->getNumParams() == 1) || | |||
8501 | (Constructor->getNumParams() > 1 && | |||
8502 | Constructor->getParamDecl(1)->hasDefaultArg())) && | |||
8503 | Constructor->getTemplateSpecializationKind() | |||
8504 | != TSK_ImplicitInstantiation) { | |||
8505 | QualType ParamType = Constructor->getParamDecl(0)->getType(); | |||
8506 | QualType ClassTy = Context.getTagDeclType(ClassDecl); | |||
8507 | if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { | |||
8508 | SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); | |||
8509 | const char *ConstRef | |||
8510 | = Constructor->getParamDecl(0)->getIdentifier() ? "const &" | |||
8511 | : " const &"; | |||
8512 | Diag(ParamLoc, diag::err_constructor_byvalue_arg) | |||
8513 | << FixItHint::CreateInsertion(ParamLoc, ConstRef); | |||
8514 | ||||
8515 | // FIXME: Rather that making the constructor invalid, we should endeavor | |||
8516 | // to fix the type. | |||
8517 | Constructor->setInvalidDecl(); | |||
8518 | } | |||
8519 | } | |||
8520 | } | |||
8521 | ||||
8522 | /// CheckDestructor - Checks a fully-formed destructor definition for | |||
8523 | /// well-formedness, issuing any diagnostics required. Returns true | |||
8524 | /// on error. | |||
8525 | bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { | |||
8526 | CXXRecordDecl *RD = Destructor->getParent(); | |||
8527 | ||||
8528 | if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { | |||
8529 | SourceLocation Loc; | |||
8530 | ||||
8531 | if (!Destructor->isImplicit()) | |||
8532 | Loc = Destructor->getLocation(); | |||
8533 | else | |||
8534 | Loc = RD->getLocation(); | |||
8535 | ||||
8536 | // If we have a virtual destructor, look up the deallocation function | |||
8537 | if (FunctionDecl *OperatorDelete = | |||
8538 | FindDeallocationFunctionForDestructor(Loc, RD)) { | |||
8539 | Expr *ThisArg = nullptr; | |||
8540 | ||||
8541 | // If the notional 'delete this' expression requires a non-trivial | |||
8542 | // conversion from 'this' to the type of a destroying operator delete's | |||
8543 | // first parameter, perform that conversion now. | |||
8544 | if (OperatorDelete->isDestroyingOperatorDelete()) { | |||
8545 | QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); | |||
8546 | if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { | |||
8547 | // C++ [class.dtor]p13: | |||
8548 | // ... as if for the expression 'delete this' appearing in a | |||
8549 | // non-virtual destructor of the destructor's class. | |||
8550 | ContextRAII SwitchContext(*this, Destructor); | |||
8551 | ExprResult This = | |||
8552 | ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); | |||
8553 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8553, __PRETTY_FUNCTION__)); | |||
8554 | This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); | |||
8555 | if (This.isInvalid()) { | |||
8556 | // FIXME: Register this as a context note so that it comes out | |||
8557 | // in the right order. | |||
8558 | Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); | |||
8559 | return true; | |||
8560 | } | |||
8561 | ThisArg = This.get(); | |||
8562 | } | |||
8563 | } | |||
8564 | ||||
8565 | DiagnoseUseOfDecl(OperatorDelete, Loc); | |||
8566 | MarkFunctionReferenced(Loc, OperatorDelete); | |||
8567 | Destructor->setOperatorDelete(OperatorDelete, ThisArg); | |||
8568 | } | |||
8569 | } | |||
8570 | ||||
8571 | return false; | |||
8572 | } | |||
8573 | ||||
8574 | /// CheckDestructorDeclarator - Called by ActOnDeclarator to check | |||
8575 | /// the well-formednes of the destructor declarator @p D with type @p | |||
8576 | /// R. If there are any errors in the declarator, this routine will | |||
8577 | /// emit diagnostics and set the declarator to invalid. Even if this happens, | |||
8578 | /// will be updated to reflect a well-formed type for the destructor and | |||
8579 | /// returned. | |||
8580 | QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, | |||
8581 | StorageClass& SC) { | |||
8582 | // C++ [class.dtor]p1: | |||
8583 | // [...] A typedef-name that names a class is a class-name | |||
8584 | // (7.1.3); however, a typedef-name that names a class shall not | |||
8585 | // be used as the identifier in the declarator for a destructor | |||
8586 | // declaration. | |||
8587 | QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); | |||
8588 | if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) | |||
8589 | Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) | |||
8590 | << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); | |||
8591 | else if (const TemplateSpecializationType *TST = | |||
8592 | DeclaratorType->getAs<TemplateSpecializationType>()) | |||
8593 | if (TST->isTypeAlias()) | |||
8594 | Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) | |||
8595 | << DeclaratorType << 1; | |||
8596 | ||||
8597 | // C++ [class.dtor]p2: | |||
8598 | // A destructor is used to destroy objects of its class type. A | |||
8599 | // destructor takes no parameters, and no return type can be | |||
8600 | // specified for it (not even void). The address of a destructor | |||
8601 | // shall not be taken. A destructor shall not be static. A | |||
8602 | // destructor can be invoked for a const, volatile or const | |||
8603 | // volatile object. A destructor shall not be declared const, | |||
8604 | // volatile or const volatile (9.3.2). | |||
8605 | if (SC == SC_Static) { | |||
8606 | if (!D.isInvalidType()) | |||
8607 | Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) | |||
8608 | << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) | |||
8609 | << SourceRange(D.getIdentifierLoc()) | |||
8610 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
8611 | ||||
8612 | SC = SC_None; | |||
8613 | } | |||
8614 | if (!D.isInvalidType()) { | |||
8615 | // Destructors don't have return types, but the parser will | |||
8616 | // happily parse something like: | |||
8617 | // | |||
8618 | // class X { | |||
8619 | // float ~X(); | |||
8620 | // }; | |||
8621 | // | |||
8622 | // The return type will be eliminated later. | |||
8623 | if (D.getDeclSpec().hasTypeSpecifier()) | |||
8624 | Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) | |||
8625 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | |||
8626 | << SourceRange(D.getIdentifierLoc()); | |||
8627 | else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { | |||
8628 | diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, | |||
8629 | SourceLocation(), | |||
8630 | D.getDeclSpec().getConstSpecLoc(), | |||
8631 | D.getDeclSpec().getVolatileSpecLoc(), | |||
8632 | D.getDeclSpec().getRestrictSpecLoc(), | |||
8633 | D.getDeclSpec().getAtomicSpecLoc()); | |||
8634 | D.setInvalidType(); | |||
8635 | } | |||
8636 | } | |||
8637 | ||||
8638 | checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); | |||
8639 | ||||
8640 | // C++0x [class.dtor]p2: | |||
8641 | // A destructor shall not be declared with a ref-qualifier. | |||
8642 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | |||
8643 | if (FTI.hasRefQualifier()) { | |||
8644 | Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) | |||
8645 | << FTI.RefQualifierIsLValueRef | |||
8646 | << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); | |||
8647 | D.setInvalidType(); | |||
8648 | } | |||
8649 | ||||
8650 | // Make sure we don't have any parameters. | |||
8651 | if (FTIHasNonVoidParameters(FTI)) { | |||
8652 | Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); | |||
8653 | ||||
8654 | // Delete the parameters. | |||
8655 | FTI.freeParams(); | |||
8656 | D.setInvalidType(); | |||
8657 | } | |||
8658 | ||||
8659 | // Make sure the destructor isn't variadic. | |||
8660 | if (FTI.isVariadic) { | |||
8661 | Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); | |||
8662 | D.setInvalidType(); | |||
8663 | } | |||
8664 | ||||
8665 | // Rebuild the function type "R" without any type qualifiers or | |||
8666 | // parameters (in case any of the errors above fired) and with | |||
8667 | // "void" as the return type, since destructors don't have return | |||
8668 | // types. | |||
8669 | if (!D.isInvalidType()) | |||
8670 | return R; | |||
8671 | ||||
8672 | const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); | |||
8673 | FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); | |||
8674 | EPI.Variadic = false; | |||
8675 | EPI.TypeQuals = Qualifiers(); | |||
8676 | EPI.RefQualifier = RQ_None; | |||
8677 | return Context.getFunctionType(Context.VoidTy, None, EPI); | |||
8678 | } | |||
8679 | ||||
8680 | static void extendLeft(SourceRange &R, SourceRange Before) { | |||
8681 | if (Before.isInvalid()) | |||
8682 | return; | |||
8683 | R.setBegin(Before.getBegin()); | |||
8684 | if (R.getEnd().isInvalid()) | |||
8685 | R.setEnd(Before.getEnd()); | |||
8686 | } | |||
8687 | ||||
8688 | static void extendRight(SourceRange &R, SourceRange After) { | |||
8689 | if (After.isInvalid()) | |||
8690 | return; | |||
8691 | if (R.getBegin().isInvalid()) | |||
8692 | R.setBegin(After.getBegin()); | |||
8693 | R.setEnd(After.getEnd()); | |||
8694 | } | |||
8695 | ||||
8696 | /// CheckConversionDeclarator - Called by ActOnDeclarator to check the | |||
8697 | /// well-formednes of the conversion function declarator @p D with | |||
8698 | /// type @p R. If there are any errors in the declarator, this routine | |||
8699 | /// will emit diagnostics and return true. Otherwise, it will return | |||
8700 | /// false. Either way, the type @p R will be updated to reflect a | |||
8701 | /// well-formed type for the conversion operator. | |||
8702 | void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, | |||
8703 | StorageClass& SC) { | |||
8704 | // C++ [class.conv.fct]p1: | |||
8705 | // Neither parameter types nor return type can be specified. The | |||
8706 | // type of a conversion function (8.3.5) is "function taking no | |||
8707 | // parameter returning conversion-type-id." | |||
8708 | if (SC == SC_Static) { | |||
8709 | if (!D.isInvalidType()) | |||
8710 | Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) | |||
8711 | << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) | |||
8712 | << D.getName().getSourceRange(); | |||
8713 | D.setInvalidType(); | |||
8714 | SC = SC_None; | |||
8715 | } | |||
8716 | ||||
8717 | TypeSourceInfo *ConvTSI = nullptr; | |||
8718 | QualType ConvType = | |||
8719 | GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); | |||
8720 | ||||
8721 | const DeclSpec &DS = D.getDeclSpec(); | |||
8722 | if (DS.hasTypeSpecifier() && !D.isInvalidType()) { | |||
8723 | // Conversion functions don't have return types, but the parser will | |||
8724 | // happily parse something like: | |||
8725 | // | |||
8726 | // class X { | |||
8727 | // float operator bool(); | |||
8728 | // }; | |||
8729 | // | |||
8730 | // The return type will be changed later anyway. | |||
8731 | Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) | |||
8732 | << SourceRange(DS.getTypeSpecTypeLoc()) | |||
8733 | << SourceRange(D.getIdentifierLoc()); | |||
8734 | D.setInvalidType(); | |||
8735 | } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { | |||
8736 | // It's also plausible that the user writes type qualifiers in the wrong | |||
8737 | // place, such as: | |||
8738 | // struct S { const operator int(); }; | |||
8739 | // FIXME: we could provide a fixit to move the qualifiers onto the | |||
8740 | // conversion type. | |||
8741 | Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) | |||
8742 | << SourceRange(D.getIdentifierLoc()) << 0; | |||
8743 | D.setInvalidType(); | |||
8744 | } | |||
8745 | ||||
8746 | const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); | |||
8747 | ||||
8748 | // Make sure we don't have any parameters. | |||
8749 | if (Proto->getNumParams() > 0) { | |||
8750 | Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); | |||
8751 | ||||
8752 | // Delete the parameters. | |||
8753 | D.getFunctionTypeInfo().freeParams(); | |||
8754 | D.setInvalidType(); | |||
8755 | } else if (Proto->isVariadic()) { | |||
8756 | Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); | |||
8757 | D.setInvalidType(); | |||
8758 | } | |||
8759 | ||||
8760 | // Diagnose "&operator bool()" and other such nonsense. This | |||
8761 | // is actually a gcc extension which we don't support. | |||
8762 | if (Proto->getReturnType() != ConvType) { | |||
8763 | bool NeedsTypedef = false; | |||
8764 | SourceRange Before, After; | |||
8765 | ||||
8766 | // Walk the chunks and extract information on them for our diagnostic. | |||
8767 | bool PastFunctionChunk = false; | |||
8768 | for (auto &Chunk : D.type_objects()) { | |||
8769 | switch (Chunk.Kind) { | |||
8770 | case DeclaratorChunk::Function: | |||
8771 | if (!PastFunctionChunk) { | |||
8772 | if (Chunk.Fun.HasTrailingReturnType) { | |||
8773 | TypeSourceInfo *TRT = nullptr; | |||
8774 | GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); | |||
8775 | if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); | |||
8776 | } | |||
8777 | PastFunctionChunk = true; | |||
8778 | break; | |||
8779 | } | |||
8780 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
8781 | case DeclaratorChunk::Array: | |||
8782 | NeedsTypedef = true; | |||
8783 | extendRight(After, Chunk.getSourceRange()); | |||
8784 | break; | |||
8785 | ||||
8786 | case DeclaratorChunk::Pointer: | |||
8787 | case DeclaratorChunk::BlockPointer: | |||
8788 | case DeclaratorChunk::Reference: | |||
8789 | case DeclaratorChunk::MemberPointer: | |||
8790 | case DeclaratorChunk::Pipe: | |||
8791 | extendLeft(Before, Chunk.getSourceRange()); | |||
8792 | break; | |||
8793 | ||||
8794 | case DeclaratorChunk::Paren: | |||
8795 | extendLeft(Before, Chunk.Loc); | |||
8796 | extendRight(After, Chunk.EndLoc); | |||
8797 | break; | |||
8798 | } | |||
8799 | } | |||
8800 | ||||
8801 | SourceLocation Loc = Before.isValid() ? Before.getBegin() : | |||
8802 | After.isValid() ? After.getBegin() : | |||
8803 | D.getIdentifierLoc(); | |||
8804 | auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); | |||
8805 | DB << Before << After; | |||
8806 | ||||
8807 | if (!NeedsTypedef) { | |||
8808 | DB << /*don't need a typedef*/0; | |||
8809 | ||||
8810 | // If we can provide a correct fix-it hint, do so. | |||
8811 | if (After.isInvalid() && ConvTSI) { | |||
8812 | SourceLocation InsertLoc = | |||
8813 | getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); | |||
8814 | DB << FixItHint::CreateInsertion(InsertLoc, " ") | |||
8815 | << FixItHint::CreateInsertionFromRange( | |||
8816 | InsertLoc, CharSourceRange::getTokenRange(Before)) | |||
8817 | << FixItHint::CreateRemoval(Before); | |||
8818 | } | |||
8819 | } else if (!Proto->getReturnType()->isDependentType()) { | |||
8820 | DB << /*typedef*/1 << Proto->getReturnType(); | |||
8821 | } else if (getLangOpts().CPlusPlus11) { | |||
8822 | DB << /*alias template*/2 << Proto->getReturnType(); | |||
8823 | } else { | |||
8824 | DB << /*might not be fixable*/3; | |||
8825 | } | |||
8826 | ||||
8827 | // Recover by incorporating the other type chunks into the result type. | |||
8828 | // Note, this does *not* change the name of the function. This is compatible | |||
8829 | // with the GCC extension: | |||
8830 | // struct S { &operator int(); } s; | |||
8831 | // int &r = s.operator int(); // ok in GCC | |||
8832 | // S::operator int&() {} // error in GCC, function name is 'operator int'. | |||
8833 | ConvType = Proto->getReturnType(); | |||
8834 | } | |||
8835 | ||||
8836 | // C++ [class.conv.fct]p4: | |||
8837 | // The conversion-type-id shall not represent a function type nor | |||
8838 | // an array type. | |||
8839 | if (ConvType->isArrayType()) { | |||
8840 | Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); | |||
8841 | ConvType = Context.getPointerType(ConvType); | |||
8842 | D.setInvalidType(); | |||
8843 | } else if (ConvType->isFunctionType()) { | |||
8844 | Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); | |||
8845 | ConvType = Context.getPointerType(ConvType); | |||
8846 | D.setInvalidType(); | |||
8847 | } | |||
8848 | ||||
8849 | // Rebuild the function type "R" without any parameters (in case any | |||
8850 | // of the errors above fired) and with the conversion type as the | |||
8851 | // return type. | |||
8852 | if (D.isInvalidType()) | |||
8853 | R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); | |||
8854 | ||||
8855 | // C++0x explicit conversion operators. | |||
8856 | if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a) | |||
8857 | Diag(DS.getExplicitSpecLoc(), | |||
8858 | getLangOpts().CPlusPlus11 | |||
8859 | ? diag::warn_cxx98_compat_explicit_conversion_functions | |||
8860 | : diag::ext_explicit_conversion_functions) | |||
8861 | << SourceRange(DS.getExplicitSpecRange()); | |||
8862 | } | |||
8863 | ||||
8864 | /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete | |||
8865 | /// the declaration of the given C++ conversion function. This routine | |||
8866 | /// is responsible for recording the conversion function in the C++ | |||
8867 | /// class, if possible. | |||
8868 | Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { | |||
8869 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8869, __PRETTY_FUNCTION__)); | |||
8870 | ||||
8871 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); | |||
8872 | ||||
8873 | // Make sure we aren't redeclaring the conversion function. | |||
8874 | QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); | |||
8875 | ||||
8876 | // C++ [class.conv.fct]p1: | |||
8877 | // [...] A conversion function is never used to convert a | |||
8878 | // (possibly cv-qualified) object to the (possibly cv-qualified) | |||
8879 | // same object type (or a reference to it), to a (possibly | |||
8880 | // cv-qualified) base class of that type (or a reference to it), | |||
8881 | // or to (possibly cv-qualified) void. | |||
8882 | // FIXME: Suppress this warning if the conversion function ends up being a | |||
8883 | // virtual function that overrides a virtual function in a base class. | |||
8884 | QualType ClassType | |||
8885 | = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); | |||
8886 | if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) | |||
8887 | ConvType = ConvTypeRef->getPointeeType(); | |||
8888 | if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && | |||
8889 | Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) | |||
8890 | /* Suppress diagnostics for instantiations. */; | |||
8891 | else if (ConvType->isRecordType()) { | |||
8892 | ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); | |||
8893 | if (ConvType == ClassType) | |||
8894 | Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) | |||
8895 | << ClassType; | |||
8896 | else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) | |||
8897 | Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) | |||
8898 | << ClassType << ConvType; | |||
8899 | } else if (ConvType->isVoidType()) { | |||
8900 | Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) | |||
8901 | << ClassType << ConvType; | |||
8902 | } | |||
8903 | ||||
8904 | if (FunctionTemplateDecl *ConversionTemplate | |||
8905 | = Conversion->getDescribedFunctionTemplate()) | |||
8906 | return ConversionTemplate; | |||
8907 | ||||
8908 | return Conversion; | |||
8909 | } | |||
8910 | ||||
8911 | namespace { | |||
8912 | /// Utility class to accumulate and print a diagnostic listing the invalid | |||
8913 | /// specifier(s) on a declaration. | |||
8914 | struct BadSpecifierDiagnoser { | |||
8915 | BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) | |||
8916 | : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} | |||
8917 | ~BadSpecifierDiagnoser() { | |||
8918 | Diagnostic << Specifiers; | |||
8919 | } | |||
8920 | ||||
8921 | template<typename T> void check(SourceLocation SpecLoc, T Spec) { | |||
8922 | return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); | |||
8923 | } | |||
8924 | void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { | |||
8925 | return check(SpecLoc, | |||
8926 | DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); | |||
8927 | } | |||
8928 | void check(SourceLocation SpecLoc, const char *Spec) { | |||
8929 | if (SpecLoc.isInvalid()) return; | |||
8930 | Diagnostic << SourceRange(SpecLoc, SpecLoc); | |||
8931 | if (!Specifiers.empty()) Specifiers += " "; | |||
8932 | Specifiers += Spec; | |||
8933 | } | |||
8934 | ||||
8935 | Sema &S; | |||
8936 | Sema::SemaDiagnosticBuilder Diagnostic; | |||
8937 | std::string Specifiers; | |||
8938 | }; | |||
8939 | } | |||
8940 | ||||
8941 | /// Check the validity of a declarator that we parsed for a deduction-guide. | |||
8942 | /// These aren't actually declarators in the grammar, so we need to check that | |||
8943 | /// the user didn't specify any pieces that are not part of the deduction-guide | |||
8944 | /// grammar. | |||
8945 | void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, | |||
8946 | StorageClass &SC) { | |||
8947 | TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); | |||
8948 | TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); | |||
8949 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 8949, __PRETTY_FUNCTION__)); | |||
8950 | ||||
8951 | // C++ [temp.deduct.guide]p3: | |||
8952 | // A deduction-gide shall be declared in the same scope as the | |||
8953 | // corresponding class template. | |||
8954 | if (!CurContext->getRedeclContext()->Equals( | |||
8955 | GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { | |||
8956 | Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) | |||
8957 | << GuidedTemplateDecl; | |||
8958 | Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); | |||
8959 | } | |||
8960 | ||||
8961 | auto &DS = D.getMutableDeclSpec(); | |||
8962 | // We leave 'friend' and 'virtual' to be rejected in the normal way. | |||
8963 | if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || | |||
8964 | DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || | |||
8965 | DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { | |||
8966 | BadSpecifierDiagnoser Diagnoser( | |||
8967 | *this, D.getIdentifierLoc(), | |||
8968 | diag::err_deduction_guide_invalid_specifier); | |||
8969 | ||||
8970 | Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); | |||
8971 | DS.ClearStorageClassSpecs(); | |||
8972 | SC = SC_None; | |||
8973 | ||||
8974 | // 'explicit' is permitted. | |||
8975 | Diagnoser.check(DS.getInlineSpecLoc(), "inline"); | |||
8976 | Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); | |||
8977 | Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); | |||
8978 | DS.ClearConstexprSpec(); | |||
8979 | ||||
8980 | Diagnoser.check(DS.getConstSpecLoc(), "const"); | |||
8981 | Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); | |||
8982 | Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); | |||
8983 | Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); | |||
8984 | Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); | |||
8985 | DS.ClearTypeQualifiers(); | |||
8986 | ||||
8987 | Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); | |||
8988 | Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); | |||
8989 | Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); | |||
8990 | Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); | |||
8991 | DS.ClearTypeSpecType(); | |||
8992 | } | |||
8993 | ||||
8994 | if (D.isInvalidType()) | |||
8995 | return; | |||
8996 | ||||
8997 | // Check the declarator is simple enough. | |||
8998 | bool FoundFunction = false; | |||
8999 | for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { | |||
9000 | if (Chunk.Kind == DeclaratorChunk::Paren) | |||
9001 | continue; | |||
9002 | if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { | |||
9003 | Diag(D.getDeclSpec().getBeginLoc(), | |||
9004 | diag::err_deduction_guide_with_complex_decl) | |||
9005 | << D.getSourceRange(); | |||
9006 | break; | |||
9007 | } | |||
9008 | if (!Chunk.Fun.hasTrailingReturnType()) { | |||
9009 | Diag(D.getName().getBeginLoc(), | |||
9010 | diag::err_deduction_guide_no_trailing_return_type); | |||
9011 | break; | |||
9012 | } | |||
9013 | ||||
9014 | // Check that the return type is written as a specialization of | |||
9015 | // the template specified as the deduction-guide's name. | |||
9016 | ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); | |||
9017 | TypeSourceInfo *TSI = nullptr; | |||
9018 | QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); | |||
9019 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9019, __PRETTY_FUNCTION__)); | |||
9020 | bool AcceptableReturnType = false; | |||
9021 | bool MightInstantiateToSpecialization = false; | |||
9022 | if (auto RetTST = | |||
9023 | TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { | |||
9024 | TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); | |||
9025 | bool TemplateMatches = | |||
9026 | Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); | |||
9027 | if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) | |||
9028 | AcceptableReturnType = true; | |||
9029 | else { | |||
9030 | // This could still instantiate to the right type, unless we know it | |||
9031 | // names the wrong class template. | |||
9032 | auto *TD = SpecifiedName.getAsTemplateDecl(); | |||
9033 | MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && | |||
9034 | !TemplateMatches); | |||
9035 | } | |||
9036 | } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { | |||
9037 | MightInstantiateToSpecialization = true; | |||
9038 | } | |||
9039 | ||||
9040 | if (!AcceptableReturnType) { | |||
9041 | Diag(TSI->getTypeLoc().getBeginLoc(), | |||
9042 | diag::err_deduction_guide_bad_trailing_return_type) | |||
9043 | << GuidedTemplate << TSI->getType() | |||
9044 | << MightInstantiateToSpecialization | |||
9045 | << TSI->getTypeLoc().getSourceRange(); | |||
9046 | } | |||
9047 | ||||
9048 | // Keep going to check that we don't have any inner declarator pieces (we | |||
9049 | // could still have a function returning a pointer to a function). | |||
9050 | FoundFunction = true; | |||
9051 | } | |||
9052 | ||||
9053 | if (D.isFunctionDefinition()) | |||
9054 | Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); | |||
9055 | } | |||
9056 | ||||
9057 | //===----------------------------------------------------------------------===// | |||
9058 | // Namespace Handling | |||
9059 | //===----------------------------------------------------------------------===// | |||
9060 | ||||
9061 | /// Diagnose a mismatch in 'inline' qualifiers when a namespace is | |||
9062 | /// reopened. | |||
9063 | static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, | |||
9064 | SourceLocation Loc, | |||
9065 | IdentifierInfo *II, bool *IsInline, | |||
9066 | NamespaceDecl *PrevNS) { | |||
9067 | assert(*IsInline != PrevNS->isInline())((*IsInline != PrevNS->isInline()) ? static_cast<void> (0) : __assert_fail ("*IsInline != PrevNS->isInline()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9067, __PRETTY_FUNCTION__)); | |||
9068 | ||||
9069 | // HACK: Work around a bug in libstdc++4.6's <atomic>, where | |||
9070 | // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as | |||
9071 | // inline namespaces, with the intention of bringing names into namespace std. | |||
9072 | // | |||
9073 | // We support this just well enough to get that case working; this is not | |||
9074 | // sufficient to support reopening namespaces as inline in general. | |||
9075 | if (*IsInline && II && II->getName().startswith("__atomic") && | |||
9076 | S.getSourceManager().isInSystemHeader(Loc)) { | |||
9077 | // Mark all prior declarations of the namespace as inline. | |||
9078 | for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; | |||
9079 | NS = NS->getPreviousDecl()) | |||
9080 | NS->setInline(*IsInline); | |||
9081 | // Patch up the lookup table for the containing namespace. This isn't really | |||
9082 | // correct, but it's good enough for this particular case. | |||
9083 | for (auto *I : PrevNS->decls()) | |||
9084 | if (auto *ND = dyn_cast<NamedDecl>(I)) | |||
9085 | PrevNS->getParent()->makeDeclVisibleInContext(ND); | |||
9086 | return; | |||
9087 | } | |||
9088 | ||||
9089 | if (PrevNS->isInline()) | |||
9090 | // The user probably just forgot the 'inline', so suggest that it | |||
9091 | // be added back. | |||
9092 | S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) | |||
9093 | << FixItHint::CreateInsertion(KeywordLoc, "inline "); | |||
9094 | else | |||
9095 | S.Diag(Loc, diag::err_inline_namespace_mismatch); | |||
9096 | ||||
9097 | S.Diag(PrevNS->getLocation(), diag::note_previous_definition); | |||
9098 | *IsInline = PrevNS->isInline(); | |||
9099 | } | |||
9100 | ||||
9101 | /// ActOnStartNamespaceDef - This is called at the start of a namespace | |||
9102 | /// definition. | |||
9103 | Decl *Sema::ActOnStartNamespaceDef( | |||
9104 | Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, | |||
9105 | SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, | |||
9106 | const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { | |||
9107 | SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; | |||
9108 | // For anonymous namespace, take the location of the left brace. | |||
9109 | SourceLocation Loc = II ? IdentLoc : LBrace; | |||
9110 | bool IsInline = InlineLoc.isValid(); | |||
9111 | bool IsInvalid = false; | |||
9112 | bool IsStd = false; | |||
9113 | bool AddToKnown = false; | |||
9114 | Scope *DeclRegionScope = NamespcScope->getParent(); | |||
9115 | ||||
9116 | NamespaceDecl *PrevNS = nullptr; | |||
9117 | if (II) { | |||
9118 | // C++ [namespace.def]p2: | |||
9119 | // The identifier in an original-namespace-definition shall not | |||
9120 | // have been previously defined in the declarative region in | |||
9121 | // which the original-namespace-definition appears. The | |||
9122 | // identifier in an original-namespace-definition is the name of | |||
9123 | // the namespace. Subsequently in that declarative region, it is | |||
9124 | // treated as an original-namespace-name. | |||
9125 | // | |||
9126 | // Since namespace names are unique in their scope, and we don't | |||
9127 | // look through using directives, just look for any ordinary names | |||
9128 | // as if by qualified name lookup. | |||
9129 | LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, | |||
9130 | ForExternalRedeclaration); | |||
9131 | LookupQualifiedName(R, CurContext->getRedeclContext()); | |||
9132 | NamedDecl *PrevDecl = | |||
9133 | R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; | |||
9134 | PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); | |||
9135 | ||||
9136 | if (PrevNS) { | |||
9137 | // This is an extended namespace definition. | |||
9138 | if (IsInline != PrevNS->isInline()) | |||
9139 | DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, | |||
9140 | &IsInline, PrevNS); | |||
9141 | } else if (PrevDecl) { | |||
9142 | // This is an invalid name redefinition. | |||
9143 | Diag(Loc, diag::err_redefinition_different_kind) | |||
9144 | << II; | |||
9145 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); | |||
9146 | IsInvalid = true; | |||
9147 | // Continue on to push Namespc as current DeclContext and return it. | |||
9148 | } else if (II->isStr("std") && | |||
9149 | CurContext->getRedeclContext()->isTranslationUnit()) { | |||
9150 | // This is the first "real" definition of the namespace "std", so update | |||
9151 | // our cache of the "std" namespace to point at this definition. | |||
9152 | PrevNS = getStdNamespace(); | |||
9153 | IsStd = true; | |||
9154 | AddToKnown = !IsInline; | |||
9155 | } else { | |||
9156 | // We've seen this namespace for the first time. | |||
9157 | AddToKnown = !IsInline; | |||
9158 | } | |||
9159 | } else { | |||
9160 | // Anonymous namespaces. | |||
9161 | ||||
9162 | // Determine whether the parent already has an anonymous namespace. | |||
9163 | DeclContext *Parent = CurContext->getRedeclContext(); | |||
9164 | if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { | |||
9165 | PrevNS = TU->getAnonymousNamespace(); | |||
9166 | } else { | |||
9167 | NamespaceDecl *ND = cast<NamespaceDecl>(Parent); | |||
9168 | PrevNS = ND->getAnonymousNamespace(); | |||
9169 | } | |||
9170 | ||||
9171 | if (PrevNS && IsInline != PrevNS->isInline()) | |||
9172 | DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, | |||
9173 | &IsInline, PrevNS); | |||
9174 | } | |||
9175 | ||||
9176 | NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, | |||
9177 | StartLoc, Loc, II, PrevNS); | |||
9178 | if (IsInvalid) | |||
9179 | Namespc->setInvalidDecl(); | |||
9180 | ||||
9181 | ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); | |||
9182 | AddPragmaAttributes(DeclRegionScope, Namespc); | |||
9183 | ||||
9184 | // FIXME: Should we be merging attributes? | |||
9185 | if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) | |||
9186 | PushNamespaceVisibilityAttr(Attr, Loc); | |||
9187 | ||||
9188 | if (IsStd) | |||
9189 | StdNamespace = Namespc; | |||
9190 | if (AddToKnown) | |||
9191 | KnownNamespaces[Namespc] = false; | |||
9192 | ||||
9193 | if (II) { | |||
9194 | PushOnScopeChains(Namespc, DeclRegionScope); | |||
9195 | } else { | |||
9196 | // Link the anonymous namespace into its parent. | |||
9197 | DeclContext *Parent = CurContext->getRedeclContext(); | |||
9198 | if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { | |||
9199 | TU->setAnonymousNamespace(Namespc); | |||
9200 | } else { | |||
9201 | cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); | |||
9202 | } | |||
9203 | ||||
9204 | CurContext->addDecl(Namespc); | |||
9205 | ||||
9206 | // C++ [namespace.unnamed]p1. An unnamed-namespace-definition | |||
9207 | // behaves as if it were replaced by | |||
9208 | // namespace unique { /* empty body */ } | |||
9209 | // using namespace unique; | |||
9210 | // namespace unique { namespace-body } | |||
9211 | // where all occurrences of 'unique' in a translation unit are | |||
9212 | // replaced by the same identifier and this identifier differs | |||
9213 | // from all other identifiers in the entire program. | |||
9214 | ||||
9215 | // We just create the namespace with an empty name and then add an | |||
9216 | // implicit using declaration, just like the standard suggests. | |||
9217 | // | |||
9218 | // CodeGen enforces the "universally unique" aspect by giving all | |||
9219 | // declarations semantically contained within an anonymous | |||
9220 | // namespace internal linkage. | |||
9221 | ||||
9222 | if (!PrevNS) { | |||
9223 | UD = UsingDirectiveDecl::Create(Context, Parent, | |||
9224 | /* 'using' */ LBrace, | |||
9225 | /* 'namespace' */ SourceLocation(), | |||
9226 | /* qualifier */ NestedNameSpecifierLoc(), | |||
9227 | /* identifier */ SourceLocation(), | |||
9228 | Namespc, | |||
9229 | /* Ancestor */ Parent); | |||
9230 | UD->setImplicit(); | |||
9231 | Parent->addDecl(UD); | |||
9232 | } | |||
9233 | } | |||
9234 | ||||
9235 | ActOnDocumentableDecl(Namespc); | |||
9236 | ||||
9237 | // Although we could have an invalid decl (i.e. the namespace name is a | |||
9238 | // redefinition), push it as current DeclContext and try to continue parsing. | |||
9239 | // FIXME: We should be able to push Namespc here, so that the each DeclContext | |||
9240 | // for the namespace has the declarations that showed up in that particular | |||
9241 | // namespace definition. | |||
9242 | PushDeclContext(NamespcScope, Namespc); | |||
9243 | return Namespc; | |||
9244 | } | |||
9245 | ||||
9246 | /// getNamespaceDecl - Returns the namespace a decl represents. If the decl | |||
9247 | /// is a namespace alias, returns the namespace it points to. | |||
9248 | static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { | |||
9249 | if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) | |||
9250 | return AD->getNamespace(); | |||
9251 | return dyn_cast_or_null<NamespaceDecl>(D); | |||
9252 | } | |||
9253 | ||||
9254 | /// ActOnFinishNamespaceDef - This callback is called after a namespace is | |||
9255 | /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. | |||
9256 | void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { | |||
9257 | NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); | |||
9258 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9258, __PRETTY_FUNCTION__)); | |||
9259 | Namespc->setRBraceLoc(RBrace); | |||
9260 | PopDeclContext(); | |||
9261 | if (Namespc->hasAttr<VisibilityAttr>()) | |||
9262 | PopPragmaVisibility(true, RBrace); | |||
9263 | // If this namespace contains an export-declaration, export it now. | |||
9264 | if (DeferredExportedNamespaces.erase(Namespc)) | |||
9265 | Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); | |||
9266 | } | |||
9267 | ||||
9268 | CXXRecordDecl *Sema::getStdBadAlloc() const { | |||
9269 | return cast_or_null<CXXRecordDecl>( | |||
9270 | StdBadAlloc.get(Context.getExternalSource())); | |||
9271 | } | |||
9272 | ||||
9273 | EnumDecl *Sema::getStdAlignValT() const { | |||
9274 | return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); | |||
9275 | } | |||
9276 | ||||
9277 | NamespaceDecl *Sema::getStdNamespace() const { | |||
9278 | return cast_or_null<NamespaceDecl>( | |||
9279 | StdNamespace.get(Context.getExternalSource())); | |||
9280 | } | |||
9281 | ||||
9282 | NamespaceDecl *Sema::lookupStdExperimentalNamespace() { | |||
9283 | if (!StdExperimentalNamespaceCache) { | |||
9284 | if (auto Std = getStdNamespace()) { | |||
9285 | LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), | |||
9286 | SourceLocation(), LookupNamespaceName); | |||
9287 | if (!LookupQualifiedName(Result, Std) || | |||
9288 | !(StdExperimentalNamespaceCache = | |||
9289 | Result.getAsSingle<NamespaceDecl>())) | |||
9290 | Result.suppressDiagnostics(); | |||
9291 | } | |||
9292 | } | |||
9293 | return StdExperimentalNamespaceCache; | |||
9294 | } | |||
9295 | ||||
9296 | namespace { | |||
9297 | ||||
9298 | enum UnsupportedSTLSelect { | |||
9299 | USS_InvalidMember, | |||
9300 | USS_MissingMember, | |||
9301 | USS_NonTrivial, | |||
9302 | USS_Other | |||
9303 | }; | |||
9304 | ||||
9305 | struct InvalidSTLDiagnoser { | |||
9306 | Sema &S; | |||
9307 | SourceLocation Loc; | |||
9308 | QualType TyForDiags; | |||
9309 | ||||
9310 | QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", | |||
9311 | const VarDecl *VD = nullptr) { | |||
9312 | { | |||
9313 | auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) | |||
9314 | << TyForDiags << ((int)Sel); | |||
9315 | if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { | |||
9316 | assert(!Name.empty())((!Name.empty()) ? static_cast<void> (0) : __assert_fail ("!Name.empty()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9316, __PRETTY_FUNCTION__)); | |||
9317 | D << Name; | |||
9318 | } | |||
9319 | } | |||
9320 | if (Sel == USS_InvalidMember) { | |||
9321 | S.Diag(VD->getLocation(), diag::note_var_declared_here) | |||
9322 | << VD << VD->getSourceRange(); | |||
9323 | } | |||
9324 | return QualType(); | |||
9325 | } | |||
9326 | }; | |||
9327 | } // namespace | |||
9328 | ||||
9329 | QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, | |||
9330 | SourceLocation Loc) { | |||
9331 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9332, __PRETTY_FUNCTION__)) | |||
9332 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9332, __PRETTY_FUNCTION__)); | |||
9333 | ||||
9334 | // Check if we've already successfully checked the comparison category type | |||
9335 | // before. If so, skip checking it again. | |||
9336 | ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); | |||
9337 | if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) | |||
9338 | return Info->getType(); | |||
9339 | ||||
9340 | // If lookup failed | |||
9341 | if (!Info) { | |||
9342 | std::string NameForDiags = "std::"; | |||
9343 | NameForDiags += ComparisonCategories::getCategoryString(Kind); | |||
9344 | Diag(Loc, diag::err_implied_comparison_category_type_not_found) | |||
9345 | << NameForDiags; | |||
9346 | return QualType(); | |||
9347 | } | |||
9348 | ||||
9349 | assert(Info->Kind == Kind)((Info->Kind == Kind) ? static_cast<void> (0) : __assert_fail ("Info->Kind == Kind", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9349, __PRETTY_FUNCTION__)); | |||
9350 | assert(Info->Record)((Info->Record) ? static_cast<void> (0) : __assert_fail ("Info->Record", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9350, __PRETTY_FUNCTION__)); | |||
9351 | ||||
9352 | // Update the Record decl in case we encountered a forward declaration on our | |||
9353 | // first pass. FIXME: This is a bit of a hack. | |||
9354 | if (Info->Record->hasDefinition()) | |||
9355 | Info->Record = Info->Record->getDefinition(); | |||
9356 | ||||
9357 | // Use an elaborated type for diagnostics which has a name containing the | |||
9358 | // prepended 'std' namespace but not any inline namespace names. | |||
9359 | QualType TyForDiags = [&]() { | |||
9360 | auto *NNS = | |||
9361 | NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); | |||
9362 | return Context.getElaboratedType(ETK_None, NNS, Info->getType()); | |||
9363 | }(); | |||
9364 | ||||
9365 | if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) | |||
9366 | return QualType(); | |||
9367 | ||||
9368 | InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; | |||
9369 | ||||
9370 | if (!Info->Record->isTriviallyCopyable()) | |||
9371 | return UnsupportedSTLError(USS_NonTrivial); | |||
9372 | ||||
9373 | for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { | |||
9374 | CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); | |||
9375 | // Tolerate empty base classes. | |||
9376 | if (Base->isEmpty()) | |||
9377 | continue; | |||
9378 | // Reject STL implementations which have at least one non-empty base. | |||
9379 | return UnsupportedSTLError(); | |||
9380 | } | |||
9381 | ||||
9382 | // Check that the STL has implemented the types using a single integer field. | |||
9383 | // This expectation allows better codegen for builtin operators. We require: | |||
9384 | // (1) The class has exactly one field. | |||
9385 | // (2) The field is an integral or enumeration type. | |||
9386 | auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); | |||
9387 | if (std::distance(FIt, FEnd) != 1 || | |||
9388 | !FIt->getType()->isIntegralOrEnumerationType()) { | |||
9389 | return UnsupportedSTLError(); | |||
9390 | } | |||
9391 | ||||
9392 | // Build each of the require values and store them in Info. | |||
9393 | for (ComparisonCategoryResult CCR : | |||
9394 | ComparisonCategories::getPossibleResultsForType(Kind)) { | |||
9395 | StringRef MemName = ComparisonCategories::getResultString(CCR); | |||
9396 | ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); | |||
9397 | ||||
9398 | if (!ValInfo) | |||
9399 | return UnsupportedSTLError(USS_MissingMember, MemName); | |||
9400 | ||||
9401 | VarDecl *VD = ValInfo->VD; | |||
9402 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9402, __PRETTY_FUNCTION__)); | |||
9403 | ||||
9404 | // Attempt to diagnose reasons why the STL definition of this type | |||
9405 | // might be foobar, including it failing to be a constant expression. | |||
9406 | // TODO Handle more ways the lookup or result can be invalid. | |||
9407 | if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || | |||
9408 | !VD->checkInitIsICE()) | |||
9409 | return UnsupportedSTLError(USS_InvalidMember, MemName, VD); | |||
9410 | ||||
9411 | // Attempt to evaluate the var decl as a constant expression and extract | |||
9412 | // the value of its first field as a ICE. If this fails, the STL | |||
9413 | // implementation is not supported. | |||
9414 | if (!ValInfo->hasValidIntValue()) | |||
9415 | return UnsupportedSTLError(); | |||
9416 | ||||
9417 | MarkVariableReferenced(Loc, VD); | |||
9418 | } | |||
9419 | ||||
9420 | // We've successfully built the required types and expressions. Update | |||
9421 | // the cache and return the newly cached value. | |||
9422 | FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; | |||
9423 | return Info->getType(); | |||
9424 | } | |||
9425 | ||||
9426 | /// Retrieve the special "std" namespace, which may require us to | |||
9427 | /// implicitly define the namespace. | |||
9428 | NamespaceDecl *Sema::getOrCreateStdNamespace() { | |||
9429 | if (!StdNamespace) { | |||
9430 | // The "std" namespace has not yet been defined, so build one implicitly. | |||
9431 | StdNamespace = NamespaceDecl::Create(Context, | |||
9432 | Context.getTranslationUnitDecl(), | |||
9433 | /*Inline=*/false, | |||
9434 | SourceLocation(), SourceLocation(), | |||
9435 | &PP.getIdentifierTable().get("std"), | |||
9436 | /*PrevDecl=*/nullptr); | |||
9437 | getStdNamespace()->setImplicit(true); | |||
9438 | } | |||
9439 | ||||
9440 | return getStdNamespace(); | |||
9441 | } | |||
9442 | ||||
9443 | bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { | |||
9444 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9445, __PRETTY_FUNCTION__)) | |||
9445 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9445, __PRETTY_FUNCTION__)); | |||
9446 | ||||
9447 | // We're looking for implicit instantiations of | |||
9448 | // template <typename E> class std::initializer_list. | |||
9449 | ||||
9450 | if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. | |||
9451 | return false; | |||
9452 | ||||
9453 | ClassTemplateDecl *Template = nullptr; | |||
9454 | const TemplateArgument *Arguments = nullptr; | |||
9455 | ||||
9456 | if (const RecordType *RT = Ty->getAs<RecordType>()) { | |||
9457 | ||||
9458 | ClassTemplateSpecializationDecl *Specialization = | |||
9459 | dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); | |||
9460 | if (!Specialization) | |||
9461 | return false; | |||
9462 | ||||
9463 | Template = Specialization->getSpecializedTemplate(); | |||
9464 | Arguments = Specialization->getTemplateArgs().data(); | |||
9465 | } else if (const TemplateSpecializationType *TST = | |||
9466 | Ty->getAs<TemplateSpecializationType>()) { | |||
9467 | Template = dyn_cast_or_null<ClassTemplateDecl>( | |||
9468 | TST->getTemplateName().getAsTemplateDecl()); | |||
9469 | Arguments = TST->getArgs(); | |||
9470 | } | |||
9471 | if (!Template) | |||
9472 | return false; | |||
9473 | ||||
9474 | if (!StdInitializerList) { | |||
9475 | // Haven't recognized std::initializer_list yet, maybe this is it. | |||
9476 | CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); | |||
9477 | if (TemplateClass->getIdentifier() != | |||
9478 | &PP.getIdentifierTable().get("initializer_list") || | |||
9479 | !getStdNamespace()->InEnclosingNamespaceSetOf( | |||
9480 | TemplateClass->getDeclContext())) | |||
9481 | return false; | |||
9482 | // This is a template called std::initializer_list, but is it the right | |||
9483 | // template? | |||
9484 | TemplateParameterList *Params = Template->getTemplateParameters(); | |||
9485 | if (Params->getMinRequiredArguments() != 1) | |||
9486 | return false; | |||
9487 | if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) | |||
9488 | return false; | |||
9489 | ||||
9490 | // It's the right template. | |||
9491 | StdInitializerList = Template; | |||
9492 | } | |||
9493 | ||||
9494 | if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) | |||
9495 | return false; | |||
9496 | ||||
9497 | // This is an instance of std::initializer_list. Find the argument type. | |||
9498 | if (Element) | |||
9499 | *Element = Arguments[0].getAsType(); | |||
9500 | return true; | |||
9501 | } | |||
9502 | ||||
9503 | static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ | |||
9504 | NamespaceDecl *Std = S.getStdNamespace(); | |||
9505 | if (!Std) { | |||
9506 | S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); | |||
9507 | return nullptr; | |||
9508 | } | |||
9509 | ||||
9510 | LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), | |||
9511 | Loc, Sema::LookupOrdinaryName); | |||
9512 | if (!S.LookupQualifiedName(Result, Std)) { | |||
9513 | S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); | |||
9514 | return nullptr; | |||
9515 | } | |||
9516 | ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); | |||
9517 | if (!Template) { | |||
9518 | Result.suppressDiagnostics(); | |||
9519 | // We found something weird. Complain about the first thing we found. | |||
9520 | NamedDecl *Found = *Result.begin(); | |||
9521 | S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); | |||
9522 | return nullptr; | |||
9523 | } | |||
9524 | ||||
9525 | // We found some template called std::initializer_list. Now verify that it's | |||
9526 | // correct. | |||
9527 | TemplateParameterList *Params = Template->getTemplateParameters(); | |||
9528 | if (Params->getMinRequiredArguments() != 1 || | |||
9529 | !isa<TemplateTypeParmDecl>(Params->getParam(0))) { | |||
9530 | S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); | |||
9531 | return nullptr; | |||
9532 | } | |||
9533 | ||||
9534 | return Template; | |||
9535 | } | |||
9536 | ||||
9537 | QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { | |||
9538 | if (!StdInitializerList) { | |||
9539 | StdInitializerList = LookupStdInitializerList(*this, Loc); | |||
9540 | if (!StdInitializerList) | |||
9541 | return QualType(); | |||
9542 | } | |||
9543 | ||||
9544 | TemplateArgumentListInfo Args(Loc, Loc); | |||
9545 | Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), | |||
9546 | Context.getTrivialTypeSourceInfo(Element, | |||
9547 | Loc))); | |||
9548 | return Context.getCanonicalType( | |||
9549 | CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); | |||
9550 | } | |||
9551 | ||||
9552 | bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { | |||
9553 | // C++ [dcl.init.list]p2: | |||
9554 | // A constructor is an initializer-list constructor if its first parameter | |||
9555 | // is of type std::initializer_list<E> or reference to possibly cv-qualified | |||
9556 | // std::initializer_list<E> for some type E, and either there are no other | |||
9557 | // parameters or else all other parameters have default arguments. | |||
9558 | if (Ctor->getNumParams() < 1 || | |||
9559 | (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) | |||
9560 | return false; | |||
9561 | ||||
9562 | QualType ArgType = Ctor->getParamDecl(0)->getType(); | |||
9563 | if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) | |||
9564 | ArgType = RT->getPointeeType().getUnqualifiedType(); | |||
9565 | ||||
9566 | return isStdInitializerList(ArgType, nullptr); | |||
9567 | } | |||
9568 | ||||
9569 | /// Determine whether a using statement is in a context where it will be | |||
9570 | /// apply in all contexts. | |||
9571 | static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { | |||
9572 | switch (CurContext->getDeclKind()) { | |||
9573 | case Decl::TranslationUnit: | |||
9574 | return true; | |||
9575 | case Decl::LinkageSpec: | |||
9576 | return IsUsingDirectiveInToplevelContext(CurContext->getParent()); | |||
9577 | default: | |||
9578 | return false; | |||
9579 | } | |||
9580 | } | |||
9581 | ||||
9582 | namespace { | |||
9583 | ||||
9584 | // Callback to only accept typo corrections that are namespaces. | |||
9585 | class NamespaceValidatorCCC final : public CorrectionCandidateCallback { | |||
9586 | public: | |||
9587 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
9588 | if (NamedDecl *ND = candidate.getCorrectionDecl()) | |||
9589 | return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); | |||
9590 | return false; | |||
9591 | } | |||
9592 | ||||
9593 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
9594 | return std::make_unique<NamespaceValidatorCCC>(*this); | |||
9595 | } | |||
9596 | }; | |||
9597 | ||||
9598 | } | |||
9599 | ||||
9600 | static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, | |||
9601 | CXXScopeSpec &SS, | |||
9602 | SourceLocation IdentLoc, | |||
9603 | IdentifierInfo *Ident) { | |||
9604 | R.clear(); | |||
9605 | NamespaceValidatorCCC CCC{}; | |||
9606 | if (TypoCorrection Corrected = | |||
9607 | S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, | |||
9608 | Sema::CTK_ErrorRecovery)) { | |||
9609 | if (DeclContext *DC = S.computeDeclContext(SS, false)) { | |||
9610 | std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); | |||
9611 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | |||
9612 | Ident->getName().equals(CorrectedStr); | |||
9613 | S.diagnoseTypo(Corrected, | |||
9614 | S.PDiag(diag::err_using_directive_member_suggest) | |||
9615 | << Ident << DC << DroppedSpecifier << SS.getRange(), | |||
9616 | S.PDiag(diag::note_namespace_defined_here)); | |||
9617 | } else { | |||
9618 | S.diagnoseTypo(Corrected, | |||
9619 | S.PDiag(diag::err_using_directive_suggest) << Ident, | |||
9620 | S.PDiag(diag::note_namespace_defined_here)); | |||
9621 | } | |||
9622 | R.addDecl(Corrected.getFoundDecl()); | |||
9623 | return true; | |||
9624 | } | |||
9625 | return false; | |||
9626 | } | |||
9627 | ||||
9628 | Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, | |||
9629 | SourceLocation NamespcLoc, CXXScopeSpec &SS, | |||
9630 | SourceLocation IdentLoc, | |||
9631 | IdentifierInfo *NamespcName, | |||
9632 | const ParsedAttributesView &AttrList) { | |||
9633 | assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")((!SS.isInvalid() && "Invalid CXXScopeSpec.") ? static_cast <void> (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9633, __PRETTY_FUNCTION__)); | |||
9634 | assert(NamespcName && "Invalid NamespcName.")((NamespcName && "Invalid NamespcName.") ? static_cast <void> (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9634, __PRETTY_FUNCTION__)); | |||
9635 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9635, __PRETTY_FUNCTION__)); | |||
9636 | ||||
9637 | // This can only happen along a recovery path. | |||
9638 | while (S->isTemplateParamScope()) | |||
9639 | S = S->getParent(); | |||
9640 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9640, __PRETTY_FUNCTION__)); | |||
9641 | ||||
9642 | UsingDirectiveDecl *UDir = nullptr; | |||
9643 | NestedNameSpecifier *Qualifier = nullptr; | |||
9644 | if (SS.isSet()) | |||
9645 | Qualifier = SS.getScopeRep(); | |||
9646 | ||||
9647 | // Lookup namespace name. | |||
9648 | LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); | |||
9649 | LookupParsedName(R, S, &SS); | |||
9650 | if (R.isAmbiguous()) | |||
9651 | return nullptr; | |||
9652 | ||||
9653 | if (R.empty()) { | |||
9654 | R.clear(); | |||
9655 | // Allow "using namespace std;" or "using namespace ::std;" even if | |||
9656 | // "std" hasn't been defined yet, for GCC compatibility. | |||
9657 | if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && | |||
9658 | NamespcName->isStr("std")) { | |||
9659 | Diag(IdentLoc, diag::ext_using_undefined_std); | |||
9660 | R.addDecl(getOrCreateStdNamespace()); | |||
9661 | R.resolveKind(); | |||
9662 | } | |||
9663 | // Otherwise, attempt typo correction. | |||
9664 | else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); | |||
9665 | } | |||
9666 | ||||
9667 | if (!R.empty()) { | |||
9668 | NamedDecl *Named = R.getRepresentativeDecl(); | |||
9669 | NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); | |||
9670 | assert(NS && "expected namespace decl")((NS && "expected namespace decl") ? static_cast<void > (0) : __assert_fail ("NS && \"expected namespace decl\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9670, __PRETTY_FUNCTION__)); | |||
9671 | ||||
9672 | // The use of a nested name specifier may trigger deprecation warnings. | |||
9673 | DiagnoseUseOfDecl(Named, IdentLoc); | |||
9674 | ||||
9675 | // C++ [namespace.udir]p1: | |||
9676 | // A using-directive specifies that the names in the nominated | |||
9677 | // namespace can be used in the scope in which the | |||
9678 | // using-directive appears after the using-directive. During | |||
9679 | // unqualified name lookup (3.4.1), the names appear as if they | |||
9680 | // were declared in the nearest enclosing namespace which | |||
9681 | // contains both the using-directive and the nominated | |||
9682 | // namespace. [Note: in this context, "contains" means "contains | |||
9683 | // directly or indirectly". ] | |||
9684 | ||||
9685 | // Find enclosing context containing both using-directive and | |||
9686 | // nominated namespace. | |||
9687 | DeclContext *CommonAncestor = NS; | |||
9688 | while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) | |||
9689 | CommonAncestor = CommonAncestor->getParent(); | |||
9690 | ||||
9691 | UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, | |||
9692 | SS.getWithLocInContext(Context), | |||
9693 | IdentLoc, Named, CommonAncestor); | |||
9694 | ||||
9695 | if (IsUsingDirectiveInToplevelContext(CurContext) && | |||
9696 | !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { | |||
9697 | Diag(IdentLoc, diag::warn_using_directive_in_header); | |||
9698 | } | |||
9699 | ||||
9700 | PushUsingDirective(S, UDir); | |||
9701 | } else { | |||
9702 | Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); | |||
9703 | } | |||
9704 | ||||
9705 | if (UDir) | |||
9706 | ProcessDeclAttributeList(S, UDir, AttrList); | |||
9707 | ||||
9708 | return UDir; | |||
9709 | } | |||
9710 | ||||
9711 | void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { | |||
9712 | // If the scope has an associated entity and the using directive is at | |||
9713 | // namespace or translation unit scope, add the UsingDirectiveDecl into | |||
9714 | // its lookup structure so qualified name lookup can find it. | |||
9715 | DeclContext *Ctx = S->getEntity(); | |||
9716 | if (Ctx && !Ctx->isFunctionOrMethod()) | |||
9717 | Ctx->addDecl(UDir); | |||
9718 | else | |||
9719 | // Otherwise, it is at block scope. The using-directives will affect lookup | |||
9720 | // only to the end of the scope. | |||
9721 | S->PushUsingDirective(UDir); | |||
9722 | } | |||
9723 | ||||
9724 | Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, | |||
9725 | SourceLocation UsingLoc, | |||
9726 | SourceLocation TypenameLoc, CXXScopeSpec &SS, | |||
9727 | UnqualifiedId &Name, | |||
9728 | SourceLocation EllipsisLoc, | |||
9729 | const ParsedAttributesView &AttrList) { | |||
9730 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9730, __PRETTY_FUNCTION__)); | |||
9731 | ||||
9732 | if (SS.isEmpty()) { | |||
9733 | Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); | |||
9734 | return nullptr; | |||
9735 | } | |||
9736 | ||||
9737 | switch (Name.getKind()) { | |||
9738 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
9739 | case UnqualifiedIdKind::IK_Identifier: | |||
9740 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
9741 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
9742 | case UnqualifiedIdKind::IK_ConversionFunctionId: | |||
9743 | break; | |||
9744 | ||||
9745 | case UnqualifiedIdKind::IK_ConstructorName: | |||
9746 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | |||
9747 | // C++11 inheriting constructors. | |||
9748 | Diag(Name.getBeginLoc(), | |||
9749 | getLangOpts().CPlusPlus11 | |||
9750 | ? diag::warn_cxx98_compat_using_decl_constructor | |||
9751 | : diag::err_using_decl_constructor) | |||
9752 | << SS.getRange(); | |||
9753 | ||||
9754 | if (getLangOpts().CPlusPlus11) break; | |||
9755 | ||||
9756 | return nullptr; | |||
9757 | ||||
9758 | case UnqualifiedIdKind::IK_DestructorName: | |||
9759 | Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); | |||
9760 | return nullptr; | |||
9761 | ||||
9762 | case UnqualifiedIdKind::IK_TemplateId: | |||
9763 | Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) | |||
9764 | << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); | |||
9765 | return nullptr; | |||
9766 | ||||
9767 | case UnqualifiedIdKind::IK_DeductionGuideName: | |||
9768 | llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9768); | |||
9769 | } | |||
9770 | ||||
9771 | DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); | |||
9772 | DeclarationName TargetName = TargetNameInfo.getName(); | |||
9773 | if (!TargetName) | |||
9774 | return nullptr; | |||
9775 | ||||
9776 | // Warn about access declarations. | |||
9777 | if (UsingLoc.isInvalid()) { | |||
9778 | Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 | |||
9779 | ? diag::err_access_decl | |||
9780 | : diag::warn_access_decl_deprecated) | |||
9781 | << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); | |||
9782 | } | |||
9783 | ||||
9784 | if (EllipsisLoc.isInvalid()) { | |||
9785 | if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || | |||
9786 | DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) | |||
9787 | return nullptr; | |||
9788 | } else { | |||
9789 | if (!SS.getScopeRep()->containsUnexpandedParameterPack() && | |||
9790 | !TargetNameInfo.containsUnexpandedParameterPack()) { | |||
9791 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) | |||
9792 | << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); | |||
9793 | EllipsisLoc = SourceLocation(); | |||
9794 | } | |||
9795 | } | |||
9796 | ||||
9797 | NamedDecl *UD = | |||
9798 | BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, | |||
9799 | SS, TargetNameInfo, EllipsisLoc, AttrList, | |||
9800 | /*IsInstantiation*/false); | |||
9801 | if (UD) | |||
9802 | PushOnScopeChains(UD, S, /*AddToContext*/ false); | |||
9803 | ||||
9804 | return UD; | |||
9805 | } | |||
9806 | ||||
9807 | /// Determine whether a using declaration considers the given | |||
9808 | /// declarations as "equivalent", e.g., if they are redeclarations of | |||
9809 | /// the same entity or are both typedefs of the same type. | |||
9810 | static bool | |||
9811 | IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { | |||
9812 | if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) | |||
9813 | return true; | |||
9814 | ||||
9815 | if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) | |||
9816 | if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) | |||
9817 | return Context.hasSameType(TD1->getUnderlyingType(), | |||
9818 | TD2->getUnderlyingType()); | |||
9819 | ||||
9820 | return false; | |||
9821 | } | |||
9822 | ||||
9823 | ||||
9824 | /// Determines whether to create a using shadow decl for a particular | |||
9825 | /// decl, given the set of decls existing prior to this using lookup. | |||
9826 | bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, | |||
9827 | const LookupResult &Previous, | |||
9828 | UsingShadowDecl *&PrevShadow) { | |||
9829 | // Diagnose finding a decl which is not from a base class of the | |||
9830 | // current class. We do this now because there are cases where this | |||
9831 | // function will silently decide not to build a shadow decl, which | |||
9832 | // will pre-empt further diagnostics. | |||
9833 | // | |||
9834 | // We don't need to do this in C++11 because we do the check once on | |||
9835 | // the qualifier. | |||
9836 | // | |||
9837 | // FIXME: diagnose the following if we care enough: | |||
9838 | // struct A { int foo; }; | |||
9839 | // struct B : A { using A::foo; }; | |||
9840 | // template <class T> struct C : A {}; | |||
9841 | // template <class T> struct D : C<T> { using B::foo; } // <--- | |||
9842 | // This is invalid (during instantiation) in C++03 because B::foo | |||
9843 | // resolves to the using decl in B, which is not a base class of D<T>. | |||
9844 | // We can't diagnose it immediately because C<T> is an unknown | |||
9845 | // specialization. The UsingShadowDecl in D<T> then points directly | |||
9846 | // to A::foo, which will look well-formed when we instantiate. | |||
9847 | // The right solution is to not collapse the shadow-decl chain. | |||
9848 | if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { | |||
9849 | DeclContext *OrigDC = Orig->getDeclContext(); | |||
9850 | ||||
9851 | // Handle enums and anonymous structs. | |||
9852 | if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); | |||
9853 | CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); | |||
9854 | while (OrigRec->isAnonymousStructOrUnion()) | |||
9855 | OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); | |||
9856 | ||||
9857 | if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { | |||
9858 | if (OrigDC == CurContext) { | |||
9859 | Diag(Using->getLocation(), | |||
9860 | diag::err_using_decl_nested_name_specifier_is_current_class) | |||
9861 | << Using->getQualifierLoc().getSourceRange(); | |||
9862 | Diag(Orig->getLocation(), diag::note_using_decl_target); | |||
9863 | Using->setInvalidDecl(); | |||
9864 | return true; | |||
9865 | } | |||
9866 | ||||
9867 | Diag(Using->getQualifierLoc().getBeginLoc(), | |||
9868 | diag::err_using_decl_nested_name_specifier_is_not_base_class) | |||
9869 | << Using->getQualifier() | |||
9870 | << cast<CXXRecordDecl>(CurContext) | |||
9871 | << Using->getQualifierLoc().getSourceRange(); | |||
9872 | Diag(Orig->getLocation(), diag::note_using_decl_target); | |||
9873 | Using->setInvalidDecl(); | |||
9874 | return true; | |||
9875 | } | |||
9876 | } | |||
9877 | ||||
9878 | if (Previous.empty()) return false; | |||
9879 | ||||
9880 | NamedDecl *Target = Orig; | |||
9881 | if (isa<UsingShadowDecl>(Target)) | |||
9882 | Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); | |||
9883 | ||||
9884 | // If the target happens to be one of the previous declarations, we | |||
9885 | // don't have a conflict. | |||
9886 | // | |||
9887 | // FIXME: but we might be increasing its access, in which case we | |||
9888 | // should redeclare it. | |||
9889 | NamedDecl *NonTag = nullptr, *Tag = nullptr; | |||
9890 | bool FoundEquivalentDecl = false; | |||
9891 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | |||
9892 | I != E; ++I) { | |||
9893 | NamedDecl *D = (*I)->getUnderlyingDecl(); | |||
9894 | // We can have UsingDecls in our Previous results because we use the same | |||
9895 | // LookupResult for checking whether the UsingDecl itself is a valid | |||
9896 | // redeclaration. | |||
9897 | if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) | |||
9898 | continue; | |||
9899 | ||||
9900 | if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { | |||
9901 | // C++ [class.mem]p19: | |||
9902 | // If T is the name of a class, then [every named member other than | |||
9903 | // a non-static data member] shall have a name different from T | |||
9904 | if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && | |||
9905 | !isa<IndirectFieldDecl>(Target) && | |||
9906 | !isa<UnresolvedUsingValueDecl>(Target) && | |||
9907 | DiagnoseClassNameShadow( | |||
9908 | CurContext, | |||
9909 | DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) | |||
9910 | return true; | |||
9911 | } | |||
9912 | ||||
9913 | if (IsEquivalentForUsingDecl(Context, D, Target)) { | |||
9914 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) | |||
9915 | PrevShadow = Shadow; | |||
9916 | FoundEquivalentDecl = true; | |||
9917 | } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { | |||
9918 | // We don't conflict with an existing using shadow decl of an equivalent | |||
9919 | // declaration, but we're not a redeclaration of it. | |||
9920 | FoundEquivalentDecl = true; | |||
9921 | } | |||
9922 | ||||
9923 | if (isVisible(D)) | |||
9924 | (isa<TagDecl>(D) ? Tag : NonTag) = D; | |||
9925 | } | |||
9926 | ||||
9927 | if (FoundEquivalentDecl) | |||
9928 | return false; | |||
9929 | ||||
9930 | if (FunctionDecl *FD = Target->getAsFunction()) { | |||
9931 | NamedDecl *OldDecl = nullptr; | |||
9932 | switch (CheckOverload(nullptr, FD, Previous, OldDecl, | |||
9933 | /*IsForUsingDecl*/ true)) { | |||
9934 | case Ovl_Overload: | |||
9935 | return false; | |||
9936 | ||||
9937 | case Ovl_NonFunction: | |||
9938 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | |||
9939 | break; | |||
9940 | ||||
9941 | // We found a decl with the exact signature. | |||
9942 | case Ovl_Match: | |||
9943 | // If we're in a record, we want to hide the target, so we | |||
9944 | // return true (without a diagnostic) to tell the caller not to | |||
9945 | // build a shadow decl. | |||
9946 | if (CurContext->isRecord()) | |||
9947 | return true; | |||
9948 | ||||
9949 | // If we're not in a record, this is an error. | |||
9950 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | |||
9951 | break; | |||
9952 | } | |||
9953 | ||||
9954 | Diag(Target->getLocation(), diag::note_using_decl_target); | |||
9955 | Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); | |||
9956 | Using->setInvalidDecl(); | |||
9957 | return true; | |||
9958 | } | |||
9959 | ||||
9960 | // Target is not a function. | |||
9961 | ||||
9962 | if (isa<TagDecl>(Target)) { | |||
9963 | // No conflict between a tag and a non-tag. | |||
9964 | if (!Tag) return false; | |||
9965 | ||||
9966 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | |||
9967 | Diag(Target->getLocation(), diag::note_using_decl_target); | |||
9968 | Diag(Tag->getLocation(), diag::note_using_decl_conflict); | |||
9969 | Using->setInvalidDecl(); | |||
9970 | return true; | |||
9971 | } | |||
9972 | ||||
9973 | // No conflict between a tag and a non-tag. | |||
9974 | if (!NonTag) return false; | |||
9975 | ||||
9976 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | |||
9977 | Diag(Target->getLocation(), diag::note_using_decl_target); | |||
9978 | Diag(NonTag->getLocation(), diag::note_using_decl_conflict); | |||
9979 | Using->setInvalidDecl(); | |||
9980 | return true; | |||
9981 | } | |||
9982 | ||||
9983 | /// Determine whether a direct base class is a virtual base class. | |||
9984 | static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { | |||
9985 | if (!Derived->getNumVBases()) | |||
9986 | return false; | |||
9987 | for (auto &B : Derived->bases()) | |||
9988 | if (B.getType()->getAsCXXRecordDecl() == Base) | |||
9989 | return B.isVirtual(); | |||
9990 | llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 9990); | |||
9991 | } | |||
9992 | ||||
9993 | /// Builds a shadow declaration corresponding to a 'using' declaration. | |||
9994 | UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, | |||
9995 | UsingDecl *UD, | |||
9996 | NamedDecl *Orig, | |||
9997 | UsingShadowDecl *PrevDecl) { | |||
9998 | // If we resolved to another shadow declaration, just coalesce them. | |||
9999 | NamedDecl *Target = Orig; | |||
10000 | if (isa<UsingShadowDecl>(Target)) { | |||
10001 | Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); | |||
10002 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10002, __PRETTY_FUNCTION__)); | |||
10003 | } | |||
10004 | ||||
10005 | NamedDecl *NonTemplateTarget = Target; | |||
10006 | if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) | |||
10007 | NonTemplateTarget = TargetTD->getTemplatedDecl(); | |||
10008 | ||||
10009 | UsingShadowDecl *Shadow; | |||
10010 | if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { | |||
10011 | bool IsVirtualBase = | |||
10012 | isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), | |||
10013 | UD->getQualifier()->getAsRecordDecl()); | |||
10014 | Shadow = ConstructorUsingShadowDecl::Create( | |||
10015 | Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); | |||
10016 | } else { | |||
10017 | Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, | |||
10018 | Target); | |||
10019 | } | |||
10020 | UD->addShadowDecl(Shadow); | |||
10021 | ||||
10022 | Shadow->setAccess(UD->getAccess()); | |||
10023 | if (Orig->isInvalidDecl() || UD->isInvalidDecl()) | |||
10024 | Shadow->setInvalidDecl(); | |||
10025 | ||||
10026 | Shadow->setPreviousDecl(PrevDecl); | |||
10027 | ||||
10028 | if (S) | |||
10029 | PushOnScopeChains(Shadow, S); | |||
10030 | else | |||
10031 | CurContext->addDecl(Shadow); | |||
10032 | ||||
10033 | ||||
10034 | return Shadow; | |||
10035 | } | |||
10036 | ||||
10037 | /// Hides a using shadow declaration. This is required by the current | |||
10038 | /// using-decl implementation when a resolvable using declaration in a | |||
10039 | /// class is followed by a declaration which would hide or override | |||
10040 | /// one or more of the using decl's targets; for example: | |||
10041 | /// | |||
10042 | /// struct Base { void foo(int); }; | |||
10043 | /// struct Derived : Base { | |||
10044 | /// using Base::foo; | |||
10045 | /// void foo(int); | |||
10046 | /// }; | |||
10047 | /// | |||
10048 | /// The governing language is C++03 [namespace.udecl]p12: | |||
10049 | /// | |||
10050 | /// When a using-declaration brings names from a base class into a | |||
10051 | /// derived class scope, member functions in the derived class | |||
10052 | /// override and/or hide member functions with the same name and | |||
10053 | /// parameter types in a base class (rather than conflicting). | |||
10054 | /// | |||
10055 | /// There are two ways to implement this: | |||
10056 | /// (1) optimistically create shadow decls when they're not hidden | |||
10057 | /// by existing declarations, or | |||
10058 | /// (2) don't create any shadow decls (or at least don't make them | |||
10059 | /// visible) until we've fully parsed/instantiated the class. | |||
10060 | /// The problem with (1) is that we might have to retroactively remove | |||
10061 | /// a shadow decl, which requires several O(n) operations because the | |||
10062 | /// decl structures are (very reasonably) not designed for removal. | |||
10063 | /// (2) avoids this but is very fiddly and phase-dependent. | |||
10064 | void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { | |||
10065 | if (Shadow->getDeclName().getNameKind() == | |||
10066 | DeclarationName::CXXConversionFunctionName) | |||
10067 | cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); | |||
10068 | ||||
10069 | // Remove it from the DeclContext... | |||
10070 | Shadow->getDeclContext()->removeDecl(Shadow); | |||
10071 | ||||
10072 | // ...and the scope, if applicable... | |||
10073 | if (S) { | |||
10074 | S->RemoveDecl(Shadow); | |||
10075 | IdResolver.RemoveDecl(Shadow); | |||
10076 | } | |||
10077 | ||||
10078 | // ...and the using decl. | |||
10079 | Shadow->getUsingDecl()->removeShadowDecl(Shadow); | |||
10080 | ||||
10081 | // TODO: complain somehow if Shadow was used. It shouldn't | |||
10082 | // be possible for this to happen, because...? | |||
10083 | } | |||
10084 | ||||
10085 | /// Find the base specifier for a base class with the given type. | |||
10086 | static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, | |||
10087 | QualType DesiredBase, | |||
10088 | bool &AnyDependentBases) { | |||
10089 | // Check whether the named type is a direct base class. | |||
10090 | CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() | |||
10091 | .getUnqualifiedType(); | |||
10092 | for (auto &Base : Derived->bases()) { | |||
10093 | CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); | |||
10094 | if (CanonicalDesiredBase == BaseType) | |||
10095 | return &Base; | |||
10096 | if (BaseType->isDependentType()) | |||
10097 | AnyDependentBases = true; | |||
10098 | } | |||
10099 | return nullptr; | |||
10100 | } | |||
10101 | ||||
10102 | namespace { | |||
10103 | class UsingValidatorCCC final : public CorrectionCandidateCallback { | |||
10104 | public: | |||
10105 | UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, | |||
10106 | NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) | |||
10107 | : HasTypenameKeyword(HasTypenameKeyword), | |||
10108 | IsInstantiation(IsInstantiation), OldNNS(NNS), | |||
10109 | RequireMemberOf(RequireMemberOf) {} | |||
10110 | ||||
10111 | bool ValidateCandidate(const TypoCorrection &Candidate) override { | |||
10112 | NamedDecl *ND = Candidate.getCorrectionDecl(); | |||
10113 | ||||
10114 | // Keywords are not valid here. | |||
10115 | if (!ND || isa<NamespaceDecl>(ND)) | |||
10116 | return false; | |||
10117 | ||||
10118 | // Completely unqualified names are invalid for a 'using' declaration. | |||
10119 | if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) | |||
10120 | return false; | |||
10121 | ||||
10122 | // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would | |||
10123 | // reject. | |||
10124 | ||||
10125 | if (RequireMemberOf) { | |||
10126 | auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); | |||
10127 | if (FoundRecord && FoundRecord->isInjectedClassName()) { | |||
10128 | // No-one ever wants a using-declaration to name an injected-class-name | |||
10129 | // of a base class, unless they're declaring an inheriting constructor. | |||
10130 | ASTContext &Ctx = ND->getASTContext(); | |||
10131 | if (!Ctx.getLangOpts().CPlusPlus11) | |||
10132 | return false; | |||
10133 | QualType FoundType = Ctx.getRecordType(FoundRecord); | |||
10134 | ||||
10135 | // Check that the injected-class-name is named as a member of its own | |||
10136 | // type; we don't want to suggest 'using Derived::Base;', since that | |||
10137 | // means something else. | |||
10138 | NestedNameSpecifier *Specifier = | |||
10139 | Candidate.WillReplaceSpecifier() | |||
10140 | ? Candidate.getCorrectionSpecifier() | |||
10141 | : OldNNS; | |||
10142 | if (!Specifier->getAsType() || | |||
10143 | !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) | |||
10144 | return false; | |||
10145 | ||||
10146 | // Check that this inheriting constructor declaration actually names a | |||
10147 | // direct base class of the current class. | |||
10148 | bool AnyDependentBases = false; | |||
10149 | if (!findDirectBaseWithType(RequireMemberOf, | |||
10150 | Ctx.getRecordType(FoundRecord), | |||
10151 | AnyDependentBases) && | |||
10152 | !AnyDependentBases) | |||
10153 | return false; | |||
10154 | } else { | |||
10155 | auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); | |||
10156 | if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) | |||
10157 | return false; | |||
10158 | ||||
10159 | // FIXME: Check that the base class member is accessible? | |||
10160 | } | |||
10161 | } else { | |||
10162 | auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); | |||
10163 | if (FoundRecord && FoundRecord->isInjectedClassName()) | |||
10164 | return false; | |||
10165 | } | |||
10166 | ||||
10167 | if (isa<TypeDecl>(ND)) | |||
10168 | return HasTypenameKeyword || !IsInstantiation; | |||
10169 | ||||
10170 | return !HasTypenameKeyword; | |||
10171 | } | |||
10172 | ||||
10173 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
10174 | return std::make_unique<UsingValidatorCCC>(*this); | |||
10175 | } | |||
10176 | ||||
10177 | private: | |||
10178 | bool HasTypenameKeyword; | |||
10179 | bool IsInstantiation; | |||
10180 | NestedNameSpecifier *OldNNS; | |||
10181 | CXXRecordDecl *RequireMemberOf; | |||
10182 | }; | |||
10183 | } // end anonymous namespace | |||
10184 | ||||
10185 | /// Builds a using declaration. | |||
10186 | /// | |||
10187 | /// \param IsInstantiation - Whether this call arises from an | |||
10188 | /// instantiation of an unresolved using declaration. We treat | |||
10189 | /// the lookup differently for these declarations. | |||
10190 | NamedDecl *Sema::BuildUsingDeclaration( | |||
10191 | Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, | |||
10192 | bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, | |||
10193 | DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, | |||
10194 | const ParsedAttributesView &AttrList, bool IsInstantiation) { | |||
10195 | assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")((!SS.isInvalid() && "Invalid CXXScopeSpec.") ? static_cast <void> (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10195, __PRETTY_FUNCTION__)); | |||
10196 | SourceLocation IdentLoc = NameInfo.getLoc(); | |||
10197 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10197, __PRETTY_FUNCTION__)); | |||
10198 | ||||
10199 | // FIXME: We ignore attributes for now. | |||
10200 | ||||
10201 | // For an inheriting constructor declaration, the name of the using | |||
10202 | // declaration is the name of a constructor in this class, not in the | |||
10203 | // base class. | |||
10204 | DeclarationNameInfo UsingName = NameInfo; | |||
10205 | if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) | |||
10206 | if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) | |||
10207 | UsingName.setName(Context.DeclarationNames.getCXXConstructorName( | |||
10208 | Context.getCanonicalType(Context.getRecordType(RD)))); | |||
10209 | ||||
10210 | // Do the redeclaration lookup in the current scope. | |||
10211 | LookupResult Previous(*this, UsingName, LookupUsingDeclName, | |||
10212 | ForVisibleRedeclaration); | |||
10213 | Previous.setHideTags(false); | |||
10214 | if (S) { | |||
10215 | LookupName(Previous, S); | |||
10216 | ||||
10217 | // It is really dumb that we have to do this. | |||
10218 | LookupResult::Filter F = Previous.makeFilter(); | |||
10219 | while (F.hasNext()) { | |||
10220 | NamedDecl *D = F.next(); | |||
10221 | if (!isDeclInScope(D, CurContext, S)) | |||
10222 | F.erase(); | |||
10223 | // If we found a local extern declaration that's not ordinarily visible, | |||
10224 | // and this declaration is being added to a non-block scope, ignore it. | |||
10225 | // We're only checking for scope conflicts here, not also for violations | |||
10226 | // of the linkage rules. | |||
10227 | else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && | |||
10228 | !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) | |||
10229 | F.erase(); | |||
10230 | } | |||
10231 | F.done(); | |||
10232 | } else { | |||
10233 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10233, __PRETTY_FUNCTION__)); | |||
10234 | if (CurContext->isRecord()) | |||
10235 | LookupQualifiedName(Previous, CurContext); | |||
10236 | else { | |||
10237 | // No redeclaration check is needed here; in non-member contexts we | |||
10238 | // diagnosed all possible conflicts with other using-declarations when | |||
10239 | // building the template: | |||
10240 | // | |||
10241 | // For a dependent non-type using declaration, the only valid case is | |||
10242 | // if we instantiate to a single enumerator. We check for conflicts | |||
10243 | // between shadow declarations we introduce, and we check in the template | |||
10244 | // definition for conflicts between a non-type using declaration and any | |||
10245 | // other declaration, which together covers all cases. | |||
10246 | // | |||
10247 | // A dependent typename using declaration will never successfully | |||
10248 | // instantiate, since it will always name a class member, so we reject | |||
10249 | // that in the template definition. | |||
10250 | } | |||
10251 | } | |||
10252 | ||||
10253 | // Check for invalid redeclarations. | |||
10254 | if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, | |||
10255 | SS, IdentLoc, Previous)) | |||
10256 | return nullptr; | |||
10257 | ||||
10258 | // Check for bad qualifiers. | |||
10259 | if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, | |||
10260 | IdentLoc)) | |||
10261 | return nullptr; | |||
10262 | ||||
10263 | DeclContext *LookupContext = computeDeclContext(SS); | |||
10264 | NamedDecl *D; | |||
10265 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); | |||
10266 | if (!LookupContext || EllipsisLoc.isValid()) { | |||
10267 | if (HasTypenameKeyword) { | |||
10268 | // FIXME: not all declaration name kinds are legal here | |||
10269 | D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, | |||
10270 | UsingLoc, TypenameLoc, | |||
10271 | QualifierLoc, | |||
10272 | IdentLoc, NameInfo.getName(), | |||
10273 | EllipsisLoc); | |||
10274 | } else { | |||
10275 | D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, | |||
10276 | QualifierLoc, NameInfo, EllipsisLoc); | |||
10277 | } | |||
10278 | D->setAccess(AS); | |||
10279 | CurContext->addDecl(D); | |||
10280 | return D; | |||
10281 | } | |||
10282 | ||||
10283 | auto Build = [&](bool Invalid) { | |||
10284 | UsingDecl *UD = | |||
10285 | UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, | |||
10286 | UsingName, HasTypenameKeyword); | |||
10287 | UD->setAccess(AS); | |||
10288 | CurContext->addDecl(UD); | |||
10289 | UD->setInvalidDecl(Invalid); | |||
10290 | return UD; | |||
10291 | }; | |||
10292 | auto BuildInvalid = [&]{ return Build(true); }; | |||
10293 | auto BuildValid = [&]{ return Build(false); }; | |||
10294 | ||||
10295 | if (RequireCompleteDeclContext(SS, LookupContext)) | |||
10296 | return BuildInvalid(); | |||
10297 | ||||
10298 | // Look up the target name. | |||
10299 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | |||
10300 | ||||
10301 | // Unlike most lookups, we don't always want to hide tag | |||
10302 | // declarations: tag names are visible through the using declaration | |||
10303 | // even if hidden by ordinary names, *except* in a dependent context | |||
10304 | // where it's important for the sanity of two-phase lookup. | |||
10305 | if (!IsInstantiation) | |||
10306 | R.setHideTags(false); | |||
10307 | ||||
10308 | // For the purposes of this lookup, we have a base object type | |||
10309 | // equal to that of the current context. | |||
10310 | if (CurContext->isRecord()) { | |||
10311 | R.setBaseObjectType( | |||
10312 | Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); | |||
10313 | } | |||
10314 | ||||
10315 | LookupQualifiedName(R, LookupContext); | |||
10316 | ||||
10317 | // Try to correct typos if possible. If constructor name lookup finds no | |||
10318 | // results, that means the named class has no explicit constructors, and we | |||
10319 | // suppressed declaring implicit ones (probably because it's dependent or | |||
10320 | // invalid). | |||
10321 | if (R.empty() && | |||
10322 | NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { | |||
10323 | // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes | |||
10324 | // it will believe that glibc provides a ::gets in cases where it does not, | |||
10325 | // and will try to pull it into namespace std with a using-declaration. | |||
10326 | // Just ignore the using-declaration in that case. | |||
10327 | auto *II = NameInfo.getName().getAsIdentifierInfo(); | |||
10328 | if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && | |||
10329 | CurContext->isStdNamespace() && | |||
10330 | isa<TranslationUnitDecl>(LookupContext) && | |||
10331 | getSourceManager().isInSystemHeader(UsingLoc)) | |||
10332 | return nullptr; | |||
10333 | UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), | |||
10334 | dyn_cast<CXXRecordDecl>(CurContext)); | |||
10335 | if (TypoCorrection Corrected = | |||
10336 | CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | |||
10337 | CTK_ErrorRecovery)) { | |||
10338 | // We reject candidates where DroppedSpecifier == true, hence the | |||
10339 | // literal '0' below. | |||
10340 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | |||
10341 | << NameInfo.getName() << LookupContext << 0 | |||
10342 | << SS.getRange()); | |||
10343 | ||||
10344 | // If we picked a correction with no attached Decl we can't do anything | |||
10345 | // useful with it, bail out. | |||
10346 | NamedDecl *ND = Corrected.getCorrectionDecl(); | |||
10347 | if (!ND) | |||
10348 | return BuildInvalid(); | |||
10349 | ||||
10350 | // If we corrected to an inheriting constructor, handle it as one. | |||
10351 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | |||
10352 | if (RD && RD->isInjectedClassName()) { | |||
10353 | // The parent of the injected class name is the class itself. | |||
10354 | RD = cast<CXXRecordDecl>(RD->getParent()); | |||
10355 | ||||
10356 | // Fix up the information we'll use to build the using declaration. | |||
10357 | if (Corrected.WillReplaceSpecifier()) { | |||
10358 | NestedNameSpecifierLocBuilder Builder; | |||
10359 | Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), | |||
10360 | QualifierLoc.getSourceRange()); | |||
10361 | QualifierLoc = Builder.getWithLocInContext(Context); | |||
10362 | } | |||
10363 | ||||
10364 | // In this case, the name we introduce is the name of a derived class | |||
10365 | // constructor. | |||
10366 | auto *CurClass = cast<CXXRecordDecl>(CurContext); | |||
10367 | UsingName.setName(Context.DeclarationNames.getCXXConstructorName( | |||
10368 | Context.getCanonicalType(Context.getRecordType(CurClass)))); | |||
10369 | UsingName.setNamedTypeInfo(nullptr); | |||
10370 | for (auto *Ctor : LookupConstructors(RD)) | |||
10371 | R.addDecl(Ctor); | |||
10372 | R.resolveKind(); | |||
10373 | } else { | |||
10374 | // FIXME: Pick up all the declarations if we found an overloaded | |||
10375 | // function. | |||
10376 | UsingName.setName(ND->getDeclName()); | |||
10377 | R.addDecl(ND); | |||
10378 | } | |||
10379 | } else { | |||
10380 | Diag(IdentLoc, diag::err_no_member) | |||
10381 | << NameInfo.getName() << LookupContext << SS.getRange(); | |||
10382 | return BuildInvalid(); | |||
10383 | } | |||
10384 | } | |||
10385 | ||||
10386 | if (R.isAmbiguous()) | |||
10387 | return BuildInvalid(); | |||
10388 | ||||
10389 | if (HasTypenameKeyword) { | |||
10390 | // If we asked for a typename and got a non-type decl, error out. | |||
10391 | if (!R.getAsSingle<TypeDecl>()) { | |||
10392 | Diag(IdentLoc, diag::err_using_typename_non_type); | |||
10393 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) | |||
10394 | Diag((*I)->getUnderlyingDecl()->getLocation(), | |||
10395 | diag::note_using_decl_target); | |||
10396 | return BuildInvalid(); | |||
10397 | } | |||
10398 | } else { | |||
10399 | // If we asked for a non-typename and we got a type, error out, | |||
10400 | // but only if this is an instantiation of an unresolved using | |||
10401 | // decl. Otherwise just silently find the type name. | |||
10402 | if (IsInstantiation && R.getAsSingle<TypeDecl>()) { | |||
10403 | Diag(IdentLoc, diag::err_using_dependent_value_is_type); | |||
10404 | Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); | |||
10405 | return BuildInvalid(); | |||
10406 | } | |||
10407 | } | |||
10408 | ||||
10409 | // C++14 [namespace.udecl]p6: | |||
10410 | // A using-declaration shall not name a namespace. | |||
10411 | if (R.getAsSingle<NamespaceDecl>()) { | |||
10412 | Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) | |||
10413 | << SS.getRange(); | |||
10414 | return BuildInvalid(); | |||
10415 | } | |||
10416 | ||||
10417 | // C++14 [namespace.udecl]p7: | |||
10418 | // A using-declaration shall not name a scoped enumerator. | |||
10419 | if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { | |||
10420 | if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { | |||
10421 | Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) | |||
10422 | << SS.getRange(); | |||
10423 | return BuildInvalid(); | |||
10424 | } | |||
10425 | } | |||
10426 | ||||
10427 | UsingDecl *UD = BuildValid(); | |||
10428 | ||||
10429 | // Some additional rules apply to inheriting constructors. | |||
10430 | if (UsingName.getName().getNameKind() == | |||
10431 | DeclarationName::CXXConstructorName) { | |||
10432 | // Suppress access diagnostics; the access check is instead performed at the | |||
10433 | // point of use for an inheriting constructor. | |||
10434 | R.suppressDiagnostics(); | |||
10435 | if (CheckInheritingConstructorUsingDecl(UD)) | |||
10436 | return UD; | |||
10437 | } | |||
10438 | ||||
10439 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { | |||
10440 | UsingShadowDecl *PrevDecl = nullptr; | |||
10441 | if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) | |||
10442 | BuildUsingShadowDecl(S, UD, *I, PrevDecl); | |||
10443 | } | |||
10444 | ||||
10445 | return UD; | |||
10446 | } | |||
10447 | ||||
10448 | NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, | |||
10449 | ArrayRef<NamedDecl *> Expansions) { | |||
10450 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10452, __PRETTY_FUNCTION__)) | |||
10451 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10452, __PRETTY_FUNCTION__)) | |||
10452 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10452, __PRETTY_FUNCTION__)); | |||
10453 | ||||
10454 | auto *UPD = | |||
10455 | UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); | |||
10456 | UPD->setAccess(InstantiatedFrom->getAccess()); | |||
10457 | CurContext->addDecl(UPD); | |||
10458 | return UPD; | |||
10459 | } | |||
10460 | ||||
10461 | /// Additional checks for a using declaration referring to a constructor name. | |||
10462 | bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { | |||
10463 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10463, __PRETTY_FUNCTION__)); | |||
10464 | ||||
10465 | const Type *SourceType = UD->getQualifier()->getAsType(); | |||
10466 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10467, __PRETTY_FUNCTION__)) | |||
10467 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10467, __PRETTY_FUNCTION__)); | |||
10468 | CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); | |||
10469 | ||||
10470 | // Check whether the named type is a direct base class. | |||
10471 | bool AnyDependentBases = false; | |||
10472 | auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), | |||
10473 | AnyDependentBases); | |||
10474 | if (!Base && !AnyDependentBases) { | |||
10475 | Diag(UD->getUsingLoc(), | |||
10476 | diag::err_using_decl_constructor_not_in_direct_base) | |||
10477 | << UD->getNameInfo().getSourceRange() | |||
10478 | << QualType(SourceType, 0) << TargetClass; | |||
10479 | UD->setInvalidDecl(); | |||
10480 | return true; | |||
10481 | } | |||
10482 | ||||
10483 | if (Base) | |||
10484 | Base->setInheritConstructors(); | |||
10485 | ||||
10486 | return false; | |||
10487 | } | |||
10488 | ||||
10489 | /// Checks that the given using declaration is not an invalid | |||
10490 | /// redeclaration. Note that this is checking only for the using decl | |||
10491 | /// itself, not for any ill-formedness among the UsingShadowDecls. | |||
10492 | bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, | |||
10493 | bool HasTypenameKeyword, | |||
10494 | const CXXScopeSpec &SS, | |||
10495 | SourceLocation NameLoc, | |||
10496 | const LookupResult &Prev) { | |||
10497 | NestedNameSpecifier *Qual = SS.getScopeRep(); | |||
10498 | ||||
10499 | // C++03 [namespace.udecl]p8: | |||
10500 | // C++0x [namespace.udecl]p10: | |||
10501 | // A using-declaration is a declaration and can therefore be used | |||
10502 | // repeatedly where (and only where) multiple declarations are | |||
10503 | // allowed. | |||
10504 | // | |||
10505 | // That's in non-member contexts. | |||
10506 | if (!CurContext->getRedeclContext()->isRecord()) { | |||
10507 | // A dependent qualifier outside a class can only ever resolve to an | |||
10508 | // enumeration type. Therefore it conflicts with any other non-type | |||
10509 | // declaration in the same scope. | |||
10510 | // FIXME: How should we check for dependent type-type conflicts at block | |||
10511 | // scope? | |||
10512 | if (Qual->isDependent() && !HasTypenameKeyword) { | |||
10513 | for (auto *D : Prev) { | |||
10514 | if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { | |||
10515 | bool OldCouldBeEnumerator = | |||
10516 | isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); | |||
10517 | Diag(NameLoc, | |||
10518 | OldCouldBeEnumerator ? diag::err_redefinition | |||
10519 | : diag::err_redefinition_different_kind) | |||
10520 | << Prev.getLookupName(); | |||
10521 | Diag(D->getLocation(), diag::note_previous_definition); | |||
10522 | return true; | |||
10523 | } | |||
10524 | } | |||
10525 | } | |||
10526 | return false; | |||
10527 | } | |||
10528 | ||||
10529 | for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { | |||
10530 | NamedDecl *D = *I; | |||
10531 | ||||
10532 | bool DTypename; | |||
10533 | NestedNameSpecifier *DQual; | |||
10534 | if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { | |||
10535 | DTypename = UD->hasTypename(); | |||
10536 | DQual = UD->getQualifier(); | |||
10537 | } else if (UnresolvedUsingValueDecl *UD | |||
10538 | = dyn_cast<UnresolvedUsingValueDecl>(D)) { | |||
10539 | DTypename = false; | |||
10540 | DQual = UD->getQualifier(); | |||
10541 | } else if (UnresolvedUsingTypenameDecl *UD | |||
10542 | = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { | |||
10543 | DTypename = true; | |||
10544 | DQual = UD->getQualifier(); | |||
10545 | } else continue; | |||
10546 | ||||
10547 | // using decls differ if one says 'typename' and the other doesn't. | |||
10548 | // FIXME: non-dependent using decls? | |||
10549 | if (HasTypenameKeyword != DTypename) continue; | |||
10550 | ||||
10551 | // using decls differ if they name different scopes (but note that | |||
10552 | // template instantiation can cause this check to trigger when it | |||
10553 | // didn't before instantiation). | |||
10554 | if (Context.getCanonicalNestedNameSpecifier(Qual) != | |||
10555 | Context.getCanonicalNestedNameSpecifier(DQual)) | |||
10556 | continue; | |||
10557 | ||||
10558 | Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); | |||
10559 | Diag(D->getLocation(), diag::note_using_decl) << 1; | |||
10560 | return true; | |||
10561 | } | |||
10562 | ||||
10563 | return false; | |||
10564 | } | |||
10565 | ||||
10566 | ||||
10567 | /// Checks that the given nested-name qualifier used in a using decl | |||
10568 | /// in the current context is appropriately related to the current | |||
10569 | /// scope. If an error is found, diagnoses it and returns true. | |||
10570 | bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, | |||
10571 | bool HasTypename, | |||
10572 | const CXXScopeSpec &SS, | |||
10573 | const DeclarationNameInfo &NameInfo, | |||
10574 | SourceLocation NameLoc) { | |||
10575 | DeclContext *NamedContext = computeDeclContext(SS); | |||
10576 | ||||
10577 | if (!CurContext->isRecord()) { | |||
10578 | // C++03 [namespace.udecl]p3: | |||
10579 | // C++0x [namespace.udecl]p8: | |||
10580 | // A using-declaration for a class member shall be a member-declaration. | |||
10581 | ||||
10582 | // If we weren't able to compute a valid scope, it might validly be a | |||
10583 | // dependent class scope or a dependent enumeration unscoped scope. If | |||
10584 | // we have a 'typename' keyword, the scope must resolve to a class type. | |||
10585 | if ((HasTypename && !NamedContext) || | |||
10586 | (NamedContext && NamedContext->getRedeclContext()->isRecord())) { | |||
10587 | auto *RD = NamedContext | |||
10588 | ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) | |||
10589 | : nullptr; | |||
10590 | if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) | |||
10591 | RD = nullptr; | |||
10592 | ||||
10593 | Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) | |||
10594 | << SS.getRange(); | |||
10595 | ||||
10596 | // If we have a complete, non-dependent source type, try to suggest a | |||
10597 | // way to get the same effect. | |||
10598 | if (!RD) | |||
10599 | return true; | |||
10600 | ||||
10601 | // Find what this using-declaration was referring to. | |||
10602 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | |||
10603 | R.setHideTags(false); | |||
10604 | R.suppressDiagnostics(); | |||
10605 | LookupQualifiedName(R, RD); | |||
10606 | ||||
10607 | if (R.getAsSingle<TypeDecl>()) { | |||
10608 | if (getLangOpts().CPlusPlus11) { | |||
10609 | // Convert 'using X::Y;' to 'using Y = X::Y;'. | |||
10610 | Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) | |||
10611 | << 0 // alias declaration | |||
10612 | << FixItHint::CreateInsertion(SS.getBeginLoc(), | |||
10613 | NameInfo.getName().getAsString() + | |||
10614 | " = "); | |||
10615 | } else { | |||
10616 | // Convert 'using X::Y;' to 'typedef X::Y Y;'. | |||
10617 | SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); | |||
10618 | Diag(InsertLoc, diag::note_using_decl_class_member_workaround) | |||
10619 | << 1 // typedef declaration | |||
10620 | << FixItHint::CreateReplacement(UsingLoc, "typedef") | |||
10621 | << FixItHint::CreateInsertion( | |||
10622 | InsertLoc, " " + NameInfo.getName().getAsString()); | |||
10623 | } | |||
10624 | } else if (R.getAsSingle<VarDecl>()) { | |||
10625 | // Don't provide a fixit outside C++11 mode; we don't want to suggest | |||
10626 | // repeating the type of the static data member here. | |||
10627 | FixItHint FixIt; | |||
10628 | if (getLangOpts().CPlusPlus11) { | |||
10629 | // Convert 'using X::Y;' to 'auto &Y = X::Y;'. | |||
10630 | FixIt = FixItHint::CreateReplacement( | |||
10631 | UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); | |||
10632 | } | |||
10633 | ||||
10634 | Diag(UsingLoc, diag::note_using_decl_class_member_workaround) | |||
10635 | << 2 // reference declaration | |||
10636 | << FixIt; | |||
10637 | } else if (R.getAsSingle<EnumConstantDecl>()) { | |||
10638 | // Don't provide a fixit outside C++11 mode; we don't want to suggest | |||
10639 | // repeating the type of the enumeration here, and we can't do so if | |||
10640 | // the type is anonymous. | |||
10641 | FixItHint FixIt; | |||
10642 | if (getLangOpts().CPlusPlus11) { | |||
10643 | // Convert 'using X::Y;' to 'auto &Y = X::Y;'. | |||
10644 | FixIt = FixItHint::CreateReplacement( | |||
10645 | UsingLoc, | |||
10646 | "constexpr auto " + NameInfo.getName().getAsString() + " = "); | |||
10647 | } | |||
10648 | ||||
10649 | Diag(UsingLoc, diag::note_using_decl_class_member_workaround) | |||
10650 | << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable | |||
10651 | << FixIt; | |||
10652 | } | |||
10653 | return true; | |||
10654 | } | |||
10655 | ||||
10656 | // Otherwise, this might be valid. | |||
10657 | return false; | |||
10658 | } | |||
10659 | ||||
10660 | // The current scope is a record. | |||
10661 | ||||
10662 | // If the named context is dependent, we can't decide much. | |||
10663 | if (!NamedContext) { | |||
10664 | // FIXME: in C++0x, we can diagnose if we can prove that the | |||
10665 | // nested-name-specifier does not refer to a base class, which is | |||
10666 | // still possible in some cases. | |||
10667 | ||||
10668 | // Otherwise we have to conservatively report that things might be | |||
10669 | // okay. | |||
10670 | return false; | |||
10671 | } | |||
10672 | ||||
10673 | if (!NamedContext->isRecord()) { | |||
10674 | // Ideally this would point at the last name in the specifier, | |||
10675 | // but we don't have that level of source info. | |||
10676 | Diag(SS.getRange().getBegin(), | |||
10677 | diag::err_using_decl_nested_name_specifier_is_not_class) | |||
10678 | << SS.getScopeRep() << SS.getRange(); | |||
10679 | return true; | |||
10680 | } | |||
10681 | ||||
10682 | if (!NamedContext->isDependentContext() && | |||
10683 | RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) | |||
10684 | return true; | |||
10685 | ||||
10686 | if (getLangOpts().CPlusPlus11) { | |||
10687 | // C++11 [namespace.udecl]p3: | |||
10688 | // In a using-declaration used as a member-declaration, the | |||
10689 | // nested-name-specifier shall name a base class of the class | |||
10690 | // being defined. | |||
10691 | ||||
10692 | if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( | |||
10693 | cast<CXXRecordDecl>(NamedContext))) { | |||
10694 | if (CurContext == NamedContext) { | |||
10695 | Diag(NameLoc, | |||
10696 | diag::err_using_decl_nested_name_specifier_is_current_class) | |||
10697 | << SS.getRange(); | |||
10698 | return true; | |||
10699 | } | |||
10700 | ||||
10701 | if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { | |||
10702 | Diag(SS.getRange().getBegin(), | |||
10703 | diag::err_using_decl_nested_name_specifier_is_not_base_class) | |||
10704 | << SS.getScopeRep() | |||
10705 | << cast<CXXRecordDecl>(CurContext) | |||
10706 | << SS.getRange(); | |||
10707 | } | |||
10708 | return true; | |||
10709 | } | |||
10710 | ||||
10711 | return false; | |||
10712 | } | |||
10713 | ||||
10714 | // C++03 [namespace.udecl]p4: | |||
10715 | // A using-declaration used as a member-declaration shall refer | |||
10716 | // to a member of a base class of the class being defined [etc.]. | |||
10717 | ||||
10718 | // Salient point: SS doesn't have to name a base class as long as | |||
10719 | // lookup only finds members from base classes. Therefore we can | |||
10720 | // diagnose here only if we can prove that that can't happen, | |||
10721 | // i.e. if the class hierarchies provably don't intersect. | |||
10722 | ||||
10723 | // TODO: it would be nice if "definitely valid" results were cached | |||
10724 | // in the UsingDecl and UsingShadowDecl so that these checks didn't | |||
10725 | // need to be repeated. | |||
10726 | ||||
10727 | llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; | |||
10728 | auto Collect = [&Bases](const CXXRecordDecl *Base) { | |||
10729 | Bases.insert(Base); | |||
10730 | return true; | |||
10731 | }; | |||
10732 | ||||
10733 | // Collect all bases. Return false if we find a dependent base. | |||
10734 | if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) | |||
10735 | return false; | |||
10736 | ||||
10737 | // Returns true if the base is dependent or is one of the accumulated base | |||
10738 | // classes. | |||
10739 | auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { | |||
10740 | return !Bases.count(Base); | |||
10741 | }; | |||
10742 | ||||
10743 | // Return false if the class has a dependent base or if it or one | |||
10744 | // of its bases is present in the base set of the current context. | |||
10745 | if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || | |||
10746 | !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) | |||
10747 | return false; | |||
10748 | ||||
10749 | Diag(SS.getRange().getBegin(), | |||
10750 | diag::err_using_decl_nested_name_specifier_is_not_base_class) | |||
10751 | << SS.getScopeRep() | |||
10752 | << cast<CXXRecordDecl>(CurContext) | |||
10753 | << SS.getRange(); | |||
10754 | ||||
10755 | return true; | |||
10756 | } | |||
10757 | ||||
10758 | Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, | |||
10759 | MultiTemplateParamsArg TemplateParamLists, | |||
10760 | SourceLocation UsingLoc, UnqualifiedId &Name, | |||
10761 | const ParsedAttributesView &AttrList, | |||
10762 | TypeResult Type, Decl *DeclFromDeclSpec) { | |||
10763 | // Skip up to the relevant declaration scope. | |||
10764 | while (S->isTemplateParamScope()) | |||
10765 | S = S->getParent(); | |||
10766 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10767, __PRETTY_FUNCTION__)) | |||
10767 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10767, __PRETTY_FUNCTION__)); | |||
10768 | ||||
10769 | if (Type.isInvalid()) | |||
10770 | return nullptr; | |||
10771 | ||||
10772 | bool Invalid = false; | |||
10773 | DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); | |||
10774 | TypeSourceInfo *TInfo = nullptr; | |||
10775 | GetTypeFromParser(Type.get(), &TInfo); | |||
10776 | ||||
10777 | if (DiagnoseClassNameShadow(CurContext, NameInfo)) | |||
10778 | return nullptr; | |||
10779 | ||||
10780 | if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, | |||
10781 | UPPC_DeclarationType)) { | |||
10782 | Invalid = true; | |||
10783 | TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, | |||
10784 | TInfo->getTypeLoc().getBeginLoc()); | |||
10785 | } | |||
10786 | ||||
10787 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
10788 | TemplateParamLists.size() | |||
10789 | ? forRedeclarationInCurContext() | |||
10790 | : ForVisibleRedeclaration); | |||
10791 | LookupName(Previous, S); | |||
10792 | ||||
10793 | // Warn about shadowing the name of a template parameter. | |||
10794 | if (Previous.isSingleResult() && | |||
10795 | Previous.getFoundDecl()->isTemplateParameter()) { | |||
10796 | DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); | |||
10797 | Previous.clear(); | |||
10798 | } | |||
10799 | ||||
10800 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10801, __PRETTY_FUNCTION__)) | |||
10801 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10801, __PRETTY_FUNCTION__)); | |||
10802 | TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, | |||
10803 | Name.StartLocation, | |||
10804 | Name.Identifier, TInfo); | |||
10805 | ||||
10806 | NewTD->setAccess(AS); | |||
10807 | ||||
10808 | if (Invalid) | |||
10809 | NewTD->setInvalidDecl(); | |||
10810 | ||||
10811 | ProcessDeclAttributeList(S, NewTD, AttrList); | |||
10812 | AddPragmaAttributes(S, NewTD); | |||
10813 | ||||
10814 | CheckTypedefForVariablyModifiedType(S, NewTD); | |||
10815 | Invalid |= NewTD->isInvalidDecl(); | |||
10816 | ||||
10817 | bool Redeclaration = false; | |||
10818 | ||||
10819 | NamedDecl *NewND; | |||
10820 | if (TemplateParamLists.size()) { | |||
10821 | TypeAliasTemplateDecl *OldDecl = nullptr; | |||
10822 | TemplateParameterList *OldTemplateParams = nullptr; | |||
10823 | ||||
10824 | if (TemplateParamLists.size() != 1) { | |||
10825 | Diag(UsingLoc, diag::err_alias_template_extra_headers) | |||
10826 | << SourceRange(TemplateParamLists[1]->getTemplateLoc(), | |||
10827 | TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); | |||
10828 | } | |||
10829 | TemplateParameterList *TemplateParams = TemplateParamLists[0]; | |||
10830 | ||||
10831 | // Check that we can declare a template here. | |||
10832 | if (CheckTemplateDeclScope(S, TemplateParams)) | |||
10833 | return nullptr; | |||
10834 | ||||
10835 | // Only consider previous declarations in the same scope. | |||
10836 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, | |||
10837 | /*ExplicitInstantiationOrSpecialization*/false); | |||
10838 | if (!Previous.empty()) { | |||
10839 | Redeclaration = true; | |||
10840 | ||||
10841 | OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); | |||
10842 | if (!OldDecl && !Invalid) { | |||
10843 | Diag(UsingLoc, diag::err_redefinition_different_kind) | |||
10844 | << Name.Identifier; | |||
10845 | ||||
10846 | NamedDecl *OldD = Previous.getRepresentativeDecl(); | |||
10847 | if (OldD->getLocation().isValid()) | |||
10848 | Diag(OldD->getLocation(), diag::note_previous_definition); | |||
10849 | ||||
10850 | Invalid = true; | |||
10851 | } | |||
10852 | ||||
10853 | if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { | |||
10854 | if (TemplateParameterListsAreEqual(TemplateParams, | |||
10855 | OldDecl->getTemplateParameters(), | |||
10856 | /*Complain=*/true, | |||
10857 | TPL_TemplateMatch)) | |||
10858 | OldTemplateParams = | |||
10859 | OldDecl->getMostRecentDecl()->getTemplateParameters(); | |||
10860 | else | |||
10861 | Invalid = true; | |||
10862 | ||||
10863 | TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); | |||
10864 | if (!Invalid && | |||
10865 | !Context.hasSameType(OldTD->getUnderlyingType(), | |||
10866 | NewTD->getUnderlyingType())) { | |||
10867 | // FIXME: The C++0x standard does not clearly say this is ill-formed, | |||
10868 | // but we can't reasonably accept it. | |||
10869 | Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) | |||
10870 | << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); | |||
10871 | if (OldTD->getLocation().isValid()) | |||
10872 | Diag(OldTD->getLocation(), diag::note_previous_definition); | |||
10873 | Invalid = true; | |||
10874 | } | |||
10875 | } | |||
10876 | } | |||
10877 | ||||
10878 | // Merge any previous default template arguments into our parameters, | |||
10879 | // and check the parameter list. | |||
10880 | if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, | |||
10881 | TPC_TypeAliasTemplate)) | |||
10882 | return nullptr; | |||
10883 | ||||
10884 | TypeAliasTemplateDecl *NewDecl = | |||
10885 | TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, | |||
10886 | Name.Identifier, TemplateParams, | |||
10887 | NewTD); | |||
10888 | NewTD->setDescribedAliasTemplate(NewDecl); | |||
10889 | ||||
10890 | NewDecl->setAccess(AS); | |||
10891 | ||||
10892 | if (Invalid) | |||
10893 | NewDecl->setInvalidDecl(); | |||
10894 | else if (OldDecl) { | |||
10895 | NewDecl->setPreviousDecl(OldDecl); | |||
10896 | CheckRedeclarationModuleOwnership(NewDecl, OldDecl); | |||
10897 | } | |||
10898 | ||||
10899 | NewND = NewDecl; | |||
10900 | } else { | |||
10901 | if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { | |||
10902 | setTagNameForLinkagePurposes(TD, NewTD); | |||
10903 | handleTagNumbering(TD, S); | |||
10904 | } | |||
10905 | ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); | |||
10906 | NewND = NewTD; | |||
10907 | } | |||
10908 | ||||
10909 | PushOnScopeChains(NewND, S); | |||
10910 | ActOnDocumentableDecl(NewND); | |||
10911 | return NewND; | |||
10912 | } | |||
10913 | ||||
10914 | Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, | |||
10915 | SourceLocation AliasLoc, | |||
10916 | IdentifierInfo *Alias, CXXScopeSpec &SS, | |||
10917 | SourceLocation IdentLoc, | |||
10918 | IdentifierInfo *Ident) { | |||
10919 | ||||
10920 | // Lookup the namespace name. | |||
10921 | LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); | |||
10922 | LookupParsedName(R, S, &SS); | |||
10923 | ||||
10924 | if (R.isAmbiguous()) | |||
10925 | return nullptr; | |||
10926 | ||||
10927 | if (R.empty()) { | |||
10928 | if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { | |||
10929 | Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); | |||
10930 | return nullptr; | |||
10931 | } | |||
10932 | } | |||
10933 | assert(!R.isAmbiguous() && !R.empty())((!R.isAmbiguous() && !R.empty()) ? static_cast<void > (0) : __assert_fail ("!R.isAmbiguous() && !R.empty()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 10933, __PRETTY_FUNCTION__)); | |||
10934 | NamedDecl *ND = R.getRepresentativeDecl(); | |||
10935 | ||||
10936 | // Check if we have a previous declaration with the same name. | |||
10937 | LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, | |||
10938 | ForVisibleRedeclaration); | |||
10939 | LookupName(PrevR, S); | |||
10940 | ||||
10941 | // Check we're not shadowing a template parameter. | |||
10942 | if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { | |||
10943 | DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); | |||
10944 | PrevR.clear(); | |||
10945 | } | |||
10946 | ||||
10947 | // Filter out any other lookup result from an enclosing scope. | |||
10948 | FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, | |||
10949 | /*AllowInlineNamespace*/false); | |||
10950 | ||||
10951 | // Find the previous declaration and check that we can redeclare it. | |||
10952 | NamespaceAliasDecl *Prev = nullptr; | |||
10953 | if (PrevR.isSingleResult()) { | |||
10954 | NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); | |||
10955 | if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { | |||
10956 | // We already have an alias with the same name that points to the same | |||
10957 | // namespace; check that it matches. | |||
10958 | if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { | |||
10959 | Prev = AD; | |||
10960 | } else if (isVisible(PrevDecl)) { | |||
10961 | Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) | |||
10962 | << Alias; | |||
10963 | Diag(AD->getLocation(), diag::note_previous_namespace_alias) | |||
10964 | << AD->getNamespace(); | |||
10965 | return nullptr; | |||
10966 | } | |||
10967 | } else if (isVisible(PrevDecl)) { | |||
10968 | unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) | |||
10969 | ? diag::err_redefinition | |||
10970 | : diag::err_redefinition_different_kind; | |||
10971 | Diag(AliasLoc, DiagID) << Alias; | |||
10972 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); | |||
10973 | return nullptr; | |||
10974 | } | |||
10975 | } | |||
10976 | ||||
10977 | // The use of a nested name specifier may trigger deprecation warnings. | |||
10978 | DiagnoseUseOfDecl(ND, IdentLoc); | |||
10979 | ||||
10980 | NamespaceAliasDecl *AliasDecl = | |||
10981 | NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, | |||
10982 | Alias, SS.getWithLocInContext(Context), | |||
10983 | IdentLoc, ND); | |||
10984 | if (Prev) | |||
10985 | AliasDecl->setPreviousDecl(Prev); | |||
10986 | ||||
10987 | PushOnScopeChains(AliasDecl, S); | |||
10988 | return AliasDecl; | |||
10989 | } | |||
10990 | ||||
10991 | namespace { | |||
10992 | struct SpecialMemberExceptionSpecInfo | |||
10993 | : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { | |||
10994 | SourceLocation Loc; | |||
10995 | Sema::ImplicitExceptionSpecification ExceptSpec; | |||
10996 | ||||
10997 | SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, | |||
10998 | Sema::CXXSpecialMember CSM, | |||
10999 | Sema::InheritedConstructorInfo *ICI, | |||
11000 | SourceLocation Loc) | |||
11001 | : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} | |||
11002 | ||||
11003 | bool visitBase(CXXBaseSpecifier *Base); | |||
11004 | bool visitField(FieldDecl *FD); | |||
11005 | ||||
11006 | void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, | |||
11007 | unsigned Quals); | |||
11008 | ||||
11009 | void visitSubobjectCall(Subobject Subobj, | |||
11010 | Sema::SpecialMemberOverloadResult SMOR); | |||
11011 | }; | |||
11012 | } | |||
11013 | ||||
11014 | bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { | |||
11015 | auto *RT = Base->getType()->getAs<RecordType>(); | |||
11016 | if (!RT) | |||
11017 | return false; | |||
11018 | ||||
11019 | auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); | |||
11020 | Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); | |||
11021 | if (auto *BaseCtor = SMOR.getMethod()) { | |||
11022 | visitSubobjectCall(Base, BaseCtor); | |||
11023 | return false; | |||
11024 | } | |||
11025 | ||||
11026 | visitClassSubobject(BaseClass, Base, 0); | |||
11027 | return false; | |||
11028 | } | |||
11029 | ||||
11030 | bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { | |||
11031 | if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { | |||
11032 | Expr *E = FD->getInClassInitializer(); | |||
11033 | if (!E) | |||
11034 | // FIXME: It's a little wasteful to build and throw away a | |||
11035 | // CXXDefaultInitExpr here. | |||
11036 | // FIXME: We should have a single context note pointing at Loc, and | |||
11037 | // this location should be MD->getLocation() instead, since that's | |||
11038 | // the location where we actually use the default init expression. | |||
11039 | E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); | |||
11040 | if (E) | |||
11041 | ExceptSpec.CalledExpr(E); | |||
11042 | } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) | |||
11043 | ->getAs<RecordType>()) { | |||
11044 | visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, | |||
11045 | FD->getType().getCVRQualifiers()); | |||
11046 | } | |||
11047 | return false; | |||
11048 | } | |||
11049 | ||||
11050 | void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, | |||
11051 | Subobject Subobj, | |||
11052 | unsigned Quals) { | |||
11053 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); | |||
11054 | bool IsMutable = Field && Field->isMutable(); | |||
11055 | visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); | |||
11056 | } | |||
11057 | ||||
11058 | void SpecialMemberExceptionSpecInfo::visitSubobjectCall( | |||
11059 | Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { | |||
11060 | // Note, if lookup fails, it doesn't matter what exception specification we | |||
11061 | // choose because the special member will be deleted. | |||
11062 | if (CXXMethodDecl *MD = SMOR.getMethod()) | |||
11063 | ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); | |||
11064 | } | |||
11065 | ||||
11066 | namespace { | |||
11067 | /// RAII object to register a special member as being currently declared. | |||
11068 | struct ComputingExceptionSpec { | |||
11069 | Sema &S; | |||
11070 | ||||
11071 | ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc) | |||
11072 | : S(S) { | |||
11073 | Sema::CodeSynthesisContext Ctx; | |||
11074 | Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; | |||
11075 | Ctx.PointOfInstantiation = Loc; | |||
11076 | Ctx.Entity = MD; | |||
11077 | S.pushCodeSynthesisContext(Ctx); | |||
11078 | } | |||
11079 | ~ComputingExceptionSpec() { | |||
11080 | S.popCodeSynthesisContext(); | |||
11081 | } | |||
11082 | }; | |||
11083 | } | |||
11084 | ||||
11085 | bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { | |||
11086 | llvm::APSInt Result; | |||
11087 | ExprResult Converted = CheckConvertedConstantExpression( | |||
11088 | ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); | |||
11089 | ExplicitSpec.setExpr(Converted.get()); | |||
11090 | if (Converted.isUsable() && !Converted.get()->isValueDependent()) { | |||
11091 | ExplicitSpec.setKind(Result.getBoolValue() | |||
11092 | ? ExplicitSpecKind::ResolvedTrue | |||
11093 | : ExplicitSpecKind::ResolvedFalse); | |||
11094 | return true; | |||
11095 | } | |||
11096 | ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); | |||
11097 | return false; | |||
11098 | } | |||
11099 | ||||
11100 | ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { | |||
11101 | ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); | |||
11102 | if (!ExplicitExpr->isTypeDependent()) | |||
11103 | tryResolveExplicitSpecifier(ES); | |||
11104 | return ES; | |||
11105 | } | |||
11106 | ||||
11107 | static Sema::ImplicitExceptionSpecification | |||
11108 | ComputeDefaultedSpecialMemberExceptionSpec( | |||
11109 | Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, | |||
11110 | Sema::InheritedConstructorInfo *ICI) { | |||
11111 | ComputingExceptionSpec CES(S, MD, Loc); | |||
11112 | ||||
11113 | CXXRecordDecl *ClassDecl = MD->getParent(); | |||
11114 | ||||
11115 | // C++ [except.spec]p14: | |||
11116 | // An implicitly declared special member function (Clause 12) shall have an | |||
11117 | // exception-specification. [...] | |||
11118 | SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); | |||
11119 | if (ClassDecl->isInvalidDecl()) | |||
11120 | return Info.ExceptSpec; | |||
11121 | ||||
11122 | // FIXME: If this diagnostic fires, we're probably missing a check for | |||
11123 | // attempting to resolve an exception specification before it's known | |||
11124 | // at a higher level. | |||
11125 | if (S.RequireCompleteType(MD->getLocation(), | |||
11126 | S.Context.getRecordType(ClassDecl), | |||
11127 | diag::err_exception_spec_incomplete_type)) | |||
11128 | return Info.ExceptSpec; | |||
11129 | ||||
11130 | // C++1z [except.spec]p7: | |||
11131 | // [Look for exceptions thrown by] a constructor selected [...] to | |||
11132 | // initialize a potentially constructed subobject, | |||
11133 | // C++1z [except.spec]p8: | |||
11134 | // The exception specification for an implicitly-declared destructor, or a | |||
11135 | // destructor without a noexcept-specifier, is potentially-throwing if and | |||
11136 | // only if any of the destructors for any of its potentially constructed | |||
11137 | // subojects is potentially throwing. | |||
11138 | // FIXME: We respect the first rule but ignore the "potentially constructed" | |||
11139 | // in the second rule to resolve a core issue (no number yet) that would have | |||
11140 | // us reject: | |||
11141 | // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; | |||
11142 | // struct B : A {}; | |||
11143 | // struct C : B { void f(); }; | |||
11144 | // ... due to giving B::~B() a non-throwing exception specification. | |||
11145 | Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases | |||
11146 | : Info.VisitAllBases); | |||
11147 | ||||
11148 | return Info.ExceptSpec; | |||
11149 | } | |||
11150 | ||||
11151 | namespace { | |||
11152 | /// RAII object to register a special member as being currently declared. | |||
11153 | struct DeclaringSpecialMember { | |||
11154 | Sema &S; | |||
11155 | Sema::SpecialMemberDecl D; | |||
11156 | Sema::ContextRAII SavedContext; | |||
11157 | bool WasAlreadyBeingDeclared; | |||
11158 | ||||
11159 | DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) | |||
11160 | : S(S), D(RD, CSM), SavedContext(S, RD) { | |||
11161 | WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; | |||
11162 | if (WasAlreadyBeingDeclared) | |||
11163 | // This almost never happens, but if it does, ensure that our cache | |||
11164 | // doesn't contain a stale result. | |||
11165 | S.SpecialMemberCache.clear(); | |||
11166 | else { | |||
11167 | // Register a note to be produced if we encounter an error while | |||
11168 | // declaring the special member. | |||
11169 | Sema::CodeSynthesisContext Ctx; | |||
11170 | Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; | |||
11171 | // FIXME: We don't have a location to use here. Using the class's | |||
11172 | // location maintains the fiction that we declare all special members | |||
11173 | // with the class, but (1) it's not clear that lying about that helps our | |||
11174 | // users understand what's going on, and (2) there may be outer contexts | |||
11175 | // on the stack (some of which are relevant) and printing them exposes | |||
11176 | // our lies. | |||
11177 | Ctx.PointOfInstantiation = RD->getLocation(); | |||
11178 | Ctx.Entity = RD; | |||
11179 | Ctx.SpecialMember = CSM; | |||
11180 | S.pushCodeSynthesisContext(Ctx); | |||
11181 | } | |||
11182 | } | |||
11183 | ~DeclaringSpecialMember() { | |||
11184 | if (!WasAlreadyBeingDeclared) { | |||
11185 | S.SpecialMembersBeingDeclared.erase(D); | |||
11186 | S.popCodeSynthesisContext(); | |||
11187 | } | |||
11188 | } | |||
11189 | ||||
11190 | /// Are we already trying to declare this special member? | |||
11191 | bool isAlreadyBeingDeclared() const { | |||
11192 | return WasAlreadyBeingDeclared; | |||
11193 | } | |||
11194 | }; | |||
11195 | } | |||
11196 | ||||
11197 | void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { | |||
11198 | // Look up any existing declarations, but don't trigger declaration of all | |||
11199 | // implicit special members with this name. | |||
11200 | DeclarationName Name = FD->getDeclName(); | |||
11201 | LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, | |||
11202 | ForExternalRedeclaration); | |||
11203 | for (auto *D : FD->getParent()->lookup(Name)) | |||
11204 | if (auto *Acceptable = R.getAcceptableDecl(D)) | |||
11205 | R.addDecl(Acceptable); | |||
11206 | R.resolveKind(); | |||
11207 | R.suppressDiagnostics(); | |||
11208 | ||||
11209 | CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); | |||
11210 | } | |||
11211 | ||||
11212 | void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, | |||
11213 | QualType ResultTy, | |||
11214 | ArrayRef<QualType> Args) { | |||
11215 | // Build an exception specification pointing back at this constructor. | |||
11216 | FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); | |||
11217 | ||||
11218 | if (getLangOpts().OpenCLCPlusPlus) { | |||
11219 | // OpenCL: Implicitly defaulted special member are of the generic address | |||
11220 | // space. | |||
11221 | EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic); | |||
11222 | } | |||
11223 | ||||
11224 | auto QT = Context.getFunctionType(ResultTy, Args, EPI); | |||
11225 | SpecialMem->setType(QT); | |||
11226 | } | |||
11227 | ||||
11228 | CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( | |||
11229 | CXXRecordDecl *ClassDecl) { | |||
11230 | // C++ [class.ctor]p5: | |||
11231 | // A default constructor for a class X is a constructor of class X | |||
11232 | // that can be called without an argument. If there is no | |||
11233 | // user-declared constructor for class X, a default constructor is | |||
11234 | // implicitly declared. An implicitly-declared default constructor | |||
11235 | // is an inline public member of its class. | |||
11236 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11237, __PRETTY_FUNCTION__)) | |||
11237 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11237, __PRETTY_FUNCTION__)); | |||
11238 | ||||
11239 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); | |||
11240 | if (DSM.isAlreadyBeingDeclared()) | |||
11241 | return nullptr; | |||
11242 | ||||
11243 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
11244 | CXXDefaultConstructor, | |||
11245 | false); | |||
11246 | ||||
11247 | // Create the actual constructor declaration. | |||
11248 | CanQualType ClassType | |||
11249 | = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); | |||
11250 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
11251 | DeclarationName Name | |||
11252 | = Context.DeclarationNames.getCXXConstructorName(ClassType); | |||
11253 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
11254 | CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( | |||
11255 | Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), | |||
11256 | /*TInfo=*/nullptr, ExplicitSpecifier(), | |||
11257 | /*isInline=*/true, /*isImplicitlyDeclared=*/true, | |||
11258 | Constexpr ? CSK_constexpr : CSK_unspecified); | |||
11259 | DefaultCon->setAccess(AS_public); | |||
11260 | DefaultCon->setDefaulted(); | |||
11261 | ||||
11262 | if (getLangOpts().CUDA) { | |||
11263 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, | |||
11264 | DefaultCon, | |||
11265 | /* ConstRHS */ false, | |||
11266 | /* Diagnose */ false); | |||
11267 | } | |||
11268 | ||||
11269 | setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); | |||
11270 | ||||
11271 | // We don't need to use SpecialMemberIsTrivial here; triviality for default | |||
11272 | // constructors is easy to compute. | |||
11273 | DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); | |||
11274 | ||||
11275 | // Note that we have declared this constructor. | |||
11276 | ++getASTContext().NumImplicitDefaultConstructorsDeclared; | |||
11277 | ||||
11278 | Scope *S = getScopeForContext(ClassDecl); | |||
11279 | CheckImplicitSpecialMemberDeclaration(S, DefaultCon); | |||
11280 | ||||
11281 | if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) | |||
11282 | SetDeclDeleted(DefaultCon, ClassLoc); | |||
11283 | ||||
11284 | if (S) | |||
11285 | PushOnScopeChains(DefaultCon, S, false); | |||
11286 | ClassDecl->addDecl(DefaultCon); | |||
11287 | ||||
11288 | return DefaultCon; | |||
11289 | } | |||
11290 | ||||
11291 | void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, | |||
11292 | CXXConstructorDecl *Constructor) { | |||
11293 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11296, __PRETTY_FUNCTION__)) | |||
11294 | !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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11296, __PRETTY_FUNCTION__)) | |||
11295 | !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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11296, __PRETTY_FUNCTION__)) | |||
11296 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11296, __PRETTY_FUNCTION__)); | |||
11297 | if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) | |||
11298 | return; | |||
11299 | ||||
11300 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
11301 | assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor")((ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitDefaultConstructor - invalid constructor\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11301, __PRETTY_FUNCTION__)); | |||
11302 | ||||
11303 | SynthesizedFunctionScope Scope(*this, Constructor); | |||
11304 | ||||
11305 | // The exception specification is needed because we are defining the | |||
11306 | // function. | |||
11307 | ResolveExceptionSpec(CurrentLocation, | |||
11308 | Constructor->getType()->castAs<FunctionProtoType>()); | |||
11309 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
11310 | ||||
11311 | // Add a context note for diagnostics produced after this point. | |||
11312 | Scope.addContextNote(CurrentLocation); | |||
11313 | ||||
11314 | if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { | |||
11315 | Constructor->setInvalidDecl(); | |||
11316 | return; | |||
11317 | } | |||
11318 | ||||
11319 | SourceLocation Loc = Constructor->getEndLoc().isValid() | |||
11320 | ? Constructor->getEndLoc() | |||
11321 | : Constructor->getLocation(); | |||
11322 | Constructor->setBody(new (Context) CompoundStmt(Loc)); | |||
11323 | Constructor->markUsed(Context); | |||
11324 | ||||
11325 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
11326 | L->CompletedImplicitDefinition(Constructor); | |||
11327 | } | |||
11328 | ||||
11329 | DiagnoseUninitializedFields(*this, Constructor); | |||
11330 | } | |||
11331 | ||||
11332 | void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { | |||
11333 | // Perform any delayed checks on exception specifications. | |||
11334 | CheckDelayedMemberExceptionSpecs(); | |||
11335 | } | |||
11336 | ||||
11337 | /// Find or create the fake constructor we synthesize to model constructing an | |||
11338 | /// object of a derived class via a constructor of a base class. | |||
11339 | CXXConstructorDecl * | |||
11340 | Sema::findInheritingConstructor(SourceLocation Loc, | |||
11341 | CXXConstructorDecl *BaseCtor, | |||
11342 | ConstructorUsingShadowDecl *Shadow) { | |||
11343 | CXXRecordDecl *Derived = Shadow->getParent(); | |||
11344 | SourceLocation UsingLoc = Shadow->getLocation(); | |||
11345 | ||||
11346 | // FIXME: Add a new kind of DeclarationName for an inherited constructor. | |||
11347 | // For now we use the name of the base class constructor as a member of the | |||
11348 | // derived class to indicate a (fake) inherited constructor name. | |||
11349 | DeclarationName Name = BaseCtor->getDeclName(); | |||
11350 | ||||
11351 | // Check to see if we already have a fake constructor for this inherited | |||
11352 | // constructor call. | |||
11353 | for (NamedDecl *Ctor : Derived->lookup(Name)) | |||
11354 | if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) | |||
11355 | ->getInheritedConstructor() | |||
11356 | .getConstructor(), | |||
11357 | BaseCtor)) | |||
11358 | return cast<CXXConstructorDecl>(Ctor); | |||
11359 | ||||
11360 | DeclarationNameInfo NameInfo(Name, UsingLoc); | |||
11361 | TypeSourceInfo *TInfo = | |||
11362 | Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); | |||
11363 | FunctionProtoTypeLoc ProtoLoc = | |||
11364 | TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); | |||
11365 | ||||
11366 | // Check the inherited constructor is valid and find the list of base classes | |||
11367 | // from which it was inherited. | |||
11368 | InheritedConstructorInfo ICI(*this, Loc, Shadow); | |||
11369 | ||||
11370 | bool Constexpr = | |||
11371 | BaseCtor->isConstexpr() && | |||
11372 | defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, | |||
11373 | false, BaseCtor, &ICI); | |||
11374 | ||||
11375 | CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( | |||
11376 | Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, | |||
11377 | BaseCtor->getExplicitSpecifier(), /*isInline=*/true, | |||
11378 | /*isImplicitlyDeclared=*/true, | |||
11379 | Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, | |||
11380 | InheritedConstructor(Shadow, BaseCtor)); | |||
11381 | if (Shadow->isInvalidDecl()) | |||
11382 | DerivedCtor->setInvalidDecl(); | |||
11383 | ||||
11384 | // Build an unevaluated exception specification for this fake constructor. | |||
11385 | const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); | |||
11386 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | |||
11387 | EPI.ExceptionSpec.Type = EST_Unevaluated; | |||
11388 | EPI.ExceptionSpec.SourceDecl = DerivedCtor; | |||
11389 | DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), | |||
11390 | FPT->getParamTypes(), EPI)); | |||
11391 | ||||
11392 | // Build the parameter declarations. | |||
11393 | SmallVector<ParmVarDecl *, 16> ParamDecls; | |||
11394 | for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { | |||
11395 | TypeSourceInfo *TInfo = | |||
11396 | Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); | |||
11397 | ParmVarDecl *PD = ParmVarDecl::Create( | |||
11398 | Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, | |||
11399 | FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); | |||
11400 | PD->setScopeInfo(0, I); | |||
11401 | PD->setImplicit(); | |||
11402 | // Ensure attributes are propagated onto parameters (this matters for | |||
11403 | // format, pass_object_size, ...). | |||
11404 | mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); | |||
11405 | ParamDecls.push_back(PD); | |||
11406 | ProtoLoc.setParam(I, PD); | |||
11407 | } | |||
11408 | ||||
11409 | // Set up the new constructor. | |||
11410 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11410, __PRETTY_FUNCTION__)); | |||
11411 | DerivedCtor->setAccess(BaseCtor->getAccess()); | |||
11412 | DerivedCtor->setParams(ParamDecls); | |||
11413 | Derived->addDecl(DerivedCtor); | |||
11414 | ||||
11415 | if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) | |||
11416 | SetDeclDeleted(DerivedCtor, UsingLoc); | |||
11417 | ||||
11418 | return DerivedCtor; | |||
11419 | } | |||
11420 | ||||
11421 | void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { | |||
11422 | InheritedConstructorInfo ICI(*this, Ctor->getLocation(), | |||
11423 | Ctor->getInheritedConstructor().getShadowDecl()); | |||
11424 | ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, | |||
11425 | /*Diagnose*/true); | |||
11426 | } | |||
11427 | ||||
11428 | void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, | |||
11429 | CXXConstructorDecl *Constructor) { | |||
11430 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
11431 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11433, __PRETTY_FUNCTION__)) | |||
11432 | !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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11433, __PRETTY_FUNCTION__)) | |||
11433 | !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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11433, __PRETTY_FUNCTION__)); | |||
11434 | if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) | |||
11435 | return; | |||
11436 | ||||
11437 | // Initializations are performed "as if by a defaulted default constructor", | |||
11438 | // so enter the appropriate scope. | |||
11439 | SynthesizedFunctionScope Scope(*this, Constructor); | |||
11440 | ||||
11441 | // The exception specification is needed because we are defining the | |||
11442 | // function. | |||
11443 | ResolveExceptionSpec(CurrentLocation, | |||
11444 | Constructor->getType()->castAs<FunctionProtoType>()); | |||
11445 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
11446 | ||||
11447 | // Add a context note for diagnostics produced after this point. | |||
11448 | Scope.addContextNote(CurrentLocation); | |||
11449 | ||||
11450 | ConstructorUsingShadowDecl *Shadow = | |||
11451 | Constructor->getInheritedConstructor().getShadowDecl(); | |||
11452 | CXXConstructorDecl *InheritedCtor = | |||
11453 | Constructor->getInheritedConstructor().getConstructor(); | |||
11454 | ||||
11455 | // [class.inhctor.init]p1: | |||
11456 | // initialization proceeds as if a defaulted default constructor is used to | |||
11457 | // initialize the D object and each base class subobject from which the | |||
11458 | // constructor was inherited | |||
11459 | ||||
11460 | InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); | |||
11461 | CXXRecordDecl *RD = Shadow->getParent(); | |||
11462 | SourceLocation InitLoc = Shadow->getLocation(); | |||
11463 | ||||
11464 | // Build explicit initializers for all base classes from which the | |||
11465 | // constructor was inherited. | |||
11466 | SmallVector<CXXCtorInitializer*, 8> Inits; | |||
11467 | for (bool VBase : {false, true}) { | |||
11468 | for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { | |||
11469 | if (B.isVirtual() != VBase) | |||
11470 | continue; | |||
11471 | ||||
11472 | auto *BaseRD = B.getType()->getAsCXXRecordDecl(); | |||
11473 | if (!BaseRD) | |||
11474 | continue; | |||
11475 | ||||
11476 | auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); | |||
11477 | if (!BaseCtor.first) | |||
11478 | continue; | |||
11479 | ||||
11480 | MarkFunctionReferenced(CurrentLocation, BaseCtor.first); | |||
11481 | ExprResult Init = new (Context) CXXInheritedCtorInitExpr( | |||
11482 | InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); | |||
11483 | ||||
11484 | auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); | |||
11485 | Inits.push_back(new (Context) CXXCtorInitializer( | |||
11486 | Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, | |||
11487 | SourceLocation())); | |||
11488 | } | |||
11489 | } | |||
11490 | ||||
11491 | // We now proceed as if for a defaulted default constructor, with the relevant | |||
11492 | // initializers replaced. | |||
11493 | ||||
11494 | if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { | |||
11495 | Constructor->setInvalidDecl(); | |||
11496 | return; | |||
11497 | } | |||
11498 | ||||
11499 | Constructor->setBody(new (Context) CompoundStmt(InitLoc)); | |||
11500 | Constructor->markUsed(Context); | |||
11501 | ||||
11502 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
11503 | L->CompletedImplicitDefinition(Constructor); | |||
11504 | } | |||
11505 | ||||
11506 | DiagnoseUninitializedFields(*this, Constructor); | |||
11507 | } | |||
11508 | ||||
11509 | CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { | |||
11510 | // C++ [class.dtor]p2: | |||
11511 | // If a class has no user-declared destructor, a destructor is | |||
11512 | // declared implicitly. An implicitly-declared destructor is an | |||
11513 | // inline public member of its class. | |||
11514 | assert(ClassDecl->needsImplicitDestructor())((ClassDecl->needsImplicitDestructor()) ? static_cast<void > (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11514, __PRETTY_FUNCTION__)); | |||
11515 | ||||
11516 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); | |||
11517 | if (DSM.isAlreadyBeingDeclared()) | |||
11518 | return nullptr; | |||
11519 | ||||
11520 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
11521 | CXXDestructor, | |||
11522 | false); | |||
11523 | ||||
11524 | // Create the actual destructor declaration. | |||
11525 | CanQualType ClassType | |||
11526 | = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); | |||
11527 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
11528 | DeclarationName Name | |||
11529 | = Context.DeclarationNames.getCXXDestructorName(ClassType); | |||
11530 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
11531 | CXXDestructorDecl *Destructor = | |||
11532 | CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, | |||
11533 | QualType(), nullptr, /*isInline=*/true, | |||
11534 | /*isImplicitlyDeclared=*/true, | |||
11535 | Constexpr ? CSK_constexpr : CSK_unspecified); | |||
11536 | Destructor->setAccess(AS_public); | |||
11537 | Destructor->setDefaulted(); | |||
11538 | ||||
11539 | if (getLangOpts().CUDA) { | |||
11540 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, | |||
11541 | Destructor, | |||
11542 | /* ConstRHS */ false, | |||
11543 | /* Diagnose */ false); | |||
11544 | } | |||
11545 | ||||
11546 | setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); | |||
11547 | ||||
11548 | // We don't need to use SpecialMemberIsTrivial here; triviality for | |||
11549 | // destructors is easy to compute. | |||
11550 | Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); | |||
11551 | Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || | |||
11552 | ClassDecl->hasTrivialDestructorForCall()); | |||
11553 | ||||
11554 | // Note that we have declared this destructor. | |||
11555 | ++getASTContext().NumImplicitDestructorsDeclared; | |||
11556 | ||||
11557 | Scope *S = getScopeForContext(ClassDecl); | |||
11558 | CheckImplicitSpecialMemberDeclaration(S, Destructor); | |||
11559 | ||||
11560 | // We can't check whether an implicit destructor is deleted before we complete | |||
11561 | // the definition of the class, because its validity depends on the alignment | |||
11562 | // of the class. We'll check this from ActOnFields once the class is complete. | |||
11563 | if (ClassDecl->isCompleteDefinition() && | |||
11564 | ShouldDeleteSpecialMember(Destructor, CXXDestructor)) | |||
11565 | SetDeclDeleted(Destructor, ClassLoc); | |||
11566 | ||||
11567 | // Introduce this destructor into its scope. | |||
11568 | if (S) | |||
11569 | PushOnScopeChains(Destructor, S, false); | |||
11570 | ClassDecl->addDecl(Destructor); | |||
11571 | ||||
11572 | return Destructor; | |||
11573 | } | |||
11574 | ||||
11575 | void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, | |||
11576 | CXXDestructorDecl *Destructor) { | |||
11577 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11580, __PRETTY_FUNCTION__)) | |||
11578 | !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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11580, __PRETTY_FUNCTION__)) | |||
11579 | !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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11580, __PRETTY_FUNCTION__)) | |||
11580 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11580, __PRETTY_FUNCTION__)); | |||
11581 | if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) | |||
11582 | return; | |||
11583 | ||||
11584 | CXXRecordDecl *ClassDecl = Destructor->getParent(); | |||
11585 | assert(ClassDecl && "DefineImplicitDestructor - invalid destructor")((ClassDecl && "DefineImplicitDestructor - invalid destructor" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitDestructor - invalid destructor\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11585, __PRETTY_FUNCTION__)); | |||
11586 | ||||
11587 | SynthesizedFunctionScope Scope(*this, Destructor); | |||
11588 | ||||
11589 | // The exception specification is needed because we are defining the | |||
11590 | // function. | |||
11591 | ResolveExceptionSpec(CurrentLocation, | |||
11592 | Destructor->getType()->castAs<FunctionProtoType>()); | |||
11593 | MarkVTableUsed(CurrentLocation, ClassDecl); | |||
11594 | ||||
11595 | // Add a context note for diagnostics produced after this point. | |||
11596 | Scope.addContextNote(CurrentLocation); | |||
11597 | ||||
11598 | MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), | |||
11599 | Destructor->getParent()); | |||
11600 | ||||
11601 | if (CheckDestructor(Destructor)) { | |||
11602 | Destructor->setInvalidDecl(); | |||
11603 | return; | |||
11604 | } | |||
11605 | ||||
11606 | SourceLocation Loc = Destructor->getEndLoc().isValid() | |||
11607 | ? Destructor->getEndLoc() | |||
11608 | : Destructor->getLocation(); | |||
11609 | Destructor->setBody(new (Context) CompoundStmt(Loc)); | |||
11610 | Destructor->markUsed(Context); | |||
11611 | ||||
11612 | if (ASTMutationListener *L = getASTMutationListener()) { | |||
11613 | L->CompletedImplicitDefinition(Destructor); | |||
11614 | } | |||
11615 | } | |||
11616 | ||||
11617 | /// Perform any semantic analysis which needs to be delayed until all | |||
11618 | /// pending class member declarations have been parsed. | |||
11619 | void Sema::ActOnFinishCXXMemberDecls() { | |||
11620 | // If the context is an invalid C++ class, just suppress these checks. | |||
11621 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { | |||
11622 | if (Record->isInvalidDecl()) { | |||
11623 | DelayedOverridingExceptionSpecChecks.clear(); | |||
11624 | DelayedEquivalentExceptionSpecChecks.clear(); | |||
11625 | return; | |||
11626 | } | |||
11627 | checkForMultipleExportedDefaultConstructors(*this, Record); | |||
11628 | } | |||
11629 | } | |||
11630 | ||||
11631 | void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { | |||
11632 | referenceDLLExportedClassMethods(); | |||
11633 | ||||
11634 | if (!DelayedDllExportMemberFunctions.empty()) { | |||
| ||||
11635 | SmallVector<CXXMethodDecl*, 4> WorkList; | |||
11636 | std::swap(DelayedDllExportMemberFunctions, WorkList); | |||
11637 | for (CXXMethodDecl *M : WorkList) { | |||
11638 | DefineImplicitSpecialMember(*this, M, M->getLocation()); | |||
11639 | ||||
11640 | // Pass the method to the consumer to get emitted. This is not necessary | |||
11641 | // for explicit instantiation definitions, as they will get emitted | |||
11642 | // anyway. | |||
11643 | if (M->getParent()->getTemplateSpecializationKind() != | |||
11644 | TSK_ExplicitInstantiationDefinition) | |||
11645 | ActOnFinishInlineFunctionDef(M); | |||
11646 | } | |||
11647 | } | |||
11648 | } | |||
11649 | ||||
11650 | void Sema::referenceDLLExportedClassMethods() { | |||
11651 | if (!DelayedDllExportClasses.empty()) { | |||
11652 | // Calling ReferenceDllExportedMembers might cause the current function to | |||
11653 | // be called again, so use a local copy of DelayedDllExportClasses. | |||
11654 | SmallVector<CXXRecordDecl *, 4> WorkList; | |||
11655 | std::swap(DelayedDllExportClasses, WorkList); | |||
11656 | for (CXXRecordDecl *Class : WorkList) | |||
11657 | ReferenceDllExportedMembers(*this, Class); | |||
11658 | } | |||
11659 | } | |||
11660 | ||||
11661 | void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { | |||
11662 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11663, __PRETTY_FUNCTION__)) | |||
11663 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11663, __PRETTY_FUNCTION__)); | |||
11664 | ||||
11665 | if (Destructor->isDependentContext()) | |||
11666 | return; | |||
11667 | ||||
11668 | // C++11 [class.dtor]p3: | |||
11669 | // A declaration of a destructor that does not have an exception- | |||
11670 | // specification is implicitly considered to have the same exception- | |||
11671 | // specification as an implicit declaration. | |||
11672 | const FunctionProtoType *DtorType = Destructor->getType()-> | |||
11673 | getAs<FunctionProtoType>(); | |||
11674 | if (DtorType->hasExceptionSpec()) | |||
11675 | return; | |||
11676 | ||||
11677 | // Replace the destructor's type, building off the existing one. Fortunately, | |||
11678 | // the only thing of interest in the destructor type is its extended info. | |||
11679 | // The return and arguments are fixed. | |||
11680 | FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); | |||
11681 | EPI.ExceptionSpec.Type = EST_Unevaluated; | |||
11682 | EPI.ExceptionSpec.SourceDecl = Destructor; | |||
11683 | Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); | |||
11684 | ||||
11685 | // FIXME: If the destructor has a body that could throw, and the newly created | |||
11686 | // spec doesn't allow exceptions, we should emit a warning, because this | |||
11687 | // change in behavior can break conforming C++03 programs at runtime. | |||
11688 | // However, we don't have a body or an exception specification yet, so it | |||
11689 | // needs to be done somewhere else. | |||
11690 | } | |||
11691 | ||||
11692 | namespace { | |||
11693 | /// An abstract base class for all helper classes used in building the | |||
11694 | // copy/move operators. These classes serve as factory functions and help us | |||
11695 | // avoid using the same Expr* in the AST twice. | |||
11696 | class ExprBuilder { | |||
11697 | ExprBuilder(const ExprBuilder&) = delete; | |||
11698 | ExprBuilder &operator=(const ExprBuilder&) = delete; | |||
11699 | ||||
11700 | protected: | |||
11701 | static Expr *assertNotNull(Expr *E) { | |||
11702 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11702, __PRETTY_FUNCTION__)); | |||
11703 | return E; | |||
11704 | } | |||
11705 | ||||
11706 | public: | |||
11707 | ExprBuilder() {} | |||
11708 | virtual ~ExprBuilder() {} | |||
11709 | ||||
11710 | virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; | |||
11711 | }; | |||
11712 | ||||
11713 | class RefBuilder: public ExprBuilder { | |||
11714 | VarDecl *Var; | |||
11715 | QualType VarType; | |||
11716 | ||||
11717 | public: | |||
11718 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11719 | return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); | |||
11720 | } | |||
11721 | ||||
11722 | RefBuilder(VarDecl *Var, QualType VarType) | |||
11723 | : Var(Var), VarType(VarType) {} | |||
11724 | }; | |||
11725 | ||||
11726 | class ThisBuilder: public ExprBuilder { | |||
11727 | public: | |||
11728 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11729 | return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); | |||
11730 | } | |||
11731 | }; | |||
11732 | ||||
11733 | class CastBuilder: public ExprBuilder { | |||
11734 | const ExprBuilder &Builder; | |||
11735 | QualType Type; | |||
11736 | ExprValueKind Kind; | |||
11737 | const CXXCastPath &Path; | |||
11738 | ||||
11739 | public: | |||
11740 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11741 | return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, | |||
11742 | CK_UncheckedDerivedToBase, Kind, | |||
11743 | &Path).get()); | |||
11744 | } | |||
11745 | ||||
11746 | CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, | |||
11747 | const CXXCastPath &Path) | |||
11748 | : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} | |||
11749 | }; | |||
11750 | ||||
11751 | class DerefBuilder: public ExprBuilder { | |||
11752 | const ExprBuilder &Builder; | |||
11753 | ||||
11754 | public: | |||
11755 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11756 | return assertNotNull( | |||
11757 | S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); | |||
11758 | } | |||
11759 | ||||
11760 | DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} | |||
11761 | }; | |||
11762 | ||||
11763 | class MemberBuilder: public ExprBuilder { | |||
11764 | const ExprBuilder &Builder; | |||
11765 | QualType Type; | |||
11766 | CXXScopeSpec SS; | |||
11767 | bool IsArrow; | |||
11768 | LookupResult &MemberLookup; | |||
11769 | ||||
11770 | public: | |||
11771 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11772 | return assertNotNull(S.BuildMemberReferenceExpr( | |||
11773 | Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), | |||
11774 | nullptr, MemberLookup, nullptr, nullptr).get()); | |||
11775 | } | |||
11776 | ||||
11777 | MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, | |||
11778 | LookupResult &MemberLookup) | |||
11779 | : Builder(Builder), Type(Type), IsArrow(IsArrow), | |||
11780 | MemberLookup(MemberLookup) {} | |||
11781 | }; | |||
11782 | ||||
11783 | class MoveCastBuilder: public ExprBuilder { | |||
11784 | const ExprBuilder &Builder; | |||
11785 | ||||
11786 | public: | |||
11787 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11788 | return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); | |||
11789 | } | |||
11790 | ||||
11791 | MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} | |||
11792 | }; | |||
11793 | ||||
11794 | class LvalueConvBuilder: public ExprBuilder { | |||
11795 | const ExprBuilder &Builder; | |||
11796 | ||||
11797 | public: | |||
11798 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11799 | return assertNotNull( | |||
11800 | S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); | |||
11801 | } | |||
11802 | ||||
11803 | LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} | |||
11804 | }; | |||
11805 | ||||
11806 | class SubscriptBuilder: public ExprBuilder { | |||
11807 | const ExprBuilder &Base; | |||
11808 | const ExprBuilder &Index; | |||
11809 | ||||
11810 | public: | |||
11811 | Expr *build(Sema &S, SourceLocation Loc) const override { | |||
11812 | return assertNotNull(S.CreateBuiltinArraySubscriptExpr( | |||
11813 | Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); | |||
11814 | } | |||
11815 | ||||
11816 | SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) | |||
11817 | : Base(Base), Index(Index) {} | |||
11818 | }; | |||
11819 | ||||
11820 | } // end anonymous namespace | |||
11821 | ||||
11822 | /// When generating a defaulted copy or move assignment operator, if a field | |||
11823 | /// should be copied with __builtin_memcpy rather than via explicit assignments, | |||
11824 | /// do so. This optimization only applies for arrays of scalars, and for arrays | |||
11825 | /// of class type where the selected copy/move-assignment operator is trivial. | |||
11826 | static StmtResult | |||
11827 | buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, | |||
11828 | const ExprBuilder &ToB, const ExprBuilder &FromB) { | |||
11829 | // Compute the size of the memory buffer to be copied. | |||
11830 | QualType SizeType = S.Context.getSizeType(); | |||
11831 | llvm::APInt Size(S.Context.getTypeSize(SizeType), | |||
11832 | S.Context.getTypeSizeInChars(T).getQuantity()); | |||
11833 | ||||
11834 | // Take the address of the field references for "from" and "to". We | |||
11835 | // directly construct UnaryOperators here because semantic analysis | |||
11836 | // does not permit us to take the address of an xvalue. | |||
11837 | Expr *From = FromB.build(S, Loc); | |||
11838 | From = new (S.Context) UnaryOperator(From, UO_AddrOf, | |||
11839 | S.Context.getPointerType(From->getType()), | |||
11840 | VK_RValue, OK_Ordinary, Loc, false); | |||
11841 | Expr *To = ToB.build(S, Loc); | |||
11842 | To = new (S.Context) UnaryOperator(To, UO_AddrOf, | |||
11843 | S.Context.getPointerType(To->getType()), | |||
11844 | VK_RValue, OK_Ordinary, Loc, false); | |||
11845 | ||||
11846 | const Type *E = T->getBaseElementTypeUnsafe(); | |||
11847 | bool NeedsCollectableMemCpy = | |||
11848 | E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); | |||
| ||||
11849 | ||||
11850 | // Create a reference to the __builtin_objc_memmove_collectable function | |||
11851 | StringRef MemCpyName = NeedsCollectableMemCpy ? | |||
11852 | "__builtin_objc_memmove_collectable" : | |||
11853 | "__builtin_memcpy"; | |||
11854 | LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, | |||
11855 | Sema::LookupOrdinaryName); | |||
11856 | S.LookupName(R, S.TUScope, true); | |||
11857 | ||||
11858 | FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); | |||
11859 | if (!MemCpy) | |||
11860 | // Something went horribly wrong earlier, and we will have complained | |||
11861 | // about it. | |||
11862 | return StmtError(); | |||
11863 | ||||
11864 | ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, | |||
11865 | VK_RValue, Loc, nullptr); | |||
11866 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11866, __PRETTY_FUNCTION__)); | |||
11867 | ||||
11868 | Expr *CallArgs[] = { | |||
11869 | To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) | |||
11870 | }; | |||
11871 | ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), | |||
11872 | Loc, CallArgs, Loc); | |||
11873 | ||||
11874 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 11874, __PRETTY_FUNCTION__)); | |||
11875 | return Call.getAs<Stmt>(); | |||
11876 | } | |||
11877 | ||||
11878 | /// Builds a statement that copies/moves the given entity from \p From to | |||
11879 | /// \c To. | |||
11880 | /// | |||
11881 | /// This routine is used to copy/move the members of a class with an | |||
11882 | /// implicitly-declared copy/move assignment operator. When the entities being | |||
11883 | /// copied are arrays, this routine builds for loops to copy them. | |||
11884 | /// | |||
11885 | /// \param S The Sema object used for type-checking. | |||
11886 | /// | |||
11887 | /// \param Loc The location where the implicit copy/move is being generated. | |||
11888 | /// | |||
11889 | /// \param T The type of the expressions being copied/moved. Both expressions | |||
11890 | /// must have this type. | |||
11891 | /// | |||
11892 | /// \param To The expression we are copying/moving to. | |||
11893 | /// | |||
11894 | /// \param From The expression we are copying/moving from. | |||
11895 | /// | |||
11896 | /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. | |||
11897 | /// Otherwise, it's a non-static member subobject. | |||
11898 | /// | |||
11899 | /// \param Copying Whether we're copying or moving. | |||
11900 | /// | |||
11901 | /// \param Depth Internal parameter recording the depth of the recursion. | |||
11902 | /// | |||
11903 | /// \returns A statement or a loop that copies the expressions, or StmtResult(0) | |||
11904 | /// if a memcpy should be used instead. | |||
11905 | static StmtResult | |||
11906 | buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, | |||
11907 | const ExprBuilder &To, const ExprBuilder &From, | |||
11908 | bool CopyingBaseSubobject, bool Copying, | |||
11909 | unsigned Depth = 0) { | |||
11910 | // C++11 [class.copy]p28: | |||
11911 | // Each subobject is assigned in the manner appropriate to its type: | |||
11912 | // | |||
11913 | // - if the subobject is of class type, as if by a call to operator= with | |||
11914 | // the subobject as the object expression and the corresponding | |||
11915 | // subobject of x as a single function argument (as if by explicit | |||
11916 | // qualification; that is, ignoring any possible virtual overriding | |||
11917 | // functions in more derived classes); | |||
11918 | // | |||
11919 | // C++03 [class.copy]p13: | |||
11920 | // - if the subobject is of class type, the copy assignment operator for | |||
11921 | // the class is used (as if by explicit qualification; that is, | |||
11922 | // ignoring any possible virtual overriding functions in more derived | |||
11923 | // classes); | |||
11924 | if (const RecordType *RecordTy = T->getAs<RecordType>()) { | |||
11925 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); | |||
11926 | ||||
11927 | // Look for operator=. | |||
11928 | DeclarationName Name | |||
11929 | = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); | |||
11930 | LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); | |||
11931 | S.LookupQualifiedName(OpLookup, ClassDecl, false); | |||
11932 | ||||
11933 | // Prior to C++11, filter out any result that isn't a copy/move-assignment | |||
11934 | // operator. | |||
11935 | if (!S.getLangOpts().CPlusPlus11) { | |||
11936 | LookupResult::Filter F = OpLookup.makeFilter(); | |||
11937 | while (F.hasNext()) { | |||
11938 | NamedDecl *D = F.next(); | |||
11939 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) | |||
11940 | if (Method->isCopyAssignmentOperator() || | |||
11941 | (!Copying && Method->isMoveAssignmentOperator())) | |||
11942 | continue; | |||
11943 | ||||
11944 | F.erase(); | |||
11945 | } | |||
11946 | F.done(); | |||
11947 | } | |||
11948 | ||||
11949 | // Suppress the protected check (C++ [class.protected]) for each of the | |||
11950 | // assignment operators we found. This strange dance is required when | |||
11951 | // we're assigning via a base classes's copy-assignment operator. To | |||
11952 | // ensure that we're getting the right base class subobject (without | |||
11953 | // ambiguities), we need to cast "this" to that subobject type; to | |||
11954 | // ensure that we don't go through the virtual call mechanism, we need | |||
11955 | // to qualify the operator= name with the base class (see below). However, | |||
11956 | // this means that if the base class has a protected copy assignment | |||
11957 | // operator, the protected member access check will fail. So, we | |||
11958 | // rewrite "protected" access to "public" access in this case, since we | |||
11959 | // know by construction that we're calling from a derived class. | |||
11960 | if (CopyingBaseSubobject) { | |||
11961 | for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); | |||
11962 | L != LEnd; ++L) { | |||
11963 | if (L.getAccess() == AS_protected) | |||
11964 | L.setAccess(AS_public); | |||
11965 | } | |||
11966 | } | |||
11967 | ||||
11968 | // Create the nested-name-specifier that will be used to qualify the | |||
11969 | // reference to operator=; this is required to suppress the virtual | |||
11970 | // call mechanism. | |||
11971 | CXXScopeSpec SS; | |||
11972 | const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); | |||
11973 | SS.MakeTrivial(S.Context, | |||
11974 | NestedNameSpecifier::Create(S.Context, nullptr, false, | |||
11975 | CanonicalT), | |||
11976 | Loc); | |||
11977 | ||||
11978 | // Create the reference to operator=. | |||
11979 | ExprResult OpEqualRef | |||
11980 | = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, | |||
11981 | SS, /*TemplateKWLoc=*/SourceLocation(), | |||
11982 | /*FirstQualifierInScope=*/nullptr, | |||
11983 | OpLookup, | |||
11984 | /*TemplateArgs=*/nullptr, /*S*/nullptr, | |||
11985 | /*SuppressQualifierCheck=*/true); | |||
11986 | if (OpEqualRef.isInvalid()) | |||
11987 | return StmtError(); | |||
11988 | ||||
11989 | // Build the call to the assignment operator. | |||
11990 | ||||
11991 | Expr *FromInst = From.build(S, Loc); | |||
11992 | ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, | |||
11993 | OpEqualRef.getAs<Expr>(), | |||
11994 | Loc, FromInst, Loc); | |||
11995 | if (Call.isInvalid()) | |||
11996 | return StmtError(); | |||
11997 | ||||
11998 | // If we built a call to a trivial 'operator=' while copying an array, | |||
11999 | // bail out. We'll replace the whole shebang with a memcpy. | |||
12000 | CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); | |||
12001 | if (CE && CE->getMethodDecl()->isTrivial() && Depth) | |||
12002 | return StmtResult((Stmt*)nullptr); | |||
12003 | ||||
12004 | // Convert to an expression-statement, and clean up any produced | |||
12005 | // temporaries. | |||
12006 | return S.ActOnExprStmt(Call); | |||
12007 | } | |||
12008 | ||||
12009 | // - if the subobject is of scalar type, the built-in assignment | |||
12010 | // operator is used. | |||
12011 | const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); | |||
12012 | if (!ArrayTy) { | |||
12013 | ExprResult Assignment = S.CreateBuiltinBinOp( | |||
12014 | Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); | |||
12015 | if (Assignment.isInvalid()) | |||
12016 | return StmtError(); | |||
12017 | return S.ActOnExprStmt(Assignment); | |||
12018 | } | |||
12019 | ||||
12020 | // - if the subobject is an array, each element is assigned, in the | |||
12021 | // manner appropriate to the element type; | |||
12022 | ||||
12023 | // Construct a loop over the array bounds, e.g., | |||
12024 | // | |||
12025 | // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) | |||
12026 | // | |||
12027 | // that will copy each of the array elements. | |||
12028 | QualType SizeType = S.Context.getSizeType(); | |||
12029 | ||||
12030 | // Create the iteration variable. | |||
12031 | IdentifierInfo *IterationVarName = nullptr; | |||
12032 | { | |||
12033 | SmallString<8> Str; | |||
12034 | llvm::raw_svector_ostream OS(Str); | |||
12035 | OS << "__i" << Depth; | |||
12036 | IterationVarName = &S.Context.Idents.get(OS.str()); | |||
12037 | } | |||
12038 | VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, | |||
12039 | IterationVarName, SizeType, | |||
12040 | S.Context.getTrivialTypeSourceInfo(SizeType, Loc), | |||
12041 | SC_None); | |||
12042 | ||||
12043 | // Initialize the iteration variable to zero. | |||
12044 | llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); | |||
12045 | IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); | |||
12046 | ||||
12047 | // Creates a reference to the iteration variable. | |||
12048 | RefBuilder IterationVarRef(IterationVar, SizeType); | |||
12049 | LvalueConvBuilder IterationVarRefRVal(IterationVarRef); | |||
12050 | ||||
12051 | // Create the DeclStmt that holds the iteration variable. | |||
12052 | Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); | |||
12053 | ||||
12054 | // Subscript the "from" and "to" expressions with the iteration variable. | |||
12055 | SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); | |||
12056 | MoveCastBuilder FromIndexMove(FromIndexCopy); | |||
12057 | const ExprBuilder *FromIndex; | |||
12058 | if (Copying) | |||
12059 | FromIndex = &FromIndexCopy; | |||
12060 | else | |||
12061 | FromIndex = &FromIndexMove; | |||
12062 | ||||
12063 | SubscriptBuilder ToIndex(To, IterationVarRefRVal); | |||
12064 | ||||
12065 | // Build the copy/move for an individual element of the array. | |||
12066 | StmtResult Copy = | |||
12067 | buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), | |||
12068 | ToIndex, *FromIndex, CopyingBaseSubobject, | |||
12069 | Copying, Depth + 1); | |||
12070 | // Bail out if copying fails or if we determined that we should use memcpy. | |||
12071 | if (Copy.isInvalid() || !Copy.get()) | |||
12072 | return Copy; | |||
12073 | ||||
12074 | // Create the comparison against the array bound. | |||
12075 | llvm::APInt Upper | |||
12076 | = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); | |||
12077 | Expr *Comparison | |||
12078 | = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), | |||
12079 | IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), | |||
12080 | BO_NE, S.Context.BoolTy, | |||
12081 | VK_RValue, OK_Ordinary, Loc, FPOptions()); | |||
12082 | ||||
12083 | // Create the pre-increment of the iteration variable. We can determine | |||
12084 | // whether the increment will overflow based on the value of the array | |||
12085 | // bound. | |||
12086 | Expr *Increment = new (S.Context) | |||
12087 | UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, | |||
12088 | VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); | |||
12089 | ||||
12090 | // Construct the loop that copies all elements of this array. | |||
12091 | return S.ActOnForStmt( | |||
12092 | Loc, Loc, InitStmt, | |||
12093 | S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), | |||
12094 | S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); | |||
12095 | } | |||
12096 | ||||
12097 | static StmtResult | |||
12098 | buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, | |||
12099 | const ExprBuilder &To, const ExprBuilder &From, | |||
12100 | bool CopyingBaseSubobject, bool Copying) { | |||
12101 | // Maybe we should use a memcpy? | |||
12102 | if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && | |||
12103 | T.isTriviallyCopyableType(S.Context)) | |||
12104 | return buildMemcpyForAssignmentOp(S, Loc, T, To, From); | |||
12105 | ||||
12106 | StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, | |||
12107 | CopyingBaseSubobject, | |||
12108 | Copying, 0)); | |||
12109 | ||||
12110 | // If we ended up picking a trivial assignment operator for an array of a | |||
12111 | // non-trivially-copyable class type, just emit a memcpy. | |||
12112 | if (!Result.isInvalid() && !Result.get()) | |||
12113 | return buildMemcpyForAssignmentOp(S, Loc, T, To, From); | |||
12114 | ||||
12115 | return Result; | |||
12116 | } | |||
12117 | ||||
12118 | CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { | |||
12119 | // Note: The following rules are largely analoguous to the copy | |||
12120 | // constructor rules. Note that virtual bases are not taken into account | |||
12121 | // for determining the argument type of the operator. Note also that | |||
12122 | // operators taking an object instead of a reference are allowed. | |||
12123 | assert(ClassDecl->needsImplicitCopyAssignment())((ClassDecl->needsImplicitCopyAssignment()) ? static_cast< void> (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12123, __PRETTY_FUNCTION__)); | |||
12124 | ||||
12125 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); | |||
12126 | if (DSM.isAlreadyBeingDeclared()) | |||
12127 | return nullptr; | |||
12128 | ||||
12129 | QualType ArgType = Context.getTypeDeclType(ClassDecl); | |||
12130 | if (Context.getLangOpts().OpenCLCPlusPlus) | |||
12131 | ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); | |||
12132 | QualType RetType = Context.getLValueReferenceType(ArgType); | |||
12133 | bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); | |||
12134 | if (Const) | |||
12135 | ArgType = ArgType.withConst(); | |||
12136 | ||||
12137 | ArgType = Context.getLValueReferenceType(ArgType); | |||
12138 | ||||
12139 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | |||
12140 | CXXCopyAssignment, | |||
12141 | Const); | |||
12142 | ||||
12143 | // An implicitly-declared copy assignment operator is an inline public | |||
12144 | // member of its class. | |||
12145 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); | |||
12146 | SourceLocation ClassLoc = ClassDecl->getLocation(); | |||
12147 | DeclarationNameInfo NameInfo(Name, ClassLoc); | |||
12148 | CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( | |||
12149 | Context, ClassDecl, ClassLoc, NameInfo, QualType(), | |||
12150 | /*TInfo=*/nullptr, /*StorageClass=*/SC_None, | |||
12151 | /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, | |||
12152 | SourceLocation()); | |||
12153 | CopyAssignment->setAccess(AS_public); | |||
12154 | CopyAssignment->setDefaulted(); | |||
12155 | CopyAssignment->setImplicit(); | |||
12156 | ||||
12157 | if (getLangOpts().CUDA) { | |||
12158 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, | |||
12159 | CopyAssignment, | |||
12160 | /* ConstRHS */ Const, | |||
12161 | /* Diagnose */ false); | |||
12162 | } | |||
12163 | ||||
12164 | setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); | |||
12165 | ||||
12166 | // Add the parameter to the operator. | |||
12167 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, | |||
12168 | ClassLoc, ClassLoc, | |||
12169 | /*Id=*/nullptr, ArgType, | |||
12170 | /*TInfo=*/nullptr, SC_None, | |||
12171 | nullptr); | |||
12172 | CopyAssignment->setParams(FromParam); | |||
12173 | ||||
12174 | CopyAssignment->setTrivial( | |||
12175 | ClassDecl->needsOverloadResolutionForCopyAssignment() | |||
12176 | ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) | |||
12177 | : ClassDecl->hasTrivialCopyAssignment()); | |||
12178 | ||||
12179 | // Note that we have added this copy-assignment operator. | |||
12180 | ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; | |||
12181 | ||||
12182 | Scope *S = getScopeForContext(ClassDecl); | |||
12183 | CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); | |||
12184 | ||||
12185 | if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) | |||
12186 | SetDeclDeleted(CopyAssignment, ClassLoc); | |||
12187 | ||||
12188 | if (S) | |||
12189 | PushOnScopeChains(CopyAssignment, S, false); | |||
12190 | ClassDecl->addDecl(CopyAssignment); | |||
12191 | ||||
12192 | return CopyAssignment; | |||
12193 | } | |||
12194 | ||||
12195 | /// Diagnose an implicit copy operation for a class which is odr-used, but | |||
12196 | /// which is deprecated because the class has a user-declared copy constructor, | |||
12197 | /// copy assignment operator, or destructor. | |||
12198 | static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { | |||
12199 | assert(CopyOp->isImplicit())((CopyOp->isImplicit()) ? static_cast<void> (0) : __assert_fail ("CopyOp->isImplicit()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12199, __PRETTY_FUNCTION__)); | |||
12200 | ||||
12201 | CXXRecordDecl *RD = CopyOp->getParent(); | |||
12202 | CXXMethodDecl *UserDeclaredOperation = nullptr; | |||
12203 | ||||
12204 | // In Microsoft mode, assignment operations don't affect constructors and | |||
12205 | // vice versa. | |||
12206 | if (RD->hasUserDeclaredDestructor()) { | |||
12207 | UserDeclaredOperation = RD->getDestructor(); | |||
12208 | } else if (!isa<CXXConstructorDecl>(CopyOp) && | |||
12209 | RD->hasUserDeclaredCopyConstructor() && | |||
12210 | !S.getLangOpts().MSVCCompat) { | |||
12211 | // Find any user-declared copy constructor. | |||
12212 | for (auto *I : RD->ctors()) { | |||
12213 | if (I->isCopyConstructor()) { | |||
12214 | UserDeclaredOperation = I; | |||
12215 | break; | |||
12216 | } | |||
12217 | } | |||
12218 | assert(UserDeclaredOperation)((UserDeclaredOperation) ? static_cast<void> (0) : __assert_fail ("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12218, __PRETTY_FUNCTION__)); | |||
12219 | } else if (isa<CXXConstructorDecl>(CopyOp) && | |||
12220 | RD->hasUserDeclaredCopyAssignment() && | |||
12221 | !S.getLangOpts().MSVCCompat) { | |||
12222 | // Find any user-declared move assignment operator. | |||
12223 | for (auto *I : RD->methods()) { | |||
12224 | if (I->isCopyAssignmentOperator()) { | |||
12225 | UserDeclaredOperation = I; | |||
12226 | break; | |||
12227 | } | |||
12228 | } | |||
12229 | assert(UserDeclaredOperation)((UserDeclaredOperation) ? static_cast<void> (0) : __assert_fail ("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12229, __PRETTY_FUNCTION__)); | |||
12230 | } | |||
12231 | ||||
12232 | if (UserDeclaredOperation) { | |||
12233 | S.Diag(UserDeclaredOperation->getLocation(), | |||
12234 | diag::warn_deprecated_copy_operation) | |||
12235 | << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) | |||
12236 | << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); | |||
12237 | } | |||
12238 | } | |||
12239 | ||||
12240 | void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, | |||
12241 | CXXMethodDecl *CopyAssignOperator) { | |||
12242 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12247, __PRETTY_FUNCTION__)) | |||
12243 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12247, __PRETTY_FUNCTION__)) | |||
12244 | 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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12247, __PRETTY_FUNCTION__)) | |||
12245 | !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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12247, __PRETTY_FUNCTION__)) | |||
12246 | !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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12247, __PRETTY_FUNCTION__)) | |||
12247 | "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~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp" , 12247, __PRETTY_FUNCTION__)); | |||
12248 | if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) | |||
12249 | return; | |||
12250 | ||||
12251 | CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); | |||
12252 | if (ClassDecl->isInvalidDecl()) { | |||
12253 | CopyAssignOperator->setInvalidDecl(); | |||
12254 | return; | |||
12255 | } | |||
12256 | ||||
12257 | SynthesizedFunctionScope Scope(*this, CopyAssignOperator); | |||
12258 | ||||
12259 | // The exception specification is needed because we are defining the | |||
12260 | // function. | |||
12261 | ResolveExceptionSpec(CurrentLocation, | |||
12262 | CopyAssignOperator->getType()->castAs<FunctionProtoType>()); | |||
12263 | ||||
12264 | // Add a context note for diagnostics produced after this point. | |||
12265 | Scope.addContextNote(CurrentLocation); | |||
12266 | ||||
12267 | // C++11 [class.copy]p18: | |||
12268 | // The [definition of an implicitly declared copy assignment operator] is | |||
12269 | // deprecated if the class has a user-declared copy constructor or a | |||
12270 | // user-declared destructor. | |||
12271 | if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) | |||
12272 | diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); | |||
12273 | ||||
12274 | // C++0x [class.copy]p30: | |||
12275 | // The implicitly-defined or explicitly-defaulted copy assignment operator | |||
12276 | // for a non-union class X performs memberwise copy assignment of its | |||
12277 | // subobjects. The direct base classes of X are assigned first, in the | |||
12278 | // order of their declaration in the base-specifier-list, and then the | |||
12279 | // immediate non-static data members of X are assigned, in the order in | |||
12280 | // which they were declared in the class definition. | |||
12281 | ||||
12282 | // The statements that form the synthesized function body. | |||
12283 | SmallVector<Stmt*, 8> Statements; | |||
12284 | ||||
12285 | // The parameter for the "other" object, which we are copying from. | |||
12286 | ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); | |||
12287 | Qualifiers OtherQuals = Other->getType().getQualifiers(); | |||
12288 | QualType OtherRefType = Other->getType(); | |||
12289 | if (const LValueReferenceType *OtherRef
|
18.1 | 'OtherRef' is null |
1 | //===- Type.h - C Language Family Type Representation -----------*- 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 | /// C Language Family Type Representation |
11 | /// |
12 | /// This file defines the clang::Type interface and subclasses, used to |
13 | /// represent types for languages in the C family. |
14 | // |
15 | //===----------------------------------------------------------------------===// |
16 | |
17 | #ifndef LLVM_CLANG_AST_TYPE_H |
18 | #define LLVM_CLANG_AST_TYPE_H |
19 | |
20 | #include "clang/AST/NestedNameSpecifier.h" |
21 | #include "clang/AST/TemplateName.h" |
22 | #include "clang/Basic/AddressSpaces.h" |
23 | #include "clang/Basic/AttrKinds.h" |
24 | #include "clang/Basic/Diagnostic.h" |
25 | #include "clang/Basic/ExceptionSpecificationType.h" |
26 | #include "clang/Basic/LLVM.h" |
27 | #include "clang/Basic/Linkage.h" |
28 | #include "clang/Basic/PartialDiagnostic.h" |
29 | #include "clang/Basic/SourceLocation.h" |
30 | #include "clang/Basic/Specifiers.h" |
31 | #include "clang/Basic/Visibility.h" |
32 | #include "llvm/ADT/APInt.h" |
33 | #include "llvm/ADT/APSInt.h" |
34 | #include "llvm/ADT/ArrayRef.h" |
35 | #include "llvm/ADT/FoldingSet.h" |
36 | #include "llvm/ADT/None.h" |
37 | #include "llvm/ADT/Optional.h" |
38 | #include "llvm/ADT/PointerIntPair.h" |
39 | #include "llvm/ADT/PointerUnion.h" |
40 | #include "llvm/ADT/StringRef.h" |
41 | #include "llvm/ADT/Twine.h" |
42 | #include "llvm/ADT/iterator_range.h" |
43 | #include "llvm/Support/Casting.h" |
44 | #include "llvm/Support/Compiler.h" |
45 | #include "llvm/Support/ErrorHandling.h" |
46 | #include "llvm/Support/PointerLikeTypeTraits.h" |
47 | #include "llvm/Support/type_traits.h" |
48 | #include "llvm/Support/TrailingObjects.h" |
49 | #include <cassert> |
50 | #include <cstddef> |
51 | #include <cstdint> |
52 | #include <cstring> |
53 | #include <string> |
54 | #include <type_traits> |
55 | #include <utility> |
56 | |
57 | namespace clang { |
58 | |
59 | class ExtQuals; |
60 | class QualType; |
61 | class TagDecl; |
62 | class Type; |
63 | |
64 | enum { |
65 | TypeAlignmentInBits = 4, |
66 | TypeAlignment = 1 << TypeAlignmentInBits |
67 | }; |
68 | |
69 | } // namespace clang |
70 | |
71 | namespace llvm { |
72 | |
73 | template <typename T> |
74 | struct PointerLikeTypeTraits; |
75 | template<> |
76 | struct PointerLikeTypeTraits< ::clang::Type*> { |
77 | static inline void *getAsVoidPointer(::clang::Type *P) { return P; } |
78 | |
79 | static inline ::clang::Type *getFromVoidPointer(void *P) { |
80 | return static_cast< ::clang::Type*>(P); |
81 | } |
82 | |
83 | enum { NumLowBitsAvailable = clang::TypeAlignmentInBits }; |
84 | }; |
85 | |
86 | template<> |
87 | struct PointerLikeTypeTraits< ::clang::ExtQuals*> { |
88 | static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; } |
89 | |
90 | static inline ::clang::ExtQuals *getFromVoidPointer(void *P) { |
91 | return static_cast< ::clang::ExtQuals*>(P); |
92 | } |
93 | |
94 | enum { NumLowBitsAvailable = clang::TypeAlignmentInBits }; |
95 | }; |
96 | |
97 | } // namespace llvm |
98 | |
99 | namespace clang { |
100 | |
101 | class ASTContext; |
102 | template <typename> class CanQual; |
103 | class CXXRecordDecl; |
104 | class DeclContext; |
105 | class EnumDecl; |
106 | class Expr; |
107 | class ExtQualsTypeCommonBase; |
108 | class FunctionDecl; |
109 | class IdentifierInfo; |
110 | class NamedDecl; |
111 | class ObjCInterfaceDecl; |
112 | class ObjCProtocolDecl; |
113 | class ObjCTypeParamDecl; |
114 | struct PrintingPolicy; |
115 | class RecordDecl; |
116 | class Stmt; |
117 | class TagDecl; |
118 | class TemplateArgument; |
119 | class TemplateArgumentListInfo; |
120 | class TemplateArgumentLoc; |
121 | class TemplateTypeParmDecl; |
122 | class TypedefNameDecl; |
123 | class UnresolvedUsingTypenameDecl; |
124 | |
125 | using CanQualType = CanQual<Type>; |
126 | |
127 | // Provide forward declarations for all of the *Type classes. |
128 | #define TYPE(Class, Base) class Class##Type; |
129 | #include "clang/AST/TypeNodes.inc" |
130 | |
131 | /// The collection of all-type qualifiers we support. |
132 | /// Clang supports five independent qualifiers: |
133 | /// * C99: const, volatile, and restrict |
134 | /// * MS: __unaligned |
135 | /// * Embedded C (TR18037): address spaces |
136 | /// * Objective C: the GC attributes (none, weak, or strong) |
137 | class Qualifiers { |
138 | public: |
139 | enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ. |
140 | Const = 0x1, |
141 | Restrict = 0x2, |
142 | Volatile = 0x4, |
143 | CVRMask = Const | Volatile | Restrict |
144 | }; |
145 | |
146 | enum GC { |
147 | GCNone = 0, |
148 | Weak, |
149 | Strong |
150 | }; |
151 | |
152 | enum ObjCLifetime { |
153 | /// There is no lifetime qualification on this type. |
154 | OCL_None, |
155 | |
156 | /// This object can be modified without requiring retains or |
157 | /// releases. |
158 | OCL_ExplicitNone, |
159 | |
160 | /// Assigning into this object requires the old value to be |
161 | /// released and the new value to be retained. The timing of the |
162 | /// release of the old value is inexact: it may be moved to |
163 | /// immediately after the last known point where the value is |
164 | /// live. |
165 | OCL_Strong, |
166 | |
167 | /// Reading or writing from this object requires a barrier call. |
168 | OCL_Weak, |
169 | |
170 | /// Assigning into this object requires a lifetime extension. |
171 | OCL_Autoreleasing |
172 | }; |
173 | |
174 | enum { |
175 | /// The maximum supported address space number. |
176 | /// 23 bits should be enough for anyone. |
177 | MaxAddressSpace = 0x7fffffu, |
178 | |
179 | /// The width of the "fast" qualifier mask. |
180 | FastWidth = 3, |
181 | |
182 | /// The fast qualifier mask. |
183 | FastMask = (1 << FastWidth) - 1 |
184 | }; |
185 | |
186 | /// Returns the common set of qualifiers while removing them from |
187 | /// the given sets. |
188 | static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) { |
189 | // If both are only CVR-qualified, bit operations are sufficient. |
190 | if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) { |
191 | Qualifiers Q; |
192 | Q.Mask = L.Mask & R.Mask; |
193 | L.Mask &= ~Q.Mask; |
194 | R.Mask &= ~Q.Mask; |
195 | return Q; |
196 | } |
197 | |
198 | Qualifiers Q; |
199 | unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers(); |
200 | Q.addCVRQualifiers(CommonCRV); |
201 | L.removeCVRQualifiers(CommonCRV); |
202 | R.removeCVRQualifiers(CommonCRV); |
203 | |
204 | if (L.getObjCGCAttr() == R.getObjCGCAttr()) { |
205 | Q.setObjCGCAttr(L.getObjCGCAttr()); |
206 | L.removeObjCGCAttr(); |
207 | R.removeObjCGCAttr(); |
208 | } |
209 | |
210 | if (L.getObjCLifetime() == R.getObjCLifetime()) { |
211 | Q.setObjCLifetime(L.getObjCLifetime()); |
212 | L.removeObjCLifetime(); |
213 | R.removeObjCLifetime(); |
214 | } |
215 | |
216 | if (L.getAddressSpace() == R.getAddressSpace()) { |
217 | Q.setAddressSpace(L.getAddressSpace()); |
218 | L.removeAddressSpace(); |
219 | R.removeAddressSpace(); |
220 | } |
221 | return Q; |
222 | } |
223 | |
224 | static Qualifiers fromFastMask(unsigned Mask) { |
225 | Qualifiers Qs; |
226 | Qs.addFastQualifiers(Mask); |
227 | return Qs; |
228 | } |
229 | |
230 | static Qualifiers fromCVRMask(unsigned CVR) { |
231 | Qualifiers Qs; |
232 | Qs.addCVRQualifiers(CVR); |
233 | return Qs; |
234 | } |
235 | |
236 | static Qualifiers fromCVRUMask(unsigned CVRU) { |
237 | Qualifiers Qs; |
238 | Qs.addCVRUQualifiers(CVRU); |
239 | return Qs; |
240 | } |
241 | |
242 | // Deserialize qualifiers from an opaque representation. |
243 | static Qualifiers fromOpaqueValue(unsigned opaque) { |
244 | Qualifiers Qs; |
245 | Qs.Mask = opaque; |
246 | return Qs; |
247 | } |
248 | |
249 | // Serialize these qualifiers into an opaque representation. |
250 | unsigned getAsOpaqueValue() const { |
251 | return Mask; |
252 | } |
253 | |
254 | bool hasConst() const { return Mask & Const; } |
255 | bool hasOnlyConst() const { return Mask == Const; } |
256 | void removeConst() { Mask &= ~Const; } |
257 | void addConst() { Mask |= Const; } |
258 | |
259 | bool hasVolatile() const { return Mask & Volatile; } |
260 | bool hasOnlyVolatile() const { return Mask == Volatile; } |
261 | void removeVolatile() { Mask &= ~Volatile; } |
262 | void addVolatile() { Mask |= Volatile; } |
263 | |
264 | bool hasRestrict() const { return Mask & Restrict; } |
265 | bool hasOnlyRestrict() const { return Mask == Restrict; } |
266 | void removeRestrict() { Mask &= ~Restrict; } |
267 | void addRestrict() { Mask |= Restrict; } |
268 | |
269 | bool hasCVRQualifiers() const { return getCVRQualifiers(); } |
270 | unsigned getCVRQualifiers() const { return Mask & CVRMask; } |
271 | unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); } |
272 | |
273 | void setCVRQualifiers(unsigned mask) { |
274 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 274, __PRETTY_FUNCTION__)); |
275 | Mask = (Mask & ~CVRMask) | mask; |
276 | } |
277 | void removeCVRQualifiers(unsigned mask) { |
278 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 278, __PRETTY_FUNCTION__)); |
279 | Mask &= ~mask; |
280 | } |
281 | void removeCVRQualifiers() { |
282 | removeCVRQualifiers(CVRMask); |
283 | } |
284 | void addCVRQualifiers(unsigned mask) { |
285 | assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 285, __PRETTY_FUNCTION__)); |
286 | Mask |= mask; |
287 | } |
288 | void addCVRUQualifiers(unsigned mask) { |
289 | assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 289, __PRETTY_FUNCTION__)); |
290 | Mask |= mask; |
291 | } |
292 | |
293 | bool hasUnaligned() const { return Mask & UMask; } |
294 | void setUnaligned(bool flag) { |
295 | Mask = (Mask & ~UMask) | (flag ? UMask : 0); |
296 | } |
297 | void removeUnaligned() { Mask &= ~UMask; } |
298 | void addUnaligned() { Mask |= UMask; } |
299 | |
300 | bool hasObjCGCAttr() const { return Mask & GCAttrMask; } |
301 | GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); } |
302 | void setObjCGCAttr(GC type) { |
303 | Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift); |
304 | } |
305 | void removeObjCGCAttr() { setObjCGCAttr(GCNone); } |
306 | void addObjCGCAttr(GC type) { |
307 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 307, __PRETTY_FUNCTION__)); |
308 | setObjCGCAttr(type); |
309 | } |
310 | Qualifiers withoutObjCGCAttr() const { |
311 | Qualifiers qs = *this; |
312 | qs.removeObjCGCAttr(); |
313 | return qs; |
314 | } |
315 | Qualifiers withoutObjCLifetime() const { |
316 | Qualifiers qs = *this; |
317 | qs.removeObjCLifetime(); |
318 | return qs; |
319 | } |
320 | Qualifiers withoutAddressSpace() const { |
321 | Qualifiers qs = *this; |
322 | qs.removeAddressSpace(); |
323 | return qs; |
324 | } |
325 | |
326 | bool hasObjCLifetime() const { return Mask & LifetimeMask; } |
327 | ObjCLifetime getObjCLifetime() const { |
328 | return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift); |
329 | } |
330 | void setObjCLifetime(ObjCLifetime type) { |
331 | Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift); |
332 | } |
333 | void removeObjCLifetime() { setObjCLifetime(OCL_None); } |
334 | void addObjCLifetime(ObjCLifetime type) { |
335 | assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 335, __PRETTY_FUNCTION__)); |
336 | assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 336, __PRETTY_FUNCTION__)); |
337 | Mask |= (type << LifetimeShift); |
338 | } |
339 | |
340 | /// True if the lifetime is neither None or ExplicitNone. |
341 | bool hasNonTrivialObjCLifetime() const { |
342 | ObjCLifetime lifetime = getObjCLifetime(); |
343 | return (lifetime > OCL_ExplicitNone); |
344 | } |
345 | |
346 | /// True if the lifetime is either strong or weak. |
347 | bool hasStrongOrWeakObjCLifetime() const { |
348 | ObjCLifetime lifetime = getObjCLifetime(); |
349 | return (lifetime == OCL_Strong || lifetime == OCL_Weak); |
350 | } |
351 | |
352 | bool hasAddressSpace() const { return Mask & AddressSpaceMask; } |
353 | LangAS getAddressSpace() const { |
354 | return static_cast<LangAS>(Mask >> AddressSpaceShift); |
355 | } |
356 | bool hasTargetSpecificAddressSpace() const { |
357 | return isTargetAddressSpace(getAddressSpace()); |
358 | } |
359 | /// Get the address space attribute value to be printed by diagnostics. |
360 | unsigned getAddressSpaceAttributePrintValue() const { |
361 | auto Addr = getAddressSpace(); |
362 | // This function is not supposed to be used with language specific |
363 | // address spaces. If that happens, the diagnostic message should consider |
364 | // printing the QualType instead of the address space value. |
365 | assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace()) ? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 365, __PRETTY_FUNCTION__)); |
366 | if (Addr != LangAS::Default) |
367 | return toTargetAddressSpace(Addr); |
368 | // TODO: The diagnostic messages where Addr may be 0 should be fixed |
369 | // since it cannot differentiate the situation where 0 denotes the default |
370 | // address space or user specified __attribute__((address_space(0))). |
371 | return 0; |
372 | } |
373 | void setAddressSpace(LangAS space) { |
374 | assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void > (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 374, __PRETTY_FUNCTION__)); |
375 | Mask = (Mask & ~AddressSpaceMask) |
376 | | (((uint32_t) space) << AddressSpaceShift); |
377 | } |
378 | void removeAddressSpace() { setAddressSpace(LangAS::Default); } |
379 | void addAddressSpace(LangAS space) { |
380 | assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail ("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 380, __PRETTY_FUNCTION__)); |
381 | setAddressSpace(space); |
382 | } |
383 | |
384 | // Fast qualifiers are those that can be allocated directly |
385 | // on a QualType object. |
386 | bool hasFastQualifiers() const { return getFastQualifiers(); } |
387 | unsigned getFastQualifiers() const { return Mask & FastMask; } |
388 | void setFastQualifiers(unsigned mask) { |
389 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 389, __PRETTY_FUNCTION__)); |
390 | Mask = (Mask & ~FastMask) | mask; |
391 | } |
392 | void removeFastQualifiers(unsigned mask) { |
393 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 393, __PRETTY_FUNCTION__)); |
394 | Mask &= ~mask; |
395 | } |
396 | void removeFastQualifiers() { |
397 | removeFastQualifiers(FastMask); |
398 | } |
399 | void addFastQualifiers(unsigned mask) { |
400 | assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits" ) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 400, __PRETTY_FUNCTION__)); |
401 | Mask |= mask; |
402 | } |
403 | |
404 | /// Return true if the set contains any qualifiers which require an ExtQuals |
405 | /// node to be allocated. |
406 | bool hasNonFastQualifiers() const { return Mask & ~FastMask; } |
407 | Qualifiers getNonFastQualifiers() const { |
408 | Qualifiers Quals = *this; |
409 | Quals.setFastQualifiers(0); |
410 | return Quals; |
411 | } |
412 | |
413 | /// Return true if the set contains any qualifiers. |
414 | bool hasQualifiers() const { return Mask; } |
415 | bool empty() const { return !Mask; } |
416 | |
417 | /// Add the qualifiers from the given set to this set. |
418 | void addQualifiers(Qualifiers Q) { |
419 | // If the other set doesn't have any non-boolean qualifiers, just |
420 | // bit-or it in. |
421 | if (!(Q.Mask & ~CVRMask)) |
422 | Mask |= Q.Mask; |
423 | else { |
424 | Mask |= (Q.Mask & CVRMask); |
425 | if (Q.hasAddressSpace()) |
426 | addAddressSpace(Q.getAddressSpace()); |
427 | if (Q.hasObjCGCAttr()) |
428 | addObjCGCAttr(Q.getObjCGCAttr()); |
429 | if (Q.hasObjCLifetime()) |
430 | addObjCLifetime(Q.getObjCLifetime()); |
431 | } |
432 | } |
433 | |
434 | /// Remove the qualifiers from the given set from this set. |
435 | void removeQualifiers(Qualifiers Q) { |
436 | // If the other set doesn't have any non-boolean qualifiers, just |
437 | // bit-and the inverse in. |
438 | if (!(Q.Mask & ~CVRMask)) |
439 | Mask &= ~Q.Mask; |
440 | else { |
441 | Mask &= ~(Q.Mask & CVRMask); |
442 | if (getObjCGCAttr() == Q.getObjCGCAttr()) |
443 | removeObjCGCAttr(); |
444 | if (getObjCLifetime() == Q.getObjCLifetime()) |
445 | removeObjCLifetime(); |
446 | if (getAddressSpace() == Q.getAddressSpace()) |
447 | removeAddressSpace(); |
448 | } |
449 | } |
450 | |
451 | /// Add the qualifiers from the given set to this set, given that |
452 | /// they don't conflict. |
453 | void addConsistentQualifiers(Qualifiers qs) { |
454 | assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 455, __PRETTY_FUNCTION__)) |
455 | !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace () || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 455, __PRETTY_FUNCTION__)); |
456 | assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 457, __PRETTY_FUNCTION__)) |
457 | !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail ("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 457, __PRETTY_FUNCTION__)); |
458 | assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 459, __PRETTY_FUNCTION__)) |
459 | !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime () || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 459, __PRETTY_FUNCTION__)); |
460 | Mask |= qs.Mask; |
461 | } |
462 | |
463 | /// Returns true if address space A is equal to or a superset of B. |
464 | /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of |
465 | /// overlapping address spaces. |
466 | /// CL1.1 or CL1.2: |
467 | /// every address space is a superset of itself. |
468 | /// CL2.0 adds: |
469 | /// __generic is a superset of any address space except for __constant. |
470 | static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) { |
471 | // Address spaces must match exactly. |
472 | return A == B || |
473 | // Otherwise in OpenCLC v2.0 s6.5.5: every address space except |
474 | // for __constant can be used as __generic. |
475 | (A == LangAS::opencl_generic && B != LangAS::opencl_constant); |
476 | } |
477 | |
478 | /// Returns true if the address space in these qualifiers is equal to or |
479 | /// a superset of the address space in the argument qualifiers. |
480 | bool isAddressSpaceSupersetOf(Qualifiers other) const { |
481 | return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace()); |
482 | } |
483 | |
484 | /// Determines if these qualifiers compatibly include another set. |
485 | /// Generally this answers the question of whether an object with the other |
486 | /// qualifiers can be safely used as an object with these qualifiers. |
487 | bool compatiblyIncludes(Qualifiers other) const { |
488 | return isAddressSpaceSupersetOf(other) && |
489 | // ObjC GC qualifiers can match, be added, or be removed, but can't |
490 | // be changed. |
491 | (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() || |
492 | !other.hasObjCGCAttr()) && |
493 | // ObjC lifetime qualifiers must match exactly. |
494 | getObjCLifetime() == other.getObjCLifetime() && |
495 | // CVR qualifiers may subset. |
496 | (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) && |
497 | // U qualifier may superset. |
498 | (!other.hasUnaligned() || hasUnaligned()); |
499 | } |
500 | |
501 | /// Determines if these qualifiers compatibly include another set of |
502 | /// qualifiers from the narrow perspective of Objective-C ARC lifetime. |
503 | /// |
504 | /// One set of Objective-C lifetime qualifiers compatibly includes the other |
505 | /// if the lifetime qualifiers match, or if both are non-__weak and the |
506 | /// including set also contains the 'const' qualifier, or both are non-__weak |
507 | /// and one is None (which can only happen in non-ARC modes). |
508 | bool compatiblyIncludesObjCLifetime(Qualifiers other) const { |
509 | if (getObjCLifetime() == other.getObjCLifetime()) |
510 | return true; |
511 | |
512 | if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak) |
513 | return false; |
514 | |
515 | if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None) |
516 | return true; |
517 | |
518 | return hasConst(); |
519 | } |
520 | |
521 | /// Determine whether this set of qualifiers is a strict superset of |
522 | /// another set of qualifiers, not considering qualifier compatibility. |
523 | bool isStrictSupersetOf(Qualifiers Other) const; |
524 | |
525 | bool operator==(Qualifiers Other) const { return Mask == Other.Mask; } |
526 | bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; } |
527 | |
528 | explicit operator bool() const { return hasQualifiers(); } |
529 | |
530 | Qualifiers &operator+=(Qualifiers R) { |
531 | addQualifiers(R); |
532 | return *this; |
533 | } |
534 | |
535 | // Union two qualifier sets. If an enumerated qualifier appears |
536 | // in both sets, use the one from the right. |
537 | friend Qualifiers operator+(Qualifiers L, Qualifiers R) { |
538 | L += R; |
539 | return L; |
540 | } |
541 | |
542 | Qualifiers &operator-=(Qualifiers R) { |
543 | removeQualifiers(R); |
544 | return *this; |
545 | } |
546 | |
547 | /// Compute the difference between two qualifier sets. |
548 | friend Qualifiers operator-(Qualifiers L, Qualifiers R) { |
549 | L -= R; |
550 | return L; |
551 | } |
552 | |
553 | std::string getAsString() const; |
554 | std::string getAsString(const PrintingPolicy &Policy) const; |
555 | |
556 | bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const; |
557 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
558 | bool appendSpaceIfNonEmpty = false) const; |
559 | |
560 | void Profile(llvm::FoldingSetNodeID &ID) const { |
561 | ID.AddInteger(Mask); |
562 | } |
563 | |
564 | private: |
565 | // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31| |
566 | // |C R V|U|GCAttr|Lifetime|AddressSpace| |
567 | uint32_t Mask = 0; |
568 | |
569 | static const uint32_t UMask = 0x8; |
570 | static const uint32_t UShift = 3; |
571 | static const uint32_t GCAttrMask = 0x30; |
572 | static const uint32_t GCAttrShift = 4; |
573 | static const uint32_t LifetimeMask = 0x1C0; |
574 | static const uint32_t LifetimeShift = 6; |
575 | static const uint32_t AddressSpaceMask = |
576 | ~(CVRMask | UMask | GCAttrMask | LifetimeMask); |
577 | static const uint32_t AddressSpaceShift = 9; |
578 | }; |
579 | |
580 | /// A std::pair-like structure for storing a qualified type split |
581 | /// into its local qualifiers and its locally-unqualified type. |
582 | struct SplitQualType { |
583 | /// The locally-unqualified type. |
584 | const Type *Ty = nullptr; |
585 | |
586 | /// The local qualifiers. |
587 | Qualifiers Quals; |
588 | |
589 | SplitQualType() = default; |
590 | SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {} |
591 | |
592 | SplitQualType getSingleStepDesugaredType() const; // end of this file |
593 | |
594 | // Make std::tie work. |
595 | std::pair<const Type *,Qualifiers> asPair() const { |
596 | return std::pair<const Type *, Qualifiers>(Ty, Quals); |
597 | } |
598 | |
599 | friend bool operator==(SplitQualType a, SplitQualType b) { |
600 | return a.Ty == b.Ty && a.Quals == b.Quals; |
601 | } |
602 | friend bool operator!=(SplitQualType a, SplitQualType b) { |
603 | return a.Ty != b.Ty || a.Quals != b.Quals; |
604 | } |
605 | }; |
606 | |
607 | /// The kind of type we are substituting Objective-C type arguments into. |
608 | /// |
609 | /// The kind of substitution affects the replacement of type parameters when |
610 | /// no concrete type information is provided, e.g., when dealing with an |
611 | /// unspecialized type. |
612 | enum class ObjCSubstitutionContext { |
613 | /// An ordinary type. |
614 | Ordinary, |
615 | |
616 | /// The result type of a method or function. |
617 | Result, |
618 | |
619 | /// The parameter type of a method or function. |
620 | Parameter, |
621 | |
622 | /// The type of a property. |
623 | Property, |
624 | |
625 | /// The superclass of a type. |
626 | Superclass, |
627 | }; |
628 | |
629 | /// A (possibly-)qualified type. |
630 | /// |
631 | /// For efficiency, we don't store CV-qualified types as nodes on their |
632 | /// own: instead each reference to a type stores the qualifiers. This |
633 | /// greatly reduces the number of nodes we need to allocate for types (for |
634 | /// example we only need one for 'int', 'const int', 'volatile int', |
635 | /// 'const volatile int', etc). |
636 | /// |
637 | /// As an added efficiency bonus, instead of making this a pair, we |
638 | /// just store the two bits we care about in the low bits of the |
639 | /// pointer. To handle the packing/unpacking, we make QualType be a |
640 | /// simple wrapper class that acts like a smart pointer. A third bit |
641 | /// indicates whether there are extended qualifiers present, in which |
642 | /// case the pointer points to a special structure. |
643 | class QualType { |
644 | friend class QualifierCollector; |
645 | |
646 | // Thankfully, these are efficiently composable. |
647 | llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>, |
648 | Qualifiers::FastWidth> Value; |
649 | |
650 | const ExtQuals *getExtQualsUnsafe() const { |
651 | return Value.getPointer().get<const ExtQuals*>(); |
652 | } |
653 | |
654 | const Type *getTypePtrUnsafe() const { |
655 | return Value.getPointer().get<const Type*>(); |
656 | } |
657 | |
658 | const ExtQualsTypeCommonBase *getCommonPtr() const { |
659 | assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer") ? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 659, __PRETTY_FUNCTION__)); |
660 | auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue()); |
661 | CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1); |
662 | return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal); |
663 | } |
664 | |
665 | public: |
666 | QualType() = default; |
667 | QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
668 | QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {} |
669 | |
670 | unsigned getLocalFastQualifiers() const { return Value.getInt(); } |
671 | void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); } |
672 | |
673 | /// Retrieves a pointer to the underlying (unqualified) type. |
674 | /// |
675 | /// This function requires that the type not be NULL. If the type might be |
676 | /// NULL, use the (slightly less efficient) \c getTypePtrOrNull(). |
677 | const Type *getTypePtr() const; |
678 | |
679 | const Type *getTypePtrOrNull() const; |
680 | |
681 | /// Retrieves a pointer to the name of the base type. |
682 | const IdentifierInfo *getBaseTypeIdentifier() const; |
683 | |
684 | /// Divides a QualType into its unqualified type and a set of local |
685 | /// qualifiers. |
686 | SplitQualType split() const; |
687 | |
688 | void *getAsOpaquePtr() const { return Value.getOpaqueValue(); } |
689 | |
690 | static QualType getFromOpaquePtr(const void *Ptr) { |
691 | QualType T; |
692 | T.Value.setFromOpaqueValue(const_cast<void*>(Ptr)); |
693 | return T; |
694 | } |
695 | |
696 | const Type &operator*() const { |
697 | return *getTypePtr(); |
698 | } |
699 | |
700 | const Type *operator->() const { |
701 | return getTypePtr(); |
702 | } |
703 | |
704 | bool isCanonical() const; |
705 | bool isCanonicalAsParam() const; |
706 | |
707 | /// Return true if this QualType doesn't point to a type yet. |
708 | bool isNull() const { |
709 | return Value.getPointer().isNull(); |
710 | } |
711 | |
712 | /// Determine whether this particular QualType instance has the |
713 | /// "const" qualifier set, without looking through typedefs that may have |
714 | /// added "const" at a different level. |
715 | bool isLocalConstQualified() const { |
716 | return (getLocalFastQualifiers() & Qualifiers::Const); |
717 | } |
718 | |
719 | /// Determine whether this type is const-qualified. |
720 | bool isConstQualified() const; |
721 | |
722 | /// Determine whether this particular QualType instance has the |
723 | /// "restrict" qualifier set, without looking through typedefs that may have |
724 | /// added "restrict" at a different level. |
725 | bool isLocalRestrictQualified() const { |
726 | return (getLocalFastQualifiers() & Qualifiers::Restrict); |
727 | } |
728 | |
729 | /// Determine whether this type is restrict-qualified. |
730 | bool isRestrictQualified() const; |
731 | |
732 | /// Determine whether this particular QualType instance has the |
733 | /// "volatile" qualifier set, without looking through typedefs that may have |
734 | /// added "volatile" at a different level. |
735 | bool isLocalVolatileQualified() const { |
736 | return (getLocalFastQualifiers() & Qualifiers::Volatile); |
737 | } |
738 | |
739 | /// Determine whether this type is volatile-qualified. |
740 | bool isVolatileQualified() const; |
741 | |
742 | /// Determine whether this particular QualType instance has any |
743 | /// qualifiers, without looking through any typedefs that might add |
744 | /// qualifiers at a different level. |
745 | bool hasLocalQualifiers() const { |
746 | return getLocalFastQualifiers() || hasLocalNonFastQualifiers(); |
747 | } |
748 | |
749 | /// Determine whether this type has any qualifiers. |
750 | bool hasQualifiers() const; |
751 | |
752 | /// Determine whether this particular QualType instance has any |
753 | /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType |
754 | /// instance. |
755 | bool hasLocalNonFastQualifiers() const { |
756 | return Value.getPointer().is<const ExtQuals*>(); |
757 | } |
758 | |
759 | /// Retrieve the set of qualifiers local to this particular QualType |
760 | /// instance, not including any qualifiers acquired through typedefs or |
761 | /// other sugar. |
762 | Qualifiers getLocalQualifiers() const; |
763 | |
764 | /// Retrieve the set of qualifiers applied to this type. |
765 | Qualifiers getQualifiers() const; |
766 | |
767 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
768 | /// local to this particular QualType instance, not including any qualifiers |
769 | /// acquired through typedefs or other sugar. |
770 | unsigned getLocalCVRQualifiers() const { |
771 | return getLocalFastQualifiers(); |
772 | } |
773 | |
774 | /// Retrieve the set of CVR (const-volatile-restrict) qualifiers |
775 | /// applied to this type. |
776 | unsigned getCVRQualifiers() const; |
777 | |
778 | bool isConstant(const ASTContext& Ctx) const { |
779 | return QualType::isConstant(*this, Ctx); |
780 | } |
781 | |
782 | /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10). |
783 | bool isPODType(const ASTContext &Context) const; |
784 | |
785 | /// Return true if this is a POD type according to the rules of the C++98 |
786 | /// standard, regardless of the current compilation's language. |
787 | bool isCXX98PODType(const ASTContext &Context) const; |
788 | |
789 | /// Return true if this is a POD type according to the more relaxed rules |
790 | /// of the C++11 standard, regardless of the current compilation's language. |
791 | /// (C++0x [basic.types]p9). Note that, unlike |
792 | /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account. |
793 | bool isCXX11PODType(const ASTContext &Context) const; |
794 | |
795 | /// Return true if this is a trivial type per (C++0x [basic.types]p9) |
796 | bool isTrivialType(const ASTContext &Context) const; |
797 | |
798 | /// Return true if this is a trivially copyable type (C++0x [basic.types]p9) |
799 | bool isTriviallyCopyableType(const ASTContext &Context) const; |
800 | |
801 | |
802 | /// Returns true if it is a class and it might be dynamic. |
803 | bool mayBeDynamicClass() const; |
804 | |
805 | /// Returns true if it is not a class or if the class might not be dynamic. |
806 | bool mayBeNotDynamicClass() const; |
807 | |
808 | // Don't promise in the API that anything besides 'const' can be |
809 | // easily added. |
810 | |
811 | /// Add the `const` type qualifier to this QualType. |
812 | void addConst() { |
813 | addFastQualifiers(Qualifiers::Const); |
814 | } |
815 | QualType withConst() const { |
816 | return withFastQualifiers(Qualifiers::Const); |
817 | } |
818 | |
819 | /// Add the `volatile` type qualifier to this QualType. |
820 | void addVolatile() { |
821 | addFastQualifiers(Qualifiers::Volatile); |
822 | } |
823 | QualType withVolatile() const { |
824 | return withFastQualifiers(Qualifiers::Volatile); |
825 | } |
826 | |
827 | /// Add the `restrict` qualifier to this QualType. |
828 | void addRestrict() { |
829 | addFastQualifiers(Qualifiers::Restrict); |
830 | } |
831 | QualType withRestrict() const { |
832 | return withFastQualifiers(Qualifiers::Restrict); |
833 | } |
834 | |
835 | QualType withCVRQualifiers(unsigned CVR) const { |
836 | return withFastQualifiers(CVR); |
837 | } |
838 | |
839 | void addFastQualifiers(unsigned TQs) { |
840 | assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 841, __PRETTY_FUNCTION__)) |
841 | && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!" ) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 841, __PRETTY_FUNCTION__)); |
842 | Value.setInt(Value.getInt() | TQs); |
843 | } |
844 | |
845 | void removeLocalConst(); |
846 | void removeLocalVolatile(); |
847 | void removeLocalRestrict(); |
848 | void removeLocalCVRQualifiers(unsigned Mask); |
849 | |
850 | void removeLocalFastQualifiers() { Value.setInt(0); } |
851 | void removeLocalFastQualifiers(unsigned Mask) { |
852 | assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 852, __PRETTY_FUNCTION__)); |
853 | Value.setInt(Value.getInt() & ~Mask); |
854 | } |
855 | |
856 | // Creates a type with the given qualifiers in addition to any |
857 | // qualifiers already on this type. |
858 | QualType withFastQualifiers(unsigned TQs) const { |
859 | QualType T = *this; |
860 | T.addFastQualifiers(TQs); |
861 | return T; |
862 | } |
863 | |
864 | // Creates a type with exactly the given fast qualifiers, removing |
865 | // any existing fast qualifiers. |
866 | QualType withExactLocalFastQualifiers(unsigned TQs) const { |
867 | return withoutLocalFastQualifiers().withFastQualifiers(TQs); |
868 | } |
869 | |
870 | // Removes fast qualifiers, but leaves any extended qualifiers in place. |
871 | QualType withoutLocalFastQualifiers() const { |
872 | QualType T = *this; |
873 | T.removeLocalFastQualifiers(); |
874 | return T; |
875 | } |
876 | |
877 | QualType getCanonicalType() const; |
878 | |
879 | /// Return this type with all of the instance-specific qualifiers |
880 | /// removed, but without removing any qualifiers that may have been applied |
881 | /// through typedefs. |
882 | QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); } |
883 | |
884 | /// Retrieve the unqualified variant of the given type, |
885 | /// removing as little sugar as possible. |
886 | /// |
887 | /// This routine looks through various kinds of sugar to find the |
888 | /// least-desugared type that is unqualified. For example, given: |
889 | /// |
890 | /// \code |
891 | /// typedef int Integer; |
892 | /// typedef const Integer CInteger; |
893 | /// typedef CInteger DifferenceType; |
894 | /// \endcode |
895 | /// |
896 | /// Executing \c getUnqualifiedType() on the type \c DifferenceType will |
897 | /// desugar until we hit the type \c Integer, which has no qualifiers on it. |
898 | /// |
899 | /// The resulting type might still be qualified if it's sugar for an array |
900 | /// type. To strip qualifiers even from within a sugared array type, use |
901 | /// ASTContext::getUnqualifiedArrayType. |
902 | inline QualType getUnqualifiedType() const; |
903 | |
904 | /// Retrieve the unqualified variant of the given type, removing as little |
905 | /// sugar as possible. |
906 | /// |
907 | /// Like getUnqualifiedType(), but also returns the set of |
908 | /// qualifiers that were built up. |
909 | /// |
910 | /// The resulting type might still be qualified if it's sugar for an array |
911 | /// type. To strip qualifiers even from within a sugared array type, use |
912 | /// ASTContext::getUnqualifiedArrayType. |
913 | inline SplitQualType getSplitUnqualifiedType() const; |
914 | |
915 | /// Determine whether this type is more qualified than the other |
916 | /// given type, requiring exact equality for non-CVR qualifiers. |
917 | bool isMoreQualifiedThan(QualType Other) const; |
918 | |
919 | /// Determine whether this type is at least as qualified as the other |
920 | /// given type, requiring exact equality for non-CVR qualifiers. |
921 | bool isAtLeastAsQualifiedAs(QualType Other) const; |
922 | |
923 | QualType getNonReferenceType() const; |
924 | |
925 | /// Determine the type of a (typically non-lvalue) expression with the |
926 | /// specified result type. |
927 | /// |
928 | /// This routine should be used for expressions for which the return type is |
929 | /// explicitly specified (e.g., in a cast or call) and isn't necessarily |
930 | /// an lvalue. It removes a top-level reference (since there are no |
931 | /// expressions of reference type) and deletes top-level cvr-qualifiers |
932 | /// from non-class types (in C++) or all types (in C). |
933 | QualType getNonLValueExprType(const ASTContext &Context) const; |
934 | |
935 | /// Return the specified type with any "sugar" removed from |
936 | /// the type. This takes off typedefs, typeof's etc. If the outer level of |
937 | /// the type is already concrete, it returns it unmodified. This is similar |
938 | /// to getting the canonical type, but it doesn't remove *all* typedefs. For |
939 | /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is |
940 | /// concrete. |
941 | /// |
942 | /// Qualifiers are left in place. |
943 | QualType getDesugaredType(const ASTContext &Context) const { |
944 | return getDesugaredType(*this, Context); |
945 | } |
946 | |
947 | SplitQualType getSplitDesugaredType() const { |
948 | return getSplitDesugaredType(*this); |
949 | } |
950 | |
951 | /// Return the specified type with one level of "sugar" removed from |
952 | /// the type. |
953 | /// |
954 | /// This routine takes off the first typedef, typeof, etc. If the outer level |
955 | /// of the type is already concrete, it returns it unmodified. |
956 | QualType getSingleStepDesugaredType(const ASTContext &Context) const { |
957 | return getSingleStepDesugaredTypeImpl(*this, Context); |
958 | } |
959 | |
960 | /// Returns the specified type after dropping any |
961 | /// outer-level parentheses. |
962 | QualType IgnoreParens() const { |
963 | if (isa<ParenType>(*this)) |
964 | return QualType::IgnoreParens(*this); |
965 | return *this; |
966 | } |
967 | |
968 | /// Indicate whether the specified types and qualifiers are identical. |
969 | friend bool operator==(const QualType &LHS, const QualType &RHS) { |
970 | return LHS.Value == RHS.Value; |
971 | } |
972 | friend bool operator!=(const QualType &LHS, const QualType &RHS) { |
973 | return LHS.Value != RHS.Value; |
974 | } |
975 | friend bool operator<(const QualType &LHS, const QualType &RHS) { |
976 | return LHS.Value < RHS.Value; |
977 | } |
978 | |
979 | static std::string getAsString(SplitQualType split, |
980 | const PrintingPolicy &Policy) { |
981 | return getAsString(split.Ty, split.Quals, Policy); |
982 | } |
983 | static std::string getAsString(const Type *ty, Qualifiers qs, |
984 | const PrintingPolicy &Policy); |
985 | |
986 | std::string getAsString() const; |
987 | std::string getAsString(const PrintingPolicy &Policy) const; |
988 | |
989 | void print(raw_ostream &OS, const PrintingPolicy &Policy, |
990 | const Twine &PlaceHolder = Twine(), |
991 | unsigned Indentation = 0) const; |
992 | |
993 | static void print(SplitQualType split, raw_ostream &OS, |
994 | const PrintingPolicy &policy, const Twine &PlaceHolder, |
995 | unsigned Indentation = 0) { |
996 | return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation); |
997 | } |
998 | |
999 | static void print(const Type *ty, Qualifiers qs, |
1000 | raw_ostream &OS, const PrintingPolicy &policy, |
1001 | const Twine &PlaceHolder, |
1002 | unsigned Indentation = 0); |
1003 | |
1004 | void getAsStringInternal(std::string &Str, |
1005 | const PrintingPolicy &Policy) const; |
1006 | |
1007 | static void getAsStringInternal(SplitQualType split, std::string &out, |
1008 | const PrintingPolicy &policy) { |
1009 | return getAsStringInternal(split.Ty, split.Quals, out, policy); |
1010 | } |
1011 | |
1012 | static void getAsStringInternal(const Type *ty, Qualifiers qs, |
1013 | std::string &out, |
1014 | const PrintingPolicy &policy); |
1015 | |
1016 | class StreamedQualTypeHelper { |
1017 | const QualType &T; |
1018 | const PrintingPolicy &Policy; |
1019 | const Twine &PlaceHolder; |
1020 | unsigned Indentation; |
1021 | |
1022 | public: |
1023 | StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy, |
1024 | const Twine &PlaceHolder, unsigned Indentation) |
1025 | : T(T), Policy(Policy), PlaceHolder(PlaceHolder), |
1026 | Indentation(Indentation) {} |
1027 | |
1028 | friend raw_ostream &operator<<(raw_ostream &OS, |
1029 | const StreamedQualTypeHelper &SQT) { |
1030 | SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation); |
1031 | return OS; |
1032 | } |
1033 | }; |
1034 | |
1035 | StreamedQualTypeHelper stream(const PrintingPolicy &Policy, |
1036 | const Twine &PlaceHolder = Twine(), |
1037 | unsigned Indentation = 0) const { |
1038 | return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation); |
1039 | } |
1040 | |
1041 | void dump(const char *s) const; |
1042 | void dump() const; |
1043 | void dump(llvm::raw_ostream &OS) const; |
1044 | |
1045 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1046 | ID.AddPointer(getAsOpaquePtr()); |
1047 | } |
1048 | |
1049 | /// Return the address space of this type. |
1050 | inline LangAS getAddressSpace() const; |
1051 | |
1052 | /// Returns gc attribute of this type. |
1053 | inline Qualifiers::GC getObjCGCAttr() const; |
1054 | |
1055 | /// true when Type is objc's weak. |
1056 | bool isObjCGCWeak() const { |
1057 | return getObjCGCAttr() == Qualifiers::Weak; |
1058 | } |
1059 | |
1060 | /// true when Type is objc's strong. |
1061 | bool isObjCGCStrong() const { |
1062 | return getObjCGCAttr() == Qualifiers::Strong; |
1063 | } |
1064 | |
1065 | /// Returns lifetime attribute of this type. |
1066 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1067 | return getQualifiers().getObjCLifetime(); |
1068 | } |
1069 | |
1070 | bool hasNonTrivialObjCLifetime() const { |
1071 | return getQualifiers().hasNonTrivialObjCLifetime(); |
1072 | } |
1073 | |
1074 | bool hasStrongOrWeakObjCLifetime() const { |
1075 | return getQualifiers().hasStrongOrWeakObjCLifetime(); |
1076 | } |
1077 | |
1078 | // true when Type is objc's weak and weak is enabled but ARC isn't. |
1079 | bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const; |
1080 | |
1081 | enum PrimitiveDefaultInitializeKind { |
1082 | /// The type does not fall into any of the following categories. Note that |
1083 | /// this case is zero-valued so that values of this enum can be used as a |
1084 | /// boolean condition for non-triviality. |
1085 | PDIK_Trivial, |
1086 | |
1087 | /// The type is an Objective-C retainable pointer type that is qualified |
1088 | /// with the ARC __strong qualifier. |
1089 | PDIK_ARCStrong, |
1090 | |
1091 | /// The type is an Objective-C retainable pointer type that is qualified |
1092 | /// with the ARC __weak qualifier. |
1093 | PDIK_ARCWeak, |
1094 | |
1095 | /// The type is a struct containing a field whose type is not PCK_Trivial. |
1096 | PDIK_Struct |
1097 | }; |
1098 | |
1099 | /// Functions to query basic properties of non-trivial C struct types. |
1100 | |
1101 | /// Check if this is a non-trivial type that would cause a C struct |
1102 | /// transitively containing this type to be non-trivial to default initialize |
1103 | /// and return the kind. |
1104 | PrimitiveDefaultInitializeKind |
1105 | isNonTrivialToPrimitiveDefaultInitialize() const; |
1106 | |
1107 | enum PrimitiveCopyKind { |
1108 | /// The type does not fall into any of the following categories. Note that |
1109 | /// this case is zero-valued so that values of this enum can be used as a |
1110 | /// boolean condition for non-triviality. |
1111 | PCK_Trivial, |
1112 | |
1113 | /// The type would be trivial except that it is volatile-qualified. Types |
1114 | /// that fall into one of the other non-trivial cases may additionally be |
1115 | /// volatile-qualified. |
1116 | PCK_VolatileTrivial, |
1117 | |
1118 | /// The type is an Objective-C retainable pointer type that is qualified |
1119 | /// with the ARC __strong qualifier. |
1120 | PCK_ARCStrong, |
1121 | |
1122 | /// The type is an Objective-C retainable pointer type that is qualified |
1123 | /// with the ARC __weak qualifier. |
1124 | PCK_ARCWeak, |
1125 | |
1126 | /// The type is a struct containing a field whose type is neither |
1127 | /// PCK_Trivial nor PCK_VolatileTrivial. |
1128 | /// Note that a C++ struct type does not necessarily match this; C++ copying |
1129 | /// semantics are too complex to express here, in part because they depend |
1130 | /// on the exact constructor or assignment operator that is chosen by |
1131 | /// overload resolution to do the copy. |
1132 | PCK_Struct |
1133 | }; |
1134 | |
1135 | /// Check if this is a non-trivial type that would cause a C struct |
1136 | /// transitively containing this type to be non-trivial to copy and return the |
1137 | /// kind. |
1138 | PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const; |
1139 | |
1140 | /// Check if this is a non-trivial type that would cause a C struct |
1141 | /// transitively containing this type to be non-trivial to destructively |
1142 | /// move and return the kind. Destructive move in this context is a C++-style |
1143 | /// move in which the source object is placed in a valid but unspecified state |
1144 | /// after it is moved, as opposed to a truly destructive move in which the |
1145 | /// source object is placed in an uninitialized state. |
1146 | PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const; |
1147 | |
1148 | enum DestructionKind { |
1149 | DK_none, |
1150 | DK_cxx_destructor, |
1151 | DK_objc_strong_lifetime, |
1152 | DK_objc_weak_lifetime, |
1153 | DK_nontrivial_c_struct |
1154 | }; |
1155 | |
1156 | /// Returns a nonzero value if objects of this type require |
1157 | /// non-trivial work to clean up after. Non-zero because it's |
1158 | /// conceivable that qualifiers (objc_gc(weak)?) could make |
1159 | /// something require destruction. |
1160 | DestructionKind isDestructedType() const { |
1161 | return isDestructedTypeImpl(*this); |
1162 | } |
1163 | |
1164 | /// Check if this is or contains a C union that is non-trivial to |
1165 | /// default-initialize, which is a union that has a member that is non-trivial |
1166 | /// to default-initialize. If this returns true, |
1167 | /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct. |
1168 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const; |
1169 | |
1170 | /// Check if this is or contains a C union that is non-trivial to destruct, |
1171 | /// which is a union that has a member that is non-trivial to destruct. If |
1172 | /// this returns true, isDestructedType returns DK_nontrivial_c_struct. |
1173 | bool hasNonTrivialToPrimitiveDestructCUnion() const; |
1174 | |
1175 | /// Check if this is or contains a C union that is non-trivial to copy, which |
1176 | /// is a union that has a member that is non-trivial to copy. If this returns |
1177 | /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct. |
1178 | bool hasNonTrivialToPrimitiveCopyCUnion() const; |
1179 | |
1180 | /// Determine whether expressions of the given type are forbidden |
1181 | /// from being lvalues in C. |
1182 | /// |
1183 | /// The expression types that are forbidden to be lvalues are: |
1184 | /// - 'void', but not qualified void |
1185 | /// - function types |
1186 | /// |
1187 | /// The exact rule here is C99 6.3.2.1: |
1188 | /// An lvalue is an expression with an object type or an incomplete |
1189 | /// type other than void. |
1190 | bool isCForbiddenLValueType() const; |
1191 | |
1192 | /// Substitute type arguments for the Objective-C type parameters used in the |
1193 | /// subject type. |
1194 | /// |
1195 | /// \param ctx ASTContext in which the type exists. |
1196 | /// |
1197 | /// \param typeArgs The type arguments that will be substituted for the |
1198 | /// Objective-C type parameters in the subject type, which are generally |
1199 | /// computed via \c Type::getObjCSubstitutions. If empty, the type |
1200 | /// parameters will be replaced with their bounds or id/Class, as appropriate |
1201 | /// for the context. |
1202 | /// |
1203 | /// \param context The context in which the subject type was written. |
1204 | /// |
1205 | /// \returns the resulting type. |
1206 | QualType substObjCTypeArgs(ASTContext &ctx, |
1207 | ArrayRef<QualType> typeArgs, |
1208 | ObjCSubstitutionContext context) const; |
1209 | |
1210 | /// Substitute type arguments from an object type for the Objective-C type |
1211 | /// parameters used in the subject type. |
1212 | /// |
1213 | /// This operation combines the computation of type arguments for |
1214 | /// substitution (\c Type::getObjCSubstitutions) with the actual process of |
1215 | /// substitution (\c QualType::substObjCTypeArgs) for the convenience of |
1216 | /// callers that need to perform a single substitution in isolation. |
1217 | /// |
1218 | /// \param objectType The type of the object whose member type we're |
1219 | /// substituting into. For example, this might be the receiver of a message |
1220 | /// or the base of a property access. |
1221 | /// |
1222 | /// \param dc The declaration context from which the subject type was |
1223 | /// retrieved, which indicates (for example) which type parameters should |
1224 | /// be substituted. |
1225 | /// |
1226 | /// \param context The context in which the subject type was written. |
1227 | /// |
1228 | /// \returns the subject type after replacing all of the Objective-C type |
1229 | /// parameters with their corresponding arguments. |
1230 | QualType substObjCMemberType(QualType objectType, |
1231 | const DeclContext *dc, |
1232 | ObjCSubstitutionContext context) const; |
1233 | |
1234 | /// Strip Objective-C "__kindof" types from the given type. |
1235 | QualType stripObjCKindOfType(const ASTContext &ctx) const; |
1236 | |
1237 | /// Remove all qualifiers including _Atomic. |
1238 | QualType getAtomicUnqualifiedType() const; |
1239 | |
1240 | private: |
1241 | // These methods are implemented in a separate translation unit; |
1242 | // "static"-ize them to avoid creating temporary QualTypes in the |
1243 | // caller. |
1244 | static bool isConstant(QualType T, const ASTContext& Ctx); |
1245 | static QualType getDesugaredType(QualType T, const ASTContext &Context); |
1246 | static SplitQualType getSplitDesugaredType(QualType T); |
1247 | static SplitQualType getSplitUnqualifiedTypeImpl(QualType type); |
1248 | static QualType getSingleStepDesugaredTypeImpl(QualType type, |
1249 | const ASTContext &C); |
1250 | static QualType IgnoreParens(QualType T); |
1251 | static DestructionKind isDestructedTypeImpl(QualType type); |
1252 | |
1253 | /// Check if \param RD is or contains a non-trivial C union. |
1254 | static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD); |
1255 | static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD); |
1256 | static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD); |
1257 | }; |
1258 | |
1259 | } // namespace clang |
1260 | |
1261 | namespace llvm { |
1262 | |
1263 | /// Implement simplify_type for QualType, so that we can dyn_cast from QualType |
1264 | /// to a specific Type class. |
1265 | template<> struct simplify_type< ::clang::QualType> { |
1266 | using SimpleType = const ::clang::Type *; |
1267 | |
1268 | static SimpleType getSimplifiedValue(::clang::QualType Val) { |
1269 | return Val.getTypePtr(); |
1270 | } |
1271 | }; |
1272 | |
1273 | // Teach SmallPtrSet that QualType is "basically a pointer". |
1274 | template<> |
1275 | struct PointerLikeTypeTraits<clang::QualType> { |
1276 | static inline void *getAsVoidPointer(clang::QualType P) { |
1277 | return P.getAsOpaquePtr(); |
1278 | } |
1279 | |
1280 | static inline clang::QualType getFromVoidPointer(void *P) { |
1281 | return clang::QualType::getFromOpaquePtr(P); |
1282 | } |
1283 | |
1284 | // Various qualifiers go in low bits. |
1285 | enum { NumLowBitsAvailable = 0 }; |
1286 | }; |
1287 | |
1288 | } // namespace llvm |
1289 | |
1290 | namespace clang { |
1291 | |
1292 | /// Base class that is common to both the \c ExtQuals and \c Type |
1293 | /// classes, which allows \c QualType to access the common fields between the |
1294 | /// two. |
1295 | class ExtQualsTypeCommonBase { |
1296 | friend class ExtQuals; |
1297 | friend class QualType; |
1298 | friend class Type; |
1299 | |
1300 | /// The "base" type of an extended qualifiers type (\c ExtQuals) or |
1301 | /// a self-referential pointer (for \c Type). |
1302 | /// |
1303 | /// This pointer allows an efficient mapping from a QualType to its |
1304 | /// underlying type pointer. |
1305 | const Type *const BaseType; |
1306 | |
1307 | /// The canonical type of this type. A QualType. |
1308 | QualType CanonicalType; |
1309 | |
1310 | ExtQualsTypeCommonBase(const Type *baseType, QualType canon) |
1311 | : BaseType(baseType), CanonicalType(canon) {} |
1312 | }; |
1313 | |
1314 | /// We can encode up to four bits in the low bits of a |
1315 | /// type pointer, but there are many more type qualifiers that we want |
1316 | /// to be able to apply to an arbitrary type. Therefore we have this |
1317 | /// struct, intended to be heap-allocated and used by QualType to |
1318 | /// store qualifiers. |
1319 | /// |
1320 | /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers |
1321 | /// in three low bits on the QualType pointer; a fourth bit records whether |
1322 | /// the pointer is an ExtQuals node. The extended qualifiers (address spaces, |
1323 | /// Objective-C GC attributes) are much more rare. |
1324 | class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode { |
1325 | // NOTE: changing the fast qualifiers should be straightforward as |
1326 | // long as you don't make 'const' non-fast. |
1327 | // 1. Qualifiers: |
1328 | // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ). |
1329 | // Fast qualifiers must occupy the low-order bits. |
1330 | // b) Update Qualifiers::FastWidth and FastMask. |
1331 | // 2. QualType: |
1332 | // a) Update is{Volatile,Restrict}Qualified(), defined inline. |
1333 | // b) Update remove{Volatile,Restrict}, defined near the end of |
1334 | // this header. |
1335 | // 3. ASTContext: |
1336 | // a) Update get{Volatile,Restrict}Type. |
1337 | |
1338 | /// The immutable set of qualifiers applied by this node. Always contains |
1339 | /// extended qualifiers. |
1340 | Qualifiers Quals; |
1341 | |
1342 | ExtQuals *this_() { return this; } |
1343 | |
1344 | public: |
1345 | ExtQuals(const Type *baseType, QualType canon, Qualifiers quals) |
1346 | : ExtQualsTypeCommonBase(baseType, |
1347 | canon.isNull() ? QualType(this_(), 0) : canon), |
1348 | Quals(quals) { |
1349 | assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1350, __PRETTY_FUNCTION__)) |
1350 | && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1350, __PRETTY_FUNCTION__)); |
1351 | assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1352, __PRETTY_FUNCTION__)) |
1352 | && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1352, __PRETTY_FUNCTION__)); |
1353 | } |
1354 | |
1355 | Qualifiers getQualifiers() const { return Quals; } |
1356 | |
1357 | bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); } |
1358 | Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); } |
1359 | |
1360 | bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); } |
1361 | Qualifiers::ObjCLifetime getObjCLifetime() const { |
1362 | return Quals.getObjCLifetime(); |
1363 | } |
1364 | |
1365 | bool hasAddressSpace() const { return Quals.hasAddressSpace(); } |
1366 | LangAS getAddressSpace() const { return Quals.getAddressSpace(); } |
1367 | |
1368 | const Type *getBaseType() const { return BaseType; } |
1369 | |
1370 | public: |
1371 | void Profile(llvm::FoldingSetNodeID &ID) const { |
1372 | Profile(ID, getBaseType(), Quals); |
1373 | } |
1374 | |
1375 | static void Profile(llvm::FoldingSetNodeID &ID, |
1376 | const Type *BaseType, |
1377 | Qualifiers Quals) { |
1378 | assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!" ) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1378, __PRETTY_FUNCTION__)); |
1379 | ID.AddPointer(BaseType); |
1380 | Quals.Profile(ID); |
1381 | } |
1382 | }; |
1383 | |
1384 | /// The kind of C++11 ref-qualifier associated with a function type. |
1385 | /// This determines whether a member function's "this" object can be an |
1386 | /// lvalue, rvalue, or neither. |
1387 | enum RefQualifierKind { |
1388 | /// No ref-qualifier was provided. |
1389 | RQ_None = 0, |
1390 | |
1391 | /// An lvalue ref-qualifier was provided (\c &). |
1392 | RQ_LValue, |
1393 | |
1394 | /// An rvalue ref-qualifier was provided (\c &&). |
1395 | RQ_RValue |
1396 | }; |
1397 | |
1398 | /// Which keyword(s) were used to create an AutoType. |
1399 | enum class AutoTypeKeyword { |
1400 | /// auto |
1401 | Auto, |
1402 | |
1403 | /// decltype(auto) |
1404 | DecltypeAuto, |
1405 | |
1406 | /// __auto_type (GNU extension) |
1407 | GNUAutoType |
1408 | }; |
1409 | |
1410 | /// The base class of the type hierarchy. |
1411 | /// |
1412 | /// A central concept with types is that each type always has a canonical |
1413 | /// type. A canonical type is the type with any typedef names stripped out |
1414 | /// of it or the types it references. For example, consider: |
1415 | /// |
1416 | /// typedef int foo; |
1417 | /// typedef foo* bar; |
1418 | /// 'int *' 'foo *' 'bar' |
1419 | /// |
1420 | /// There will be a Type object created for 'int'. Since int is canonical, its |
1421 | /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a |
1422 | /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next |
1423 | /// there is a PointerType that represents 'int*', which, like 'int', is |
1424 | /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical |
1425 | /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type |
1426 | /// is also 'int*'. |
1427 | /// |
1428 | /// Non-canonical types are useful for emitting diagnostics, without losing |
1429 | /// information about typedefs being used. Canonical types are useful for type |
1430 | /// comparisons (they allow by-pointer equality tests) and useful for reasoning |
1431 | /// about whether something has a particular form (e.g. is a function type), |
1432 | /// because they implicitly, recursively, strip all typedefs out of a type. |
1433 | /// |
1434 | /// Types, once created, are immutable. |
1435 | /// |
1436 | class alignas(8) Type : public ExtQualsTypeCommonBase { |
1437 | public: |
1438 | enum TypeClass { |
1439 | #define TYPE(Class, Base) Class, |
1440 | #define LAST_TYPE(Class) TypeLast = Class |
1441 | #define ABSTRACT_TYPE(Class, Base) |
1442 | #include "clang/AST/TypeNodes.inc" |
1443 | }; |
1444 | |
1445 | private: |
1446 | /// Bitfields required by the Type class. |
1447 | class TypeBitfields { |
1448 | friend class Type; |
1449 | template <class T> friend class TypePropertyCache; |
1450 | |
1451 | /// TypeClass bitfield - Enum that specifies what subclass this belongs to. |
1452 | unsigned TC : 8; |
1453 | |
1454 | /// Whether this type is a dependent type (C++ [temp.dep.type]). |
1455 | unsigned Dependent : 1; |
1456 | |
1457 | /// Whether this type somehow involves a template parameter, even |
1458 | /// if the resolution of the type does not depend on a template parameter. |
1459 | unsigned InstantiationDependent : 1; |
1460 | |
1461 | /// Whether this type is a variably-modified type (C99 6.7.5). |
1462 | unsigned VariablyModified : 1; |
1463 | |
1464 | /// Whether this type contains an unexpanded parameter pack |
1465 | /// (for C++11 variadic templates). |
1466 | unsigned ContainsUnexpandedParameterPack : 1; |
1467 | |
1468 | /// True if the cache (i.e. the bitfields here starting with |
1469 | /// 'Cache') is valid. |
1470 | mutable unsigned CacheValid : 1; |
1471 | |
1472 | /// Linkage of this type. |
1473 | mutable unsigned CachedLinkage : 3; |
1474 | |
1475 | /// Whether this type involves and local or unnamed types. |
1476 | mutable unsigned CachedLocalOrUnnamed : 1; |
1477 | |
1478 | /// Whether this type comes from an AST file. |
1479 | mutable unsigned FromAST : 1; |
1480 | |
1481 | bool isCacheValid() const { |
1482 | return CacheValid; |
1483 | } |
1484 | |
1485 | Linkage getLinkage() const { |
1486 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1486, __PRETTY_FUNCTION__)); |
1487 | return static_cast<Linkage>(CachedLinkage); |
1488 | } |
1489 | |
1490 | bool hasLocalOrUnnamedType() const { |
1491 | assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache" ) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 1491, __PRETTY_FUNCTION__)); |
1492 | return CachedLocalOrUnnamed; |
1493 | } |
1494 | }; |
1495 | enum { NumTypeBits = 18 }; |
1496 | |
1497 | protected: |
1498 | // These classes allow subclasses to somewhat cleanly pack bitfields |
1499 | // into Type. |
1500 | |
1501 | class ArrayTypeBitfields { |
1502 | friend class ArrayType; |
1503 | |
1504 | unsigned : NumTypeBits; |
1505 | |
1506 | /// CVR qualifiers from declarations like |
1507 | /// 'int X[static restrict 4]'. For function parameters only. |
1508 | unsigned IndexTypeQuals : 3; |
1509 | |
1510 | /// Storage class qualifiers from declarations like |
1511 | /// 'int X[static restrict 4]'. For function parameters only. |
1512 | /// Actually an ArrayType::ArraySizeModifier. |
1513 | unsigned SizeModifier : 3; |
1514 | }; |
1515 | |
1516 | class BuiltinTypeBitfields { |
1517 | friend class BuiltinType; |
1518 | |
1519 | unsigned : NumTypeBits; |
1520 | |
1521 | /// The kind (BuiltinType::Kind) of builtin type this is. |
1522 | unsigned Kind : 8; |
1523 | }; |
1524 | |
1525 | /// FunctionTypeBitfields store various bits belonging to FunctionProtoType. |
1526 | /// Only common bits are stored here. Additional uncommon bits are stored |
1527 | /// in a trailing object after FunctionProtoType. |
1528 | class FunctionTypeBitfields { |
1529 | friend class FunctionProtoType; |
1530 | friend class FunctionType; |
1531 | |
1532 | unsigned : NumTypeBits; |
1533 | |
1534 | /// Extra information which affects how the function is called, like |
1535 | /// regparm and the calling convention. |
1536 | unsigned ExtInfo : 12; |
1537 | |
1538 | /// The ref-qualifier associated with a \c FunctionProtoType. |
1539 | /// |
1540 | /// This is a value of type \c RefQualifierKind. |
1541 | unsigned RefQualifier : 2; |
1542 | |
1543 | /// Used only by FunctionProtoType, put here to pack with the |
1544 | /// other bitfields. |
1545 | /// The qualifiers are part of FunctionProtoType because... |
1546 | /// |
1547 | /// C++ 8.3.5p4: The return type, the parameter type list and the |
1548 | /// cv-qualifier-seq, [...], are part of the function type. |
1549 | unsigned FastTypeQuals : Qualifiers::FastWidth; |
1550 | /// Whether this function has extended Qualifiers. |
1551 | unsigned HasExtQuals : 1; |
1552 | |
1553 | /// The number of parameters this function has, not counting '...'. |
1554 | /// According to [implimits] 8 bits should be enough here but this is |
1555 | /// somewhat easy to exceed with metaprogramming and so we would like to |
1556 | /// keep NumParams as wide as reasonably possible. |
1557 | unsigned NumParams : 16; |
1558 | |
1559 | /// The type of exception specification this function has. |
1560 | unsigned ExceptionSpecType : 4; |
1561 | |
1562 | /// Whether this function has extended parameter information. |
1563 | unsigned HasExtParameterInfos : 1; |
1564 | |
1565 | /// Whether the function is variadic. |
1566 | unsigned Variadic : 1; |
1567 | |
1568 | /// Whether this function has a trailing return type. |
1569 | unsigned HasTrailingReturn : 1; |
1570 | }; |
1571 | |
1572 | class ObjCObjectTypeBitfields { |
1573 | friend class ObjCObjectType; |
1574 | |
1575 | unsigned : NumTypeBits; |
1576 | |
1577 | /// The number of type arguments stored directly on this object type. |
1578 | unsigned NumTypeArgs : 7; |
1579 | |
1580 | /// The number of protocols stored directly on this object type. |
1581 | unsigned NumProtocols : 6; |
1582 | |
1583 | /// Whether this is a "kindof" type. |
1584 | unsigned IsKindOf : 1; |
1585 | }; |
1586 | |
1587 | class ReferenceTypeBitfields { |
1588 | friend class ReferenceType; |
1589 | |
1590 | unsigned : NumTypeBits; |
1591 | |
1592 | /// True if the type was originally spelled with an lvalue sigil. |
1593 | /// This is never true of rvalue references but can also be false |
1594 | /// on lvalue references because of C++0x [dcl.typedef]p9, |
1595 | /// as follows: |
1596 | /// |
1597 | /// typedef int &ref; // lvalue, spelled lvalue |
1598 | /// typedef int &&rvref; // rvalue |
1599 | /// ref &a; // lvalue, inner ref, spelled lvalue |
1600 | /// ref &&a; // lvalue, inner ref |
1601 | /// rvref &a; // lvalue, inner ref, spelled lvalue |
1602 | /// rvref &&a; // rvalue, inner ref |
1603 | unsigned SpelledAsLValue : 1; |
1604 | |
1605 | /// True if the inner type is a reference type. This only happens |
1606 | /// in non-canonical forms. |
1607 | unsigned InnerRef : 1; |
1608 | }; |
1609 | |
1610 | class TypeWithKeywordBitfields { |
1611 | friend class TypeWithKeyword; |
1612 | |
1613 | unsigned : NumTypeBits; |
1614 | |
1615 | /// An ElaboratedTypeKeyword. 8 bits for efficient access. |
1616 | unsigned Keyword : 8; |
1617 | }; |
1618 | |
1619 | enum { NumTypeWithKeywordBits = 8 }; |
1620 | |
1621 | class ElaboratedTypeBitfields { |
1622 | friend class ElaboratedType; |
1623 | |
1624 | unsigned : NumTypeBits; |
1625 | unsigned : NumTypeWithKeywordBits; |
1626 | |
1627 | /// Whether the ElaboratedType has a trailing OwnedTagDecl. |
1628 | unsigned HasOwnedTagDecl : 1; |
1629 | }; |
1630 | |
1631 | class VectorTypeBitfields { |
1632 | friend class VectorType; |
1633 | friend class DependentVectorType; |
1634 | |
1635 | unsigned : NumTypeBits; |
1636 | |
1637 | /// The kind of vector, either a generic vector type or some |
1638 | /// target-specific vector type such as for AltiVec or Neon. |
1639 | unsigned VecKind : 3; |
1640 | |
1641 | /// The number of elements in the vector. |
1642 | unsigned NumElements : 29 - NumTypeBits; |
1643 | |
1644 | enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 }; |
1645 | }; |
1646 | |
1647 | class AttributedTypeBitfields { |
1648 | friend class AttributedType; |
1649 | |
1650 | unsigned : NumTypeBits; |
1651 | |
1652 | /// An AttributedType::Kind |
1653 | unsigned AttrKind : 32 - NumTypeBits; |
1654 | }; |
1655 | |
1656 | class AutoTypeBitfields { |
1657 | friend class AutoType; |
1658 | |
1659 | unsigned : NumTypeBits; |
1660 | |
1661 | /// Was this placeholder type spelled as 'auto', 'decltype(auto)', |
1662 | /// or '__auto_type'? AutoTypeKeyword value. |
1663 | unsigned Keyword : 2; |
1664 | }; |
1665 | |
1666 | class SubstTemplateTypeParmPackTypeBitfields { |
1667 | friend class SubstTemplateTypeParmPackType; |
1668 | |
1669 | unsigned : NumTypeBits; |
1670 | |
1671 | /// The number of template arguments in \c Arguments, which is |
1672 | /// expected to be able to hold at least 1024 according to [implimits]. |
1673 | /// However as this limit is somewhat easy to hit with template |
1674 | /// metaprogramming we'd prefer to keep it as large as possible. |
1675 | /// At the moment it has been left as a non-bitfield since this type |
1676 | /// safely fits in 64 bits as an unsigned, so there is no reason to |
1677 | /// introduce the performance impact of a bitfield. |
1678 | unsigned NumArgs; |
1679 | }; |
1680 | |
1681 | class TemplateSpecializationTypeBitfields { |
1682 | friend class TemplateSpecializationType; |
1683 | |
1684 | unsigned : NumTypeBits; |
1685 | |
1686 | /// Whether this template specialization type is a substituted type alias. |
1687 | unsigned TypeAlias : 1; |
1688 | |
1689 | /// The number of template arguments named in this class template |
1690 | /// specialization, which is expected to be able to hold at least 1024 |
1691 | /// according to [implimits]. However, as this limit is somewhat easy to |
1692 | /// hit with template metaprogramming we'd prefer to keep it as large |
1693 | /// as possible. At the moment it has been left as a non-bitfield since |
1694 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1695 | /// to introduce the performance impact of a bitfield. |
1696 | unsigned NumArgs; |
1697 | }; |
1698 | |
1699 | class DependentTemplateSpecializationTypeBitfields { |
1700 | friend class DependentTemplateSpecializationType; |
1701 | |
1702 | unsigned : NumTypeBits; |
1703 | unsigned : NumTypeWithKeywordBits; |
1704 | |
1705 | /// The number of template arguments named in this class template |
1706 | /// specialization, which is expected to be able to hold at least 1024 |
1707 | /// according to [implimits]. However, as this limit is somewhat easy to |
1708 | /// hit with template metaprogramming we'd prefer to keep it as large |
1709 | /// as possible. At the moment it has been left as a non-bitfield since |
1710 | /// this type safely fits in 64 bits as an unsigned, so there is no reason |
1711 | /// to introduce the performance impact of a bitfield. |
1712 | unsigned NumArgs; |
1713 | }; |
1714 | |
1715 | class PackExpansionTypeBitfields { |
1716 | friend class PackExpansionType; |
1717 | |
1718 | unsigned : NumTypeBits; |
1719 | |
1720 | /// The number of expansions that this pack expansion will |
1721 | /// generate when substituted (+1), which is expected to be able to |
1722 | /// hold at least 1024 according to [implimits]. However, as this limit |
1723 | /// is somewhat easy to hit with template metaprogramming we'd prefer to |
1724 | /// keep it as large as possible. At the moment it has been left as a |
1725 | /// non-bitfield since this type safely fits in 64 bits as an unsigned, so |
1726 | /// there is no reason to introduce the performance impact of a bitfield. |
1727 | /// |
1728 | /// This field will only have a non-zero value when some of the parameter |
1729 | /// packs that occur within the pattern have been substituted but others |
1730 | /// have not. |
1731 | unsigned NumExpansions; |
1732 | }; |
1733 | |
1734 | union { |
1735 | TypeBitfields TypeBits; |
1736 | ArrayTypeBitfields ArrayTypeBits; |
1737 | AttributedTypeBitfields AttributedTypeBits; |
1738 | AutoTypeBitfields AutoTypeBits; |
1739 | BuiltinTypeBitfields BuiltinTypeBits; |
1740 | FunctionTypeBitfields FunctionTypeBits; |
1741 | ObjCObjectTypeBitfields ObjCObjectTypeBits; |
1742 | ReferenceTypeBitfields ReferenceTypeBits; |
1743 | TypeWithKeywordBitfields TypeWithKeywordBits; |
1744 | ElaboratedTypeBitfields ElaboratedTypeBits; |
1745 | VectorTypeBitfields VectorTypeBits; |
1746 | SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits; |
1747 | TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits; |
1748 | DependentTemplateSpecializationTypeBitfields |
1749 | DependentTemplateSpecializationTypeBits; |
1750 | PackExpansionTypeBitfields PackExpansionTypeBits; |
1751 | |
1752 | static_assert(sizeof(TypeBitfields) <= 8, |
1753 | "TypeBitfields is larger than 8 bytes!"); |
1754 | static_assert(sizeof(ArrayTypeBitfields) <= 8, |
1755 | "ArrayTypeBitfields is larger than 8 bytes!"); |
1756 | static_assert(sizeof(AttributedTypeBitfields) <= 8, |
1757 | "AttributedTypeBitfields is larger than 8 bytes!"); |
1758 | static_assert(sizeof(AutoTypeBitfields) <= 8, |
1759 | "AutoTypeBitfields is larger than 8 bytes!"); |
1760 | static_assert(sizeof(BuiltinTypeBitfields) <= 8, |
1761 | "BuiltinTypeBitfields is larger than 8 bytes!"); |
1762 | static_assert(sizeof(FunctionTypeBitfields) <= 8, |
1763 | "FunctionTypeBitfields is larger than 8 bytes!"); |
1764 | static_assert(sizeof(ObjCObjectTypeBitfields) <= 8, |
1765 | "ObjCObjectTypeBitfields is larger than 8 bytes!"); |
1766 | static_assert(sizeof(ReferenceTypeBitfields) <= 8, |
1767 | "ReferenceTypeBitfields is larger than 8 bytes!"); |
1768 | static_assert(sizeof(TypeWithKeywordBitfields) <= 8, |
1769 | "TypeWithKeywordBitfields is larger than 8 bytes!"); |
1770 | static_assert(sizeof(ElaboratedTypeBitfields) <= 8, |
1771 | "ElaboratedTypeBitfields is larger than 8 bytes!"); |
1772 | static_assert(sizeof(VectorTypeBitfields) <= 8, |
1773 | "VectorTypeBitfields is larger than 8 bytes!"); |
1774 | static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8, |
1775 | "SubstTemplateTypeParmPackTypeBitfields is larger" |
1776 | " than 8 bytes!"); |
1777 | static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8, |
1778 | "TemplateSpecializationTypeBitfields is larger" |
1779 | " than 8 bytes!"); |
1780 | static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8, |
1781 | "DependentTemplateSpecializationTypeBitfields is larger" |
1782 | " than 8 bytes!"); |
1783 | static_assert(sizeof(PackExpansionTypeBitfields) <= 8, |
1784 | "PackExpansionTypeBitfields is larger than 8 bytes"); |
1785 | }; |
1786 | |
1787 | private: |
1788 | template <class T> friend class TypePropertyCache; |
1789 | |
1790 | /// Set whether this type comes from an AST file. |
1791 | void setFromAST(bool V = true) const { |
1792 | TypeBits.FromAST = V; |
1793 | } |
1794 | |
1795 | protected: |
1796 | friend class ASTContext; |
1797 | |
1798 | Type(TypeClass tc, QualType canon, bool Dependent, |
1799 | bool InstantiationDependent, bool VariablyModified, |
1800 | bool ContainsUnexpandedParameterPack) |
1801 | : ExtQualsTypeCommonBase(this, |
1802 | canon.isNull() ? QualType(this_(), 0) : canon) { |
1803 | TypeBits.TC = tc; |
1804 | TypeBits.Dependent = Dependent; |
1805 | TypeBits.InstantiationDependent = Dependent || InstantiationDependent; |
1806 | TypeBits.VariablyModified = VariablyModified; |
1807 | TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; |
1808 | TypeBits.CacheValid = false; |
1809 | TypeBits.CachedLocalOrUnnamed = false; |
1810 | TypeBits.CachedLinkage = NoLinkage; |
1811 | TypeBits.FromAST = false; |
1812 | } |
1813 | |
1814 | // silence VC++ warning C4355: 'this' : used in base member initializer list |
1815 | Type *this_() { return this; } |
1816 | |
1817 | void setDependent(bool D = true) { |
1818 | TypeBits.Dependent = D; |
1819 | if (D) |
1820 | TypeBits.InstantiationDependent = true; |
1821 | } |
1822 | |
1823 | void setInstantiationDependent(bool D = true) { |
1824 | TypeBits.InstantiationDependent = D; } |
1825 | |
1826 | void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; } |
1827 | |
1828 | void setContainsUnexpandedParameterPack(bool PP = true) { |
1829 | TypeBits.ContainsUnexpandedParameterPack = PP; |
1830 | } |
1831 | |
1832 | public: |
1833 | friend class ASTReader; |
1834 | friend class ASTWriter; |
1835 | |
1836 | Type(const Type &) = delete; |
1837 | Type(Type &&) = delete; |
1838 | Type &operator=(const Type &) = delete; |
1839 | Type &operator=(Type &&) = delete; |
1840 | |
1841 | TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); } |
1842 | |
1843 | /// Whether this type comes from an AST file. |
1844 | bool isFromAST() const { return TypeBits.FromAST; } |
1845 | |
1846 | /// Whether this type is or contains an unexpanded parameter |
1847 | /// pack, used to support C++0x variadic templates. |
1848 | /// |
1849 | /// A type that contains a parameter pack shall be expanded by the |
1850 | /// ellipsis operator at some point. For example, the typedef in the |
1851 | /// following example contains an unexpanded parameter pack 'T': |
1852 | /// |
1853 | /// \code |
1854 | /// template<typename ...T> |
1855 | /// struct X { |
1856 | /// typedef T* pointer_types; // ill-formed; T is a parameter pack. |
1857 | /// }; |
1858 | /// \endcode |
1859 | /// |
1860 | /// Note that this routine does not specify which |
1861 | bool containsUnexpandedParameterPack() const { |
1862 | return TypeBits.ContainsUnexpandedParameterPack; |
1863 | } |
1864 | |
1865 | /// Determines if this type would be canonical if it had no further |
1866 | /// qualification. |
1867 | bool isCanonicalUnqualified() const { |
1868 | return CanonicalType == QualType(this, 0); |
1869 | } |
1870 | |
1871 | /// Pull a single level of sugar off of this locally-unqualified type. |
1872 | /// Users should generally prefer SplitQualType::getSingleStepDesugaredType() |
1873 | /// or QualType::getSingleStepDesugaredType(const ASTContext&). |
1874 | QualType getLocallyUnqualifiedSingleStepDesugaredType() const; |
1875 | |
1876 | /// Types are partitioned into 3 broad categories (C99 6.2.5p1): |
1877 | /// object types, function types, and incomplete types. |
1878 | |
1879 | /// Return true if this is an incomplete type. |
1880 | /// A type that can describe objects, but which lacks information needed to |
1881 | /// determine its size (e.g. void, or a fwd declared struct). Clients of this |
1882 | /// routine will need to determine if the size is actually required. |
1883 | /// |
1884 | /// Def If non-null, and the type refers to some kind of declaration |
1885 | /// that can be completed (such as a C struct, C++ class, or Objective-C |
1886 | /// class), will be set to the declaration. |
1887 | bool isIncompleteType(NamedDecl **Def = nullptr) const; |
1888 | |
1889 | /// Return true if this is an incomplete or object |
1890 | /// type, in other words, not a function type. |
1891 | bool isIncompleteOrObjectType() const { |
1892 | return !isFunctionType(); |
1893 | } |
1894 | |
1895 | /// Determine whether this type is an object type. |
1896 | bool isObjectType() const { |
1897 | // C++ [basic.types]p8: |
1898 | // An object type is a (possibly cv-qualified) type that is not a |
1899 | // function type, not a reference type, and not a void type. |
1900 | return !isReferenceType() && !isFunctionType() && !isVoidType(); |
1901 | } |
1902 | |
1903 | /// Return true if this is a literal type |
1904 | /// (C++11 [basic.types]p10) |
1905 | bool isLiteralType(const ASTContext &Ctx) const; |
1906 | |
1907 | /// Test if this type is a standard-layout type. |
1908 | /// (C++0x [basic.type]p9) |
1909 | bool isStandardLayoutType() const; |
1910 | |
1911 | /// Helper methods to distinguish type categories. All type predicates |
1912 | /// operate on the canonical type, ignoring typedefs and qualifiers. |
1913 | |
1914 | /// Returns true if the type is a builtin type. |
1915 | bool isBuiltinType() const; |
1916 | |
1917 | /// Test for a particular builtin type. |
1918 | bool isSpecificBuiltinType(unsigned K) const; |
1919 | |
1920 | /// Test for a type which does not represent an actual type-system type but |
1921 | /// is instead used as a placeholder for various convenient purposes within |
1922 | /// Clang. All such types are BuiltinTypes. |
1923 | bool isPlaceholderType() const; |
1924 | const BuiltinType *getAsPlaceholderType() const; |
1925 | |
1926 | /// Test for a specific placeholder type. |
1927 | bool isSpecificPlaceholderType(unsigned K) const; |
1928 | |
1929 | /// Test for a placeholder type other than Overload; see |
1930 | /// BuiltinType::isNonOverloadPlaceholderType. |
1931 | bool isNonOverloadPlaceholderType() const; |
1932 | |
1933 | /// isIntegerType() does *not* include complex integers (a GCC extension). |
1934 | /// isComplexIntegerType() can be used to test for complex integers. |
1935 | bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum) |
1936 | bool isEnumeralType() const; |
1937 | |
1938 | /// Determine whether this type is a scoped enumeration type. |
1939 | bool isScopedEnumeralType() const; |
1940 | bool isBooleanType() const; |
1941 | bool isCharType() const; |
1942 | bool isWideCharType() const; |
1943 | bool isChar8Type() const; |
1944 | bool isChar16Type() const; |
1945 | bool isChar32Type() const; |
1946 | bool isAnyCharacterType() const; |
1947 | bool isIntegralType(const ASTContext &Ctx) const; |
1948 | |
1949 | /// Determine whether this type is an integral or enumeration type. |
1950 | bool isIntegralOrEnumerationType() const; |
1951 | |
1952 | /// Determine whether this type is an integral or unscoped enumeration type. |
1953 | bool isIntegralOrUnscopedEnumerationType() const; |
1954 | |
1955 | /// Floating point categories. |
1956 | bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double) |
1957 | /// isComplexType() does *not* include complex integers (a GCC extension). |
1958 | /// isComplexIntegerType() can be used to test for complex integers. |
1959 | bool isComplexType() const; // C99 6.2.5p11 (complex) |
1960 | bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int. |
1961 | bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex) |
1962 | bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half) |
1963 | bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661 |
1964 | bool isFloat128Type() const; |
1965 | bool isRealType() const; // C99 6.2.5p17 (real floating + integer) |
1966 | bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating) |
1967 | bool isVoidType() const; // C99 6.2.5p19 |
1968 | bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers) |
1969 | bool isAggregateType() const; |
1970 | bool isFundamentalType() const; |
1971 | bool isCompoundType() const; |
1972 | |
1973 | // Type Predicates: Check to see if this type is structurally the specified |
1974 | // type, ignoring typedefs and qualifiers. |
1975 | bool isFunctionType() const; |
1976 | bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); } |
1977 | bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); } |
1978 | bool isPointerType() const; |
1979 | bool isAnyPointerType() const; // Any C pointer or ObjC object pointer |
1980 | bool isBlockPointerType() const; |
1981 | bool isVoidPointerType() const; |
1982 | bool isReferenceType() const; |
1983 | bool isLValueReferenceType() const; |
1984 | bool isRValueReferenceType() const; |
1985 | bool isFunctionPointerType() const; |
1986 | bool isFunctionReferenceType() const; |
1987 | bool isMemberPointerType() const; |
1988 | bool isMemberFunctionPointerType() const; |
1989 | bool isMemberDataPointerType() const; |
1990 | bool isArrayType() const; |
1991 | bool isConstantArrayType() const; |
1992 | bool isIncompleteArrayType() const; |
1993 | bool isVariableArrayType() const; |
1994 | bool isDependentSizedArrayType() const; |
1995 | bool isRecordType() const; |
1996 | bool isClassType() const; |
1997 | bool isStructureType() const; |
1998 | bool isObjCBoxableRecordType() const; |
1999 | bool isInterfaceType() const; |
2000 | bool isStructureOrClassType() const; |
2001 | bool isUnionType() const; |
2002 | bool isComplexIntegerType() const; // GCC _Complex integer type. |
2003 | bool isVectorType() const; // GCC vector type. |
2004 | bool isExtVectorType() const; // Extended vector type. |
2005 | bool isDependentAddressSpaceType() const; // value-dependent address space qualifier |
2006 | bool isObjCObjectPointerType() const; // pointer to ObjC object |
2007 | bool isObjCRetainableType() const; // ObjC object or block pointer |
2008 | bool isObjCLifetimeType() const; // (array of)* retainable type |
2009 | bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type |
2010 | bool isObjCNSObjectType() const; // __attribute__((NSObject)) |
2011 | bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class)) |
2012 | // FIXME: change this to 'raw' interface type, so we can used 'interface' type |
2013 | // for the common case. |
2014 | bool isObjCObjectType() const; // NSString or typeof(*(id)0) |
2015 | bool isObjCQualifiedInterfaceType() const; // NSString<foo> |
2016 | bool isObjCQualifiedIdType() const; // id<foo> |
2017 | bool isObjCQualifiedClassType() const; // Class<foo> |
2018 | bool isObjCObjectOrInterfaceType() const; |
2019 | bool isObjCIdType() const; // id |
2020 | bool isDecltypeType() const; |
2021 | /// Was this type written with the special inert-in-ARC __unsafe_unretained |
2022 | /// qualifier? |
2023 | /// |
2024 | /// This approximates the answer to the following question: if this |
2025 | /// translation unit were compiled in ARC, would this type be qualified |
2026 | /// with __unsafe_unretained? |
2027 | bool isObjCInertUnsafeUnretainedType() const { |
2028 | return hasAttr(attr::ObjCInertUnsafeUnretained); |
2029 | } |
2030 | |
2031 | /// Whether the type is Objective-C 'id' or a __kindof type of an |
2032 | /// object type, e.g., __kindof NSView * or __kindof id |
2033 | /// <NSCopying>. |
2034 | /// |
2035 | /// \param bound Will be set to the bound on non-id subtype types, |
2036 | /// which will be (possibly specialized) Objective-C class type, or |
2037 | /// null for 'id. |
2038 | bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, |
2039 | const ObjCObjectType *&bound) const; |
2040 | |
2041 | bool isObjCClassType() const; // Class |
2042 | |
2043 | /// Whether the type is Objective-C 'Class' or a __kindof type of an |
2044 | /// Class type, e.g., __kindof Class <NSCopying>. |
2045 | /// |
2046 | /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound |
2047 | /// here because Objective-C's type system cannot express "a class |
2048 | /// object for a subclass of NSFoo". |
2049 | bool isObjCClassOrClassKindOfType() const; |
2050 | |
2051 | bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const; |
2052 | bool isObjCSelType() const; // Class |
2053 | bool isObjCBuiltinType() const; // 'id' or 'Class' |
2054 | bool isObjCARCBridgableType() const; |
2055 | bool isCARCBridgableType() const; |
2056 | bool isTemplateTypeParmType() const; // C++ template type parameter |
2057 | bool isNullPtrType() const; // C++11 std::nullptr_t |
2058 | bool isNothrowT() const; // C++ std::nothrow_t |
2059 | bool isAlignValT() const; // C++17 std::align_val_t |
2060 | bool isStdByteType() const; // C++17 std::byte |
2061 | bool isAtomicType() const; // C11 _Atomic() |
2062 | |
2063 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
2064 | bool is##Id##Type() const; |
2065 | #include "clang/Basic/OpenCLImageTypes.def" |
2066 | |
2067 | bool isImageType() const; // Any OpenCL image type |
2068 | |
2069 | bool isSamplerT() const; // OpenCL sampler_t |
2070 | bool isEventT() const; // OpenCL event_t |
2071 | bool isClkEventT() const; // OpenCL clk_event_t |
2072 | bool isQueueT() const; // OpenCL queue_t |
2073 | bool isReserveIDT() const; // OpenCL reserve_id_t |
2074 | |
2075 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
2076 | bool is##Id##Type() const; |
2077 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2078 | // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension |
2079 | bool isOCLIntelSubgroupAVCType() const; |
2080 | bool isOCLExtOpaqueType() const; // Any OpenCL extension type |
2081 | |
2082 | bool isPipeType() const; // OpenCL pipe type |
2083 | bool isOpenCLSpecificType() const; // Any OpenCL specific type |
2084 | |
2085 | /// Determines if this type, which must satisfy |
2086 | /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather |
2087 | /// than implicitly __strong. |
2088 | bool isObjCARCImplicitlyUnretainedType() const; |
2089 | |
2090 | /// Return the implicit lifetime for this type, which must not be dependent. |
2091 | Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const; |
2092 | |
2093 | enum ScalarTypeKind { |
2094 | STK_CPointer, |
2095 | STK_BlockPointer, |
2096 | STK_ObjCObjectPointer, |
2097 | STK_MemberPointer, |
2098 | STK_Bool, |
2099 | STK_Integral, |
2100 | STK_Floating, |
2101 | STK_IntegralComplex, |
2102 | STK_FloatingComplex, |
2103 | STK_FixedPoint |
2104 | }; |
2105 | |
2106 | /// Given that this is a scalar type, classify it. |
2107 | ScalarTypeKind getScalarTypeKind() const; |
2108 | |
2109 | /// Whether this type is a dependent type, meaning that its definition |
2110 | /// somehow depends on a template parameter (C++ [temp.dep.type]). |
2111 | bool isDependentType() const { return TypeBits.Dependent; } |
2112 | |
2113 | /// Determine whether this type is an instantiation-dependent type, |
2114 | /// meaning that the type involves a template parameter (even if the |
2115 | /// definition does not actually depend on the type substituted for that |
2116 | /// template parameter). |
2117 | bool isInstantiationDependentType() const { |
2118 | return TypeBits.InstantiationDependent; |
2119 | } |
2120 | |
2121 | /// Determine whether this type is an undeduced type, meaning that |
2122 | /// it somehow involves a C++11 'auto' type or similar which has not yet been |
2123 | /// deduced. |
2124 | bool isUndeducedType() const; |
2125 | |
2126 | /// Whether this type is a variably-modified type (C99 6.7.5). |
2127 | bool isVariablyModifiedType() const { return TypeBits.VariablyModified; } |
2128 | |
2129 | /// Whether this type involves a variable-length array type |
2130 | /// with a definite size. |
2131 | bool hasSizedVLAType() const; |
2132 | |
2133 | /// Whether this type is or contains a local or unnamed type. |
2134 | bool hasUnnamedOrLocalType() const; |
2135 | |
2136 | bool isOverloadableType() const; |
2137 | |
2138 | /// Determine wither this type is a C++ elaborated-type-specifier. |
2139 | bool isElaboratedTypeSpecifier() const; |
2140 | |
2141 | bool canDecayToPointerType() const; |
2142 | |
2143 | /// Whether this type is represented natively as a pointer. This includes |
2144 | /// pointers, references, block pointers, and Objective-C interface, |
2145 | /// qualified id, and qualified interface types, as well as nullptr_t. |
2146 | bool hasPointerRepresentation() const; |
2147 | |
2148 | /// Whether this type can represent an objective pointer type for the |
2149 | /// purpose of GC'ability |
2150 | bool hasObjCPointerRepresentation() const; |
2151 | |
2152 | /// Determine whether this type has an integer representation |
2153 | /// of some sort, e.g., it is an integer type or a vector. |
2154 | bool hasIntegerRepresentation() const; |
2155 | |
2156 | /// Determine whether this type has an signed integer representation |
2157 | /// of some sort, e.g., it is an signed integer type or a vector. |
2158 | bool hasSignedIntegerRepresentation() const; |
2159 | |
2160 | /// Determine whether this type has an unsigned integer representation |
2161 | /// of some sort, e.g., it is an unsigned integer type or a vector. |
2162 | bool hasUnsignedIntegerRepresentation() const; |
2163 | |
2164 | /// Determine whether this type has a floating-point representation |
2165 | /// of some sort, e.g., it is a floating-point type or a vector thereof. |
2166 | bool hasFloatingRepresentation() const; |
2167 | |
2168 | // Type Checking Functions: Check to see if this type is structurally the |
2169 | // specified type, ignoring typedefs and qualifiers, and return a pointer to |
2170 | // the best type we can. |
2171 | const RecordType *getAsStructureType() const; |
2172 | /// NOTE: getAs*ArrayType are methods on ASTContext. |
2173 | const RecordType *getAsUnionType() const; |
2174 | const ComplexType *getAsComplexIntegerType() const; // GCC complex int type. |
2175 | const ObjCObjectType *getAsObjCInterfaceType() const; |
2176 | |
2177 | // The following is a convenience method that returns an ObjCObjectPointerType |
2178 | // for object declared using an interface. |
2179 | const ObjCObjectPointerType *getAsObjCInterfacePointerType() const; |
2180 | const ObjCObjectPointerType *getAsObjCQualifiedIdType() const; |
2181 | const ObjCObjectPointerType *getAsObjCQualifiedClassType() const; |
2182 | const ObjCObjectType *getAsObjCQualifiedInterfaceType() const; |
2183 | |
2184 | /// Retrieves the CXXRecordDecl that this type refers to, either |
2185 | /// because the type is a RecordType or because it is the injected-class-name |
2186 | /// type of a class template or class template partial specialization. |
2187 | CXXRecordDecl *getAsCXXRecordDecl() const; |
2188 | |
2189 | /// Retrieves the RecordDecl this type refers to. |
2190 | RecordDecl *getAsRecordDecl() const; |
2191 | |
2192 | /// Retrieves the TagDecl that this type refers to, either |
2193 | /// because the type is a TagType or because it is the injected-class-name |
2194 | /// type of a class template or class template partial specialization. |
2195 | TagDecl *getAsTagDecl() const; |
2196 | |
2197 | /// If this is a pointer or reference to a RecordType, return the |
2198 | /// CXXRecordDecl that the type refers to. |
2199 | /// |
2200 | /// If this is not a pointer or reference, or the type being pointed to does |
2201 | /// not refer to a CXXRecordDecl, returns NULL. |
2202 | const CXXRecordDecl *getPointeeCXXRecordDecl() const; |
2203 | |
2204 | /// Get the DeducedType whose type will be deduced for a variable with |
2205 | /// an initializer of this type. This looks through declarators like pointer |
2206 | /// types, but not through decltype or typedefs. |
2207 | DeducedType *getContainedDeducedType() const; |
2208 | |
2209 | /// Get the AutoType whose type will be deduced for a variable with |
2210 | /// an initializer of this type. This looks through declarators like pointer |
2211 | /// types, but not through decltype or typedefs. |
2212 | AutoType *getContainedAutoType() const { |
2213 | return dyn_cast_or_null<AutoType>(getContainedDeducedType()); |
2214 | } |
2215 | |
2216 | /// Determine whether this type was written with a leading 'auto' |
2217 | /// corresponding to a trailing return type (possibly for a nested |
2218 | /// function type within a pointer to function type or similar). |
2219 | bool hasAutoForTrailingReturnType() const; |
2220 | |
2221 | /// Member-template getAs<specific type>'. Look through sugar for |
2222 | /// an instance of \<specific type>. This scheme will eventually |
2223 | /// replace the specific getAsXXXX methods above. |
2224 | /// |
2225 | /// There are some specializations of this member template listed |
2226 | /// immediately following this class. |
2227 | template <typename T> const T *getAs() const; |
2228 | |
2229 | /// Member-template getAsAdjusted<specific type>. Look through specific kinds |
2230 | /// of sugar (parens, attributes, etc) for an instance of \<specific type>. |
2231 | /// This is used when you need to walk over sugar nodes that represent some |
2232 | /// kind of type adjustment from a type that was written as a \<specific type> |
2233 | /// to another type that is still canonically a \<specific type>. |
2234 | template <typename T> const T *getAsAdjusted() const; |
2235 | |
2236 | /// A variant of getAs<> for array types which silently discards |
2237 | /// qualifiers from the outermost type. |
2238 | const ArrayType *getAsArrayTypeUnsafe() const; |
2239 | |
2240 | /// Member-template castAs<specific type>. Look through sugar for |
2241 | /// the underlying instance of \<specific type>. |
2242 | /// |
2243 | /// This method has the same relationship to getAs<T> as cast<T> has |
2244 | /// to dyn_cast<T>; which is to say, the underlying type *must* |
2245 | /// have the intended type, and this method will never return null. |
2246 | template <typename T> const T *castAs() const; |
2247 | |
2248 | /// A variant of castAs<> for array type which silently discards |
2249 | /// qualifiers from the outermost type. |
2250 | const ArrayType *castAsArrayTypeUnsafe() const; |
2251 | |
2252 | /// Determine whether this type had the specified attribute applied to it |
2253 | /// (looking through top-level type sugar). |
2254 | bool hasAttr(attr::Kind AK) const; |
2255 | |
2256 | /// Get the base element type of this type, potentially discarding type |
2257 | /// qualifiers. This should never be used when type qualifiers |
2258 | /// are meaningful. |
2259 | const Type *getBaseElementTypeUnsafe() const; |
2260 | |
2261 | /// If this is an array type, return the element type of the array, |
2262 | /// potentially with type qualifiers missing. |
2263 | /// This should never be used when type qualifiers are meaningful. |
2264 | const Type *getArrayElementTypeNoTypeQual() const; |
2265 | |
2266 | /// If this is a pointer type, return the pointee type. |
2267 | /// If this is an array type, return the array element type. |
2268 | /// This should never be used when type qualifiers are meaningful. |
2269 | const Type *getPointeeOrArrayElementType() const; |
2270 | |
2271 | /// If this is a pointer, ObjC object pointer, or block |
2272 | /// pointer, this returns the respective pointee. |
2273 | QualType getPointeeType() const; |
2274 | |
2275 | /// Return the specified type with any "sugar" removed from the type, |
2276 | /// removing any typedefs, typeofs, etc., as well as any qualifiers. |
2277 | const Type *getUnqualifiedDesugaredType() const; |
2278 | |
2279 | /// More type predicates useful for type checking/promotion |
2280 | bool isPromotableIntegerType() const; // C99 6.3.1.1p2 |
2281 | |
2282 | /// Return true if this is an integer type that is |
2283 | /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], |
2284 | /// or an enum decl which has a signed representation. |
2285 | bool isSignedIntegerType() const; |
2286 | |
2287 | /// Return true if this is an integer type that is |
2288 | /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], |
2289 | /// or an enum decl which has an unsigned representation. |
2290 | bool isUnsignedIntegerType() const; |
2291 | |
2292 | /// Determines whether this is an integer type that is signed or an |
2293 | /// enumeration types whose underlying type is a signed integer type. |
2294 | bool isSignedIntegerOrEnumerationType() const; |
2295 | |
2296 | /// Determines whether this is an integer type that is unsigned or an |
2297 | /// enumeration types whose underlying type is a unsigned integer type. |
2298 | bool isUnsignedIntegerOrEnumerationType() const; |
2299 | |
2300 | /// Return true if this is a fixed point type according to |
2301 | /// ISO/IEC JTC1 SC22 WG14 N1169. |
2302 | bool isFixedPointType() const; |
2303 | |
2304 | /// Return true if this is a fixed point or integer type. |
2305 | bool isFixedPointOrIntegerType() const; |
2306 | |
2307 | /// Return true if this is a saturated fixed point type according to |
2308 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2309 | bool isSaturatedFixedPointType() const; |
2310 | |
2311 | /// Return true if this is a saturated fixed point type according to |
2312 | /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned. |
2313 | bool isUnsaturatedFixedPointType() const; |
2314 | |
2315 | /// Return true if this is a fixed point type that is signed according |
2316 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2317 | bool isSignedFixedPointType() const; |
2318 | |
2319 | /// Return true if this is a fixed point type that is unsigned according |
2320 | /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated. |
2321 | bool isUnsignedFixedPointType() const; |
2322 | |
2323 | /// Return true if this is not a variable sized type, |
2324 | /// according to the rules of C99 6.7.5p3. It is not legal to call this on |
2325 | /// incomplete types. |
2326 | bool isConstantSizeType() const; |
2327 | |
2328 | /// Returns true if this type can be represented by some |
2329 | /// set of type specifiers. |
2330 | bool isSpecifierType() const; |
2331 | |
2332 | /// Determine the linkage of this type. |
2333 | Linkage getLinkage() const; |
2334 | |
2335 | /// Determine the visibility of this type. |
2336 | Visibility getVisibility() const { |
2337 | return getLinkageAndVisibility().getVisibility(); |
2338 | } |
2339 | |
2340 | /// Return true if the visibility was explicitly set is the code. |
2341 | bool isVisibilityExplicit() const { |
2342 | return getLinkageAndVisibility().isVisibilityExplicit(); |
2343 | } |
2344 | |
2345 | /// Determine the linkage and visibility of this type. |
2346 | LinkageInfo getLinkageAndVisibility() const; |
2347 | |
2348 | /// True if the computed linkage is valid. Used for consistency |
2349 | /// checking. Should always return true. |
2350 | bool isLinkageValid() const; |
2351 | |
2352 | /// Determine the nullability of the given type. |
2353 | /// |
2354 | /// Note that nullability is only captured as sugar within the type |
2355 | /// system, not as part of the canonical type, so nullability will |
2356 | /// be lost by canonicalization and desugaring. |
2357 | Optional<NullabilityKind> getNullability(const ASTContext &context) const; |
2358 | |
2359 | /// Determine whether the given type can have a nullability |
2360 | /// specifier applied to it, i.e., if it is any kind of pointer type. |
2361 | /// |
2362 | /// \param ResultIfUnknown The value to return if we don't yet know whether |
2363 | /// this type can have nullability because it is dependent. |
2364 | bool canHaveNullability(bool ResultIfUnknown = true) const; |
2365 | |
2366 | /// Retrieve the set of substitutions required when accessing a member |
2367 | /// of the Objective-C receiver type that is declared in the given context. |
2368 | /// |
2369 | /// \c *this is the type of the object we're operating on, e.g., the |
2370 | /// receiver for a message send or the base of a property access, and is |
2371 | /// expected to be of some object or object pointer type. |
2372 | /// |
2373 | /// \param dc The declaration context for which we are building up a |
2374 | /// substitution mapping, which should be an Objective-C class, extension, |
2375 | /// category, or method within. |
2376 | /// |
2377 | /// \returns an array of type arguments that can be substituted for |
2378 | /// the type parameters of the given declaration context in any type described |
2379 | /// within that context, or an empty optional to indicate that no |
2380 | /// substitution is required. |
2381 | Optional<ArrayRef<QualType>> |
2382 | getObjCSubstitutions(const DeclContext *dc) const; |
2383 | |
2384 | /// Determines if this is an ObjC interface type that may accept type |
2385 | /// parameters. |
2386 | bool acceptsObjCTypeParams() const; |
2387 | |
2388 | const char *getTypeClassName() const; |
2389 | |
2390 | QualType getCanonicalTypeInternal() const { |
2391 | return CanonicalType; |
2392 | } |
2393 | |
2394 | CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h |
2395 | void dump() const; |
2396 | void dump(llvm::raw_ostream &OS) const; |
2397 | }; |
2398 | |
2399 | /// This will check for a TypedefType by removing any existing sugar |
2400 | /// until it reaches a TypedefType or a non-sugared type. |
2401 | template <> const TypedefType *Type::getAs() const; |
2402 | |
2403 | /// This will check for a TemplateSpecializationType by removing any |
2404 | /// existing sugar until it reaches a TemplateSpecializationType or a |
2405 | /// non-sugared type. |
2406 | template <> const TemplateSpecializationType *Type::getAs() const; |
2407 | |
2408 | /// This will check for an AttributedType by removing any existing sugar |
2409 | /// until it reaches an AttributedType or a non-sugared type. |
2410 | template <> const AttributedType *Type::getAs() const; |
2411 | |
2412 | // We can do canonical leaf types faster, because we don't have to |
2413 | // worry about preserving child type decoration. |
2414 | #define TYPE(Class, Base) |
2415 | #define LEAF_TYPE(Class) \ |
2416 | template <> inline const Class##Type *Type::getAs() const { \ |
2417 | return dyn_cast<Class##Type>(CanonicalType); \ |
2418 | } \ |
2419 | template <> inline const Class##Type *Type::castAs() const { \ |
2420 | return cast<Class##Type>(CanonicalType); \ |
2421 | } |
2422 | #include "clang/AST/TypeNodes.inc" |
2423 | |
2424 | /// This class is used for builtin types like 'int'. Builtin |
2425 | /// types are always canonical and have a literal name field. |
2426 | class BuiltinType : public Type { |
2427 | public: |
2428 | enum Kind { |
2429 | // OpenCL image types |
2430 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id, |
2431 | #include "clang/Basic/OpenCLImageTypes.def" |
2432 | // OpenCL extension types |
2433 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id, |
2434 | #include "clang/Basic/OpenCLExtensionTypes.def" |
2435 | // SVE Types |
2436 | #define SVE_TYPE(Name, Id, SingletonId) Id, |
2437 | #include "clang/Basic/AArch64SVEACLETypes.def" |
2438 | // All other builtin types |
2439 | #define BUILTIN_TYPE(Id, SingletonId) Id, |
2440 | #define LAST_BUILTIN_TYPE(Id) LastKind = Id |
2441 | #include "clang/AST/BuiltinTypes.def" |
2442 | }; |
2443 | |
2444 | private: |
2445 | friend class ASTContext; // ASTContext creates these. |
2446 | |
2447 | BuiltinType(Kind K) |
2448 | : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent), |
2449 | /*InstantiationDependent=*/(K == Dependent), |
2450 | /*VariablyModified=*/false, |
2451 | /*Unexpanded parameter pack=*/false) { |
2452 | BuiltinTypeBits.Kind = K; |
2453 | } |
2454 | |
2455 | public: |
2456 | Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); } |
2457 | StringRef getName(const PrintingPolicy &Policy) const; |
2458 | |
2459 | const char *getNameAsCString(const PrintingPolicy &Policy) const { |
2460 | // The StringRef is null-terminated. |
2461 | StringRef str = getName(Policy); |
2462 | assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast <void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 2462, __PRETTY_FUNCTION__)); |
2463 | return str.data(); |
2464 | } |
2465 | |
2466 | bool isSugared() const { return false; } |
2467 | QualType desugar() const { return QualType(this, 0); } |
2468 | |
2469 | bool isInteger() const { |
2470 | return getKind() >= Bool && getKind() <= Int128; |
2471 | } |
2472 | |
2473 | bool isSignedInteger() const { |
2474 | return getKind() >= Char_S && getKind() <= Int128; |
2475 | } |
2476 | |
2477 | bool isUnsignedInteger() const { |
2478 | return getKind() >= Bool && getKind() <= UInt128; |
2479 | } |
2480 | |
2481 | bool isFloatingPoint() const { |
2482 | return getKind() >= Half && getKind() <= Float128; |
2483 | } |
2484 | |
2485 | /// Determines whether the given kind corresponds to a placeholder type. |
2486 | static bool isPlaceholderTypeKind(Kind K) { |
2487 | return K >= Overload; |
2488 | } |
2489 | |
2490 | /// Determines whether this type is a placeholder type, i.e. a type |
2491 | /// which cannot appear in arbitrary positions in a fully-formed |
2492 | /// expression. |
2493 | bool isPlaceholderType() const { |
2494 | return isPlaceholderTypeKind(getKind()); |
2495 | } |
2496 | |
2497 | /// Determines whether this type is a placeholder type other than |
2498 | /// Overload. Most placeholder types require only syntactic |
2499 | /// information about their context in order to be resolved (e.g. |
2500 | /// whether it is a call expression), which means they can (and |
2501 | /// should) be resolved in an earlier "phase" of analysis. |
2502 | /// Overload expressions sometimes pick up further information |
2503 | /// from their context, like whether the context expects a |
2504 | /// specific function-pointer type, and so frequently need |
2505 | /// special treatment. |
2506 | bool isNonOverloadPlaceholderType() const { |
2507 | return getKind() > Overload; |
2508 | } |
2509 | |
2510 | static bool classof(const Type *T) { return T->getTypeClass() == Builtin; } |
2511 | }; |
2512 | |
2513 | /// Complex values, per C99 6.2.5p11. This supports the C99 complex |
2514 | /// types (_Complex float etc) as well as the GCC integer complex extensions. |
2515 | class ComplexType : public Type, public llvm::FoldingSetNode { |
2516 | friend class ASTContext; // ASTContext creates these. |
2517 | |
2518 | QualType ElementType; |
2519 | |
2520 | ComplexType(QualType Element, QualType CanonicalPtr) |
2521 | : Type(Complex, CanonicalPtr, Element->isDependentType(), |
2522 | Element->isInstantiationDependentType(), |
2523 | Element->isVariablyModifiedType(), |
2524 | Element->containsUnexpandedParameterPack()), |
2525 | ElementType(Element) {} |
2526 | |
2527 | public: |
2528 | QualType getElementType() const { return ElementType; } |
2529 | |
2530 | bool isSugared() const { return false; } |
2531 | QualType desugar() const { return QualType(this, 0); } |
2532 | |
2533 | void Profile(llvm::FoldingSetNodeID &ID) { |
2534 | Profile(ID, getElementType()); |
2535 | } |
2536 | |
2537 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) { |
2538 | ID.AddPointer(Element.getAsOpaquePtr()); |
2539 | } |
2540 | |
2541 | static bool classof(const Type *T) { return T->getTypeClass() == Complex; } |
2542 | }; |
2543 | |
2544 | /// Sugar for parentheses used when specifying types. |
2545 | class ParenType : public Type, public llvm::FoldingSetNode { |
2546 | friend class ASTContext; // ASTContext creates these. |
2547 | |
2548 | QualType Inner; |
2549 | |
2550 | ParenType(QualType InnerType, QualType CanonType) |
2551 | : Type(Paren, CanonType, InnerType->isDependentType(), |
2552 | InnerType->isInstantiationDependentType(), |
2553 | InnerType->isVariablyModifiedType(), |
2554 | InnerType->containsUnexpandedParameterPack()), |
2555 | Inner(InnerType) {} |
2556 | |
2557 | public: |
2558 | QualType getInnerType() const { return Inner; } |
2559 | |
2560 | bool isSugared() const { return true; } |
2561 | QualType desugar() const { return getInnerType(); } |
2562 | |
2563 | void Profile(llvm::FoldingSetNodeID &ID) { |
2564 | Profile(ID, getInnerType()); |
2565 | } |
2566 | |
2567 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) { |
2568 | Inner.Profile(ID); |
2569 | } |
2570 | |
2571 | static bool classof(const Type *T) { return T->getTypeClass() == Paren; } |
2572 | }; |
2573 | |
2574 | /// PointerType - C99 6.7.5.1 - Pointer Declarators. |
2575 | class PointerType : public Type, public llvm::FoldingSetNode { |
2576 | friend class ASTContext; // ASTContext creates these. |
2577 | |
2578 | QualType PointeeType; |
2579 | |
2580 | PointerType(QualType Pointee, QualType CanonicalPtr) |
2581 | : Type(Pointer, CanonicalPtr, Pointee->isDependentType(), |
2582 | Pointee->isInstantiationDependentType(), |
2583 | Pointee->isVariablyModifiedType(), |
2584 | Pointee->containsUnexpandedParameterPack()), |
2585 | PointeeType(Pointee) {} |
2586 | |
2587 | public: |
2588 | QualType getPointeeType() const { return PointeeType; } |
2589 | |
2590 | /// Returns true if address spaces of pointers overlap. |
2591 | /// OpenCL v2.0 defines conversion rules for pointers to different |
2592 | /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping |
2593 | /// address spaces. |
2594 | /// CL1.1 or CL1.2: |
2595 | /// address spaces overlap iff they are they same. |
2596 | /// CL2.0 adds: |
2597 | /// __generic overlaps with any address space except for __constant. |
2598 | bool isAddressSpaceOverlapping(const PointerType &other) const { |
2599 | Qualifiers thisQuals = PointeeType.getQualifiers(); |
2600 | Qualifiers otherQuals = other.getPointeeType().getQualifiers(); |
2601 | // Address spaces overlap if at least one of them is a superset of another |
2602 | return thisQuals.isAddressSpaceSupersetOf(otherQuals) || |
2603 | otherQuals.isAddressSpaceSupersetOf(thisQuals); |
2604 | } |
2605 | |
2606 | bool isSugared() const { return false; } |
2607 | QualType desugar() const { return QualType(this, 0); } |
2608 | |
2609 | void Profile(llvm::FoldingSetNodeID &ID) { |
2610 | Profile(ID, getPointeeType()); |
2611 | } |
2612 | |
2613 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2614 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2615 | } |
2616 | |
2617 | static bool classof(const Type *T) { return T->getTypeClass() == Pointer; } |
2618 | }; |
2619 | |
2620 | /// Represents a type which was implicitly adjusted by the semantic |
2621 | /// engine for arbitrary reasons. For example, array and function types can |
2622 | /// decay, and function types can have their calling conventions adjusted. |
2623 | class AdjustedType : public Type, public llvm::FoldingSetNode { |
2624 | QualType OriginalTy; |
2625 | QualType AdjustedTy; |
2626 | |
2627 | protected: |
2628 | friend class ASTContext; // ASTContext creates these. |
2629 | |
2630 | AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy, |
2631 | QualType CanonicalPtr) |
2632 | : Type(TC, CanonicalPtr, OriginalTy->isDependentType(), |
2633 | OriginalTy->isInstantiationDependentType(), |
2634 | OriginalTy->isVariablyModifiedType(), |
2635 | OriginalTy->containsUnexpandedParameterPack()), |
2636 | OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {} |
2637 | |
2638 | public: |
2639 | QualType getOriginalType() const { return OriginalTy; } |
2640 | QualType getAdjustedType() const { return AdjustedTy; } |
2641 | |
2642 | bool isSugared() const { return true; } |
2643 | QualType desugar() const { return AdjustedTy; } |
2644 | |
2645 | void Profile(llvm::FoldingSetNodeID &ID) { |
2646 | Profile(ID, OriginalTy, AdjustedTy); |
2647 | } |
2648 | |
2649 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) { |
2650 | ID.AddPointer(Orig.getAsOpaquePtr()); |
2651 | ID.AddPointer(New.getAsOpaquePtr()); |
2652 | } |
2653 | |
2654 | static bool classof(const Type *T) { |
2655 | return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed; |
2656 | } |
2657 | }; |
2658 | |
2659 | /// Represents a pointer type decayed from an array or function type. |
2660 | class DecayedType : public AdjustedType { |
2661 | friend class ASTContext; // ASTContext creates these. |
2662 | |
2663 | inline |
2664 | DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical); |
2665 | |
2666 | public: |
2667 | QualType getDecayedType() const { return getAdjustedType(); } |
2668 | |
2669 | inline QualType getPointeeType() const; |
2670 | |
2671 | static bool classof(const Type *T) { return T->getTypeClass() == Decayed; } |
2672 | }; |
2673 | |
2674 | /// Pointer to a block type. |
2675 | /// This type is to represent types syntactically represented as |
2676 | /// "void (^)(int)", etc. Pointee is required to always be a function type. |
2677 | class BlockPointerType : public Type, public llvm::FoldingSetNode { |
2678 | friend class ASTContext; // ASTContext creates these. |
2679 | |
2680 | // Block is some kind of pointer type |
2681 | QualType PointeeType; |
2682 | |
2683 | BlockPointerType(QualType Pointee, QualType CanonicalCls) |
2684 | : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(), |
2685 | Pointee->isInstantiationDependentType(), |
2686 | Pointee->isVariablyModifiedType(), |
2687 | Pointee->containsUnexpandedParameterPack()), |
2688 | PointeeType(Pointee) {} |
2689 | |
2690 | public: |
2691 | // Get the pointee type. Pointee is required to always be a function type. |
2692 | QualType getPointeeType() const { return PointeeType; } |
2693 | |
2694 | bool isSugared() const { return false; } |
2695 | QualType desugar() const { return QualType(this, 0); } |
2696 | |
2697 | void Profile(llvm::FoldingSetNodeID &ID) { |
2698 | Profile(ID, getPointeeType()); |
2699 | } |
2700 | |
2701 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) { |
2702 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2703 | } |
2704 | |
2705 | static bool classof(const Type *T) { |
2706 | return T->getTypeClass() == BlockPointer; |
2707 | } |
2708 | }; |
2709 | |
2710 | /// Base for LValueReferenceType and RValueReferenceType |
2711 | class ReferenceType : public Type, public llvm::FoldingSetNode { |
2712 | QualType PointeeType; |
2713 | |
2714 | protected: |
2715 | ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef, |
2716 | bool SpelledAsLValue) |
2717 | : Type(tc, CanonicalRef, Referencee->isDependentType(), |
2718 | Referencee->isInstantiationDependentType(), |
2719 | Referencee->isVariablyModifiedType(), |
2720 | Referencee->containsUnexpandedParameterPack()), |
2721 | PointeeType(Referencee) { |
2722 | ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue; |
2723 | ReferenceTypeBits.InnerRef = Referencee->isReferenceType(); |
2724 | } |
2725 | |
2726 | public: |
2727 | bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; } |
2728 | bool isInnerRef() const { return ReferenceTypeBits.InnerRef; } |
2729 | |
2730 | QualType getPointeeTypeAsWritten() const { return PointeeType; } |
2731 | |
2732 | QualType getPointeeType() const { |
2733 | // FIXME: this might strip inner qualifiers; okay? |
2734 | const ReferenceType *T = this; |
2735 | while (T->isInnerRef()) |
2736 | T = T->PointeeType->castAs<ReferenceType>(); |
2737 | return T->PointeeType; |
2738 | } |
2739 | |
2740 | void Profile(llvm::FoldingSetNodeID &ID) { |
2741 | Profile(ID, PointeeType, isSpelledAsLValue()); |
2742 | } |
2743 | |
2744 | static void Profile(llvm::FoldingSetNodeID &ID, |
2745 | QualType Referencee, |
2746 | bool SpelledAsLValue) { |
2747 | ID.AddPointer(Referencee.getAsOpaquePtr()); |
2748 | ID.AddBoolean(SpelledAsLValue); |
2749 | } |
2750 | |
2751 | static bool classof(const Type *T) { |
2752 | return T->getTypeClass() == LValueReference || |
2753 | T->getTypeClass() == RValueReference; |
2754 | } |
2755 | }; |
2756 | |
2757 | /// An lvalue reference type, per C++11 [dcl.ref]. |
2758 | class LValueReferenceType : public ReferenceType { |
2759 | friend class ASTContext; // ASTContext creates these |
2760 | |
2761 | LValueReferenceType(QualType Referencee, QualType CanonicalRef, |
2762 | bool SpelledAsLValue) |
2763 | : ReferenceType(LValueReference, Referencee, CanonicalRef, |
2764 | SpelledAsLValue) {} |
2765 | |
2766 | public: |
2767 | bool isSugared() const { return false; } |
2768 | QualType desugar() const { return QualType(this, 0); } |
2769 | |
2770 | static bool classof(const Type *T) { |
2771 | return T->getTypeClass() == LValueReference; |
2772 | } |
2773 | }; |
2774 | |
2775 | /// An rvalue reference type, per C++11 [dcl.ref]. |
2776 | class RValueReferenceType : public ReferenceType { |
2777 | friend class ASTContext; // ASTContext creates these |
2778 | |
2779 | RValueReferenceType(QualType Referencee, QualType CanonicalRef) |
2780 | : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {} |
2781 | |
2782 | public: |
2783 | bool isSugared() const { return false; } |
2784 | QualType desugar() const { return QualType(this, 0); } |
2785 | |
2786 | static bool classof(const Type *T) { |
2787 | return T->getTypeClass() == RValueReference; |
2788 | } |
2789 | }; |
2790 | |
2791 | /// A pointer to member type per C++ 8.3.3 - Pointers to members. |
2792 | /// |
2793 | /// This includes both pointers to data members and pointer to member functions. |
2794 | class MemberPointerType : public Type, public llvm::FoldingSetNode { |
2795 | friend class ASTContext; // ASTContext creates these. |
2796 | |
2797 | QualType PointeeType; |
2798 | |
2799 | /// The class of which the pointee is a member. Must ultimately be a |
2800 | /// RecordType, but could be a typedef or a template parameter too. |
2801 | const Type *Class; |
2802 | |
2803 | MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) |
2804 | : Type(MemberPointer, CanonicalPtr, |
2805 | Cls->isDependentType() || Pointee->isDependentType(), |
2806 | (Cls->isInstantiationDependentType() || |
2807 | Pointee->isInstantiationDependentType()), |
2808 | Pointee->isVariablyModifiedType(), |
2809 | (Cls->containsUnexpandedParameterPack() || |
2810 | Pointee->containsUnexpandedParameterPack())), |
2811 | PointeeType(Pointee), Class(Cls) {} |
2812 | |
2813 | public: |
2814 | QualType getPointeeType() const { return PointeeType; } |
2815 | |
2816 | /// Returns true if the member type (i.e. the pointee type) is a |
2817 | /// function type rather than a data-member type. |
2818 | bool isMemberFunctionPointer() const { |
2819 | return PointeeType->isFunctionProtoType(); |
2820 | } |
2821 | |
2822 | /// Returns true if the member type (i.e. the pointee type) is a |
2823 | /// data type rather than a function type. |
2824 | bool isMemberDataPointer() const { |
2825 | return !PointeeType->isFunctionProtoType(); |
2826 | } |
2827 | |
2828 | const Type *getClass() const { return Class; } |
2829 | CXXRecordDecl *getMostRecentCXXRecordDecl() const; |
2830 | |
2831 | bool isSugared() const { return false; } |
2832 | QualType desugar() const { return QualType(this, 0); } |
2833 | |
2834 | void Profile(llvm::FoldingSetNodeID &ID) { |
2835 | Profile(ID, getPointeeType(), getClass()); |
2836 | } |
2837 | |
2838 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee, |
2839 | const Type *Class) { |
2840 | ID.AddPointer(Pointee.getAsOpaquePtr()); |
2841 | ID.AddPointer(Class); |
2842 | } |
2843 | |
2844 | static bool classof(const Type *T) { |
2845 | return T->getTypeClass() == MemberPointer; |
2846 | } |
2847 | }; |
2848 | |
2849 | /// Represents an array type, per C99 6.7.5.2 - Array Declarators. |
2850 | class ArrayType : public Type, public llvm::FoldingSetNode { |
2851 | public: |
2852 | /// Capture whether this is a normal array (e.g. int X[4]) |
2853 | /// an array with a static size (e.g. int X[static 4]), or an array |
2854 | /// with a star size (e.g. int X[*]). |
2855 | /// 'static' is only allowed on function parameters. |
2856 | enum ArraySizeModifier { |
2857 | Normal, Static, Star |
2858 | }; |
2859 | |
2860 | private: |
2861 | /// The element type of the array. |
2862 | QualType ElementType; |
2863 | |
2864 | protected: |
2865 | friend class ASTContext; // ASTContext creates these. |
2866 | |
2867 | // C++ [temp.dep.type]p1: |
2868 | // A type is dependent if it is... |
2869 | // - an array type constructed from any dependent type or whose |
2870 | // size is specified by a constant expression that is |
2871 | // value-dependent, |
2872 | ArrayType(TypeClass tc, QualType et, QualType can, |
2873 | ArraySizeModifier sm, unsigned tq, |
2874 | bool ContainsUnexpandedParameterPack) |
2875 | : Type(tc, can, et->isDependentType() || tc == DependentSizedArray, |
2876 | et->isInstantiationDependentType() || tc == DependentSizedArray, |
2877 | (tc == VariableArray || et->isVariablyModifiedType()), |
2878 | ContainsUnexpandedParameterPack), |
2879 | ElementType(et) { |
2880 | ArrayTypeBits.IndexTypeQuals = tq; |
2881 | ArrayTypeBits.SizeModifier = sm; |
2882 | } |
2883 | |
2884 | public: |
2885 | QualType getElementType() const { return ElementType; } |
2886 | |
2887 | ArraySizeModifier getSizeModifier() const { |
2888 | return ArraySizeModifier(ArrayTypeBits.SizeModifier); |
2889 | } |
2890 | |
2891 | Qualifiers getIndexTypeQualifiers() const { |
2892 | return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers()); |
2893 | } |
2894 | |
2895 | unsigned getIndexTypeCVRQualifiers() const { |
2896 | return ArrayTypeBits.IndexTypeQuals; |
2897 | } |
2898 | |
2899 | static bool classof(const Type *T) { |
2900 | return T->getTypeClass() == ConstantArray || |
2901 | T->getTypeClass() == VariableArray || |
2902 | T->getTypeClass() == IncompleteArray || |
2903 | T->getTypeClass() == DependentSizedArray; |
2904 | } |
2905 | }; |
2906 | |
2907 | /// Represents the canonical version of C arrays with a specified constant size. |
2908 | /// For example, the canonical type for 'int A[4 + 4*100]' is a |
2909 | /// ConstantArrayType where the element type is 'int' and the size is 404. |
2910 | class ConstantArrayType : public ArrayType { |
2911 | llvm::APInt Size; // Allows us to unique the type. |
2912 | |
2913 | ConstantArrayType(QualType et, QualType can, const llvm::APInt &size, |
2914 | ArraySizeModifier sm, unsigned tq) |
2915 | : ArrayType(ConstantArray, et, can, sm, tq, |
2916 | et->containsUnexpandedParameterPack()), |
2917 | Size(size) {} |
2918 | |
2919 | protected: |
2920 | friend class ASTContext; // ASTContext creates these. |
2921 | |
2922 | ConstantArrayType(TypeClass tc, QualType et, QualType can, |
2923 | const llvm::APInt &size, ArraySizeModifier sm, unsigned tq) |
2924 | : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()), |
2925 | Size(size) {} |
2926 | |
2927 | public: |
2928 | const llvm::APInt &getSize() const { return Size; } |
2929 | bool isSugared() const { return false; } |
2930 | QualType desugar() const { return QualType(this, 0); } |
2931 | |
2932 | /// Determine the number of bits required to address a member of |
2933 | // an array with the given element type and number of elements. |
2934 | static unsigned getNumAddressingBits(const ASTContext &Context, |
2935 | QualType ElementType, |
2936 | const llvm::APInt &NumElements); |
2937 | |
2938 | /// Determine the maximum number of active bits that an array's size |
2939 | /// can require, which limits the maximum size of the array. |
2940 | static unsigned getMaxSizeBits(const ASTContext &Context); |
2941 | |
2942 | void Profile(llvm::FoldingSetNodeID &ID) { |
2943 | Profile(ID, getElementType(), getSize(), |
2944 | getSizeModifier(), getIndexTypeCVRQualifiers()); |
2945 | } |
2946 | |
2947 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2948 | const llvm::APInt &ArraySize, ArraySizeModifier SizeMod, |
2949 | unsigned TypeQuals) { |
2950 | ID.AddPointer(ET.getAsOpaquePtr()); |
2951 | ID.AddInteger(ArraySize.getZExtValue()); |
2952 | ID.AddInteger(SizeMod); |
2953 | ID.AddInteger(TypeQuals); |
2954 | } |
2955 | |
2956 | static bool classof(const Type *T) { |
2957 | return T->getTypeClass() == ConstantArray; |
2958 | } |
2959 | }; |
2960 | |
2961 | /// Represents a C array with an unspecified size. For example 'int A[]' has |
2962 | /// an IncompleteArrayType where the element type is 'int' and the size is |
2963 | /// unspecified. |
2964 | class IncompleteArrayType : public ArrayType { |
2965 | friend class ASTContext; // ASTContext creates these. |
2966 | |
2967 | IncompleteArrayType(QualType et, QualType can, |
2968 | ArraySizeModifier sm, unsigned tq) |
2969 | : ArrayType(IncompleteArray, et, can, sm, tq, |
2970 | et->containsUnexpandedParameterPack()) {} |
2971 | |
2972 | public: |
2973 | friend class StmtIteratorBase; |
2974 | |
2975 | bool isSugared() const { return false; } |
2976 | QualType desugar() const { return QualType(this, 0); } |
2977 | |
2978 | static bool classof(const Type *T) { |
2979 | return T->getTypeClass() == IncompleteArray; |
2980 | } |
2981 | |
2982 | void Profile(llvm::FoldingSetNodeID &ID) { |
2983 | Profile(ID, getElementType(), getSizeModifier(), |
2984 | getIndexTypeCVRQualifiers()); |
2985 | } |
2986 | |
2987 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ET, |
2988 | ArraySizeModifier SizeMod, unsigned TypeQuals) { |
2989 | ID.AddPointer(ET.getAsOpaquePtr()); |
2990 | ID.AddInteger(SizeMod); |
2991 | ID.AddInteger(TypeQuals); |
2992 | } |
2993 | }; |
2994 | |
2995 | /// Represents a C array with a specified size that is not an |
2996 | /// integer-constant-expression. For example, 'int s[x+foo()]'. |
2997 | /// Since the size expression is an arbitrary expression, we store it as such. |
2998 | /// |
2999 | /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and |
3000 | /// should not be: two lexically equivalent variable array types could mean |
3001 | /// different things, for example, these variables do not have the same type |
3002 | /// dynamically: |
3003 | /// |
3004 | /// void foo(int x) { |
3005 | /// int Y[x]; |
3006 | /// ++x; |
3007 | /// int Z[x]; |
3008 | /// } |
3009 | class VariableArrayType : public ArrayType { |
3010 | friend class ASTContext; // ASTContext creates these. |
3011 | |
3012 | /// An assignment-expression. VLA's are only permitted within |
3013 | /// a function block. |
3014 | Stmt *SizeExpr; |
3015 | |
3016 | /// The range spanned by the left and right array brackets. |
3017 | SourceRange Brackets; |
3018 | |
3019 | VariableArrayType(QualType et, QualType can, Expr *e, |
3020 | ArraySizeModifier sm, unsigned tq, |
3021 | SourceRange brackets) |
3022 | : ArrayType(VariableArray, et, can, sm, tq, |
3023 | et->containsUnexpandedParameterPack()), |
3024 | SizeExpr((Stmt*) e), Brackets(brackets) {} |
3025 | |
3026 | public: |
3027 | friend class StmtIteratorBase; |
3028 | |
3029 | Expr *getSizeExpr() const { |
3030 | // We use C-style casts instead of cast<> here because we do not wish |
3031 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3032 | return (Expr*) SizeExpr; |
3033 | } |
3034 | |
3035 | SourceRange getBracketsRange() const { return Brackets; } |
3036 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3037 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3038 | |
3039 | bool isSugared() const { return false; } |
3040 | QualType desugar() const { return QualType(this, 0); } |
3041 | |
3042 | static bool classof(const Type *T) { |
3043 | return T->getTypeClass() == VariableArray; |
3044 | } |
3045 | |
3046 | void Profile(llvm::FoldingSetNodeID &ID) { |
3047 | llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes." , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3047); |
3048 | } |
3049 | }; |
3050 | |
3051 | /// Represents an array type in C++ whose size is a value-dependent expression. |
3052 | /// |
3053 | /// For example: |
3054 | /// \code |
3055 | /// template<typename T, int Size> |
3056 | /// class array { |
3057 | /// T data[Size]; |
3058 | /// }; |
3059 | /// \endcode |
3060 | /// |
3061 | /// For these types, we won't actually know what the array bound is |
3062 | /// until template instantiation occurs, at which point this will |
3063 | /// become either a ConstantArrayType or a VariableArrayType. |
3064 | class DependentSizedArrayType : public ArrayType { |
3065 | friend class ASTContext; // ASTContext creates these. |
3066 | |
3067 | const ASTContext &Context; |
3068 | |
3069 | /// An assignment expression that will instantiate to the |
3070 | /// size of the array. |
3071 | /// |
3072 | /// The expression itself might be null, in which case the array |
3073 | /// type will have its size deduced from an initializer. |
3074 | Stmt *SizeExpr; |
3075 | |
3076 | /// The range spanned by the left and right array brackets. |
3077 | SourceRange Brackets; |
3078 | |
3079 | DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can, |
3080 | Expr *e, ArraySizeModifier sm, unsigned tq, |
3081 | SourceRange brackets); |
3082 | |
3083 | public: |
3084 | friend class StmtIteratorBase; |
3085 | |
3086 | Expr *getSizeExpr() const { |
3087 | // We use C-style casts instead of cast<> here because we do not wish |
3088 | // to have a dependency of Type.h on Stmt.h/Expr.h. |
3089 | return (Expr*) SizeExpr; |
3090 | } |
3091 | |
3092 | SourceRange getBracketsRange() const { return Brackets; } |
3093 | SourceLocation getLBracketLoc() const { return Brackets.getBegin(); } |
3094 | SourceLocation getRBracketLoc() const { return Brackets.getEnd(); } |
3095 | |
3096 | bool isSugared() const { return false; } |
3097 | QualType desugar() const { return QualType(this, 0); } |
3098 | |
3099 | static bool classof(const Type *T) { |
3100 | return T->getTypeClass() == DependentSizedArray; |
3101 | } |
3102 | |
3103 | void Profile(llvm::FoldingSetNodeID &ID) { |
3104 | Profile(ID, Context, getElementType(), |
3105 | getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr()); |
3106 | } |
3107 | |
3108 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3109 | QualType ET, ArraySizeModifier SizeMod, |
3110 | unsigned TypeQuals, Expr *E); |
3111 | }; |
3112 | |
3113 | /// Represents an extended address space qualifier where the input address space |
3114 | /// value is dependent. Non-dependent address spaces are not represented with a |
3115 | /// special Type subclass; they are stored on an ExtQuals node as part of a QualType. |
3116 | /// |
3117 | /// For example: |
3118 | /// \code |
3119 | /// template<typename T, int AddrSpace> |
3120 | /// class AddressSpace { |
3121 | /// typedef T __attribute__((address_space(AddrSpace))) type; |
3122 | /// } |
3123 | /// \endcode |
3124 | class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode { |
3125 | friend class ASTContext; |
3126 | |
3127 | const ASTContext &Context; |
3128 | Expr *AddrSpaceExpr; |
3129 | QualType PointeeType; |
3130 | SourceLocation loc; |
3131 | |
3132 | DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType, |
3133 | QualType can, Expr *AddrSpaceExpr, |
3134 | SourceLocation loc); |
3135 | |
3136 | public: |
3137 | Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; } |
3138 | QualType getPointeeType() const { return PointeeType; } |
3139 | SourceLocation getAttributeLoc() const { return loc; } |
3140 | |
3141 | bool isSugared() const { return false; } |
3142 | QualType desugar() const { return QualType(this, 0); } |
3143 | |
3144 | static bool classof(const Type *T) { |
3145 | return T->getTypeClass() == DependentAddressSpace; |
3146 | } |
3147 | |
3148 | void Profile(llvm::FoldingSetNodeID &ID) { |
3149 | Profile(ID, Context, getPointeeType(), getAddrSpaceExpr()); |
3150 | } |
3151 | |
3152 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3153 | QualType PointeeType, Expr *AddrSpaceExpr); |
3154 | }; |
3155 | |
3156 | /// Represents an extended vector type where either the type or size is |
3157 | /// dependent. |
3158 | /// |
3159 | /// For example: |
3160 | /// \code |
3161 | /// template<typename T, int Size> |
3162 | /// class vector { |
3163 | /// typedef T __attribute__((ext_vector_type(Size))) type; |
3164 | /// } |
3165 | /// \endcode |
3166 | class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode { |
3167 | friend class ASTContext; |
3168 | |
3169 | const ASTContext &Context; |
3170 | Expr *SizeExpr; |
3171 | |
3172 | /// The element type of the array. |
3173 | QualType ElementType; |
3174 | |
3175 | SourceLocation loc; |
3176 | |
3177 | DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType, |
3178 | QualType can, Expr *SizeExpr, SourceLocation loc); |
3179 | |
3180 | public: |
3181 | Expr *getSizeExpr() const { return SizeExpr; } |
3182 | QualType getElementType() const { return ElementType; } |
3183 | SourceLocation getAttributeLoc() const { return loc; } |
3184 | |
3185 | bool isSugared() const { return false; } |
3186 | QualType desugar() const { return QualType(this, 0); } |
3187 | |
3188 | static bool classof(const Type *T) { |
3189 | return T->getTypeClass() == DependentSizedExtVector; |
3190 | } |
3191 | |
3192 | void Profile(llvm::FoldingSetNodeID &ID) { |
3193 | Profile(ID, Context, getElementType(), getSizeExpr()); |
3194 | } |
3195 | |
3196 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3197 | QualType ElementType, Expr *SizeExpr); |
3198 | }; |
3199 | |
3200 | |
3201 | /// Represents a GCC generic vector type. This type is created using |
3202 | /// __attribute__((vector_size(n)), where "n" specifies the vector size in |
3203 | /// bytes; or from an Altivec __vector or vector declaration. |
3204 | /// Since the constructor takes the number of vector elements, the |
3205 | /// client is responsible for converting the size into the number of elements. |
3206 | class VectorType : public Type, public llvm::FoldingSetNode { |
3207 | public: |
3208 | enum VectorKind { |
3209 | /// not a target-specific vector type |
3210 | GenericVector, |
3211 | |
3212 | /// is AltiVec vector |
3213 | AltiVecVector, |
3214 | |
3215 | /// is AltiVec 'vector Pixel' |
3216 | AltiVecPixel, |
3217 | |
3218 | /// is AltiVec 'vector bool ...' |
3219 | AltiVecBool, |
3220 | |
3221 | /// is ARM Neon vector |
3222 | NeonVector, |
3223 | |
3224 | /// is ARM Neon polynomial vector |
3225 | NeonPolyVector |
3226 | }; |
3227 | |
3228 | protected: |
3229 | friend class ASTContext; // ASTContext creates these. |
3230 | |
3231 | /// The element type of the vector. |
3232 | QualType ElementType; |
3233 | |
3234 | VectorType(QualType vecType, unsigned nElements, QualType canonType, |
3235 | VectorKind vecKind); |
3236 | |
3237 | VectorType(TypeClass tc, QualType vecType, unsigned nElements, |
3238 | QualType canonType, VectorKind vecKind); |
3239 | |
3240 | public: |
3241 | QualType getElementType() const { return ElementType; } |
3242 | unsigned getNumElements() const { return VectorTypeBits.NumElements; } |
3243 | |
3244 | static bool isVectorSizeTooLarge(unsigned NumElements) { |
3245 | return NumElements > VectorTypeBitfields::MaxNumElements; |
3246 | } |
3247 | |
3248 | bool isSugared() const { return false; } |
3249 | QualType desugar() const { return QualType(this, 0); } |
3250 | |
3251 | VectorKind getVectorKind() const { |
3252 | return VectorKind(VectorTypeBits.VecKind); |
3253 | } |
3254 | |
3255 | void Profile(llvm::FoldingSetNodeID &ID) { |
3256 | Profile(ID, getElementType(), getNumElements(), |
3257 | getTypeClass(), getVectorKind()); |
3258 | } |
3259 | |
3260 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType, |
3261 | unsigned NumElements, TypeClass TypeClass, |
3262 | VectorKind VecKind) { |
3263 | ID.AddPointer(ElementType.getAsOpaquePtr()); |
3264 | ID.AddInteger(NumElements); |
3265 | ID.AddInteger(TypeClass); |
3266 | ID.AddInteger(VecKind); |
3267 | } |
3268 | |
3269 | static bool classof(const Type *T) { |
3270 | return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector; |
3271 | } |
3272 | }; |
3273 | |
3274 | /// Represents a vector type where either the type or size is dependent. |
3275 | //// |
3276 | /// For example: |
3277 | /// \code |
3278 | /// template<typename T, int Size> |
3279 | /// class vector { |
3280 | /// typedef T __attribute__((vector_size(Size))) type; |
3281 | /// } |
3282 | /// \endcode |
3283 | class DependentVectorType : public Type, public llvm::FoldingSetNode { |
3284 | friend class ASTContext; |
3285 | |
3286 | const ASTContext &Context; |
3287 | QualType ElementType; |
3288 | Expr *SizeExpr; |
3289 | SourceLocation Loc; |
3290 | |
3291 | DependentVectorType(const ASTContext &Context, QualType ElementType, |
3292 | QualType CanonType, Expr *SizeExpr, |
3293 | SourceLocation Loc, VectorType::VectorKind vecKind); |
3294 | |
3295 | public: |
3296 | Expr *getSizeExpr() const { return SizeExpr; } |
3297 | QualType getElementType() const { return ElementType; } |
3298 | SourceLocation getAttributeLoc() const { return Loc; } |
3299 | VectorType::VectorKind getVectorKind() const { |
3300 | return VectorType::VectorKind(VectorTypeBits.VecKind); |
3301 | } |
3302 | |
3303 | bool isSugared() const { return false; } |
3304 | QualType desugar() const { return QualType(this, 0); } |
3305 | |
3306 | static bool classof(const Type *T) { |
3307 | return T->getTypeClass() == DependentVector; |
3308 | } |
3309 | |
3310 | void Profile(llvm::FoldingSetNodeID &ID) { |
3311 | Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind()); |
3312 | } |
3313 | |
3314 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
3315 | QualType ElementType, const Expr *SizeExpr, |
3316 | VectorType::VectorKind VecKind); |
3317 | }; |
3318 | |
3319 | /// ExtVectorType - Extended vector type. This type is created using |
3320 | /// __attribute__((ext_vector_type(n)), where "n" is the number of elements. |
3321 | /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This |
3322 | /// class enables syntactic extensions, like Vector Components for accessing |
3323 | /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL |
3324 | /// Shading Language). |
3325 | class ExtVectorType : public VectorType { |
3326 | friend class ASTContext; // ASTContext creates these. |
3327 | |
3328 | ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) |
3329 | : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {} |
3330 | |
3331 | public: |
3332 | static int getPointAccessorIdx(char c) { |
3333 | switch (c) { |
3334 | default: return -1; |
3335 | case 'x': case 'r': return 0; |
3336 | case 'y': case 'g': return 1; |
3337 | case 'z': case 'b': return 2; |
3338 | case 'w': case 'a': return 3; |
3339 | } |
3340 | } |
3341 | |
3342 | static int getNumericAccessorIdx(char c) { |
3343 | switch (c) { |
3344 | default: return -1; |
3345 | case '0': return 0; |
3346 | case '1': return 1; |
3347 | case '2': return 2; |
3348 | case '3': return 3; |
3349 | case '4': return 4; |
3350 | case '5': return 5; |
3351 | case '6': return 6; |
3352 | case '7': return 7; |
3353 | case '8': return 8; |
3354 | case '9': return 9; |
3355 | case 'A': |
3356 | case 'a': return 10; |
3357 | case 'B': |
3358 | case 'b': return 11; |
3359 | case 'C': |
3360 | case 'c': return 12; |
3361 | case 'D': |
3362 | case 'd': return 13; |
3363 | case 'E': |
3364 | case 'e': return 14; |
3365 | case 'F': |
3366 | case 'f': return 15; |
3367 | } |
3368 | } |
3369 | |
3370 | static int getAccessorIdx(char c, bool isNumericAccessor) { |
3371 | if (isNumericAccessor) |
3372 | return getNumericAccessorIdx(c); |
3373 | else |
3374 | return getPointAccessorIdx(c); |
3375 | } |
3376 | |
3377 | bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const { |
3378 | if (int idx = getAccessorIdx(c, isNumericAccessor)+1) |
3379 | return unsigned(idx-1) < getNumElements(); |
3380 | return false; |
3381 | } |
3382 | |
3383 | bool isSugared() const { return false; } |
3384 | QualType desugar() const { return QualType(this, 0); } |
3385 | |
3386 | static bool classof(const Type *T) { |
3387 | return T->getTypeClass() == ExtVector; |
3388 | } |
3389 | }; |
3390 | |
3391 | /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base |
3392 | /// class of FunctionNoProtoType and FunctionProtoType. |
3393 | class FunctionType : public Type { |
3394 | // The type returned by the function. |
3395 | QualType ResultType; |
3396 | |
3397 | public: |
3398 | /// Interesting information about a specific parameter that can't simply |
3399 | /// be reflected in parameter's type. This is only used by FunctionProtoType |
3400 | /// but is in FunctionType to make this class available during the |
3401 | /// specification of the bases of FunctionProtoType. |
3402 | /// |
3403 | /// It makes sense to model language features this way when there's some |
3404 | /// sort of parameter-specific override (such as an attribute) that |
3405 | /// affects how the function is called. For example, the ARC ns_consumed |
3406 | /// attribute changes whether a parameter is passed at +0 (the default) |
3407 | /// or +1 (ns_consumed). This must be reflected in the function type, |
3408 | /// but isn't really a change to the parameter type. |
3409 | /// |
3410 | /// One serious disadvantage of modelling language features this way is |
3411 | /// that they generally do not work with language features that attempt |
3412 | /// to destructure types. For example, template argument deduction will |
3413 | /// not be able to match a parameter declared as |
3414 | /// T (*)(U) |
3415 | /// against an argument of type |
3416 | /// void (*)(__attribute__((ns_consumed)) id) |
3417 | /// because the substitution of T=void, U=id into the former will |
3418 | /// not produce the latter. |
3419 | class ExtParameterInfo { |
3420 | enum { |
3421 | ABIMask = 0x0F, |
3422 | IsConsumed = 0x10, |
3423 | HasPassObjSize = 0x20, |
3424 | IsNoEscape = 0x40, |
3425 | }; |
3426 | unsigned char Data = 0; |
3427 | |
3428 | public: |
3429 | ExtParameterInfo() = default; |
3430 | |
3431 | /// Return the ABI treatment of this parameter. |
3432 | ParameterABI getABI() const { return ParameterABI(Data & ABIMask); } |
3433 | ExtParameterInfo withABI(ParameterABI kind) const { |
3434 | ExtParameterInfo copy = *this; |
3435 | copy.Data = (copy.Data & ~ABIMask) | unsigned(kind); |
3436 | return copy; |
3437 | } |
3438 | |
3439 | /// Is this parameter considered "consumed" by Objective-C ARC? |
3440 | /// Consumed parameters must have retainable object type. |
3441 | bool isConsumed() const { return (Data & IsConsumed); } |
3442 | ExtParameterInfo withIsConsumed(bool consumed) const { |
3443 | ExtParameterInfo copy = *this; |
3444 | if (consumed) |
3445 | copy.Data |= IsConsumed; |
3446 | else |
3447 | copy.Data &= ~IsConsumed; |
3448 | return copy; |
3449 | } |
3450 | |
3451 | bool hasPassObjectSize() const { return Data & HasPassObjSize; } |
3452 | ExtParameterInfo withHasPassObjectSize() const { |
3453 | ExtParameterInfo Copy = *this; |
3454 | Copy.Data |= HasPassObjSize; |
3455 | return Copy; |
3456 | } |
3457 | |
3458 | bool isNoEscape() const { return Data & IsNoEscape; } |
3459 | ExtParameterInfo withIsNoEscape(bool NoEscape) const { |
3460 | ExtParameterInfo Copy = *this; |
3461 | if (NoEscape) |
3462 | Copy.Data |= IsNoEscape; |
3463 | else |
3464 | Copy.Data &= ~IsNoEscape; |
3465 | return Copy; |
3466 | } |
3467 | |
3468 | unsigned char getOpaqueValue() const { return Data; } |
3469 | static ExtParameterInfo getFromOpaqueValue(unsigned char data) { |
3470 | ExtParameterInfo result; |
3471 | result.Data = data; |
3472 | return result; |
3473 | } |
3474 | |
3475 | friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3476 | return lhs.Data == rhs.Data; |
3477 | } |
3478 | |
3479 | friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) { |
3480 | return lhs.Data != rhs.Data; |
3481 | } |
3482 | }; |
3483 | |
3484 | /// A class which abstracts out some details necessary for |
3485 | /// making a call. |
3486 | /// |
3487 | /// It is not actually used directly for storing this information in |
3488 | /// a FunctionType, although FunctionType does currently use the |
3489 | /// same bit-pattern. |
3490 | /// |
3491 | // If you add a field (say Foo), other than the obvious places (both, |
3492 | // constructors, compile failures), what you need to update is |
3493 | // * Operator== |
3494 | // * getFoo |
3495 | // * withFoo |
3496 | // * functionType. Add Foo, getFoo. |
3497 | // * ASTContext::getFooType |
3498 | // * ASTContext::mergeFunctionTypes |
3499 | // * FunctionNoProtoType::Profile |
3500 | // * FunctionProtoType::Profile |
3501 | // * TypePrinter::PrintFunctionProto |
3502 | // * AST read and write |
3503 | // * Codegen |
3504 | class ExtInfo { |
3505 | friend class FunctionType; |
3506 | |
3507 | // Feel free to rearrange or add bits, but if you go over 12, |
3508 | // you'll need to adjust both the Bits field below and |
3509 | // Type::FunctionTypeBitfields. |
3510 | |
3511 | // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck| |
3512 | // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | |
3513 | // |
3514 | // regparm is either 0 (no regparm attribute) or the regparm value+1. |
3515 | enum { CallConvMask = 0x1F }; |
3516 | enum { NoReturnMask = 0x20 }; |
3517 | enum { ProducesResultMask = 0x40 }; |
3518 | enum { NoCallerSavedRegsMask = 0x80 }; |
3519 | enum { NoCfCheckMask = 0x800 }; |
3520 | enum { |
3521 | RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask | |
3522 | NoCallerSavedRegsMask | NoCfCheckMask), |
3523 | RegParmOffset = 8 |
3524 | }; // Assumed to be the last field |
3525 | uint16_t Bits = CC_C; |
3526 | |
3527 | ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {} |
3528 | |
3529 | public: |
3530 | // Constructor with no defaults. Use this when you know that you |
3531 | // have all the elements (when reading an AST file for example). |
3532 | ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc, |
3533 | bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) { |
3534 | assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value" ) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3534, __PRETTY_FUNCTION__)); |
3535 | Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) | |
3536 | (producesResult ? ProducesResultMask : 0) | |
3537 | (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) | |
3538 | (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) | |
3539 | (NoCfCheck ? NoCfCheckMask : 0); |
3540 | } |
3541 | |
3542 | // Constructor with all defaults. Use when for example creating a |
3543 | // function known to use defaults. |
3544 | ExtInfo() = default; |
3545 | |
3546 | // Constructor with just the calling convention, which is an important part |
3547 | // of the canonical type. |
3548 | ExtInfo(CallingConv CC) : Bits(CC) {} |
3549 | |
3550 | bool getNoReturn() const { return Bits & NoReturnMask; } |
3551 | bool getProducesResult() const { return Bits & ProducesResultMask; } |
3552 | bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; } |
3553 | bool getNoCfCheck() const { return Bits & NoCfCheckMask; } |
3554 | bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; } |
3555 | |
3556 | unsigned getRegParm() const { |
3557 | unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset; |
3558 | if (RegParm > 0) |
3559 | --RegParm; |
3560 | return RegParm; |
3561 | } |
3562 | |
3563 | CallingConv getCC() const { return CallingConv(Bits & CallConvMask); } |
3564 | |
3565 | bool operator==(ExtInfo Other) const { |
3566 | return Bits == Other.Bits; |
3567 | } |
3568 | bool operator!=(ExtInfo Other) const { |
3569 | return Bits != Other.Bits; |
3570 | } |
3571 | |
3572 | // Note that we don't have setters. That is by design, use |
3573 | // the following with methods instead of mutating these objects. |
3574 | |
3575 | ExtInfo withNoReturn(bool noReturn) const { |
3576 | if (noReturn) |
3577 | return ExtInfo(Bits | NoReturnMask); |
3578 | else |
3579 | return ExtInfo(Bits & ~NoReturnMask); |
3580 | } |
3581 | |
3582 | ExtInfo withProducesResult(bool producesResult) const { |
3583 | if (producesResult) |
3584 | return ExtInfo(Bits | ProducesResultMask); |
3585 | else |
3586 | return ExtInfo(Bits & ~ProducesResultMask); |
3587 | } |
3588 | |
3589 | ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const { |
3590 | if (noCallerSavedRegs) |
3591 | return ExtInfo(Bits | NoCallerSavedRegsMask); |
3592 | else |
3593 | return ExtInfo(Bits & ~NoCallerSavedRegsMask); |
3594 | } |
3595 | |
3596 | ExtInfo withNoCfCheck(bool noCfCheck) const { |
3597 | if (noCfCheck) |
3598 | return ExtInfo(Bits | NoCfCheckMask); |
3599 | else |
3600 | return ExtInfo(Bits & ~NoCfCheckMask); |
3601 | } |
3602 | |
3603 | ExtInfo withRegParm(unsigned RegParm) const { |
3604 | assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast <void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3604, __PRETTY_FUNCTION__)); |
3605 | return ExtInfo((Bits & ~RegParmMask) | |
3606 | ((RegParm + 1) << RegParmOffset)); |
3607 | } |
3608 | |
3609 | ExtInfo withCallingConv(CallingConv cc) const { |
3610 | return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc); |
3611 | } |
3612 | |
3613 | void Profile(llvm::FoldingSetNodeID &ID) const { |
3614 | ID.AddInteger(Bits); |
3615 | } |
3616 | }; |
3617 | |
3618 | /// A simple holder for a QualType representing a type in an |
3619 | /// exception specification. Unfortunately needed by FunctionProtoType |
3620 | /// because TrailingObjects cannot handle repeated types. |
3621 | struct ExceptionType { QualType Type; }; |
3622 | |
3623 | /// A simple holder for various uncommon bits which do not fit in |
3624 | /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the |
3625 | /// alignment of subsequent objects in TrailingObjects. You must update |
3626 | /// hasExtraBitfields in FunctionProtoType after adding extra data here. |
3627 | struct alignas(void *) FunctionTypeExtraBitfields { |
3628 | /// The number of types in the exception specification. |
3629 | /// A whole unsigned is not needed here and according to |
3630 | /// [implimits] 8 bits would be enough here. |
3631 | unsigned NumExceptionType; |
3632 | }; |
3633 | |
3634 | protected: |
3635 | FunctionType(TypeClass tc, QualType res, |
3636 | QualType Canonical, bool Dependent, |
3637 | bool InstantiationDependent, |
3638 | bool VariablyModified, bool ContainsUnexpandedParameterPack, |
3639 | ExtInfo Info) |
3640 | : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified, |
3641 | ContainsUnexpandedParameterPack), |
3642 | ResultType(res) { |
3643 | FunctionTypeBits.ExtInfo = Info.Bits; |
3644 | } |
3645 | |
3646 | Qualifiers getFastTypeQuals() const { |
3647 | return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals); |
3648 | } |
3649 | |
3650 | public: |
3651 | QualType getReturnType() const { return ResultType; } |
3652 | |
3653 | bool getHasRegParm() const { return getExtInfo().getHasRegParm(); } |
3654 | unsigned getRegParmType() const { return getExtInfo().getRegParm(); } |
3655 | |
3656 | /// Determine whether this function type includes the GNU noreturn |
3657 | /// attribute. The C++11 [[noreturn]] attribute does not affect the function |
3658 | /// type. |
3659 | bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); } |
3660 | |
3661 | CallingConv getCallConv() const { return getExtInfo().getCC(); } |
3662 | ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); } |
3663 | |
3664 | static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0, |
3665 | "Const, volatile and restrict are assumed to be a subset of " |
3666 | "the fast qualifiers."); |
3667 | |
3668 | bool isConst() const { return getFastTypeQuals().hasConst(); } |
3669 | bool isVolatile() const { return getFastTypeQuals().hasVolatile(); } |
3670 | bool isRestrict() const { return getFastTypeQuals().hasRestrict(); } |
3671 | |
3672 | /// Determine the type of an expression that calls a function of |
3673 | /// this type. |
3674 | QualType getCallResultType(const ASTContext &Context) const { |
3675 | return getReturnType().getNonLValueExprType(Context); |
3676 | } |
3677 | |
3678 | static StringRef getNameForCallConv(CallingConv CC); |
3679 | |
3680 | static bool classof(const Type *T) { |
3681 | return T->getTypeClass() == FunctionNoProto || |
3682 | T->getTypeClass() == FunctionProto; |
3683 | } |
3684 | }; |
3685 | |
3686 | /// Represents a K&R-style 'int foo()' function, which has |
3687 | /// no information available about its arguments. |
3688 | class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode { |
3689 | friend class ASTContext; // ASTContext creates these. |
3690 | |
3691 | FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info) |
3692 | : FunctionType(FunctionNoProto, Result, Canonical, |
3693 | /*Dependent=*/false, /*InstantiationDependent=*/false, |
3694 | Result->isVariablyModifiedType(), |
3695 | /*ContainsUnexpandedParameterPack=*/false, Info) {} |
3696 | |
3697 | public: |
3698 | // No additional state past what FunctionType provides. |
3699 | |
3700 | bool isSugared() const { return false; } |
3701 | QualType desugar() const { return QualType(this, 0); } |
3702 | |
3703 | void Profile(llvm::FoldingSetNodeID &ID) { |
3704 | Profile(ID, getReturnType(), getExtInfo()); |
3705 | } |
3706 | |
3707 | static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType, |
3708 | ExtInfo Info) { |
3709 | Info.Profile(ID); |
3710 | ID.AddPointer(ResultType.getAsOpaquePtr()); |
3711 | } |
3712 | |
3713 | static bool classof(const Type *T) { |
3714 | return T->getTypeClass() == FunctionNoProto; |
3715 | } |
3716 | }; |
3717 | |
3718 | /// Represents a prototype with parameter type info, e.g. |
3719 | /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no |
3720 | /// parameters, not as having a single void parameter. Such a type can have |
3721 | /// an exception specification, but this specification is not part of the |
3722 | /// canonical type. FunctionProtoType has several trailing objects, some of |
3723 | /// which optional. For more information about the trailing objects see |
3724 | /// the first comment inside FunctionProtoType. |
3725 | class FunctionProtoType final |
3726 | : public FunctionType, |
3727 | public llvm::FoldingSetNode, |
3728 | private llvm::TrailingObjects< |
3729 | FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields, |
3730 | FunctionType::ExceptionType, Expr *, FunctionDecl *, |
3731 | FunctionType::ExtParameterInfo, Qualifiers> { |
3732 | friend class ASTContext; // ASTContext creates these. |
3733 | friend TrailingObjects; |
3734 | |
3735 | // FunctionProtoType is followed by several trailing objects, some of |
3736 | // which optional. They are in order: |
3737 | // |
3738 | // * An array of getNumParams() QualType holding the parameter types. |
3739 | // Always present. Note that for the vast majority of FunctionProtoType, |
3740 | // these will be the only trailing objects. |
3741 | // |
3742 | // * Optionally if some extra data is stored in FunctionTypeExtraBitfields |
3743 | // (see FunctionTypeExtraBitfields and FunctionTypeBitfields): |
3744 | // a single FunctionTypeExtraBitfields. Present if and only if |
3745 | // hasExtraBitfields() is true. |
3746 | // |
3747 | // * Optionally exactly one of: |
3748 | // * an array of getNumExceptions() ExceptionType, |
3749 | // * a single Expr *, |
3750 | // * a pair of FunctionDecl *, |
3751 | // * a single FunctionDecl * |
3752 | // used to store information about the various types of exception |
3753 | // specification. See getExceptionSpecSize for the details. |
3754 | // |
3755 | // * Optionally an array of getNumParams() ExtParameterInfo holding |
3756 | // an ExtParameterInfo for each of the parameters. Present if and |
3757 | // only if hasExtParameterInfos() is true. |
3758 | // |
3759 | // * Optionally a Qualifiers object to represent extra qualifiers that can't |
3760 | // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only |
3761 | // if hasExtQualifiers() is true. |
3762 | // |
3763 | // The optional FunctionTypeExtraBitfields has to be before the data |
3764 | // related to the exception specification since it contains the number |
3765 | // of exception types. |
3766 | // |
3767 | // We put the ExtParameterInfos last. If all were equal, it would make |
3768 | // more sense to put these before the exception specification, because |
3769 | // it's much easier to skip past them compared to the elaborate switch |
3770 | // required to skip the exception specification. However, all is not |
3771 | // equal; ExtParameterInfos are used to model very uncommon features, |
3772 | // and it's better not to burden the more common paths. |
3773 | |
3774 | public: |
3775 | /// Holds information about the various types of exception specification. |
3776 | /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is |
3777 | /// used to group together the various bits of information about the |
3778 | /// exception specification. |
3779 | struct ExceptionSpecInfo { |
3780 | /// The kind of exception specification this is. |
3781 | ExceptionSpecificationType Type = EST_None; |
3782 | |
3783 | /// Explicitly-specified list of exception types. |
3784 | ArrayRef<QualType> Exceptions; |
3785 | |
3786 | /// Noexcept expression, if this is a computed noexcept specification. |
3787 | Expr *NoexceptExpr = nullptr; |
3788 | |
3789 | /// The function whose exception specification this is, for |
3790 | /// EST_Unevaluated and EST_Uninstantiated. |
3791 | FunctionDecl *SourceDecl = nullptr; |
3792 | |
3793 | /// The function template whose exception specification this is instantiated |
3794 | /// from, for EST_Uninstantiated. |
3795 | FunctionDecl *SourceTemplate = nullptr; |
3796 | |
3797 | ExceptionSpecInfo() = default; |
3798 | |
3799 | ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {} |
3800 | }; |
3801 | |
3802 | /// Extra information about a function prototype. ExtProtoInfo is not |
3803 | /// stored as such in FunctionProtoType but is used to group together |
3804 | /// the various bits of extra information about a function prototype. |
3805 | struct ExtProtoInfo { |
3806 | FunctionType::ExtInfo ExtInfo; |
3807 | bool Variadic : 1; |
3808 | bool HasTrailingReturn : 1; |
3809 | Qualifiers TypeQuals; |
3810 | RefQualifierKind RefQualifier = RQ_None; |
3811 | ExceptionSpecInfo ExceptionSpec; |
3812 | const ExtParameterInfo *ExtParameterInfos = nullptr; |
3813 | |
3814 | ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {} |
3815 | |
3816 | ExtProtoInfo(CallingConv CC) |
3817 | : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {} |
3818 | |
3819 | ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) { |
3820 | ExtProtoInfo Result(*this); |
3821 | Result.ExceptionSpec = ESI; |
3822 | return Result; |
3823 | } |
3824 | }; |
3825 | |
3826 | private: |
3827 | unsigned numTrailingObjects(OverloadToken<QualType>) const { |
3828 | return getNumParams(); |
3829 | } |
3830 | |
3831 | unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const { |
3832 | return hasExtraBitfields(); |
3833 | } |
3834 | |
3835 | unsigned numTrailingObjects(OverloadToken<ExceptionType>) const { |
3836 | return getExceptionSpecSize().NumExceptionType; |
3837 | } |
3838 | |
3839 | unsigned numTrailingObjects(OverloadToken<Expr *>) const { |
3840 | return getExceptionSpecSize().NumExprPtr; |
3841 | } |
3842 | |
3843 | unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const { |
3844 | return getExceptionSpecSize().NumFunctionDeclPtr; |
3845 | } |
3846 | |
3847 | unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const { |
3848 | return hasExtParameterInfos() ? getNumParams() : 0; |
3849 | } |
3850 | |
3851 | /// Determine whether there are any argument types that |
3852 | /// contain an unexpanded parameter pack. |
3853 | static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray, |
3854 | unsigned numArgs) { |
3855 | for (unsigned Idx = 0; Idx < numArgs; ++Idx) |
3856 | if (ArgArray[Idx]->containsUnexpandedParameterPack()) |
3857 | return true; |
3858 | |
3859 | return false; |
3860 | } |
3861 | |
3862 | FunctionProtoType(QualType result, ArrayRef<QualType> params, |
3863 | QualType canonical, const ExtProtoInfo &epi); |
3864 | |
3865 | /// This struct is returned by getExceptionSpecSize and is used to |
3866 | /// translate an ExceptionSpecificationType to the number and kind |
3867 | /// of trailing objects related to the exception specification. |
3868 | struct ExceptionSpecSizeHolder { |
3869 | unsigned NumExceptionType; |
3870 | unsigned NumExprPtr; |
3871 | unsigned NumFunctionDeclPtr; |
3872 | }; |
3873 | |
3874 | /// Return the number and kind of trailing objects |
3875 | /// related to the exception specification. |
3876 | static ExceptionSpecSizeHolder |
3877 | getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) { |
3878 | switch (EST) { |
3879 | case EST_None: |
3880 | case EST_DynamicNone: |
3881 | case EST_MSAny: |
3882 | case EST_BasicNoexcept: |
3883 | case EST_Unparsed: |
3884 | case EST_NoThrow: |
3885 | return {0, 0, 0}; |
3886 | |
3887 | case EST_Dynamic: |
3888 | return {NumExceptions, 0, 0}; |
3889 | |
3890 | case EST_DependentNoexcept: |
3891 | case EST_NoexceptFalse: |
3892 | case EST_NoexceptTrue: |
3893 | return {0, 1, 0}; |
3894 | |
3895 | case EST_Uninstantiated: |
3896 | return {0, 0, 2}; |
3897 | |
3898 | case EST_Unevaluated: |
3899 | return {0, 0, 1}; |
3900 | } |
3901 | llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3901); |
3902 | } |
3903 | |
3904 | /// Return the number and kind of trailing objects |
3905 | /// related to the exception specification. |
3906 | ExceptionSpecSizeHolder getExceptionSpecSize() const { |
3907 | return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions()); |
3908 | } |
3909 | |
3910 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
3911 | static bool hasExtraBitfields(ExceptionSpecificationType EST) { |
3912 | // If the exception spec type is EST_Dynamic then we have > 0 exception |
3913 | // types and the exact number is stored in FunctionTypeExtraBitfields. |
3914 | return EST == EST_Dynamic; |
3915 | } |
3916 | |
3917 | /// Whether the trailing FunctionTypeExtraBitfields is present. |
3918 | bool hasExtraBitfields() const { |
3919 | return hasExtraBitfields(getExceptionSpecType()); |
3920 | } |
3921 | |
3922 | bool hasExtQualifiers() const { |
3923 | return FunctionTypeBits.HasExtQuals; |
3924 | } |
3925 | |
3926 | public: |
3927 | unsigned getNumParams() const { return FunctionTypeBits.NumParams; } |
3928 | |
3929 | QualType getParamType(unsigned i) const { |
3930 | assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index") ? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3930, __PRETTY_FUNCTION__)); |
3931 | return param_type_begin()[i]; |
3932 | } |
3933 | |
3934 | ArrayRef<QualType> getParamTypes() const { |
3935 | return llvm::makeArrayRef(param_type_begin(), param_type_end()); |
3936 | } |
3937 | |
3938 | ExtProtoInfo getExtProtoInfo() const { |
3939 | ExtProtoInfo EPI; |
3940 | EPI.ExtInfo = getExtInfo(); |
3941 | EPI.Variadic = isVariadic(); |
3942 | EPI.HasTrailingReturn = hasTrailingReturn(); |
3943 | EPI.ExceptionSpec.Type = getExceptionSpecType(); |
3944 | EPI.TypeQuals = getMethodQuals(); |
3945 | EPI.RefQualifier = getRefQualifier(); |
3946 | if (EPI.ExceptionSpec.Type == EST_Dynamic) { |
3947 | EPI.ExceptionSpec.Exceptions = exceptions(); |
3948 | } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) { |
3949 | EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr(); |
3950 | } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) { |
3951 | EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl(); |
3952 | EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate(); |
3953 | } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) { |
3954 | EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl(); |
3955 | } |
3956 | EPI.ExtParameterInfos = getExtParameterInfosOrNull(); |
3957 | return EPI; |
3958 | } |
3959 | |
3960 | /// Get the kind of exception specification on this function. |
3961 | ExceptionSpecificationType getExceptionSpecType() const { |
3962 | return static_cast<ExceptionSpecificationType>( |
3963 | FunctionTypeBits.ExceptionSpecType); |
3964 | } |
3965 | |
3966 | /// Return whether this function has any kind of exception spec. |
3967 | bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; } |
3968 | |
3969 | /// Return whether this function has a dynamic (throw) exception spec. |
3970 | bool hasDynamicExceptionSpec() const { |
3971 | return isDynamicExceptionSpec(getExceptionSpecType()); |
3972 | } |
3973 | |
3974 | /// Return whether this function has a noexcept exception spec. |
3975 | bool hasNoexceptExceptionSpec() const { |
3976 | return isNoexceptExceptionSpec(getExceptionSpecType()); |
3977 | } |
3978 | |
3979 | /// Return whether this function has a dependent exception spec. |
3980 | bool hasDependentExceptionSpec() const; |
3981 | |
3982 | /// Return whether this function has an instantiation-dependent exception |
3983 | /// spec. |
3984 | bool hasInstantiationDependentExceptionSpec() const; |
3985 | |
3986 | /// Return the number of types in the exception specification. |
3987 | unsigned getNumExceptions() const { |
3988 | return getExceptionSpecType() == EST_Dynamic |
3989 | ? getTrailingObjects<FunctionTypeExtraBitfields>() |
3990 | ->NumExceptionType |
3991 | : 0; |
3992 | } |
3993 | |
3994 | /// Return the ith exception type, where 0 <= i < getNumExceptions(). |
3995 | QualType getExceptionType(unsigned i) const { |
3996 | assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!" ) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 3996, __PRETTY_FUNCTION__)); |
3997 | return exception_begin()[i]; |
3998 | } |
3999 | |
4000 | /// Return the expression inside noexcept(expression), or a null pointer |
4001 | /// if there is none (because the exception spec is not of this form). |
4002 | Expr *getNoexceptExpr() const { |
4003 | if (!isComputedNoexcept(getExceptionSpecType())) |
4004 | return nullptr; |
4005 | return *getTrailingObjects<Expr *>(); |
4006 | } |
4007 | |
4008 | /// If this function type has an exception specification which hasn't |
4009 | /// been determined yet (either because it has not been evaluated or because |
4010 | /// it has not been instantiated), this is the function whose exception |
4011 | /// specification is represented by this type. |
4012 | FunctionDecl *getExceptionSpecDecl() const { |
4013 | if (getExceptionSpecType() != EST_Uninstantiated && |
4014 | getExceptionSpecType() != EST_Unevaluated) |
4015 | return nullptr; |
4016 | return getTrailingObjects<FunctionDecl *>()[0]; |
4017 | } |
4018 | |
4019 | /// If this function type has an uninstantiated exception |
4020 | /// specification, this is the function whose exception specification |
4021 | /// should be instantiated to find the exception specification for |
4022 | /// this type. |
4023 | FunctionDecl *getExceptionSpecTemplate() const { |
4024 | if (getExceptionSpecType() != EST_Uninstantiated) |
4025 | return nullptr; |
4026 | return getTrailingObjects<FunctionDecl *>()[1]; |
4027 | } |
4028 | |
4029 | /// Determine whether this function type has a non-throwing exception |
4030 | /// specification. |
4031 | CanThrowResult canThrow() const; |
4032 | |
4033 | /// Determine whether this function type has a non-throwing exception |
4034 | /// specification. If this depends on template arguments, returns |
4035 | /// \c ResultIfDependent. |
4036 | bool isNothrow(bool ResultIfDependent = false) const { |
4037 | return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot; |
4038 | } |
4039 | |
4040 | /// Whether this function prototype is variadic. |
4041 | bool isVariadic() const { return FunctionTypeBits.Variadic; } |
4042 | |
4043 | /// Determines whether this function prototype contains a |
4044 | /// parameter pack at the end. |
4045 | /// |
4046 | /// A function template whose last parameter is a parameter pack can be |
4047 | /// called with an arbitrary number of arguments, much like a variadic |
4048 | /// function. |
4049 | bool isTemplateVariadic() const; |
4050 | |
4051 | /// Whether this function prototype has a trailing return type. |
4052 | bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; } |
4053 | |
4054 | Qualifiers getMethodQuals() const { |
4055 | if (hasExtQualifiers()) |
4056 | return *getTrailingObjects<Qualifiers>(); |
4057 | else |
4058 | return getFastTypeQuals(); |
4059 | } |
4060 | |
4061 | /// Retrieve the ref-qualifier associated with this function type. |
4062 | RefQualifierKind getRefQualifier() const { |
4063 | return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier); |
4064 | } |
4065 | |
4066 | using param_type_iterator = const QualType *; |
4067 | using param_type_range = llvm::iterator_range<param_type_iterator>; |
4068 | |
4069 | param_type_range param_types() const { |
4070 | return param_type_range(param_type_begin(), param_type_end()); |
4071 | } |
4072 | |
4073 | param_type_iterator param_type_begin() const { |
4074 | return getTrailingObjects<QualType>(); |
4075 | } |
4076 | |
4077 | param_type_iterator param_type_end() const { |
4078 | return param_type_begin() + getNumParams(); |
4079 | } |
4080 | |
4081 | using exception_iterator = const QualType *; |
4082 | |
4083 | ArrayRef<QualType> exceptions() const { |
4084 | return llvm::makeArrayRef(exception_begin(), exception_end()); |
4085 | } |
4086 | |
4087 | exception_iterator exception_begin() const { |
4088 | return reinterpret_cast<exception_iterator>( |
4089 | getTrailingObjects<ExceptionType>()); |
4090 | } |
4091 | |
4092 | exception_iterator exception_end() const { |
4093 | return exception_begin() + getNumExceptions(); |
4094 | } |
4095 | |
4096 | /// Is there any interesting extra information for any of the parameters |
4097 | /// of this function type? |
4098 | bool hasExtParameterInfos() const { |
4099 | return FunctionTypeBits.HasExtParameterInfos; |
4100 | } |
4101 | |
4102 | ArrayRef<ExtParameterInfo> getExtParameterInfos() const { |
4103 | assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail ("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4103, __PRETTY_FUNCTION__)); |
4104 | return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(), |
4105 | getNumParams()); |
4106 | } |
4107 | |
4108 | /// Return a pointer to the beginning of the array of extra parameter |
4109 | /// information, if present, or else null if none of the parameters |
4110 | /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos. |
4111 | const ExtParameterInfo *getExtParameterInfosOrNull() const { |
4112 | if (!hasExtParameterInfos()) |
4113 | return nullptr; |
4114 | return getTrailingObjects<ExtParameterInfo>(); |
4115 | } |
4116 | |
4117 | ExtParameterInfo getExtParameterInfo(unsigned I) const { |
4118 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4118, __PRETTY_FUNCTION__)); |
4119 | if (hasExtParameterInfos()) |
4120 | return getTrailingObjects<ExtParameterInfo>()[I]; |
4121 | return ExtParameterInfo(); |
4122 | } |
4123 | |
4124 | ParameterABI getParameterABI(unsigned I) const { |
4125 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4125, __PRETTY_FUNCTION__)); |
4126 | if (hasExtParameterInfos()) |
4127 | return getTrailingObjects<ExtParameterInfo>()[I].getABI(); |
4128 | return ParameterABI::Ordinary; |
4129 | } |
4130 | |
4131 | bool isParamConsumed(unsigned I) const { |
4132 | assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range" ) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4132, __PRETTY_FUNCTION__)); |
4133 | if (hasExtParameterInfos()) |
4134 | return getTrailingObjects<ExtParameterInfo>()[I].isConsumed(); |
4135 | return false; |
4136 | } |
4137 | |
4138 | bool isSugared() const { return false; } |
4139 | QualType desugar() const { return QualType(this, 0); } |
4140 | |
4141 | void printExceptionSpecification(raw_ostream &OS, |
4142 | const PrintingPolicy &Policy) const; |
4143 | |
4144 | static bool classof(const Type *T) { |
4145 | return T->getTypeClass() == FunctionProto; |
4146 | } |
4147 | |
4148 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx); |
4149 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Result, |
4150 | param_type_iterator ArgTys, unsigned NumArgs, |
4151 | const ExtProtoInfo &EPI, const ASTContext &Context, |
4152 | bool Canonical); |
4153 | }; |
4154 | |
4155 | /// Represents the dependent type named by a dependently-scoped |
4156 | /// typename using declaration, e.g. |
4157 | /// using typename Base<T>::foo; |
4158 | /// |
4159 | /// Template instantiation turns these into the underlying type. |
4160 | class UnresolvedUsingType : public Type { |
4161 | friend class ASTContext; // ASTContext creates these. |
4162 | |
4163 | UnresolvedUsingTypenameDecl *Decl; |
4164 | |
4165 | UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D) |
4166 | : Type(UnresolvedUsing, QualType(), true, true, false, |
4167 | /*ContainsUnexpandedParameterPack=*/false), |
4168 | Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {} |
4169 | |
4170 | public: |
4171 | UnresolvedUsingTypenameDecl *getDecl() const { return Decl; } |
4172 | |
4173 | bool isSugared() const { return false; } |
4174 | QualType desugar() const { return QualType(this, 0); } |
4175 | |
4176 | static bool classof(const Type *T) { |
4177 | return T->getTypeClass() == UnresolvedUsing; |
4178 | } |
4179 | |
4180 | void Profile(llvm::FoldingSetNodeID &ID) { |
4181 | return Profile(ID, Decl); |
4182 | } |
4183 | |
4184 | static void Profile(llvm::FoldingSetNodeID &ID, |
4185 | UnresolvedUsingTypenameDecl *D) { |
4186 | ID.AddPointer(D); |
4187 | } |
4188 | }; |
4189 | |
4190 | class TypedefType : public Type { |
4191 | TypedefNameDecl *Decl; |
4192 | |
4193 | protected: |
4194 | friend class ASTContext; // ASTContext creates these. |
4195 | |
4196 | TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can) |
4197 | : Type(tc, can, can->isDependentType(), |
4198 | can->isInstantiationDependentType(), |
4199 | can->isVariablyModifiedType(), |
4200 | /*ContainsUnexpandedParameterPack=*/false), |
4201 | Decl(const_cast<TypedefNameDecl*>(D)) { |
4202 | assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type" ) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4202, __PRETTY_FUNCTION__)); |
4203 | } |
4204 | |
4205 | public: |
4206 | TypedefNameDecl *getDecl() const { return Decl; } |
4207 | |
4208 | bool isSugared() const { return true; } |
4209 | QualType desugar() const; |
4210 | |
4211 | static bool classof(const Type *T) { return T->getTypeClass() == Typedef; } |
4212 | }; |
4213 | |
4214 | /// Sugar type that represents a type that was qualified by a qualifier written |
4215 | /// as a macro invocation. |
4216 | class MacroQualifiedType : public Type { |
4217 | friend class ASTContext; // ASTContext creates these. |
4218 | |
4219 | QualType UnderlyingTy; |
4220 | const IdentifierInfo *MacroII; |
4221 | |
4222 | MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy, |
4223 | const IdentifierInfo *MacroII) |
4224 | : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(), |
4225 | UnderlyingTy->isInstantiationDependentType(), |
4226 | UnderlyingTy->isVariablyModifiedType(), |
4227 | UnderlyingTy->containsUnexpandedParameterPack()), |
4228 | UnderlyingTy(UnderlyingTy), MacroII(MacroII) { |
4229 | assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types." ) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4230, __PRETTY_FUNCTION__)) |
4230 | "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types." ) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4230, __PRETTY_FUNCTION__)); |
4231 | } |
4232 | |
4233 | public: |
4234 | const IdentifierInfo *getMacroIdentifier() const { return MacroII; } |
4235 | QualType getUnderlyingType() const { return UnderlyingTy; } |
4236 | |
4237 | /// Return this attributed type's modified type with no qualifiers attached to |
4238 | /// it. |
4239 | QualType getModifiedType() const; |
4240 | |
4241 | bool isSugared() const { return true; } |
4242 | QualType desugar() const; |
4243 | |
4244 | static bool classof(const Type *T) { |
4245 | return T->getTypeClass() == MacroQualified; |
4246 | } |
4247 | }; |
4248 | |
4249 | /// Represents a `typeof` (or __typeof__) expression (a GCC extension). |
4250 | class TypeOfExprType : public Type { |
4251 | Expr *TOExpr; |
4252 | |
4253 | protected: |
4254 | friend class ASTContext; // ASTContext creates these. |
4255 | |
4256 | TypeOfExprType(Expr *E, QualType can = QualType()); |
4257 | |
4258 | public: |
4259 | Expr *getUnderlyingExpr() const { return TOExpr; } |
4260 | |
4261 | /// Remove a single level of sugar. |
4262 | QualType desugar() const; |
4263 | |
4264 | /// Returns whether this type directly provides sugar. |
4265 | bool isSugared() const; |
4266 | |
4267 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; } |
4268 | }; |
4269 | |
4270 | /// Internal representation of canonical, dependent |
4271 | /// `typeof(expr)` types. |
4272 | /// |
4273 | /// This class is used internally by the ASTContext to manage |
4274 | /// canonical, dependent types, only. Clients will only see instances |
4275 | /// of this class via TypeOfExprType nodes. |
4276 | class DependentTypeOfExprType |
4277 | : public TypeOfExprType, public llvm::FoldingSetNode { |
4278 | const ASTContext &Context; |
4279 | |
4280 | public: |
4281 | DependentTypeOfExprType(const ASTContext &Context, Expr *E) |
4282 | : TypeOfExprType(E), Context(Context) {} |
4283 | |
4284 | void Profile(llvm::FoldingSetNodeID &ID) { |
4285 | Profile(ID, Context, getUnderlyingExpr()); |
4286 | } |
4287 | |
4288 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4289 | Expr *E); |
4290 | }; |
4291 | |
4292 | /// Represents `typeof(type)`, a GCC extension. |
4293 | class TypeOfType : public Type { |
4294 | friend class ASTContext; // ASTContext creates these. |
4295 | |
4296 | QualType TOType; |
4297 | |
4298 | TypeOfType(QualType T, QualType can) |
4299 | : Type(TypeOf, can, T->isDependentType(), |
4300 | T->isInstantiationDependentType(), |
4301 | T->isVariablyModifiedType(), |
4302 | T->containsUnexpandedParameterPack()), |
4303 | TOType(T) { |
4304 | assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type" ) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4304, __PRETTY_FUNCTION__)); |
4305 | } |
4306 | |
4307 | public: |
4308 | QualType getUnderlyingType() const { return TOType; } |
4309 | |
4310 | /// Remove a single level of sugar. |
4311 | QualType desugar() const { return getUnderlyingType(); } |
4312 | |
4313 | /// Returns whether this type directly provides sugar. |
4314 | bool isSugared() const { return true; } |
4315 | |
4316 | static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; } |
4317 | }; |
4318 | |
4319 | /// Represents the type `decltype(expr)` (C++11). |
4320 | class DecltypeType : public Type { |
4321 | Expr *E; |
4322 | QualType UnderlyingType; |
4323 | |
4324 | protected: |
4325 | friend class ASTContext; // ASTContext creates these. |
4326 | |
4327 | DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType()); |
4328 | |
4329 | public: |
4330 | Expr *getUnderlyingExpr() const { return E; } |
4331 | QualType getUnderlyingType() const { return UnderlyingType; } |
4332 | |
4333 | /// Remove a single level of sugar. |
4334 | QualType desugar() const; |
4335 | |
4336 | /// Returns whether this type directly provides sugar. |
4337 | bool isSugared() const; |
4338 | |
4339 | static bool classof(const Type *T) { return T->getTypeClass() == Decltype; } |
4340 | }; |
4341 | |
4342 | /// Internal representation of canonical, dependent |
4343 | /// decltype(expr) types. |
4344 | /// |
4345 | /// This class is used internally by the ASTContext to manage |
4346 | /// canonical, dependent types, only. Clients will only see instances |
4347 | /// of this class via DecltypeType nodes. |
4348 | class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode { |
4349 | const ASTContext &Context; |
4350 | |
4351 | public: |
4352 | DependentDecltypeType(const ASTContext &Context, Expr *E); |
4353 | |
4354 | void Profile(llvm::FoldingSetNodeID &ID) { |
4355 | Profile(ID, Context, getUnderlyingExpr()); |
4356 | } |
4357 | |
4358 | static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, |
4359 | Expr *E); |
4360 | }; |
4361 | |
4362 | /// A unary type transform, which is a type constructed from another. |
4363 | class UnaryTransformType : public Type { |
4364 | public: |
4365 | enum UTTKind { |
4366 | EnumUnderlyingType |
4367 | }; |
4368 | |
4369 | private: |
4370 | /// The untransformed type. |
4371 | QualType BaseType; |
4372 | |
4373 | /// The transformed type if not dependent, otherwise the same as BaseType. |
4374 | QualType UnderlyingType; |
4375 | |
4376 | UTTKind UKind; |
4377 | |
4378 | protected: |
4379 | friend class ASTContext; |
4380 | |
4381 | UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind, |
4382 | QualType CanonicalTy); |
4383 | |
4384 | public: |
4385 | bool isSugared() const { return !isDependentType(); } |
4386 | QualType desugar() const { return UnderlyingType; } |
4387 | |
4388 | QualType getUnderlyingType() const { return UnderlyingType; } |
4389 | QualType getBaseType() const { return BaseType; } |
4390 | |
4391 | UTTKind getUTTKind() const { return UKind; } |
4392 | |
4393 | static bool classof(const Type *T) { |
4394 | return T->getTypeClass() == UnaryTransform; |
4395 | } |
4396 | }; |
4397 | |
4398 | /// Internal representation of canonical, dependent |
4399 | /// __underlying_type(type) types. |
4400 | /// |
4401 | /// This class is used internally by the ASTContext to manage |
4402 | /// canonical, dependent types, only. Clients will only see instances |
4403 | /// of this class via UnaryTransformType nodes. |
4404 | class DependentUnaryTransformType : public UnaryTransformType, |
4405 | public llvm::FoldingSetNode { |
4406 | public: |
4407 | DependentUnaryTransformType(const ASTContext &C, QualType BaseType, |
4408 | UTTKind UKind); |
4409 | |
4410 | void Profile(llvm::FoldingSetNodeID &ID) { |
4411 | Profile(ID, getBaseType(), getUTTKind()); |
4412 | } |
4413 | |
4414 | static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType, |
4415 | UTTKind UKind) { |
4416 | ID.AddPointer(BaseType.getAsOpaquePtr()); |
4417 | ID.AddInteger((unsigned)UKind); |
4418 | } |
4419 | }; |
4420 | |
4421 | class TagType : public Type { |
4422 | friend class ASTReader; |
4423 | |
4424 | /// Stores the TagDecl associated with this type. The decl may point to any |
4425 | /// TagDecl that declares the entity. |
4426 | TagDecl *decl; |
4427 | |
4428 | protected: |
4429 | TagType(TypeClass TC, const TagDecl *D, QualType can); |
4430 | |
4431 | public: |
4432 | TagDecl *getDecl() const; |
4433 | |
4434 | /// Determines whether this type is in the process of being defined. |
4435 | bool isBeingDefined() const; |
4436 | |
4437 | static bool classof(const Type *T) { |
4438 | return T->getTypeClass() == Enum || T->getTypeClass() == Record; |
4439 | } |
4440 | }; |
4441 | |
4442 | /// A helper class that allows the use of isa/cast/dyncast |
4443 | /// to detect TagType objects of structs/unions/classes. |
4444 | class RecordType : public TagType { |
4445 | protected: |
4446 | friend class ASTContext; // ASTContext creates these. |
4447 | |
4448 | explicit RecordType(const RecordDecl *D) |
4449 | : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4450 | explicit RecordType(TypeClass TC, RecordDecl *D) |
4451 | : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4452 | |
4453 | public: |
4454 | RecordDecl *getDecl() const { |
4455 | return reinterpret_cast<RecordDecl*>(TagType::getDecl()); |
4456 | } |
4457 | |
4458 | /// Recursively check all fields in the record for const-ness. If any field |
4459 | /// is declared const, return true. Otherwise, return false. |
4460 | bool hasConstFields() const; |
4461 | |
4462 | bool isSugared() const { return false; } |
4463 | QualType desugar() const { return QualType(this, 0); } |
4464 | |
4465 | static bool classof(const Type *T) { return T->getTypeClass() == Record; } |
4466 | }; |
4467 | |
4468 | /// A helper class that allows the use of isa/cast/dyncast |
4469 | /// to detect TagType objects of enums. |
4470 | class EnumType : public TagType { |
4471 | friend class ASTContext; // ASTContext creates these. |
4472 | |
4473 | explicit EnumType(const EnumDecl *D) |
4474 | : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {} |
4475 | |
4476 | public: |
4477 | EnumDecl *getDecl() const { |
4478 | return reinterpret_cast<EnumDecl*>(TagType::getDecl()); |
4479 | } |
4480 | |
4481 | bool isSugared() const { return false; } |
4482 | QualType desugar() const { return QualType(this, 0); } |
4483 | |
4484 | static bool classof(const Type *T) { return T->getTypeClass() == Enum; } |
4485 | }; |
4486 | |
4487 | /// An attributed type is a type to which a type attribute has been applied. |
4488 | /// |
4489 | /// The "modified type" is the fully-sugared type to which the attributed |
4490 | /// type was applied; generally it is not canonically equivalent to the |
4491 | /// attributed type. The "equivalent type" is the minimally-desugared type |
4492 | /// which the type is canonically equivalent to. |
4493 | /// |
4494 | /// For example, in the following attributed type: |
4495 | /// int32_t __attribute__((vector_size(16))) |
4496 | /// - the modified type is the TypedefType for int32_t |
4497 | /// - the equivalent type is VectorType(16, int32_t) |
4498 | /// - the canonical type is VectorType(16, int) |
4499 | class AttributedType : public Type, public llvm::FoldingSetNode { |
4500 | public: |
4501 | using Kind = attr::Kind; |
4502 | |
4503 | private: |
4504 | friend class ASTContext; // ASTContext creates these |
4505 | |
4506 | QualType ModifiedType; |
4507 | QualType EquivalentType; |
4508 | |
4509 | AttributedType(QualType canon, attr::Kind attrKind, QualType modified, |
4510 | QualType equivalent) |
4511 | : Type(Attributed, canon, equivalent->isDependentType(), |
4512 | equivalent->isInstantiationDependentType(), |
4513 | equivalent->isVariablyModifiedType(), |
4514 | equivalent->containsUnexpandedParameterPack()), |
4515 | ModifiedType(modified), EquivalentType(equivalent) { |
4516 | AttributedTypeBits.AttrKind = attrKind; |
4517 | } |
4518 | |
4519 | public: |
4520 | Kind getAttrKind() const { |
4521 | return static_cast<Kind>(AttributedTypeBits.AttrKind); |
4522 | } |
4523 | |
4524 | QualType getModifiedType() const { return ModifiedType; } |
4525 | QualType getEquivalentType() const { return EquivalentType; } |
4526 | |
4527 | bool isSugared() const { return true; } |
4528 | QualType desugar() const { return getEquivalentType(); } |
4529 | |
4530 | /// Does this attribute behave like a type qualifier? |
4531 | /// |
4532 | /// A type qualifier adjusts a type to provide specialized rules for |
4533 | /// a specific object, like the standard const and volatile qualifiers. |
4534 | /// This includes attributes controlling things like nullability, |
4535 | /// address spaces, and ARC ownership. The value of the object is still |
4536 | /// largely described by the modified type. |
4537 | /// |
4538 | /// In contrast, many type attributes "rewrite" their modified type to |
4539 | /// produce a fundamentally different type, not necessarily related in any |
4540 | /// formalizable way to the original type. For example, calling convention |
4541 | /// and vector attributes are not simple type qualifiers. |
4542 | /// |
4543 | /// Type qualifiers are often, but not always, reflected in the canonical |
4544 | /// type. |
4545 | bool isQualifier() const; |
4546 | |
4547 | bool isMSTypeSpec() const; |
4548 | |
4549 | bool isCallingConv() const; |
4550 | |
4551 | llvm::Optional<NullabilityKind> getImmediateNullability() const; |
4552 | |
4553 | /// Retrieve the attribute kind corresponding to the given |
4554 | /// nullability kind. |
4555 | static Kind getNullabilityAttrKind(NullabilityKind kind) { |
4556 | switch (kind) { |
4557 | case NullabilityKind::NonNull: |
4558 | return attr::TypeNonNull; |
4559 | |
4560 | case NullabilityKind::Nullable: |
4561 | return attr::TypeNullable; |
4562 | |
4563 | case NullabilityKind::Unspecified: |
4564 | return attr::TypeNullUnspecified; |
4565 | } |
4566 | llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind." , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4566); |
4567 | } |
4568 | |
4569 | /// Strip off the top-level nullability annotation on the given |
4570 | /// type, if it's there. |
4571 | /// |
4572 | /// \param T The type to strip. If the type is exactly an |
4573 | /// AttributedType specifying nullability (without looking through |
4574 | /// type sugar), the nullability is returned and this type changed |
4575 | /// to the underlying modified type. |
4576 | /// |
4577 | /// \returns the top-level nullability, if present. |
4578 | static Optional<NullabilityKind> stripOuterNullability(QualType &T); |
4579 | |
4580 | void Profile(llvm::FoldingSetNodeID &ID) { |
4581 | Profile(ID, getAttrKind(), ModifiedType, EquivalentType); |
4582 | } |
4583 | |
4584 | static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind, |
4585 | QualType modified, QualType equivalent) { |
4586 | ID.AddInteger(attrKind); |
4587 | ID.AddPointer(modified.getAsOpaquePtr()); |
4588 | ID.AddPointer(equivalent.getAsOpaquePtr()); |
4589 | } |
4590 | |
4591 | static bool classof(const Type *T) { |
4592 | return T->getTypeClass() == Attributed; |
4593 | } |
4594 | }; |
4595 | |
4596 | class TemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4597 | friend class ASTContext; // ASTContext creates these |
4598 | |
4599 | // Helper data collector for canonical types. |
4600 | struct CanonicalTTPTInfo { |
4601 | unsigned Depth : 15; |
4602 | unsigned ParameterPack : 1; |
4603 | unsigned Index : 16; |
4604 | }; |
4605 | |
4606 | union { |
4607 | // Info for the canonical type. |
4608 | CanonicalTTPTInfo CanTTPTInfo; |
4609 | |
4610 | // Info for the non-canonical type. |
4611 | TemplateTypeParmDecl *TTPDecl; |
4612 | }; |
4613 | |
4614 | /// Build a non-canonical type. |
4615 | TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon) |
4616 | : Type(TemplateTypeParm, Canon, /*Dependent=*/true, |
4617 | /*InstantiationDependent=*/true, |
4618 | /*VariablyModified=*/false, |
4619 | Canon->containsUnexpandedParameterPack()), |
4620 | TTPDecl(TTPDecl) {} |
4621 | |
4622 | /// Build the canonical type. |
4623 | TemplateTypeParmType(unsigned D, unsigned I, bool PP) |
4624 | : Type(TemplateTypeParm, QualType(this, 0), |
4625 | /*Dependent=*/true, |
4626 | /*InstantiationDependent=*/true, |
4627 | /*VariablyModified=*/false, PP) { |
4628 | CanTTPTInfo.Depth = D; |
4629 | CanTTPTInfo.Index = I; |
4630 | CanTTPTInfo.ParameterPack = PP; |
4631 | } |
4632 | |
4633 | const CanonicalTTPTInfo& getCanTTPTInfo() const { |
4634 | QualType Can = getCanonicalTypeInternal(); |
4635 | return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo; |
4636 | } |
4637 | |
4638 | public: |
4639 | unsigned getDepth() const { return getCanTTPTInfo().Depth; } |
4640 | unsigned getIndex() const { return getCanTTPTInfo().Index; } |
4641 | bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; } |
4642 | |
4643 | TemplateTypeParmDecl *getDecl() const { |
4644 | return isCanonicalUnqualified() ? nullptr : TTPDecl; |
4645 | } |
4646 | |
4647 | IdentifierInfo *getIdentifier() const; |
4648 | |
4649 | bool isSugared() const { return false; } |
4650 | QualType desugar() const { return QualType(this, 0); } |
4651 | |
4652 | void Profile(llvm::FoldingSetNodeID &ID) { |
4653 | Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl()); |
4654 | } |
4655 | |
4656 | static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth, |
4657 | unsigned Index, bool ParameterPack, |
4658 | TemplateTypeParmDecl *TTPDecl) { |
4659 | ID.AddInteger(Depth); |
4660 | ID.AddInteger(Index); |
4661 | ID.AddBoolean(ParameterPack); |
4662 | ID.AddPointer(TTPDecl); |
4663 | } |
4664 | |
4665 | static bool classof(const Type *T) { |
4666 | return T->getTypeClass() == TemplateTypeParm; |
4667 | } |
4668 | }; |
4669 | |
4670 | /// Represents the result of substituting a type for a template |
4671 | /// type parameter. |
4672 | /// |
4673 | /// Within an instantiated template, all template type parameters have |
4674 | /// been replaced with these. They are used solely to record that a |
4675 | /// type was originally written as a template type parameter; |
4676 | /// therefore they are never canonical. |
4677 | class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode { |
4678 | friend class ASTContext; |
4679 | |
4680 | // The original type parameter. |
4681 | const TemplateTypeParmType *Replaced; |
4682 | |
4683 | SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon) |
4684 | : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(), |
4685 | Canon->isInstantiationDependentType(), |
4686 | Canon->isVariablyModifiedType(), |
4687 | Canon->containsUnexpandedParameterPack()), |
4688 | Replaced(Param) {} |
4689 | |
4690 | public: |
4691 | /// Gets the template parameter that was substituted for. |
4692 | const TemplateTypeParmType *getReplacedParameter() const { |
4693 | return Replaced; |
4694 | } |
4695 | |
4696 | /// Gets the type that was substituted for the template |
4697 | /// parameter. |
4698 | QualType getReplacementType() const { |
4699 | return getCanonicalTypeInternal(); |
4700 | } |
4701 | |
4702 | bool isSugared() const { return true; } |
4703 | QualType desugar() const { return getReplacementType(); } |
4704 | |
4705 | void Profile(llvm::FoldingSetNodeID &ID) { |
4706 | Profile(ID, getReplacedParameter(), getReplacementType()); |
4707 | } |
4708 | |
4709 | static void Profile(llvm::FoldingSetNodeID &ID, |
4710 | const TemplateTypeParmType *Replaced, |
4711 | QualType Replacement) { |
4712 | ID.AddPointer(Replaced); |
4713 | ID.AddPointer(Replacement.getAsOpaquePtr()); |
4714 | } |
4715 | |
4716 | static bool classof(const Type *T) { |
4717 | return T->getTypeClass() == SubstTemplateTypeParm; |
4718 | } |
4719 | }; |
4720 | |
4721 | /// Represents the result of substituting a set of types for a template |
4722 | /// type parameter pack. |
4723 | /// |
4724 | /// When a pack expansion in the source code contains multiple parameter packs |
4725 | /// and those parameter packs correspond to different levels of template |
4726 | /// parameter lists, this type node is used to represent a template type |
4727 | /// parameter pack from an outer level, which has already had its argument pack |
4728 | /// substituted but that still lives within a pack expansion that itself |
4729 | /// could not be instantiated. When actually performing a substitution into |
4730 | /// that pack expansion (e.g., when all template parameters have corresponding |
4731 | /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType |
4732 | /// at the current pack substitution index. |
4733 | class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode { |
4734 | friend class ASTContext; |
4735 | |
4736 | /// The original type parameter. |
4737 | const TemplateTypeParmType *Replaced; |
4738 | |
4739 | /// A pointer to the set of template arguments that this |
4740 | /// parameter pack is instantiated with. |
4741 | const TemplateArgument *Arguments; |
4742 | |
4743 | SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, |
4744 | QualType Canon, |
4745 | const TemplateArgument &ArgPack); |
4746 | |
4747 | public: |
4748 | IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); } |
4749 | |
4750 | /// Gets the template parameter that was substituted for. |
4751 | const TemplateTypeParmType *getReplacedParameter() const { |
4752 | return Replaced; |
4753 | } |
4754 | |
4755 | unsigned getNumArgs() const { |
4756 | return SubstTemplateTypeParmPackTypeBits.NumArgs; |
4757 | } |
4758 | |
4759 | bool isSugared() const { return false; } |
4760 | QualType desugar() const { return QualType(this, 0); } |
4761 | |
4762 | TemplateArgument getArgumentPack() const; |
4763 | |
4764 | void Profile(llvm::FoldingSetNodeID &ID); |
4765 | static void Profile(llvm::FoldingSetNodeID &ID, |
4766 | const TemplateTypeParmType *Replaced, |
4767 | const TemplateArgument &ArgPack); |
4768 | |
4769 | static bool classof(const Type *T) { |
4770 | return T->getTypeClass() == SubstTemplateTypeParmPack; |
4771 | } |
4772 | }; |
4773 | |
4774 | /// Common base class for placeholders for types that get replaced by |
4775 | /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced |
4776 | /// class template types, and (eventually) constrained type names from the C++ |
4777 | /// Concepts TS. |
4778 | /// |
4779 | /// These types are usually a placeholder for a deduced type. However, before |
4780 | /// the initializer is attached, or (usually) if the initializer is |
4781 | /// type-dependent, there is no deduced type and the type is canonical. In |
4782 | /// the latter case, it is also a dependent type. |
4783 | class DeducedType : public Type { |
4784 | protected: |
4785 | DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent, |
4786 | bool IsInstantiationDependent, bool ContainsParameterPack) |
4787 | : Type(TC, |
4788 | // FIXME: Retain the sugared deduced type? |
4789 | DeducedAsType.isNull() ? QualType(this, 0) |
4790 | : DeducedAsType.getCanonicalType(), |
4791 | IsDependent, IsInstantiationDependent, |
4792 | /*VariablyModified=*/false, ContainsParameterPack) { |
4793 | if (!DeducedAsType.isNull()) { |
4794 | if (DeducedAsType->isDependentType()) |
4795 | setDependent(); |
4796 | if (DeducedAsType->isInstantiationDependentType()) |
4797 | setInstantiationDependent(); |
4798 | if (DeducedAsType->containsUnexpandedParameterPack()) |
4799 | setContainsUnexpandedParameterPack(); |
4800 | } |
4801 | } |
4802 | |
4803 | public: |
4804 | bool isSugared() const { return !isCanonicalUnqualified(); } |
4805 | QualType desugar() const { return getCanonicalTypeInternal(); } |
4806 | |
4807 | /// Get the type deduced for this placeholder type, or null if it's |
4808 | /// either not been deduced or was deduced to a dependent type. |
4809 | QualType getDeducedType() const { |
4810 | return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType(); |
4811 | } |
4812 | bool isDeduced() const { |
4813 | return !isCanonicalUnqualified() || isDependentType(); |
4814 | } |
4815 | |
4816 | static bool classof(const Type *T) { |
4817 | return T->getTypeClass() == Auto || |
4818 | T->getTypeClass() == DeducedTemplateSpecialization; |
4819 | } |
4820 | }; |
4821 | |
4822 | /// Represents a C++11 auto or C++14 decltype(auto) type. |
4823 | class AutoType : public DeducedType, public llvm::FoldingSetNode { |
4824 | friend class ASTContext; // ASTContext creates these |
4825 | |
4826 | AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword, |
4827 | bool IsDeducedAsDependent, bool IsDeducedAsPack) |
4828 | : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent, |
4829 | IsDeducedAsDependent, IsDeducedAsPack) { |
4830 | AutoTypeBits.Keyword = (unsigned)Keyword; |
4831 | } |
4832 | |
4833 | public: |
4834 | bool isDecltypeAuto() const { |
4835 | return getKeyword() == AutoTypeKeyword::DecltypeAuto; |
4836 | } |
4837 | |
4838 | AutoTypeKeyword getKeyword() const { |
4839 | return (AutoTypeKeyword)AutoTypeBits.Keyword; |
4840 | } |
4841 | |
4842 | void Profile(llvm::FoldingSetNodeID &ID) { |
4843 | Profile(ID, getDeducedType(), getKeyword(), isDependentType(), |
4844 | containsUnexpandedParameterPack()); |
4845 | } |
4846 | |
4847 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced, |
4848 | AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) { |
4849 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
4850 | ID.AddInteger((unsigned)Keyword); |
4851 | ID.AddBoolean(IsDependent); |
4852 | ID.AddBoolean(IsPack); |
4853 | } |
4854 | |
4855 | static bool classof(const Type *T) { |
4856 | return T->getTypeClass() == Auto; |
4857 | } |
4858 | }; |
4859 | |
4860 | /// Represents a C++17 deduced template specialization type. |
4861 | class DeducedTemplateSpecializationType : public DeducedType, |
4862 | public llvm::FoldingSetNode { |
4863 | friend class ASTContext; // ASTContext creates these |
4864 | |
4865 | /// The name of the template whose arguments will be deduced. |
4866 | TemplateName Template; |
4867 | |
4868 | DeducedTemplateSpecializationType(TemplateName Template, |
4869 | QualType DeducedAsType, |
4870 | bool IsDeducedAsDependent) |
4871 | : DeducedType(DeducedTemplateSpecialization, DeducedAsType, |
4872 | IsDeducedAsDependent || Template.isDependent(), |
4873 | IsDeducedAsDependent || Template.isInstantiationDependent(), |
4874 | Template.containsUnexpandedParameterPack()), |
4875 | Template(Template) {} |
4876 | |
4877 | public: |
4878 | /// Retrieve the name of the template that we are deducing. |
4879 | TemplateName getTemplateName() const { return Template;} |
4880 | |
4881 | void Profile(llvm::FoldingSetNodeID &ID) { |
4882 | Profile(ID, getTemplateName(), getDeducedType(), isDependentType()); |
4883 | } |
4884 | |
4885 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template, |
4886 | QualType Deduced, bool IsDependent) { |
4887 | Template.Profile(ID); |
4888 | ID.AddPointer(Deduced.getAsOpaquePtr()); |
4889 | ID.AddBoolean(IsDependent); |
4890 | } |
4891 | |
4892 | static bool classof(const Type *T) { |
4893 | return T->getTypeClass() == DeducedTemplateSpecialization; |
4894 | } |
4895 | }; |
4896 | |
4897 | /// Represents a type template specialization; the template |
4898 | /// must be a class template, a type alias template, or a template |
4899 | /// template parameter. A template which cannot be resolved to one of |
4900 | /// these, e.g. because it is written with a dependent scope |
4901 | /// specifier, is instead represented as a |
4902 | /// @c DependentTemplateSpecializationType. |
4903 | /// |
4904 | /// A non-dependent template specialization type is always "sugar", |
4905 | /// typically for a \c RecordType. For example, a class template |
4906 | /// specialization type of \c vector<int> will refer to a tag type for |
4907 | /// the instantiation \c std::vector<int, std::allocator<int>> |
4908 | /// |
4909 | /// Template specializations are dependent if either the template or |
4910 | /// any of the template arguments are dependent, in which case the |
4911 | /// type may also be canonical. |
4912 | /// |
4913 | /// Instances of this type are allocated with a trailing array of |
4914 | /// TemplateArguments, followed by a QualType representing the |
4915 | /// non-canonical aliased type when the template is a type alias |
4916 | /// template. |
4917 | class alignas(8) TemplateSpecializationType |
4918 | : public Type, |
4919 | public llvm::FoldingSetNode { |
4920 | friend class ASTContext; // ASTContext creates these |
4921 | |
4922 | /// The name of the template being specialized. This is |
4923 | /// either a TemplateName::Template (in which case it is a |
4924 | /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a |
4925 | /// TypeAliasTemplateDecl*), a |
4926 | /// TemplateName::SubstTemplateTemplateParmPack, or a |
4927 | /// TemplateName::SubstTemplateTemplateParm (in which case the |
4928 | /// replacement must, recursively, be one of these). |
4929 | TemplateName Template; |
4930 | |
4931 | TemplateSpecializationType(TemplateName T, |
4932 | ArrayRef<TemplateArgument> Args, |
4933 | QualType Canon, |
4934 | QualType Aliased); |
4935 | |
4936 | public: |
4937 | /// Determine whether any of the given template arguments are dependent. |
4938 | static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, |
4939 | bool &InstantiationDependent); |
4940 | |
4941 | static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &, |
4942 | bool &InstantiationDependent); |
4943 | |
4944 | /// True if this template specialization type matches a current |
4945 | /// instantiation in the context in which it is found. |
4946 | bool isCurrentInstantiation() const { |
4947 | return isa<InjectedClassNameType>(getCanonicalTypeInternal()); |
4948 | } |
4949 | |
4950 | /// Determine if this template specialization type is for a type alias |
4951 | /// template that has been substituted. |
4952 | /// |
4953 | /// Nearly every template specialization type whose template is an alias |
4954 | /// template will be substituted. However, this is not the case when |
4955 | /// the specialization contains a pack expansion but the template alias |
4956 | /// does not have a corresponding parameter pack, e.g., |
4957 | /// |
4958 | /// \code |
4959 | /// template<typename T, typename U, typename V> struct S; |
4960 | /// template<typename T, typename U> using A = S<T, int, U>; |
4961 | /// template<typename... Ts> struct X { |
4962 | /// typedef A<Ts...> type; // not a type alias |
4963 | /// }; |
4964 | /// \endcode |
4965 | bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; } |
4966 | |
4967 | /// Get the aliased type, if this is a specialization of a type alias |
4968 | /// template. |
4969 | QualType getAliasedType() const { |
4970 | assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization" ) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 4970, __PRETTY_FUNCTION__)); |
4971 | return *reinterpret_cast<const QualType*>(end()); |
4972 | } |
4973 | |
4974 | using iterator = const TemplateArgument *; |
4975 | |
4976 | iterator begin() const { return getArgs(); } |
4977 | iterator end() const; // defined inline in TemplateBase.h |
4978 | |
4979 | /// Retrieve the name of the template that we are specializing. |
4980 | TemplateName getTemplateName() const { return Template; } |
4981 | |
4982 | /// Retrieve the template arguments. |
4983 | const TemplateArgument *getArgs() const { |
4984 | return reinterpret_cast<const TemplateArgument *>(this + 1); |
4985 | } |
4986 | |
4987 | /// Retrieve the number of template arguments. |
4988 | unsigned getNumArgs() const { |
4989 | return TemplateSpecializationTypeBits.NumArgs; |
4990 | } |
4991 | |
4992 | /// Retrieve a specific template argument as a type. |
4993 | /// \pre \c isArgType(Arg) |
4994 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
4995 | |
4996 | ArrayRef<TemplateArgument> template_arguments() const { |
4997 | return {getArgs(), getNumArgs()}; |
4998 | } |
4999 | |
5000 | bool isSugared() const { |
5001 | return !isDependentType() || isCurrentInstantiation() || isTypeAlias(); |
5002 | } |
5003 | |
5004 | QualType desugar() const { |
5005 | return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal(); |
5006 | } |
5007 | |
5008 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) { |
5009 | Profile(ID, Template, template_arguments(), Ctx); |
5010 | if (isTypeAlias()) |
5011 | getAliasedType().Profile(ID); |
5012 | } |
5013 | |
5014 | static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T, |
5015 | ArrayRef<TemplateArgument> Args, |
5016 | const ASTContext &Context); |
5017 | |
5018 | static bool classof(const Type *T) { |
5019 | return T->getTypeClass() == TemplateSpecialization; |
5020 | } |
5021 | }; |
5022 | |
5023 | /// Print a template argument list, including the '<' and '>' |
5024 | /// enclosing the template arguments. |
5025 | void printTemplateArgumentList(raw_ostream &OS, |
5026 | ArrayRef<TemplateArgument> Args, |
5027 | const PrintingPolicy &Policy); |
5028 | |
5029 | void printTemplateArgumentList(raw_ostream &OS, |
5030 | ArrayRef<TemplateArgumentLoc> Args, |
5031 | const PrintingPolicy &Policy); |
5032 | |
5033 | void printTemplateArgumentList(raw_ostream &OS, |
5034 | const TemplateArgumentListInfo &Args, |
5035 | const PrintingPolicy &Policy); |
5036 | |
5037 | /// The injected class name of a C++ class template or class |
5038 | /// template partial specialization. Used to record that a type was |
5039 | /// spelled with a bare identifier rather than as a template-id; the |
5040 | /// equivalent for non-templated classes is just RecordType. |
5041 | /// |
5042 | /// Injected class name types are always dependent. Template |
5043 | /// instantiation turns these into RecordTypes. |
5044 | /// |
5045 | /// Injected class name types are always canonical. This works |
5046 | /// because it is impossible to compare an injected class name type |
5047 | /// with the corresponding non-injected template type, for the same |
5048 | /// reason that it is impossible to directly compare template |
5049 | /// parameters from different dependent contexts: injected class name |
5050 | /// types can only occur within the scope of a particular templated |
5051 | /// declaration, and within that scope every template specialization |
5052 | /// will canonicalize to the injected class name (when appropriate |
5053 | /// according to the rules of the language). |
5054 | class InjectedClassNameType : public Type { |
5055 | friend class ASTContext; // ASTContext creates these. |
5056 | friend class ASTNodeImporter; |
5057 | friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not |
5058 | // currently suitable for AST reading, too much |
5059 | // interdependencies. |
5060 | |
5061 | CXXRecordDecl *Decl; |
5062 | |
5063 | /// The template specialization which this type represents. |
5064 | /// For example, in |
5065 | /// template <class T> class A { ... }; |
5066 | /// this is A<T>, whereas in |
5067 | /// template <class X, class Y> class A<B<X,Y> > { ... }; |
5068 | /// this is A<B<X,Y> >. |
5069 | /// |
5070 | /// It is always unqualified, always a template specialization type, |
5071 | /// and always dependent. |
5072 | QualType InjectedType; |
5073 | |
5074 | InjectedClassNameType(CXXRecordDecl *D, QualType TST) |
5075 | : Type(InjectedClassName, QualType(), /*Dependent=*/true, |
5076 | /*InstantiationDependent=*/true, |
5077 | /*VariablyModified=*/false, |
5078 | /*ContainsUnexpandedParameterPack=*/false), |
5079 | Decl(D), InjectedType(TST) { |
5080 | assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast< void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5080, __PRETTY_FUNCTION__)); |
5081 | assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail ("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5081, __PRETTY_FUNCTION__)); |
5082 | assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail ("TST->isDependentType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5082, __PRETTY_FUNCTION__)); |
5083 | } |
5084 | |
5085 | public: |
5086 | QualType getInjectedSpecializationType() const { return InjectedType; } |
5087 | |
5088 | const TemplateSpecializationType *getInjectedTST() const { |
5089 | return cast<TemplateSpecializationType>(InjectedType.getTypePtr()); |
5090 | } |
5091 | |
5092 | TemplateName getTemplateName() const { |
5093 | return getInjectedTST()->getTemplateName(); |
5094 | } |
5095 | |
5096 | CXXRecordDecl *getDecl() const; |
5097 | |
5098 | bool isSugared() const { return false; } |
5099 | QualType desugar() const { return QualType(this, 0); } |
5100 | |
5101 | static bool classof(const Type *T) { |
5102 | return T->getTypeClass() == InjectedClassName; |
5103 | } |
5104 | }; |
5105 | |
5106 | /// The kind of a tag type. |
5107 | enum TagTypeKind { |
5108 | /// The "struct" keyword. |
5109 | TTK_Struct, |
5110 | |
5111 | /// The "__interface" keyword. |
5112 | TTK_Interface, |
5113 | |
5114 | /// The "union" keyword. |
5115 | TTK_Union, |
5116 | |
5117 | /// The "class" keyword. |
5118 | TTK_Class, |
5119 | |
5120 | /// The "enum" keyword. |
5121 | TTK_Enum |
5122 | }; |
5123 | |
5124 | /// The elaboration keyword that precedes a qualified type name or |
5125 | /// introduces an elaborated-type-specifier. |
5126 | enum ElaboratedTypeKeyword { |
5127 | /// The "struct" keyword introduces the elaborated-type-specifier. |
5128 | ETK_Struct, |
5129 | |
5130 | /// The "__interface" keyword introduces the elaborated-type-specifier. |
5131 | ETK_Interface, |
5132 | |
5133 | /// The "union" keyword introduces the elaborated-type-specifier. |
5134 | ETK_Union, |
5135 | |
5136 | /// The "class" keyword introduces the elaborated-type-specifier. |
5137 | ETK_Class, |
5138 | |
5139 | /// The "enum" keyword introduces the elaborated-type-specifier. |
5140 | ETK_Enum, |
5141 | |
5142 | /// The "typename" keyword precedes the qualified type name, e.g., |
5143 | /// \c typename T::type. |
5144 | ETK_Typename, |
5145 | |
5146 | /// No keyword precedes the qualified type name. |
5147 | ETK_None |
5148 | }; |
5149 | |
5150 | /// A helper class for Type nodes having an ElaboratedTypeKeyword. |
5151 | /// The keyword in stored in the free bits of the base class. |
5152 | /// Also provides a few static helpers for converting and printing |
5153 | /// elaborated type keyword and tag type kind enumerations. |
5154 | class TypeWithKeyword : public Type { |
5155 | protected: |
5156 | TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc, |
5157 | QualType Canonical, bool Dependent, |
5158 | bool InstantiationDependent, bool VariablyModified, |
5159 | bool ContainsUnexpandedParameterPack) |
5160 | : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified, |
5161 | ContainsUnexpandedParameterPack) { |
5162 | TypeWithKeywordBits.Keyword = Keyword; |
5163 | } |
5164 | |
5165 | public: |
5166 | ElaboratedTypeKeyword getKeyword() const { |
5167 | return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword); |
5168 | } |
5169 | |
5170 | /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword. |
5171 | static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec); |
5172 | |
5173 | /// Converts a type specifier (DeclSpec::TST) into a tag type kind. |
5174 | /// It is an error to provide a type specifier which *isn't* a tag kind here. |
5175 | static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec); |
5176 | |
5177 | /// Converts a TagTypeKind into an elaborated type keyword. |
5178 | static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag); |
5179 | |
5180 | /// Converts an elaborated type keyword into a TagTypeKind. |
5181 | /// It is an error to provide an elaborated type keyword |
5182 | /// which *isn't* a tag kind here. |
5183 | static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword); |
5184 | |
5185 | static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword); |
5186 | |
5187 | static StringRef getKeywordName(ElaboratedTypeKeyword Keyword); |
5188 | |
5189 | static StringRef getTagTypeKindName(TagTypeKind Kind) { |
5190 | return getKeywordName(getKeywordForTagTypeKind(Kind)); |
5191 | } |
5192 | |
5193 | class CannotCastToThisType {}; |
5194 | static CannotCastToThisType classof(const Type *); |
5195 | }; |
5196 | |
5197 | /// Represents a type that was referred to using an elaborated type |
5198 | /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type, |
5199 | /// or both. |
5200 | /// |
5201 | /// This type is used to keep track of a type name as written in the |
5202 | /// source code, including tag keywords and any nested-name-specifiers. |
5203 | /// The type itself is always "sugar", used to express what was written |
5204 | /// in the source code but containing no additional semantic information. |
5205 | class ElaboratedType final |
5206 | : public TypeWithKeyword, |
5207 | public llvm::FoldingSetNode, |
5208 | private llvm::TrailingObjects<ElaboratedType, TagDecl *> { |
5209 | friend class ASTContext; // ASTContext creates these |
5210 | friend TrailingObjects; |
5211 | |
5212 | /// The nested name specifier containing the qualifier. |
5213 | NestedNameSpecifier *NNS; |
5214 | |
5215 | /// The type that this qualified name refers to. |
5216 | QualType NamedType; |
5217 | |
5218 | /// The (re)declaration of this tag type owned by this occurrence is stored |
5219 | /// as a trailing object if there is one. Use getOwnedTagDecl to obtain |
5220 | /// it, or obtain a null pointer if there is none. |
5221 | |
5222 | ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5223 | QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl) |
5224 | : TypeWithKeyword(Keyword, Elaborated, CanonType, |
5225 | NamedType->isDependentType(), |
5226 | NamedType->isInstantiationDependentType(), |
5227 | NamedType->isVariablyModifiedType(), |
5228 | NamedType->containsUnexpandedParameterPack()), |
5229 | NNS(NNS), NamedType(NamedType) { |
5230 | ElaboratedTypeBits.HasOwnedTagDecl = false; |
5231 | if (OwnedTagDecl) { |
5232 | ElaboratedTypeBits.HasOwnedTagDecl = true; |
5233 | *getTrailingObjects<TagDecl *>() = OwnedTagDecl; |
5234 | } |
5235 | assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5237, __PRETTY_FUNCTION__)) |
5236 | "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5237, __PRETTY_FUNCTION__)) |
5237 | "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) && "ElaboratedType cannot have elaborated type keyword " "and name qualifier both null." ) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5237, __PRETTY_FUNCTION__)); |
5238 | } |
5239 | |
5240 | public: |
5241 | /// Retrieve the qualification on this type. |
5242 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5243 | |
5244 | /// Retrieve the type named by the qualified-id. |
5245 | QualType getNamedType() const { return NamedType; } |
5246 | |
5247 | /// Remove a single level of sugar. |
5248 | QualType desugar() const { return getNamedType(); } |
5249 | |
5250 | /// Returns whether this type directly provides sugar. |
5251 | bool isSugared() const { return true; } |
5252 | |
5253 | /// Return the (re)declaration of this type owned by this occurrence of this |
5254 | /// type, or nullptr if there is none. |
5255 | TagDecl *getOwnedTagDecl() const { |
5256 | return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>() |
5257 | : nullptr; |
5258 | } |
5259 | |
5260 | void Profile(llvm::FoldingSetNodeID &ID) { |
5261 | Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl()); |
5262 | } |
5263 | |
5264 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5265 | NestedNameSpecifier *NNS, QualType NamedType, |
5266 | TagDecl *OwnedTagDecl) { |
5267 | ID.AddInteger(Keyword); |
5268 | ID.AddPointer(NNS); |
5269 | NamedType.Profile(ID); |
5270 | ID.AddPointer(OwnedTagDecl); |
5271 | } |
5272 | |
5273 | static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; } |
5274 | }; |
5275 | |
5276 | /// Represents a qualified type name for which the type name is |
5277 | /// dependent. |
5278 | /// |
5279 | /// DependentNameType represents a class of dependent types that involve a |
5280 | /// possibly dependent nested-name-specifier (e.g., "T::") followed by a |
5281 | /// name of a type. The DependentNameType may start with a "typename" (for a |
5282 | /// typename-specifier), "class", "struct", "union", or "enum" (for a |
5283 | /// dependent elaborated-type-specifier), or nothing (in contexts where we |
5284 | /// know that we must be referring to a type, e.g., in a base class specifier). |
5285 | /// Typically the nested-name-specifier is dependent, but in MSVC compatibility |
5286 | /// mode, this type is used with non-dependent names to delay name lookup until |
5287 | /// instantiation. |
5288 | class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode { |
5289 | friend class ASTContext; // ASTContext creates these |
5290 | |
5291 | /// The nested name specifier containing the qualifier. |
5292 | NestedNameSpecifier *NNS; |
5293 | |
5294 | /// The type that this typename specifier refers to. |
5295 | const IdentifierInfo *Name; |
5296 | |
5297 | DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, |
5298 | const IdentifierInfo *Name, QualType CanonType) |
5299 | : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true, |
5300 | /*InstantiationDependent=*/true, |
5301 | /*VariablyModified=*/false, |
5302 | NNS->containsUnexpandedParameterPack()), |
5303 | NNS(NNS), Name(Name) {} |
5304 | |
5305 | public: |
5306 | /// Retrieve the qualification on this type. |
5307 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5308 | |
5309 | /// Retrieve the type named by the typename specifier as an identifier. |
5310 | /// |
5311 | /// This routine will return a non-NULL identifier pointer when the |
5312 | /// form of the original typename was terminated by an identifier, |
5313 | /// e.g., "typename T::type". |
5314 | const IdentifierInfo *getIdentifier() const { |
5315 | return Name; |
5316 | } |
5317 | |
5318 | bool isSugared() const { return false; } |
5319 | QualType desugar() const { return QualType(this, 0); } |
5320 | |
5321 | void Profile(llvm::FoldingSetNodeID &ID) { |
5322 | Profile(ID, getKeyword(), NNS, Name); |
5323 | } |
5324 | |
5325 | static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword, |
5326 | NestedNameSpecifier *NNS, const IdentifierInfo *Name) { |
5327 | ID.AddInteger(Keyword); |
5328 | ID.AddPointer(NNS); |
5329 | ID.AddPointer(Name); |
5330 | } |
5331 | |
5332 | static bool classof(const Type *T) { |
5333 | return T->getTypeClass() == DependentName; |
5334 | } |
5335 | }; |
5336 | |
5337 | /// Represents a template specialization type whose template cannot be |
5338 | /// resolved, e.g. |
5339 | /// A<T>::template B<T> |
5340 | class alignas(8) DependentTemplateSpecializationType |
5341 | : public TypeWithKeyword, |
5342 | public llvm::FoldingSetNode { |
5343 | friend class ASTContext; // ASTContext creates these |
5344 | |
5345 | /// The nested name specifier containing the qualifier. |
5346 | NestedNameSpecifier *NNS; |
5347 | |
5348 | /// The identifier of the template. |
5349 | const IdentifierInfo *Name; |
5350 | |
5351 | DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, |
5352 | NestedNameSpecifier *NNS, |
5353 | const IdentifierInfo *Name, |
5354 | ArrayRef<TemplateArgument> Args, |
5355 | QualType Canon); |
5356 | |
5357 | const TemplateArgument *getArgBuffer() const { |
5358 | return reinterpret_cast<const TemplateArgument*>(this+1); |
5359 | } |
5360 | |
5361 | TemplateArgument *getArgBuffer() { |
5362 | return reinterpret_cast<TemplateArgument*>(this+1); |
5363 | } |
5364 | |
5365 | public: |
5366 | NestedNameSpecifier *getQualifier() const { return NNS; } |
5367 | const IdentifierInfo *getIdentifier() const { return Name; } |
5368 | |
5369 | /// Retrieve the template arguments. |
5370 | const TemplateArgument *getArgs() const { |
5371 | return getArgBuffer(); |
5372 | } |
5373 | |
5374 | /// Retrieve the number of template arguments. |
5375 | unsigned getNumArgs() const { |
5376 | return DependentTemplateSpecializationTypeBits.NumArgs; |
5377 | } |
5378 | |
5379 | const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h |
5380 | |
5381 | ArrayRef<TemplateArgument> template_arguments() const { |
5382 | return {getArgs(), getNumArgs()}; |
5383 | } |
5384 | |
5385 | using iterator = const TemplateArgument *; |
5386 | |
5387 | iterator begin() const { return getArgs(); } |
5388 | iterator end() const; // inline in TemplateBase.h |
5389 | |
5390 | bool isSugared() const { return false; } |
5391 | QualType desugar() const { return QualType(this, 0); } |
5392 | |
5393 | void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) { |
5394 | Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()}); |
5395 | } |
5396 | |
5397 | static void Profile(llvm::FoldingSetNodeID &ID, |
5398 | const ASTContext &Context, |
5399 | ElaboratedTypeKeyword Keyword, |
5400 | NestedNameSpecifier *Qualifier, |
5401 | const IdentifierInfo *Name, |
5402 | ArrayRef<TemplateArgument> Args); |
5403 | |
5404 | static bool classof(const Type *T) { |
5405 | return T->getTypeClass() == DependentTemplateSpecialization; |
5406 | } |
5407 | }; |
5408 | |
5409 | /// Represents a pack expansion of types. |
5410 | /// |
5411 | /// Pack expansions are part of C++11 variadic templates. A pack |
5412 | /// expansion contains a pattern, which itself contains one or more |
5413 | /// "unexpanded" parameter packs. When instantiated, a pack expansion |
5414 | /// produces a series of types, each instantiated from the pattern of |
5415 | /// the expansion, where the Ith instantiation of the pattern uses the |
5416 | /// Ith arguments bound to each of the unexpanded parameter packs. The |
5417 | /// pack expansion is considered to "expand" these unexpanded |
5418 | /// parameter packs. |
5419 | /// |
5420 | /// \code |
5421 | /// template<typename ...Types> struct tuple; |
5422 | /// |
5423 | /// template<typename ...Types> |
5424 | /// struct tuple_of_references { |
5425 | /// typedef tuple<Types&...> type; |
5426 | /// }; |
5427 | /// \endcode |
5428 | /// |
5429 | /// Here, the pack expansion \c Types&... is represented via a |
5430 | /// PackExpansionType whose pattern is Types&. |
5431 | class PackExpansionType : public Type, public llvm::FoldingSetNode { |
5432 | friend class ASTContext; // ASTContext creates these |
5433 | |
5434 | /// The pattern of the pack expansion. |
5435 | QualType Pattern; |
5436 | |
5437 | PackExpansionType(QualType Pattern, QualType Canon, |
5438 | Optional<unsigned> NumExpansions) |
5439 | : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(), |
5440 | /*InstantiationDependent=*/true, |
5441 | /*VariablyModified=*/Pattern->isVariablyModifiedType(), |
5442 | /*ContainsUnexpandedParameterPack=*/false), |
5443 | Pattern(Pattern) { |
5444 | PackExpansionTypeBits.NumExpansions = |
5445 | NumExpansions ? *NumExpansions + 1 : 0; |
5446 | } |
5447 | |
5448 | public: |
5449 | /// Retrieve the pattern of this pack expansion, which is the |
5450 | /// type that will be repeatedly instantiated when instantiating the |
5451 | /// pack expansion itself. |
5452 | QualType getPattern() const { return Pattern; } |
5453 | |
5454 | /// Retrieve the number of expansions that this pack expansion will |
5455 | /// generate, if known. |
5456 | Optional<unsigned> getNumExpansions() const { |
5457 | if (PackExpansionTypeBits.NumExpansions) |
5458 | return PackExpansionTypeBits.NumExpansions - 1; |
5459 | return None; |
5460 | } |
5461 | |
5462 | bool isSugared() const { return !Pattern->isDependentType(); } |
5463 | QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); } |
5464 | |
5465 | void Profile(llvm::FoldingSetNodeID &ID) { |
5466 | Profile(ID, getPattern(), getNumExpansions()); |
5467 | } |
5468 | |
5469 | static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern, |
5470 | Optional<unsigned> NumExpansions) { |
5471 | ID.AddPointer(Pattern.getAsOpaquePtr()); |
5472 | ID.AddBoolean(NumExpansions.hasValue()); |
5473 | if (NumExpansions) |
5474 | ID.AddInteger(*NumExpansions); |
5475 | } |
5476 | |
5477 | static bool classof(const Type *T) { |
5478 | return T->getTypeClass() == PackExpansion; |
5479 | } |
5480 | }; |
5481 | |
5482 | /// This class wraps the list of protocol qualifiers. For types that can |
5483 | /// take ObjC protocol qualifers, they can subclass this class. |
5484 | template <class T> |
5485 | class ObjCProtocolQualifiers { |
5486 | protected: |
5487 | ObjCProtocolQualifiers() = default; |
5488 | |
5489 | ObjCProtocolDecl * const *getProtocolStorage() const { |
5490 | return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage(); |
5491 | } |
5492 | |
5493 | ObjCProtocolDecl **getProtocolStorage() { |
5494 | return static_cast<T*>(this)->getProtocolStorageImpl(); |
5495 | } |
5496 | |
5497 | void setNumProtocols(unsigned N) { |
5498 | static_cast<T*>(this)->setNumProtocolsImpl(N); |
5499 | } |
5500 | |
5501 | void initialize(ArrayRef<ObjCProtocolDecl *> protocols) { |
5502 | setNumProtocols(protocols.size()); |
5503 | assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count" ) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5504, __PRETTY_FUNCTION__)) |
5504 | "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count" ) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5504, __PRETTY_FUNCTION__)); |
5505 | if (!protocols.empty()) |
5506 | memcpy(getProtocolStorage(), protocols.data(), |
5507 | protocols.size() * sizeof(ObjCProtocolDecl*)); |
5508 | } |
5509 | |
5510 | public: |
5511 | using qual_iterator = ObjCProtocolDecl * const *; |
5512 | using qual_range = llvm::iterator_range<qual_iterator>; |
5513 | |
5514 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5515 | qual_iterator qual_begin() const { return getProtocolStorage(); } |
5516 | qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); } |
5517 | |
5518 | bool qual_empty() const { return getNumProtocols() == 0; } |
5519 | |
5520 | /// Return the number of qualifying protocols in this type, or 0 if |
5521 | /// there are none. |
5522 | unsigned getNumProtocols() const { |
5523 | return static_cast<const T*>(this)->getNumProtocolsImpl(); |
5524 | } |
5525 | |
5526 | /// Fetch a protocol by index. |
5527 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
5528 | assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access" ) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5528, __PRETTY_FUNCTION__)); |
5529 | return qual_begin()[I]; |
5530 | } |
5531 | |
5532 | /// Retrieve all of the protocol qualifiers. |
5533 | ArrayRef<ObjCProtocolDecl *> getProtocols() const { |
5534 | return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols()); |
5535 | } |
5536 | }; |
5537 | |
5538 | /// Represents a type parameter type in Objective C. It can take |
5539 | /// a list of protocols. |
5540 | class ObjCTypeParamType : public Type, |
5541 | public ObjCProtocolQualifiers<ObjCTypeParamType>, |
5542 | public llvm::FoldingSetNode { |
5543 | friend class ASTContext; |
5544 | friend class ObjCProtocolQualifiers<ObjCTypeParamType>; |
5545 | |
5546 | /// The number of protocols stored on this type. |
5547 | unsigned NumProtocols : 6; |
5548 | |
5549 | ObjCTypeParamDecl *OTPDecl; |
5550 | |
5551 | /// The protocols are stored after the ObjCTypeParamType node. In the |
5552 | /// canonical type, the list of protocols are sorted alphabetically |
5553 | /// and uniqued. |
5554 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5555 | |
5556 | /// Return the number of qualifying protocols in this interface type, |
5557 | /// or 0 if there are none. |
5558 | unsigned getNumProtocolsImpl() const { |
5559 | return NumProtocols; |
5560 | } |
5561 | |
5562 | void setNumProtocolsImpl(unsigned N) { |
5563 | NumProtocols = N; |
5564 | } |
5565 | |
5566 | ObjCTypeParamType(const ObjCTypeParamDecl *D, |
5567 | QualType can, |
5568 | ArrayRef<ObjCProtocolDecl *> protocols); |
5569 | |
5570 | public: |
5571 | bool isSugared() const { return true; } |
5572 | QualType desugar() const { return getCanonicalTypeInternal(); } |
5573 | |
5574 | static bool classof(const Type *T) { |
5575 | return T->getTypeClass() == ObjCTypeParam; |
5576 | } |
5577 | |
5578 | void Profile(llvm::FoldingSetNodeID &ID); |
5579 | static void Profile(llvm::FoldingSetNodeID &ID, |
5580 | const ObjCTypeParamDecl *OTPDecl, |
5581 | ArrayRef<ObjCProtocolDecl *> protocols); |
5582 | |
5583 | ObjCTypeParamDecl *getDecl() const { return OTPDecl; } |
5584 | }; |
5585 | |
5586 | /// Represents a class type in Objective C. |
5587 | /// |
5588 | /// Every Objective C type is a combination of a base type, a set of |
5589 | /// type arguments (optional, for parameterized classes) and a list of |
5590 | /// protocols. |
5591 | /// |
5592 | /// Given the following declarations: |
5593 | /// \code |
5594 | /// \@class C<T>; |
5595 | /// \@protocol P; |
5596 | /// \endcode |
5597 | /// |
5598 | /// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType |
5599 | /// with base C and no protocols. |
5600 | /// |
5601 | /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P]. |
5602 | /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no |
5603 | /// protocol list. |
5604 | /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*', |
5605 | /// and protocol list [P]. |
5606 | /// |
5607 | /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose |
5608 | /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType |
5609 | /// and no protocols. |
5610 | /// |
5611 | /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType |
5612 | /// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually |
5613 | /// this should get its own sugar class to better represent the source. |
5614 | class ObjCObjectType : public Type, |
5615 | public ObjCProtocolQualifiers<ObjCObjectType> { |
5616 | friend class ObjCProtocolQualifiers<ObjCObjectType>; |
5617 | |
5618 | // ObjCObjectType.NumTypeArgs - the number of type arguments stored |
5619 | // after the ObjCObjectPointerType node. |
5620 | // ObjCObjectType.NumProtocols - the number of protocols stored |
5621 | // after the type arguments of ObjCObjectPointerType node. |
5622 | // |
5623 | // These protocols are those written directly on the type. If |
5624 | // protocol qualifiers ever become additive, the iterators will need |
5625 | // to get kindof complicated. |
5626 | // |
5627 | // In the canonical object type, these are sorted alphabetically |
5628 | // and uniqued. |
5629 | |
5630 | /// Either a BuiltinType or an InterfaceType or sugar for either. |
5631 | QualType BaseType; |
5632 | |
5633 | /// Cached superclass type. |
5634 | mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool> |
5635 | CachedSuperClassType; |
5636 | |
5637 | QualType *getTypeArgStorage(); |
5638 | const QualType *getTypeArgStorage() const { |
5639 | return const_cast<ObjCObjectType *>(this)->getTypeArgStorage(); |
5640 | } |
5641 | |
5642 | ObjCProtocolDecl **getProtocolStorageImpl(); |
5643 | /// Return the number of qualifying protocols in this interface type, |
5644 | /// or 0 if there are none. |
5645 | unsigned getNumProtocolsImpl() const { |
5646 | return ObjCObjectTypeBits.NumProtocols; |
5647 | } |
5648 | void setNumProtocolsImpl(unsigned N) { |
5649 | ObjCObjectTypeBits.NumProtocols = N; |
5650 | } |
5651 | |
5652 | protected: |
5653 | enum Nonce_ObjCInterface { Nonce_ObjCInterface }; |
5654 | |
5655 | ObjCObjectType(QualType Canonical, QualType Base, |
5656 | ArrayRef<QualType> typeArgs, |
5657 | ArrayRef<ObjCProtocolDecl *> protocols, |
5658 | bool isKindOf); |
5659 | |
5660 | ObjCObjectType(enum Nonce_ObjCInterface) |
5661 | : Type(ObjCInterface, QualType(), false, false, false, false), |
5662 | BaseType(QualType(this_(), 0)) { |
5663 | ObjCObjectTypeBits.NumProtocols = 0; |
5664 | ObjCObjectTypeBits.NumTypeArgs = 0; |
5665 | ObjCObjectTypeBits.IsKindOf = 0; |
5666 | } |
5667 | |
5668 | void computeSuperClassTypeSlow() const; |
5669 | |
5670 | public: |
5671 | /// Gets the base type of this object type. This is always (possibly |
5672 | /// sugar for) one of: |
5673 | /// - the 'id' builtin type (as opposed to the 'id' type visible to the |
5674 | /// user, which is a typedef for an ObjCObjectPointerType) |
5675 | /// - the 'Class' builtin type (same caveat) |
5676 | /// - an ObjCObjectType (currently always an ObjCInterfaceType) |
5677 | QualType getBaseType() const { return BaseType; } |
5678 | |
5679 | bool isObjCId() const { |
5680 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId); |
5681 | } |
5682 | |
5683 | bool isObjCClass() const { |
5684 | return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass); |
5685 | } |
5686 | |
5687 | bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); } |
5688 | bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); } |
5689 | bool isObjCUnqualifiedIdOrClass() const { |
5690 | if (!qual_empty()) return false; |
5691 | if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>()) |
5692 | return T->getKind() == BuiltinType::ObjCId || |
5693 | T->getKind() == BuiltinType::ObjCClass; |
5694 | return false; |
5695 | } |
5696 | bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); } |
5697 | bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); } |
5698 | |
5699 | /// Gets the interface declaration for this object type, if the base type |
5700 | /// really is an interface. |
5701 | ObjCInterfaceDecl *getInterface() const; |
5702 | |
5703 | /// Determine whether this object type is "specialized", meaning |
5704 | /// that it has type arguments. |
5705 | bool isSpecialized() const; |
5706 | |
5707 | /// Determine whether this object type was written with type arguments. |
5708 | bool isSpecializedAsWritten() const { |
5709 | return ObjCObjectTypeBits.NumTypeArgs > 0; |
5710 | } |
5711 | |
5712 | /// Determine whether this object type is "unspecialized", meaning |
5713 | /// that it has no type arguments. |
5714 | bool isUnspecialized() const { return !isSpecialized(); } |
5715 | |
5716 | /// Determine whether this object type is "unspecialized" as |
5717 | /// written, meaning that it has no type arguments. |
5718 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5719 | |
5720 | /// Retrieve the type arguments of this object type (semantically). |
5721 | ArrayRef<QualType> getTypeArgs() const; |
5722 | |
5723 | /// Retrieve the type arguments of this object type as they were |
5724 | /// written. |
5725 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5726 | return llvm::makeArrayRef(getTypeArgStorage(), |
5727 | ObjCObjectTypeBits.NumTypeArgs); |
5728 | } |
5729 | |
5730 | /// Whether this is a "__kindof" type as written. |
5731 | bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; } |
5732 | |
5733 | /// Whether this ia a "__kindof" type (semantically). |
5734 | bool isKindOfType() const; |
5735 | |
5736 | /// Retrieve the type of the superclass of this object type. |
5737 | /// |
5738 | /// This operation substitutes any type arguments into the |
5739 | /// superclass of the current class type, potentially producing a |
5740 | /// specialization of the superclass type. Produces a null type if |
5741 | /// there is no superclass. |
5742 | QualType getSuperClassType() const { |
5743 | if (!CachedSuperClassType.getInt()) |
5744 | computeSuperClassTypeSlow(); |
5745 | |
5746 | assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?" ) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 5746, __PRETTY_FUNCTION__)); |
5747 | return QualType(CachedSuperClassType.getPointer(), 0); |
5748 | } |
5749 | |
5750 | /// Strip off the Objective-C "kindof" type and (with it) any |
5751 | /// protocol qualifiers. |
5752 | QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const; |
5753 | |
5754 | bool isSugared() const { return false; } |
5755 | QualType desugar() const { return QualType(this, 0); } |
5756 | |
5757 | static bool classof(const Type *T) { |
5758 | return T->getTypeClass() == ObjCObject || |
5759 | T->getTypeClass() == ObjCInterface; |
5760 | } |
5761 | }; |
5762 | |
5763 | /// A class providing a concrete implementation |
5764 | /// of ObjCObjectType, so as to not increase the footprint of |
5765 | /// ObjCInterfaceType. Code outside of ASTContext and the core type |
5766 | /// system should not reference this type. |
5767 | class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode { |
5768 | friend class ASTContext; |
5769 | |
5770 | // If anyone adds fields here, ObjCObjectType::getProtocolStorage() |
5771 | // will need to be modified. |
5772 | |
5773 | ObjCObjectTypeImpl(QualType Canonical, QualType Base, |
5774 | ArrayRef<QualType> typeArgs, |
5775 | ArrayRef<ObjCProtocolDecl *> protocols, |
5776 | bool isKindOf) |
5777 | : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {} |
5778 | |
5779 | public: |
5780 | void Profile(llvm::FoldingSetNodeID &ID); |
5781 | static void Profile(llvm::FoldingSetNodeID &ID, |
5782 | QualType Base, |
5783 | ArrayRef<QualType> typeArgs, |
5784 | ArrayRef<ObjCProtocolDecl *> protocols, |
5785 | bool isKindOf); |
5786 | }; |
5787 | |
5788 | inline QualType *ObjCObjectType::getTypeArgStorage() { |
5789 | return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1); |
5790 | } |
5791 | |
5792 | inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() { |
5793 | return reinterpret_cast<ObjCProtocolDecl**>( |
5794 | getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs); |
5795 | } |
5796 | |
5797 | inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() { |
5798 | return reinterpret_cast<ObjCProtocolDecl**>( |
5799 | static_cast<ObjCTypeParamType*>(this)+1); |
5800 | } |
5801 | |
5802 | /// Interfaces are the core concept in Objective-C for object oriented design. |
5803 | /// They basically correspond to C++ classes. There are two kinds of interface |
5804 | /// types: normal interfaces like `NSString`, and qualified interfaces, which |
5805 | /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`. |
5806 | /// |
5807 | /// ObjCInterfaceType guarantees the following properties when considered |
5808 | /// as a subtype of its superclass, ObjCObjectType: |
5809 | /// - There are no protocol qualifiers. To reinforce this, code which |
5810 | /// tries to invoke the protocol methods via an ObjCInterfaceType will |
5811 | /// fail to compile. |
5812 | /// - It is its own base type. That is, if T is an ObjCInterfaceType*, |
5813 | /// T->getBaseType() == QualType(T, 0). |
5814 | class ObjCInterfaceType : public ObjCObjectType { |
5815 | friend class ASTContext; // ASTContext creates these. |
5816 | friend class ASTReader; |
5817 | friend class ObjCInterfaceDecl; |
5818 | |
5819 | mutable ObjCInterfaceDecl *Decl; |
5820 | |
5821 | ObjCInterfaceType(const ObjCInterfaceDecl *D) |
5822 | : ObjCObjectType(Nonce_ObjCInterface), |
5823 | Decl(const_cast<ObjCInterfaceDecl*>(D)) {} |
5824 | |
5825 | public: |
5826 | /// Get the declaration of this interface. |
5827 | ObjCInterfaceDecl *getDecl() const { return Decl; } |
5828 | |
5829 | bool isSugared() const { return false; } |
5830 | QualType desugar() const { return QualType(this, 0); } |
5831 | |
5832 | static bool classof(const Type *T) { |
5833 | return T->getTypeClass() == ObjCInterface; |
5834 | } |
5835 | |
5836 | // Nonsense to "hide" certain members of ObjCObjectType within this |
5837 | // class. People asking for protocols on an ObjCInterfaceType are |
5838 | // not going to get what they want: ObjCInterfaceTypes are |
5839 | // guaranteed to have no protocols. |
5840 | enum { |
5841 | qual_iterator, |
5842 | qual_begin, |
5843 | qual_end, |
5844 | getNumProtocols, |
5845 | getProtocol |
5846 | }; |
5847 | }; |
5848 | |
5849 | inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const { |
5850 | QualType baseType = getBaseType(); |
5851 | while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) { |
5852 | if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT)) |
5853 | return T->getDecl(); |
5854 | |
5855 | baseType = ObjT->getBaseType(); |
5856 | } |
5857 | |
5858 | return nullptr; |
5859 | } |
5860 | |
5861 | /// Represents a pointer to an Objective C object. |
5862 | /// |
5863 | /// These are constructed from pointer declarators when the pointee type is |
5864 | /// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class' |
5865 | /// types are typedefs for these, and the protocol-qualified types 'id<P>' |
5866 | /// and 'Class<P>' are translated into these. |
5867 | /// |
5868 | /// Pointers to pointers to Objective C objects are still PointerTypes; |
5869 | /// only the first level of pointer gets it own type implementation. |
5870 | class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode { |
5871 | friend class ASTContext; // ASTContext creates these. |
5872 | |
5873 | QualType PointeeType; |
5874 | |
5875 | ObjCObjectPointerType(QualType Canonical, QualType Pointee) |
5876 | : Type(ObjCObjectPointer, Canonical, |
5877 | Pointee->isDependentType(), |
5878 | Pointee->isInstantiationDependentType(), |
5879 | Pointee->isVariablyModifiedType(), |
5880 | Pointee->containsUnexpandedParameterPack()), |
5881 | PointeeType(Pointee) {} |
5882 | |
5883 | public: |
5884 | /// Gets the type pointed to by this ObjC pointer. |
5885 | /// The result will always be an ObjCObjectType or sugar thereof. |
5886 | QualType getPointeeType() const { return PointeeType; } |
5887 | |
5888 | /// Gets the type pointed to by this ObjC pointer. Always returns non-null. |
5889 | /// |
5890 | /// This method is equivalent to getPointeeType() except that |
5891 | /// it discards any typedefs (or other sugar) between this |
5892 | /// type and the "outermost" object type. So for: |
5893 | /// \code |
5894 | /// \@class A; \@protocol P; \@protocol Q; |
5895 | /// typedef A<P> AP; |
5896 | /// typedef A A1; |
5897 | /// typedef A1<P> A1P; |
5898 | /// typedef A1P<Q> A1PQ; |
5899 | /// \endcode |
5900 | /// For 'A*', getObjectType() will return 'A'. |
5901 | /// For 'A<P>*', getObjectType() will return 'A<P>'. |
5902 | /// For 'AP*', getObjectType() will return 'A<P>'. |
5903 | /// For 'A1*', getObjectType() will return 'A'. |
5904 | /// For 'A1<P>*', getObjectType() will return 'A1<P>'. |
5905 | /// For 'A1P*', getObjectType() will return 'A1<P>'. |
5906 | /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because |
5907 | /// adding protocols to a protocol-qualified base discards the |
5908 | /// old qualifiers (for now). But if it didn't, getObjectType() |
5909 | /// would return 'A1P<Q>' (and we'd have to make iterating over |
5910 | /// qualifiers more complicated). |
5911 | const ObjCObjectType *getObjectType() const { |
5912 | return PointeeType->castAs<ObjCObjectType>(); |
5913 | } |
5914 | |
5915 | /// If this pointer points to an Objective C |
5916 | /// \@interface type, gets the type for that interface. Any protocol |
5917 | /// qualifiers on the interface are ignored. |
5918 | /// |
5919 | /// \return null if the base type for this pointer is 'id' or 'Class' |
5920 | const ObjCInterfaceType *getInterfaceType() const; |
5921 | |
5922 | /// If this pointer points to an Objective \@interface |
5923 | /// type, gets the declaration for that interface. |
5924 | /// |
5925 | /// \return null if the base type for this pointer is 'id' or 'Class' |
5926 | ObjCInterfaceDecl *getInterfaceDecl() const { |
5927 | return getObjectType()->getInterface(); |
5928 | } |
5929 | |
5930 | /// True if this is equivalent to the 'id' type, i.e. if |
5931 | /// its object type is the primitive 'id' type with no protocols. |
5932 | bool isObjCIdType() const { |
5933 | return getObjectType()->isObjCUnqualifiedId(); |
5934 | } |
5935 | |
5936 | /// True if this is equivalent to the 'Class' type, |
5937 | /// i.e. if its object tive is the primitive 'Class' type with no protocols. |
5938 | bool isObjCClassType() const { |
5939 | return getObjectType()->isObjCUnqualifiedClass(); |
5940 | } |
5941 | |
5942 | /// True if this is equivalent to the 'id' or 'Class' type, |
5943 | bool isObjCIdOrClassType() const { |
5944 | return getObjectType()->isObjCUnqualifiedIdOrClass(); |
5945 | } |
5946 | |
5947 | /// True if this is equivalent to 'id<P>' for some non-empty set of |
5948 | /// protocols. |
5949 | bool isObjCQualifiedIdType() const { |
5950 | return getObjectType()->isObjCQualifiedId(); |
5951 | } |
5952 | |
5953 | /// True if this is equivalent to 'Class<P>' for some non-empty set of |
5954 | /// protocols. |
5955 | bool isObjCQualifiedClassType() const { |
5956 | return getObjectType()->isObjCQualifiedClass(); |
5957 | } |
5958 | |
5959 | /// Whether this is a "__kindof" type. |
5960 | bool isKindOfType() const { return getObjectType()->isKindOfType(); } |
5961 | |
5962 | /// Whether this type is specialized, meaning that it has type arguments. |
5963 | bool isSpecialized() const { return getObjectType()->isSpecialized(); } |
5964 | |
5965 | /// Whether this type is specialized, meaning that it has type arguments. |
5966 | bool isSpecializedAsWritten() const { |
5967 | return getObjectType()->isSpecializedAsWritten(); |
5968 | } |
5969 | |
5970 | /// Whether this type is unspecialized, meaning that is has no type arguments. |
5971 | bool isUnspecialized() const { return getObjectType()->isUnspecialized(); } |
5972 | |
5973 | /// Determine whether this object type is "unspecialized" as |
5974 | /// written, meaning that it has no type arguments. |
5975 | bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); } |
5976 | |
5977 | /// Retrieve the type arguments for this type. |
5978 | ArrayRef<QualType> getTypeArgs() const { |
5979 | return getObjectType()->getTypeArgs(); |
5980 | } |
5981 | |
5982 | /// Retrieve the type arguments for this type. |
5983 | ArrayRef<QualType> getTypeArgsAsWritten() const { |
5984 | return getObjectType()->getTypeArgsAsWritten(); |
5985 | } |
5986 | |
5987 | /// An iterator over the qualifiers on the object type. Provided |
5988 | /// for convenience. This will always iterate over the full set of |
5989 | /// protocols on a type, not just those provided directly. |
5990 | using qual_iterator = ObjCObjectType::qual_iterator; |
5991 | using qual_range = llvm::iterator_range<qual_iterator>; |
5992 | |
5993 | qual_range quals() const { return qual_range(qual_begin(), qual_end()); } |
5994 | |
5995 | qual_iterator qual_begin() const { |
5996 | return getObjectType()->qual_begin(); |
5997 | } |
5998 | |
5999 | qual_iterator qual_end() const { |
6000 | return getObjectType()->qual_end(); |
6001 | } |
6002 | |
6003 | bool qual_empty() const { return getObjectType()->qual_empty(); } |
6004 | |
6005 | /// Return the number of qualifying protocols on the object type. |
6006 | unsigned getNumProtocols() const { |
6007 | return getObjectType()->getNumProtocols(); |
6008 | } |
6009 | |
6010 | /// Retrieve a qualifying protocol by index on the object type. |
6011 | ObjCProtocolDecl *getProtocol(unsigned I) const { |
6012 | return getObjectType()->getProtocol(I); |
6013 | } |
6014 | |
6015 | bool isSugared() const { return false; } |
6016 | QualType desugar() const { return QualType(this, 0); } |
6017 | |
6018 | /// Retrieve the type of the superclass of this object pointer type. |
6019 | /// |
6020 | /// This operation substitutes any type arguments into the |
6021 | /// superclass of the current class type, potentially producing a |
6022 | /// pointer to a specialization of the superclass type. Produces a |
6023 | /// null type if there is no superclass. |
6024 | QualType getSuperClassType() const; |
6025 | |
6026 | /// Strip off the Objective-C "kindof" type and (with it) any |
6027 | /// protocol qualifiers. |
6028 | const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals( |
6029 | const ASTContext &ctx) const; |
6030 | |
6031 | void Profile(llvm::FoldingSetNodeID &ID) { |
6032 | Profile(ID, getPointeeType()); |
6033 | } |
6034 | |
6035 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6036 | ID.AddPointer(T.getAsOpaquePtr()); |
6037 | } |
6038 | |
6039 | static bool classof(const Type *T) { |
6040 | return T->getTypeClass() == ObjCObjectPointer; |
6041 | } |
6042 | }; |
6043 | |
6044 | class AtomicType : public Type, public llvm::FoldingSetNode { |
6045 | friend class ASTContext; // ASTContext creates these. |
6046 | |
6047 | QualType ValueType; |
6048 | |
6049 | AtomicType(QualType ValTy, QualType Canonical) |
6050 | : Type(Atomic, Canonical, ValTy->isDependentType(), |
6051 | ValTy->isInstantiationDependentType(), |
6052 | ValTy->isVariablyModifiedType(), |
6053 | ValTy->containsUnexpandedParameterPack()), |
6054 | ValueType(ValTy) {} |
6055 | |
6056 | public: |
6057 | /// Gets the type contained by this atomic type, i.e. |
6058 | /// the type returned by performing an atomic load of this atomic type. |
6059 | QualType getValueType() const { return ValueType; } |
6060 | |
6061 | bool isSugared() const { return false; } |
6062 | QualType desugar() const { return QualType(this, 0); } |
6063 | |
6064 | void Profile(llvm::FoldingSetNodeID &ID) { |
6065 | Profile(ID, getValueType()); |
6066 | } |
6067 | |
6068 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T) { |
6069 | ID.AddPointer(T.getAsOpaquePtr()); |
6070 | } |
6071 | |
6072 | static bool classof(const Type *T) { |
6073 | return T->getTypeClass() == Atomic; |
6074 | } |
6075 | }; |
6076 | |
6077 | /// PipeType - OpenCL20. |
6078 | class PipeType : public Type, public llvm::FoldingSetNode { |
6079 | friend class ASTContext; // ASTContext creates these. |
6080 | |
6081 | QualType ElementType; |
6082 | bool isRead; |
6083 | |
6084 | PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) |
6085 | : Type(Pipe, CanonicalPtr, elemType->isDependentType(), |
6086 | elemType->isInstantiationDependentType(), |
6087 | elemType->isVariablyModifiedType(), |
6088 | elemType->containsUnexpandedParameterPack()), |
6089 | ElementType(elemType), isRead(isRead) {} |
6090 | |
6091 | public: |
6092 | QualType getElementType() const { return ElementType; } |
6093 | |
6094 | bool isSugared() const { return false; } |
6095 | |
6096 | QualType desugar() const { return QualType(this, 0); } |
6097 | |
6098 | void Profile(llvm::FoldingSetNodeID &ID) { |
6099 | Profile(ID, getElementType(), isReadOnly()); |
6100 | } |
6101 | |
6102 | static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) { |
6103 | ID.AddPointer(T.getAsOpaquePtr()); |
6104 | ID.AddBoolean(isRead); |
6105 | } |
6106 | |
6107 | static bool classof(const Type *T) { |
6108 | return T->getTypeClass() == Pipe; |
6109 | } |
6110 | |
6111 | bool isReadOnly() const { return isRead; } |
6112 | }; |
6113 | |
6114 | /// A qualifier set is used to build a set of qualifiers. |
6115 | class QualifierCollector : public Qualifiers { |
6116 | public: |
6117 | QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {} |
6118 | |
6119 | /// Collect any qualifiers on the given type and return an |
6120 | /// unqualified type. The qualifiers are assumed to be consistent |
6121 | /// with those already in the type. |
6122 | const Type *strip(QualType type) { |
6123 | addFastQualifiers(type.getLocalFastQualifiers()); |
6124 | if (!type.hasLocalNonFastQualifiers()) |
6125 | return type.getTypePtrUnsafe(); |
6126 | |
6127 | const ExtQuals *extQuals = type.getExtQualsUnsafe(); |
6128 | addConsistentQualifiers(extQuals->getQualifiers()); |
6129 | return extQuals->getBaseType(); |
6130 | } |
6131 | |
6132 | /// Apply the collected qualifiers to the given type. |
6133 | QualType apply(const ASTContext &Context, QualType QT) const; |
6134 | |
6135 | /// Apply the collected qualifiers to the given type. |
6136 | QualType apply(const ASTContext &Context, const Type* T) const; |
6137 | }; |
6138 | |
6139 | // Inline function definitions. |
6140 | |
6141 | inline SplitQualType SplitQualType::getSingleStepDesugaredType() const { |
6142 | SplitQualType desugar = |
6143 | Ty->getLocallyUnqualifiedSingleStepDesugaredType().split(); |
6144 | desugar.Quals.addConsistentQualifiers(Quals); |
6145 | return desugar; |
6146 | } |
6147 | |
6148 | inline const Type *QualType::getTypePtr() const { |
6149 | return getCommonPtr()->BaseType; |
6150 | } |
6151 | |
6152 | inline const Type *QualType::getTypePtrOrNull() const { |
6153 | return (isNull() ? nullptr : getCommonPtr()->BaseType); |
6154 | } |
6155 | |
6156 | inline SplitQualType QualType::split() const { |
6157 | if (!hasLocalNonFastQualifiers()) |
6158 | return SplitQualType(getTypePtrUnsafe(), |
6159 | Qualifiers::fromFastMask(getLocalFastQualifiers())); |
6160 | |
6161 | const ExtQuals *eq = getExtQualsUnsafe(); |
6162 | Qualifiers qs = eq->getQualifiers(); |
6163 | qs.addFastQualifiers(getLocalFastQualifiers()); |
6164 | return SplitQualType(eq->getBaseType(), qs); |
6165 | } |
6166 | |
6167 | inline Qualifiers QualType::getLocalQualifiers() const { |
6168 | Qualifiers Quals; |
6169 | if (hasLocalNonFastQualifiers()) |
6170 | Quals = getExtQualsUnsafe()->getQualifiers(); |
6171 | Quals.addFastQualifiers(getLocalFastQualifiers()); |
6172 | return Quals; |
6173 | } |
6174 | |
6175 | inline Qualifiers QualType::getQualifiers() const { |
6176 | Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers(); |
6177 | quals.addFastQualifiers(getLocalFastQualifiers()); |
6178 | return quals; |
6179 | } |
6180 | |
6181 | inline unsigned QualType::getCVRQualifiers() const { |
6182 | unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers(); |
6183 | cvr |= getLocalCVRQualifiers(); |
6184 | return cvr; |
6185 | } |
6186 | |
6187 | inline QualType QualType::getCanonicalType() const { |
6188 | QualType canon = getCommonPtr()->CanonicalType; |
6189 | return canon.withFastQualifiers(getLocalFastQualifiers()); |
6190 | } |
6191 | |
6192 | inline bool QualType::isCanonical() const { |
6193 | return getTypePtr()->isCanonicalUnqualified(); |
6194 | } |
6195 | |
6196 | inline bool QualType::isCanonicalAsParam() const { |
6197 | if (!isCanonical()) return false; |
6198 | if (hasLocalQualifiers()) return false; |
6199 | |
6200 | const Type *T = getTypePtr(); |
6201 | if (T->isVariablyModifiedType() && T->hasSizedVLAType()) |
6202 | return false; |
6203 | |
6204 | return !isa<FunctionType>(T) && !isa<ArrayType>(T); |
6205 | } |
6206 | |
6207 | inline bool QualType::isConstQualified() const { |
6208 | return isLocalConstQualified() || |
6209 | getCommonPtr()->CanonicalType.isLocalConstQualified(); |
6210 | } |
6211 | |
6212 | inline bool QualType::isRestrictQualified() const { |
6213 | return isLocalRestrictQualified() || |
6214 | getCommonPtr()->CanonicalType.isLocalRestrictQualified(); |
6215 | } |
6216 | |
6217 | |
6218 | inline bool QualType::isVolatileQualified() const { |
6219 | return isLocalVolatileQualified() || |
6220 | getCommonPtr()->CanonicalType.isLocalVolatileQualified(); |
6221 | } |
6222 | |
6223 | inline bool QualType::hasQualifiers() const { |
6224 | return hasLocalQualifiers() || |
6225 | getCommonPtr()->CanonicalType.hasLocalQualifiers(); |
6226 | } |
6227 | |
6228 | inline QualType QualType::getUnqualifiedType() const { |
6229 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6230 | return QualType(getTypePtr(), 0); |
6231 | |
6232 | return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0); |
6233 | } |
6234 | |
6235 | inline SplitQualType QualType::getSplitUnqualifiedType() const { |
6236 | if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers()) |
6237 | return split(); |
6238 | |
6239 | return getSplitUnqualifiedTypeImpl(*this); |
6240 | } |
6241 | |
6242 | inline void QualType::removeLocalConst() { |
6243 | removeLocalFastQualifiers(Qualifiers::Const); |
6244 | } |
6245 | |
6246 | inline void QualType::removeLocalRestrict() { |
6247 | removeLocalFastQualifiers(Qualifiers::Restrict); |
6248 | } |
6249 | |
6250 | inline void QualType::removeLocalVolatile() { |
6251 | removeLocalFastQualifiers(Qualifiers::Volatile); |
6252 | } |
6253 | |
6254 | inline void QualType::removeLocalCVRQualifiers(unsigned Mask) { |
6255 | assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits" ) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\"" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6255, __PRETTY_FUNCTION__)); |
6256 | static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask, |
6257 | "Fast bits differ from CVR bits!"); |
6258 | |
6259 | // Fast path: we don't need to touch the slow qualifiers. |
6260 | removeLocalFastQualifiers(Mask); |
6261 | } |
6262 | |
6263 | /// Return the address space of this type. |
6264 | inline LangAS QualType::getAddressSpace() const { |
6265 | return getQualifiers().getAddressSpace(); |
6266 | } |
6267 | |
6268 | /// Return the gc attribute of this type. |
6269 | inline Qualifiers::GC QualType::getObjCGCAttr() const { |
6270 | return getQualifiers().getObjCGCAttr(); |
6271 | } |
6272 | |
6273 | inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { |
6274 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6275 | return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD); |
6276 | return false; |
6277 | } |
6278 | |
6279 | inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const { |
6280 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6281 | return hasNonTrivialToPrimitiveDestructCUnion(RD); |
6282 | return false; |
6283 | } |
6284 | |
6285 | inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const { |
6286 | if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl()) |
6287 | return hasNonTrivialToPrimitiveCopyCUnion(RD); |
6288 | return false; |
6289 | } |
6290 | |
6291 | inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) { |
6292 | if (const auto *PT = t.getAs<PointerType>()) { |
6293 | if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>()) |
6294 | return FT->getExtInfo(); |
6295 | } else if (const auto *FT = t.getAs<FunctionType>()) |
6296 | return FT->getExtInfo(); |
6297 | |
6298 | return FunctionType::ExtInfo(); |
6299 | } |
6300 | |
6301 | inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) { |
6302 | return getFunctionExtInfo(*t); |
6303 | } |
6304 | |
6305 | /// Determine whether this type is more |
6306 | /// qualified than the Other type. For example, "const volatile int" |
6307 | /// is more qualified than "const int", "volatile int", and |
6308 | /// "int". However, it is not more qualified than "const volatile |
6309 | /// int". |
6310 | inline bool QualType::isMoreQualifiedThan(QualType other) const { |
6311 | Qualifiers MyQuals = getQualifiers(); |
6312 | Qualifiers OtherQuals = other.getQualifiers(); |
6313 | return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals)); |
6314 | } |
6315 | |
6316 | /// Determine whether this type is at last |
6317 | /// as qualified as the Other type. For example, "const volatile |
6318 | /// int" is at least as qualified as "const int", "volatile int", |
6319 | /// "int", and "const volatile int". |
6320 | inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const { |
6321 | Qualifiers OtherQuals = other.getQualifiers(); |
6322 | |
6323 | // Ignore __unaligned qualifier if this type is a void. |
6324 | if (getUnqualifiedType()->isVoidType()) |
6325 | OtherQuals.removeUnaligned(); |
6326 | |
6327 | return getQualifiers().compatiblyIncludes(OtherQuals); |
6328 | } |
6329 | |
6330 | /// If Type is a reference type (e.g., const |
6331 | /// int&), returns the type that the reference refers to ("const |
6332 | /// int"). Otherwise, returns the type itself. This routine is used |
6333 | /// throughout Sema to implement C++ 5p6: |
6334 | /// |
6335 | /// If an expression initially has the type "reference to T" (8.3.2, |
6336 | /// 8.5.3), the type is adjusted to "T" prior to any further |
6337 | /// analysis, the expression designates the object or function |
6338 | /// denoted by the reference, and the expression is an lvalue. |
6339 | inline QualType QualType::getNonReferenceType() const { |
6340 | if (const auto *RefType = (*this)->getAs<ReferenceType>()) |
6341 | return RefType->getPointeeType(); |
6342 | else |
6343 | return *this; |
6344 | } |
6345 | |
6346 | inline bool QualType::isCForbiddenLValueType() const { |
6347 | return ((getTypePtr()->isVoidType() && !hasQualifiers()) || |
6348 | getTypePtr()->isFunctionType()); |
6349 | } |
6350 | |
6351 | /// Tests whether the type is categorized as a fundamental type. |
6352 | /// |
6353 | /// \returns True for types specified in C++0x [basic.fundamental]. |
6354 | inline bool Type::isFundamentalType() const { |
6355 | return isVoidType() || |
6356 | isNullPtrType() || |
6357 | // FIXME: It's really annoying that we don't have an |
6358 | // 'isArithmeticType()' which agrees with the standard definition. |
6359 | (isArithmeticType() && !isEnumeralType()); |
6360 | } |
6361 | |
6362 | /// Tests whether the type is categorized as a compound type. |
6363 | /// |
6364 | /// \returns True for types specified in C++0x [basic.compound]. |
6365 | inline bool Type::isCompoundType() const { |
6366 | // C++0x [basic.compound]p1: |
6367 | // Compound types can be constructed in the following ways: |
6368 | // -- arrays of objects of a given type [...]; |
6369 | return isArrayType() || |
6370 | // -- functions, which have parameters of given types [...]; |
6371 | isFunctionType() || |
6372 | // -- pointers to void or objects or functions [...]; |
6373 | isPointerType() || |
6374 | // -- references to objects or functions of a given type. [...] |
6375 | isReferenceType() || |
6376 | // -- classes containing a sequence of objects of various types, [...]; |
6377 | isRecordType() || |
6378 | // -- unions, which are classes capable of containing objects of different |
6379 | // types at different times; |
6380 | isUnionType() || |
6381 | // -- enumerations, which comprise a set of named constant values. [...]; |
6382 | isEnumeralType() || |
6383 | // -- pointers to non-static class members, [...]. |
6384 | isMemberPointerType(); |
6385 | } |
6386 | |
6387 | inline bool Type::isFunctionType() const { |
6388 | return isa<FunctionType>(CanonicalType); |
6389 | } |
6390 | |
6391 | inline bool Type::isPointerType() const { |
6392 | return isa<PointerType>(CanonicalType); |
6393 | } |
6394 | |
6395 | inline bool Type::isAnyPointerType() const { |
6396 | return isPointerType() || isObjCObjectPointerType(); |
6397 | } |
6398 | |
6399 | inline bool Type::isBlockPointerType() const { |
6400 | return isa<BlockPointerType>(CanonicalType); |
6401 | } |
6402 | |
6403 | inline bool Type::isReferenceType() const { |
6404 | return isa<ReferenceType>(CanonicalType); |
6405 | } |
6406 | |
6407 | inline bool Type::isLValueReferenceType() const { |
6408 | return isa<LValueReferenceType>(CanonicalType); |
6409 | } |
6410 | |
6411 | inline bool Type::isRValueReferenceType() const { |
6412 | return isa<RValueReferenceType>(CanonicalType); |
6413 | } |
6414 | |
6415 | inline bool Type::isFunctionPointerType() const { |
6416 | if (const auto *T = getAs<PointerType>()) |
6417 | return T->getPointeeType()->isFunctionType(); |
6418 | else |
6419 | return false; |
6420 | } |
6421 | |
6422 | inline bool Type::isFunctionReferenceType() const { |
6423 | if (const auto *T = getAs<ReferenceType>()) |
6424 | return T->getPointeeType()->isFunctionType(); |
6425 | else |
6426 | return false; |
6427 | } |
6428 | |
6429 | inline bool Type::isMemberPointerType() const { |
6430 | return isa<MemberPointerType>(CanonicalType); |
6431 | } |
6432 | |
6433 | inline bool Type::isMemberFunctionPointerType() const { |
6434 | if (const auto *T = getAs<MemberPointerType>()) |
6435 | return T->isMemberFunctionPointer(); |
6436 | else |
6437 | return false; |
6438 | } |
6439 | |
6440 | inline bool Type::isMemberDataPointerType() const { |
6441 | if (const auto *T = getAs<MemberPointerType>()) |
6442 | return T->isMemberDataPointer(); |
6443 | else |
6444 | return false; |
6445 | } |
6446 | |
6447 | inline bool Type::isArrayType() const { |
6448 | return isa<ArrayType>(CanonicalType); |
6449 | } |
6450 | |
6451 | inline bool Type::isConstantArrayType() const { |
6452 | return isa<ConstantArrayType>(CanonicalType); |
6453 | } |
6454 | |
6455 | inline bool Type::isIncompleteArrayType() const { |
6456 | return isa<IncompleteArrayType>(CanonicalType); |
6457 | } |
6458 | |
6459 | inline bool Type::isVariableArrayType() const { |
6460 | return isa<VariableArrayType>(CanonicalType); |
6461 | } |
6462 | |
6463 | inline bool Type::isDependentSizedArrayType() const { |
6464 | return isa<DependentSizedArrayType>(CanonicalType); |
6465 | } |
6466 | |
6467 | inline bool Type::isBuiltinType() const { |
6468 | return isa<BuiltinType>(CanonicalType); |
6469 | } |
6470 | |
6471 | inline bool Type::isRecordType() const { |
6472 | return isa<RecordType>(CanonicalType); |
6473 | } |
6474 | |
6475 | inline bool Type::isEnumeralType() const { |
6476 | return isa<EnumType>(CanonicalType); |
6477 | } |
6478 | |
6479 | inline bool Type::isAnyComplexType() const { |
6480 | return isa<ComplexType>(CanonicalType); |
6481 | } |
6482 | |
6483 | inline bool Type::isVectorType() const { |
6484 | return isa<VectorType>(CanonicalType); |
6485 | } |
6486 | |
6487 | inline bool Type::isExtVectorType() const { |
6488 | return isa<ExtVectorType>(CanonicalType); |
6489 | } |
6490 | |
6491 | inline bool Type::isDependentAddressSpaceType() const { |
6492 | return isa<DependentAddressSpaceType>(CanonicalType); |
6493 | } |
6494 | |
6495 | inline bool Type::isObjCObjectPointerType() const { |
6496 | return isa<ObjCObjectPointerType>(CanonicalType); |
6497 | } |
6498 | |
6499 | inline bool Type::isObjCObjectType() const { |
6500 | return isa<ObjCObjectType>(CanonicalType); |
6501 | } |
6502 | |
6503 | inline bool Type::isObjCObjectOrInterfaceType() const { |
6504 | return isa<ObjCInterfaceType>(CanonicalType) || |
6505 | isa<ObjCObjectType>(CanonicalType); |
6506 | } |
6507 | |
6508 | inline bool Type::isAtomicType() const { |
6509 | return isa<AtomicType>(CanonicalType); |
6510 | } |
6511 | |
6512 | inline bool Type::isObjCQualifiedIdType() const { |
6513 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6514 | return OPT->isObjCQualifiedIdType(); |
6515 | return false; |
6516 | } |
6517 | |
6518 | inline bool Type::isObjCQualifiedClassType() const { |
6519 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6520 | return OPT->isObjCQualifiedClassType(); |
6521 | return false; |
6522 | } |
6523 | |
6524 | inline bool Type::isObjCIdType() const { |
6525 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6526 | return OPT->isObjCIdType(); |
6527 | return false; |
6528 | } |
6529 | |
6530 | inline bool Type::isObjCClassType() const { |
6531 | if (const auto *OPT = getAs<ObjCObjectPointerType>()) |
6532 | return OPT->isObjCClassType(); |
6533 | return false; |
6534 | } |
6535 | |
6536 | inline bool Type::isObjCSelType() const { |
6537 | if (const auto *OPT = getAs<PointerType>()) |
6538 | return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel); |
6539 | return false; |
6540 | } |
6541 | |
6542 | inline bool Type::isObjCBuiltinType() const { |
6543 | return isObjCIdType() || isObjCClassType() || isObjCSelType(); |
6544 | } |
6545 | |
6546 | inline bool Type::isDecltypeType() const { |
6547 | return isa<DecltypeType>(this); |
6548 | } |
6549 | |
6550 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ |
6551 | inline bool Type::is##Id##Type() const { \ |
6552 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6553 | } |
6554 | #include "clang/Basic/OpenCLImageTypes.def" |
6555 | |
6556 | inline bool Type::isSamplerT() const { |
6557 | return isSpecificBuiltinType(BuiltinType::OCLSampler); |
6558 | } |
6559 | |
6560 | inline bool Type::isEventT() const { |
6561 | return isSpecificBuiltinType(BuiltinType::OCLEvent); |
6562 | } |
6563 | |
6564 | inline bool Type::isClkEventT() const { |
6565 | return isSpecificBuiltinType(BuiltinType::OCLClkEvent); |
6566 | } |
6567 | |
6568 | inline bool Type::isQueueT() const { |
6569 | return isSpecificBuiltinType(BuiltinType::OCLQueue); |
6570 | } |
6571 | |
6572 | inline bool Type::isReserveIDT() const { |
6573 | return isSpecificBuiltinType(BuiltinType::OCLReserveID); |
6574 | } |
6575 | |
6576 | inline bool Type::isImageType() const { |
6577 | #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() || |
6578 | return |
6579 | #include "clang/Basic/OpenCLImageTypes.def" |
6580 | false; // end boolean or operation |
6581 | } |
6582 | |
6583 | inline bool Type::isPipeType() const { |
6584 | return isa<PipeType>(CanonicalType); |
6585 | } |
6586 | |
6587 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ |
6588 | inline bool Type::is##Id##Type() const { \ |
6589 | return isSpecificBuiltinType(BuiltinType::Id); \ |
6590 | } |
6591 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6592 | |
6593 | inline bool Type::isOCLIntelSubgroupAVCType() const { |
6594 | #define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \ |
6595 | isOCLIntelSubgroupAVC##Id##Type() || |
6596 | return |
6597 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6598 | false; // end of boolean or operation |
6599 | } |
6600 | |
6601 | inline bool Type::isOCLExtOpaqueType() const { |
6602 | #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() || |
6603 | return |
6604 | #include "clang/Basic/OpenCLExtensionTypes.def" |
6605 | false; // end of boolean or operation |
6606 | } |
6607 | |
6608 | inline bool Type::isOpenCLSpecificType() const { |
6609 | return isSamplerT() || isEventT() || isImageType() || isClkEventT() || |
6610 | isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType(); |
6611 | } |
6612 | |
6613 | inline bool Type::isTemplateTypeParmType() const { |
6614 | return isa<TemplateTypeParmType>(CanonicalType); |
6615 | } |
6616 | |
6617 | inline bool Type::isSpecificBuiltinType(unsigned K) const { |
6618 | if (const BuiltinType *BT = getAs<BuiltinType>()) |
6619 | if (BT->getKind() == (BuiltinType::Kind) K) |
6620 | return true; |
6621 | return false; |
6622 | } |
6623 | |
6624 | inline bool Type::isPlaceholderType() const { |
6625 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6626 | return BT->isPlaceholderType(); |
6627 | return false; |
6628 | } |
6629 | |
6630 | inline const BuiltinType *Type::getAsPlaceholderType() const { |
6631 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6632 | if (BT->isPlaceholderType()) |
6633 | return BT; |
6634 | return nullptr; |
6635 | } |
6636 | |
6637 | inline bool Type::isSpecificPlaceholderType(unsigned K) const { |
6638 | assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ? static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)" , "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6638, __PRETTY_FUNCTION__)); |
6639 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6640 | return (BT->getKind() == (BuiltinType::Kind) K); |
6641 | return false; |
6642 | } |
6643 | |
6644 | inline bool Type::isNonOverloadPlaceholderType() const { |
6645 | if (const auto *BT = dyn_cast<BuiltinType>(this)) |
6646 | return BT->isNonOverloadPlaceholderType(); |
6647 | return false; |
6648 | } |
6649 | |
6650 | inline bool Type::isVoidType() const { |
6651 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6652 | return BT->getKind() == BuiltinType::Void; |
6653 | return false; |
6654 | } |
6655 | |
6656 | inline bool Type::isHalfType() const { |
6657 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6658 | return BT->getKind() == BuiltinType::Half; |
6659 | // FIXME: Should we allow complex __fp16? Probably not. |
6660 | return false; |
6661 | } |
6662 | |
6663 | inline bool Type::isFloat16Type() const { |
6664 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6665 | return BT->getKind() == BuiltinType::Float16; |
6666 | return false; |
6667 | } |
6668 | |
6669 | inline bool Type::isFloat128Type() const { |
6670 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6671 | return BT->getKind() == BuiltinType::Float128; |
6672 | return false; |
6673 | } |
6674 | |
6675 | inline bool Type::isNullPtrType() const { |
6676 | if (const auto *BT = getAs<BuiltinType>()) |
6677 | return BT->getKind() == BuiltinType::NullPtr; |
6678 | return false; |
6679 | } |
6680 | |
6681 | bool IsEnumDeclComplete(EnumDecl *); |
6682 | bool IsEnumDeclScoped(EnumDecl *); |
6683 | |
6684 | inline bool Type::isIntegerType() const { |
6685 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6686 | return BT->getKind() >= BuiltinType::Bool && |
6687 | BT->getKind() <= BuiltinType::Int128; |
6688 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) { |
6689 | // Incomplete enum types are not treated as integer types. |
6690 | // FIXME: In C++, enum types are never integer types. |
6691 | return IsEnumDeclComplete(ET->getDecl()) && |
6692 | !IsEnumDeclScoped(ET->getDecl()); |
6693 | } |
6694 | return false; |
6695 | } |
6696 | |
6697 | inline bool Type::isFixedPointType() const { |
6698 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6699 | return BT->getKind() >= BuiltinType::ShortAccum && |
6700 | BT->getKind() <= BuiltinType::SatULongFract; |
6701 | } |
6702 | return false; |
6703 | } |
6704 | |
6705 | inline bool Type::isFixedPointOrIntegerType() const { |
6706 | return isFixedPointType() || isIntegerType(); |
6707 | } |
6708 | |
6709 | inline bool Type::isSaturatedFixedPointType() const { |
6710 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6711 | return BT->getKind() >= BuiltinType::SatShortAccum && |
6712 | BT->getKind() <= BuiltinType::SatULongFract; |
6713 | } |
6714 | return false; |
6715 | } |
6716 | |
6717 | inline bool Type::isUnsaturatedFixedPointType() const { |
6718 | return isFixedPointType() && !isSaturatedFixedPointType(); |
6719 | } |
6720 | |
6721 | inline bool Type::isSignedFixedPointType() const { |
6722 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) { |
6723 | return ((BT->getKind() >= BuiltinType::ShortAccum && |
6724 | BT->getKind() <= BuiltinType::LongAccum) || |
6725 | (BT->getKind() >= BuiltinType::ShortFract && |
6726 | BT->getKind() <= BuiltinType::LongFract) || |
6727 | (BT->getKind() >= BuiltinType::SatShortAccum && |
6728 | BT->getKind() <= BuiltinType::SatLongAccum) || |
6729 | (BT->getKind() >= BuiltinType::SatShortFract && |
6730 | BT->getKind() <= BuiltinType::SatLongFract)); |
6731 | } |
6732 | return false; |
6733 | } |
6734 | |
6735 | inline bool Type::isUnsignedFixedPointType() const { |
6736 | return isFixedPointType() && !isSignedFixedPointType(); |
6737 | } |
6738 | |
6739 | inline bool Type::isScalarType() const { |
6740 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6741 | return BT->getKind() > BuiltinType::Void && |
6742 | BT->getKind() <= BuiltinType::NullPtr; |
6743 | if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) |
6744 | // Enums are scalar types, but only if they are defined. Incomplete enums |
6745 | // are not treated as scalar types. |
6746 | return IsEnumDeclComplete(ET->getDecl()); |
6747 | return isa<PointerType>(CanonicalType) || |
6748 | isa<BlockPointerType>(CanonicalType) || |
6749 | isa<MemberPointerType>(CanonicalType) || |
6750 | isa<ComplexType>(CanonicalType) || |
6751 | isa<ObjCObjectPointerType>(CanonicalType); |
6752 | } |
6753 | |
6754 | inline bool Type::isIntegralOrEnumerationType() const { |
6755 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6756 | return BT->getKind() >= BuiltinType::Bool && |
6757 | BT->getKind() <= BuiltinType::Int128; |
6758 | |
6759 | // Check for a complete enum type; incomplete enum types are not properly an |
6760 | // enumeration type in the sense required here. |
6761 | if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) |
6762 | return IsEnumDeclComplete(ET->getDecl()); |
6763 | |
6764 | return false; |
6765 | } |
6766 | |
6767 | inline bool Type::isBooleanType() const { |
6768 | if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) |
6769 | return BT->getKind() == BuiltinType::Bool; |
6770 | return false; |
6771 | } |
6772 | |
6773 | inline bool Type::isUndeducedType() const { |
6774 | auto *DT = getContainedDeducedType(); |
6775 | return DT && !DT->isDeduced(); |
6776 | } |
6777 | |
6778 | /// Determines whether this is a type for which one can define |
6779 | /// an overloaded operator. |
6780 | inline bool Type::isOverloadableType() const { |
6781 | return isDependentType() || isRecordType() || isEnumeralType(); |
6782 | } |
6783 | |
6784 | /// Determines whether this type can decay to a pointer type. |
6785 | inline bool Type::canDecayToPointerType() const { |
6786 | return isFunctionType() || isArrayType(); |
6787 | } |
6788 | |
6789 | inline bool Type::hasPointerRepresentation() const { |
6790 | return (isPointerType() || isReferenceType() || isBlockPointerType() || |
6791 | isObjCObjectPointerType() || isNullPtrType()); |
6792 | } |
6793 | |
6794 | inline bool Type::hasObjCPointerRepresentation() const { |
6795 | return isObjCObjectPointerType(); |
6796 | } |
6797 | |
6798 | inline const Type *Type::getBaseElementTypeUnsafe() const { |
6799 | const Type *type = this; |
6800 | while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe()) |
6801 | type = arrayType->getElementType().getTypePtr(); |
6802 | return type; |
6803 | } |
6804 | |
6805 | inline const Type *Type::getPointeeOrArrayElementType() const { |
6806 | const Type *type = this; |
6807 | if (type->isAnyPointerType()) |
6808 | return type->getPointeeType().getTypePtr(); |
6809 | else if (type->isArrayType()) |
6810 | return type->getBaseElementTypeUnsafe(); |
6811 | return type; |
6812 | } |
6813 | |
6814 | /// Insertion operator for diagnostics. This allows sending Qualifiers into a |
6815 | /// diagnostic with <<. |
6816 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
6817 | Qualifiers Q) { |
6818 | DB.AddTaggedVal(Q.getAsOpaqueValue(), |
6819 | DiagnosticsEngine::ArgumentKind::ak_qual); |
6820 | return DB; |
6821 | } |
6822 | |
6823 | /// Insertion operator for partial diagnostics. This allows sending Qualifiers |
6824 | /// into a diagnostic with <<. |
6825 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
6826 | Qualifiers Q) { |
6827 | PD.AddTaggedVal(Q.getAsOpaqueValue(), |
6828 | DiagnosticsEngine::ArgumentKind::ak_qual); |
6829 | return PD; |
6830 | } |
6831 | |
6832 | /// Insertion operator for diagnostics. This allows sending QualType's into a |
6833 | /// diagnostic with <<. |
6834 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
6835 | QualType T) { |
6836 | DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
6837 | DiagnosticsEngine::ak_qualtype); |
6838 | return DB; |
6839 | } |
6840 | |
6841 | /// Insertion operator for partial diagnostics. This allows sending QualType's |
6842 | /// into a diagnostic with <<. |
6843 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
6844 | QualType T) { |
6845 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()), |
6846 | DiagnosticsEngine::ak_qualtype); |
6847 | return PD; |
6848 | } |
6849 | |
6850 | // Helper class template that is used by Type::getAs to ensure that one does |
6851 | // not try to look through a qualified type to get to an array type. |
6852 | template <typename T> |
6853 | using TypeIsArrayType = |
6854 | std::integral_constant<bool, std::is_same<T, ArrayType>::value || |
6855 | std::is_base_of<ArrayType, T>::value>; |
6856 | |
6857 | // Member-template getAs<specific type>'. |
6858 | template <typename T> const T *Type::getAs() const { |
6859 | static_assert(!TypeIsArrayType<T>::value, |
6860 | "ArrayType cannot be used with getAs!"); |
6861 | |
6862 | // If this is directly a T type, return it. |
6863 | if (const auto *Ty = dyn_cast<T>(this)) |
6864 | return Ty; |
6865 | |
6866 | // If the canonical form of this type isn't the right kind, reject it. |
6867 | if (!isa<T>(CanonicalType)) |
6868 | return nullptr; |
6869 | |
6870 | // If this is a typedef for the type, strip the typedef off without |
6871 | // losing all typedef information. |
6872 | return cast<T>(getUnqualifiedDesugaredType()); |
6873 | } |
6874 | |
6875 | template <typename T> const T *Type::getAsAdjusted() const { |
6876 | static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!"); |
6877 | |
6878 | // If this is directly a T type, return it. |
6879 | if (const auto *Ty = dyn_cast<T>(this)) |
6880 | return Ty; |
6881 | |
6882 | // If the canonical form of this type isn't the right kind, reject it. |
6883 | if (!isa<T>(CanonicalType)) |
6884 | return nullptr; |
6885 | |
6886 | // Strip off type adjustments that do not modify the underlying nature of the |
6887 | // type. |
6888 | const Type *Ty = this; |
6889 | while (Ty) { |
6890 | if (const auto *A = dyn_cast<AttributedType>(Ty)) |
6891 | Ty = A->getModifiedType().getTypePtr(); |
6892 | else if (const auto *E = dyn_cast<ElaboratedType>(Ty)) |
6893 | Ty = E->desugar().getTypePtr(); |
6894 | else if (const auto *P = dyn_cast<ParenType>(Ty)) |
6895 | Ty = P->desugar().getTypePtr(); |
6896 | else if (const auto *A = dyn_cast<AdjustedType>(Ty)) |
6897 | Ty = A->desugar().getTypePtr(); |
6898 | else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty)) |
6899 | Ty = M->desugar().getTypePtr(); |
6900 | else |
6901 | break; |
6902 | } |
6903 | |
6904 | // Just because the canonical type is correct does not mean we can use cast<>, |
6905 | // since we may not have stripped off all the sugar down to the base type. |
6906 | return dyn_cast<T>(Ty); |
6907 | } |
6908 | |
6909 | inline const ArrayType *Type::getAsArrayTypeUnsafe() const { |
6910 | // If this is directly an array type, return it. |
6911 | if (const auto *arr = dyn_cast<ArrayType>(this)) |
6912 | return arr; |
6913 | |
6914 | // If the canonical form of this type isn't the right kind, reject it. |
6915 | if (!isa<ArrayType>(CanonicalType)) |
6916 | return nullptr; |
6917 | |
6918 | // If this is a typedef for the type, strip the typedef off without |
6919 | // losing all typedef information. |
6920 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
6921 | } |
6922 | |
6923 | template <typename T> const T *Type::castAs() const { |
6924 | static_assert(!TypeIsArrayType<T>::value, |
6925 | "ArrayType cannot be used with castAs!"); |
6926 | |
6927 | if (const auto *ty = dyn_cast<T>(this)) return ty; |
6928 | assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6928, __PRETTY_FUNCTION__)); |
6929 | return cast<T>(getUnqualifiedDesugaredType()); |
6930 | } |
6931 | |
6932 | inline const ArrayType *Type::castAsArrayTypeUnsafe() const { |
6933 | assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void> (0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6933, __PRETTY_FUNCTION__)); |
6934 | if (const auto *arr = dyn_cast<ArrayType>(this)) return arr; |
6935 | return cast<ArrayType>(getUnqualifiedDesugaredType()); |
6936 | } |
6937 | |
6938 | DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr, |
6939 | QualType CanonicalPtr) |
6940 | : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) { |
6941 | #ifndef NDEBUG |
6942 | QualType Adjusted = getAdjustedType(); |
6943 | (void)AttributedType::stripOuterNullability(Adjusted); |
6944 | assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void> (0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h" , 6944, __PRETTY_FUNCTION__)); |
6945 | #endif |
6946 | } |
6947 | |
6948 | QualType DecayedType::getPointeeType() const { |
6949 | QualType Decayed = getDecayedType(); |
6950 | (void)AttributedType::stripOuterNullability(Decayed); |
6951 | return cast<PointerType>(Decayed)->getPointeeType(); |
6952 | } |
6953 | |
6954 | // Get the decimal string representation of a fixed point type, represented |
6955 | // as a scaled integer. |
6956 | // TODO: At some point, we should change the arguments to instead just accept an |
6957 | // APFixedPoint instead of APSInt and scale. |
6958 | void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val, |
6959 | unsigned Scale); |
6960 | |
6961 | } // namespace clang |
6962 | |
6963 | #endif // LLVM_CLANG_AST_TYPE_H |