Bug Summary

File:clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 4308, column 29
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDeclCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-07-26-235520-9401-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp

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/ScopeExit.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringExtras.h"
45#include <map>
46#include <set>
47
48using namespace clang;
49
50//===----------------------------------------------------------------------===//
51// CheckDefaultArgumentVisitor
52//===----------------------------------------------------------------------===//
53
54namespace {
55/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56/// the default argument of a parameter to determine whether it
57/// contains any ill-formed subexpressions. For example, this will
58/// diagnose the use of local variables or parameters within the
59/// default argument expression.
60class CheckDefaultArgumentVisitor
61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62 Sema &S;
63 const Expr *DefaultArg;
64
65public:
66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67 : S(S), DefaultArg(DefaultArg) {}
68
69 bool VisitExpr(const Expr *Node);
70 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72 bool VisitLambdaExpr(const LambdaExpr *Lambda);
73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74};
75
76/// VisitExpr - Visit all of the children of this expression.
77bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78 bool IsInvalid = false;
79 for (const Stmt *SubStmt : Node->children())
80 IsInvalid |= Visit(SubStmt);
81 return IsInvalid;
82}
83
84/// VisitDeclRefExpr - Visit a reference to a declaration, to
85/// determine whether this declaration can be used in the default
86/// argument expression.
87bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88 const NamedDecl *Decl = DRE->getDecl();
89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90 // C++ [dcl.fct.default]p9:
91 // [...] parameters of a function shall not be used in default
92 // argument expressions, even if they are not evaluated. [...]
93 //
94 // C++17 [dcl.fct.default]p9 (by CWG 2082):
95 // [...] A parameter shall not appear as a potentially-evaluated
96 // expression in a default argument. [...]
97 //
98 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99 return S.Diag(DRE->getBeginLoc(),
100 diag::err_param_default_argument_references_param)
101 << Param->getDeclName() << DefaultArg->getSourceRange();
102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103 // C++ [dcl.fct.default]p7:
104 // Local variables shall not be used in default argument
105 // expressions.
106 //
107 // C++17 [dcl.fct.default]p7 (by CWG 2082):
108 // A local variable shall not appear as a potentially-evaluated
109 // expression in a default argument.
110 //
111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112 // Note: A local variable cannot be odr-used (6.3) in a default argument.
113 //
114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115 return S.Diag(DRE->getBeginLoc(),
116 diag::err_param_default_argument_references_local)
117 << VDecl->getDeclName() << DefaultArg->getSourceRange();
118 }
119
120 return false;
121}
122
123/// VisitCXXThisExpr - Visit a C++ "this" expression.
124bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125 // C++ [dcl.fct.default]p8:
126 // The keyword this shall not be used in a default argument of a
127 // member function.
128 return S.Diag(ThisE->getBeginLoc(),
129 diag::err_param_default_argument_references_this)
130 << ThisE->getSourceRange();
131}
132
133bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134 const PseudoObjectExpr *POE) {
135 bool Invalid = false;
136 for (const Expr *E : POE->semantics()) {
137 // Look through bindings.
138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139 E = OVE->getSourceExpr();
140 assert(E && "pseudo-object binding without source expression?")(static_cast <bool> (E && "pseudo-object binding without source expression?"
) ? void (0) : __assert_fail ("E && \"pseudo-object binding without source expression?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 140, __extension__ __PRETTY_FUNCTION__))
;
141 }
142
143 Invalid |= Visit(E);
144 }
145 return Invalid;
146}
147
148bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149 // C++11 [expr.lambda.prim]p13:
150 // A lambda-expression appearing in a default argument shall not
151 // implicitly or explicitly capture any entity.
152 if (Lambda->capture_begin() == Lambda->capture_end())
153 return false;
154
155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156}
157} // namespace
158
159void
160Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161 const CXXMethodDecl *Method) {
162 // If we have an MSAny spec already, don't bother.
163 if (!Method || ComputedEST == EST_MSAny)
164 return;
165
166 const FunctionProtoType *Proto
167 = Method->getType()->getAs<FunctionProtoType>();
168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169 if (!Proto)
170 return;
171
172 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173
174 // If we have a throw-all spec at this point, ignore the function.
175 if (ComputedEST == EST_None)
176 return;
177
178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179 EST = EST_BasicNoexcept;
180
181 switch (EST) {
182 case EST_Unparsed:
183 case EST_Uninstantiated:
184 case EST_Unevaluated:
185 llvm_unreachable("should not see unresolved exception specs here")::llvm::llvm_unreachable_internal("should not see unresolved exception specs here"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 185)
;
186
187 // If this function can throw any exceptions, make a note of that.
188 case EST_MSAny:
189 case EST_None:
190 // FIXME: Whichever we see last of MSAny and None determines our result.
191 // We should make a consistent, order-independent choice here.
192 ClearExceptions();
193 ComputedEST = EST;
194 return;
195 case EST_NoexceptFalse:
196 ClearExceptions();
197 ComputedEST = EST_None;
198 return;
199 // FIXME: If the call to this decl is using any of its default arguments, we
200 // need to search them for potentially-throwing calls.
201 // If this function has a basic noexcept, it doesn't affect the outcome.
202 case EST_BasicNoexcept:
203 case EST_NoexceptTrue:
204 case EST_NoThrow:
205 return;
206 // If we're still at noexcept(true) and there's a throw() callee,
207 // change to that specification.
208 case EST_DynamicNone:
209 if (ComputedEST == EST_BasicNoexcept)
210 ComputedEST = EST_DynamicNone;
211 return;
212 case EST_DependentNoexcept:
213 llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 214)
214 "should not generate implicit declarations for dependent cases")::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 214)
;
215 case EST_Dynamic:
216 break;
217 }
218 assert(EST == EST_Dynamic && "EST case not considered earlier.")(static_cast <bool> (EST == EST_Dynamic && "EST case not considered earlier."
) ? void (0) : __assert_fail ("EST == EST_Dynamic && \"EST case not considered earlier.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 218, __extension__ __PRETTY_FUNCTION__))
;
219 assert(ComputedEST != EST_None &&(static_cast <bool> (ComputedEST != EST_None &&
"Shouldn't collect exceptions when throw-all is guaranteed."
) ? void (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 220, __extension__ __PRETTY_FUNCTION__))
220 "Shouldn't collect exceptions when throw-all is guaranteed.")(static_cast <bool> (ComputedEST != EST_None &&
"Shouldn't collect exceptions when throw-all is guaranteed."
) ? void (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 220, __extension__ __PRETTY_FUNCTION__))
;
221 ComputedEST = EST_Dynamic;
222 // Record the exceptions in this function's exception specification.
223 for (const auto &E : Proto->exceptions())
224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225 Exceptions.push_back(E);
226}
227
228void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229 if (!S || ComputedEST == EST_MSAny)
230 return;
231
232 // FIXME:
233 //
234 // C++0x [except.spec]p14:
235 // [An] implicit exception-specification specifies the type-id T if and
236 // only if T is allowed by the exception-specification of a function directly
237 // invoked by f's implicit definition; f shall allow all exceptions if any
238 // function it directly invokes allows all exceptions, and f shall allow no
239 // exceptions if every function it directly invokes allows no exceptions.
240 //
241 // Note in particular that if an implicit exception-specification is generated
242 // for a function containing a throw-expression, that specification can still
243 // be noexcept(true).
244 //
245 // Note also that 'directly invoked' is not defined in the standard, and there
246 // is no indication that we should only consider potentially-evaluated calls.
247 //
248 // Ultimately we should implement the intent of the standard: the exception
249 // specification should be the set of exceptions which can be thrown by the
250 // implicit definition. For now, we assume that any non-nothrow expression can
251 // throw any exception.
252
253 if (Self->canThrow(S))
254 ComputedEST = EST_None;
255}
256
257ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
258 SourceLocation EqualLoc) {
259 if (RequireCompleteType(Param->getLocation(), Param->getType(),
260 diag::err_typecheck_decl_incomplete_type))
261 return true;
262
263 // C++ [dcl.fct.default]p5
264 // A default argument expression is implicitly converted (clause
265 // 4) to the parameter type. The default argument expression has
266 // the same semantic constraints as the initializer expression in
267 // a declaration of a variable of the parameter type, using the
268 // copy-initialization semantics (8.5).
269 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
270 Param);
271 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
272 EqualLoc);
273 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
274 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
275 if (Result.isInvalid())
276 return true;
277 Arg = Result.getAs<Expr>();
278
279 CheckCompletedExpr(Arg, EqualLoc);
280 Arg = MaybeCreateExprWithCleanups(Arg);
281
282 return Arg;
283}
284
285void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
286 SourceLocation EqualLoc) {
287 // Add the default argument to the parameter
288 Param->setDefaultArg(Arg);
289
290 // We have already instantiated this parameter; provide each of the
291 // instantiations with the uninstantiated default argument.
292 UnparsedDefaultArgInstantiationsMap::iterator InstPos
293 = UnparsedDefaultArgInstantiations.find(Param);
294 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
295 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
296 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
297
298 // We're done tracking this parameter's instantiations.
299 UnparsedDefaultArgInstantiations.erase(InstPos);
300 }
301}
302
303/// ActOnParamDefaultArgument - Check whether the default argument
304/// provided for a function parameter is well-formed. If so, attach it
305/// to the parameter declaration.
306void
307Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
308 Expr *DefaultArg) {
309 if (!param || !DefaultArg)
310 return;
311
312 ParmVarDecl *Param = cast<ParmVarDecl>(param);
313 UnparsedDefaultArgLocs.erase(Param);
314
315 auto Fail = [&] {
316 Param->setInvalidDecl();
317 Param->setDefaultArg(new (Context) OpaqueValueExpr(
318 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
319 };
320
321 // Default arguments are only permitted in C++
322 if (!getLangOpts().CPlusPlus) {
323 Diag(EqualLoc, diag::err_param_default_argument)
324 << DefaultArg->getSourceRange();
325 return Fail();
326 }
327
328 // Check for unexpanded parameter packs.
329 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
330 return Fail();
331 }
332
333 // C++11 [dcl.fct.default]p3
334 // A default argument expression [...] shall not be specified for a
335 // parameter pack.
336 if (Param->isParameterPack()) {
337 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
338 << DefaultArg->getSourceRange();
339 // Recover by discarding the default argument.
340 Param->setDefaultArg(nullptr);
341 return;
342 }
343
344 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
345 if (Result.isInvalid())
346 return Fail();
347
348 DefaultArg = Result.getAs<Expr>();
349
350 // Check that the default argument is well-formed
351 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
352 if (DefaultArgChecker.Visit(DefaultArg))
353 return Fail();
354
355 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
356}
357
358/// ActOnParamUnparsedDefaultArgument - We've seen a default
359/// argument for a function parameter, but we can't parse it yet
360/// because we're inside a class definition. Note that this default
361/// argument will be parsed later.
362void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
363 SourceLocation EqualLoc,
364 SourceLocation ArgLoc) {
365 if (!param)
366 return;
367
368 ParmVarDecl *Param = cast<ParmVarDecl>(param);
369 Param->setUnparsedDefaultArg();
370 UnparsedDefaultArgLocs[Param] = ArgLoc;
371}
372
373/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
374/// the default argument for the parameter param failed.
375void Sema::ActOnParamDefaultArgumentError(Decl *param,
376 SourceLocation EqualLoc) {
377 if (!param)
378 return;
379
380 ParmVarDecl *Param = cast<ParmVarDecl>(param);
381 Param->setInvalidDecl();
382 UnparsedDefaultArgLocs.erase(Param);
383 Param->setDefaultArg(new (Context) OpaqueValueExpr(
384 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
385}
386
387/// CheckExtraCXXDefaultArguments - Check for any extra default
388/// arguments in the declarator, which is not a function declaration
389/// or definition and therefore is not permitted to have default
390/// arguments. This routine should be invoked for every declarator
391/// that is not a function declaration or definition.
392void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
393 // C++ [dcl.fct.default]p3
394 // A default argument expression shall be specified only in the
395 // parameter-declaration-clause of a function declaration or in a
396 // template-parameter (14.1). It shall not be specified for a
397 // parameter pack. If it is specified in a
398 // parameter-declaration-clause, it shall not occur within a
399 // declarator or abstract-declarator of a parameter-declaration.
400 bool MightBeFunction = D.isFunctionDeclarationContext();
401 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
402 DeclaratorChunk &chunk = D.getTypeObject(i);
403 if (chunk.Kind == DeclaratorChunk::Function) {
404 if (MightBeFunction) {
405 // This is a function declaration. It can have default arguments, but
406 // keep looking in case its return type is a function type with default
407 // arguments.
408 MightBeFunction = false;
409 continue;
410 }
411 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
412 ++argIdx) {
413 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
414 if (Param->hasUnparsedDefaultArg()) {
415 std::unique_ptr<CachedTokens> Toks =
416 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
417 SourceRange SR;
418 if (Toks->size() > 1)
419 SR = SourceRange((*Toks)[1].getLocation(),
420 Toks->back().getLocation());
421 else
422 SR = UnparsedDefaultArgLocs[Param];
423 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
424 << SR;
425 } else if (Param->getDefaultArg()) {
426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
427 << Param->getDefaultArg()->getSourceRange();
428 Param->setDefaultArg(nullptr);
429 }
430 }
431 } else if (chunk.Kind != DeclaratorChunk::Paren) {
432 MightBeFunction = false;
433 }
434 }
435}
436
437static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
438 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
439 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
440 });
441}
442
443/// MergeCXXFunctionDecl - Merge two declarations of the same C++
444/// function, once we already know that they have the same
445/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
446/// error, false otherwise.
447bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
448 Scope *S) {
449 bool Invalid = false;
450
451 // The declaration context corresponding to the scope is the semantic
452 // parent, unless this is a local function declaration, in which case
453 // it is that surrounding function.
454 DeclContext *ScopeDC = New->isLocalExternDecl()
455 ? New->getLexicalDeclContext()
456 : New->getDeclContext();
457
458 // Find the previous declaration for the purpose of default arguments.
459 FunctionDecl *PrevForDefaultArgs = Old;
460 for (/**/; PrevForDefaultArgs;
461 // Don't bother looking back past the latest decl if this is a local
462 // extern declaration; nothing else could work.
463 PrevForDefaultArgs = New->isLocalExternDecl()
464 ? nullptr
465 : PrevForDefaultArgs->getPreviousDecl()) {
466 // Ignore hidden declarations.
467 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
468 continue;
469
470 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
471 !New->isCXXClassMember()) {
472 // Ignore default arguments of old decl if they are not in
473 // the same scope and this is not an out-of-line definition of
474 // a member function.
475 continue;
476 }
477
478 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
479 // If only one of these is a local function declaration, then they are
480 // declared in different scopes, even though isDeclInScope may think
481 // they're in the same scope. (If both are local, the scope check is
482 // sufficient, and if neither is local, then they are in the same scope.)
483 continue;
484 }
485
486 // We found the right previous declaration.
487 break;
488 }
489
490 // C++ [dcl.fct.default]p4:
491 // For non-template functions, default arguments can be added in
492 // later declarations of a function in the same
493 // scope. Declarations in different scopes have completely
494 // distinct sets of default arguments. That is, declarations in
495 // inner scopes do not acquire default arguments from
496 // declarations in outer scopes, and vice versa. In a given
497 // function declaration, all parameters subsequent to a
498 // parameter with a default argument shall have default
499 // arguments supplied in this or previous declarations. A
500 // default argument shall not be redefined by a later
501 // declaration (not even to the same value).
502 //
503 // C++ [dcl.fct.default]p6:
504 // Except for member functions of class templates, the default arguments
505 // in a member function definition that appears outside of the class
506 // definition are added to the set of default arguments provided by the
507 // member function declaration in the class definition.
508 for (unsigned p = 0, NumParams = PrevForDefaultArgs
509 ? PrevForDefaultArgs->getNumParams()
510 : 0;
511 p < NumParams; ++p) {
512 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
513 ParmVarDecl *NewParam = New->getParamDecl(p);
514
515 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
516 bool NewParamHasDfl = NewParam->hasDefaultArg();
517
518 if (OldParamHasDfl && NewParamHasDfl) {
519 unsigned DiagDefaultParamID =
520 diag::err_param_default_argument_redefinition;
521
522 // MSVC accepts that default parameters be redefined for member functions
523 // of template class. The new default parameter's value is ignored.
524 Invalid = true;
525 if (getLangOpts().MicrosoftExt) {
526 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
527 if (MD && MD->getParent()->getDescribedClassTemplate()) {
528 // Merge the old default argument into the new parameter.
529 NewParam->setHasInheritedDefaultArg();
530 if (OldParam->hasUninstantiatedDefaultArg())
531 NewParam->setUninstantiatedDefaultArg(
532 OldParam->getUninstantiatedDefaultArg());
533 else
534 NewParam->setDefaultArg(OldParam->getInit());
535 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
536 Invalid = false;
537 }
538 }
539
540 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
541 // hint here. Alternatively, we could walk the type-source information
542 // for NewParam to find the last source location in the type... but it
543 // isn't worth the effort right now. This is the kind of test case that
544 // is hard to get right:
545 // int f(int);
546 // void g(int (*fp)(int) = f);
547 // void g(int (*fp)(int) = &f);
548 Diag(NewParam->getLocation(), DiagDefaultParamID)
549 << NewParam->getDefaultArgRange();
550
551 // Look for the function declaration where the default argument was
552 // actually written, which may be a declaration prior to Old.
553 for (auto Older = PrevForDefaultArgs;
554 OldParam->hasInheritedDefaultArg(); /**/) {
555 Older = Older->getPreviousDecl();
556 OldParam = Older->getParamDecl(p);
557 }
558
559 Diag(OldParam->getLocation(), diag::note_previous_definition)
560 << OldParam->getDefaultArgRange();
561 } else if (OldParamHasDfl) {
562 // Merge the old default argument into the new parameter unless the new
563 // function is a friend declaration in a template class. In the latter
564 // case the default arguments will be inherited when the friend
565 // declaration will be instantiated.
566 if (New->getFriendObjectKind() == Decl::FOK_None ||
567 !New->getLexicalDeclContext()->isDependentContext()) {
568 // It's important to use getInit() here; getDefaultArg()
569 // strips off any top-level ExprWithCleanups.
570 NewParam->setHasInheritedDefaultArg();
571 if (OldParam->hasUnparsedDefaultArg())
572 NewParam->setUnparsedDefaultArg();
573 else if (OldParam->hasUninstantiatedDefaultArg())
574 NewParam->setUninstantiatedDefaultArg(
575 OldParam->getUninstantiatedDefaultArg());
576 else
577 NewParam->setDefaultArg(OldParam->getInit());
578 }
579 } else if (NewParamHasDfl) {
580 if (New->getDescribedFunctionTemplate()) {
581 // Paragraph 4, quoted above, only applies to non-template functions.
582 Diag(NewParam->getLocation(),
583 diag::err_param_default_argument_template_redecl)
584 << NewParam->getDefaultArgRange();
585 Diag(PrevForDefaultArgs->getLocation(),
586 diag::note_template_prev_declaration)
587 << false;
588 } else if (New->getTemplateSpecializationKind()
589 != TSK_ImplicitInstantiation &&
590 New->getTemplateSpecializationKind() != TSK_Undeclared) {
591 // C++ [temp.expr.spec]p21:
592 // Default function arguments shall not be specified in a declaration
593 // or a definition for one of the following explicit specializations:
594 // - the explicit specialization of a function template;
595 // - the explicit specialization of a member function template;
596 // - the explicit specialization of a member function of a class
597 // template where the class template specialization to which the
598 // member function specialization belongs is implicitly
599 // instantiated.
600 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
601 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
602 << New->getDeclName()
603 << NewParam->getDefaultArgRange();
604 } else if (New->getDeclContext()->isDependentContext()) {
605 // C++ [dcl.fct.default]p6 (DR217):
606 // Default arguments for a member function of a class template shall
607 // be specified on the initial declaration of the member function
608 // within the class template.
609 //
610 // Reading the tea leaves a bit in DR217 and its reference to DR205
611 // leads me to the conclusion that one cannot add default function
612 // arguments for an out-of-line definition of a member function of a
613 // dependent type.
614 int WhichKind = 2;
615 if (CXXRecordDecl *Record
616 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
617 if (Record->getDescribedClassTemplate())
618 WhichKind = 0;
619 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
620 WhichKind = 1;
621 else
622 WhichKind = 2;
623 }
624
625 Diag(NewParam->getLocation(),
626 diag::err_param_default_argument_member_template_redecl)
627 << WhichKind
628 << NewParam->getDefaultArgRange();
629 }
630 }
631 }
632
633 // DR1344: If a default argument is added outside a class definition and that
634 // default argument makes the function a special member function, the program
635 // is ill-formed. This can only happen for constructors.
636 if (isa<CXXConstructorDecl>(New) &&
637 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
638 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
639 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
640 if (NewSM != OldSM) {
641 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
642 assert(NewParam->hasDefaultArg())(static_cast <bool> (NewParam->hasDefaultArg()) ? void
(0) : __assert_fail ("NewParam->hasDefaultArg()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 642, __extension__ __PRETTY_FUNCTION__))
;
643 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
644 << NewParam->getDefaultArgRange() << NewSM;
645 Diag(Old->getLocation(), diag::note_previous_declaration);
646 }
647 }
648
649 const FunctionDecl *Def;
650 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
651 // template has a constexpr specifier then all its declarations shall
652 // contain the constexpr specifier.
653 if (New->getConstexprKind() != Old->getConstexprKind()) {
654 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
655 << New << static_cast<int>(New->getConstexprKind())
656 << static_cast<int>(Old->getConstexprKind());
657 Diag(Old->getLocation(), diag::note_previous_declaration);
658 Invalid = true;
659 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
660 Old->isDefined(Def) &&
661 // If a friend function is inlined but does not have 'inline'
662 // specifier, it is a definition. Do not report attribute conflict
663 // in this case, redefinition will be diagnosed later.
664 (New->isInlineSpecified() ||
665 New->getFriendObjectKind() == Decl::FOK_None)) {
666 // C++11 [dcl.fcn.spec]p4:
667 // If the definition of a function appears in a translation unit before its
668 // first declaration as inline, the program is ill-formed.
669 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
670 Diag(Def->getLocation(), diag::note_previous_definition);
671 Invalid = true;
672 }
673
674 // C++17 [temp.deduct.guide]p3:
675 // Two deduction guide declarations in the same translation unit
676 // for the same class template shall not have equivalent
677 // parameter-declaration-clauses.
678 if (isa<CXXDeductionGuideDecl>(New) &&
679 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
680 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
681 Diag(Old->getLocation(), diag::note_previous_declaration);
682 }
683
684 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
685 // argument expression, that declaration shall be a definition and shall be
686 // the only declaration of the function or function template in the
687 // translation unit.
688 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
689 functionDeclHasDefaultArgument(Old)) {
690 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
691 Diag(Old->getLocation(), diag::note_previous_declaration);
692 Invalid = true;
693 }
694
695 // C++11 [temp.friend]p4 (DR329):
696 // When a function is defined in a friend function declaration in a class
697 // template, the function is instantiated when the function is odr-used.
698 // The same restrictions on multiple declarations and definitions that
699 // apply to non-template function declarations and definitions also apply
700 // to these implicit definitions.
701 const FunctionDecl *OldDefinition = nullptr;
702 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
703 Old->isDefined(OldDefinition, true))
704 CheckForFunctionRedefinition(New, OldDefinition);
705
706 return Invalid;
707}
708
709NamedDecl *
710Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
711 MultiTemplateParamsArg TemplateParamLists) {
712 assert(D.isDecompositionDeclarator())(static_cast <bool> (D.isDecompositionDeclarator()) ? void
(0) : __assert_fail ("D.isDecompositionDeclarator()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 712, __extension__ __PRETTY_FUNCTION__))
;
713 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
714
715 // The syntax only allows a decomposition declarator as a simple-declaration,
716 // a for-range-declaration, or a condition in Clang, but we parse it in more
717 // cases than that.
718 if (!D.mayHaveDecompositionDeclarator()) {
719 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
720 << Decomp.getSourceRange();
721 return nullptr;
722 }
723
724 if (!TemplateParamLists.empty()) {
725 // FIXME: There's no rule against this, but there are also no rules that
726 // would actually make it usable, so we reject it for now.
727 Diag(TemplateParamLists.front()->getTemplateLoc(),
728 diag::err_decomp_decl_template);
729 return nullptr;
730 }
731
732 Diag(Decomp.getLSquareLoc(),
733 !getLangOpts().CPlusPlus17
734 ? diag::ext_decomp_decl
735 : D.getContext() == DeclaratorContext::Condition
736 ? diag::ext_decomp_decl_cond
737 : diag::warn_cxx14_compat_decomp_decl)
738 << Decomp.getSourceRange();
739
740 // The semantic context is always just the current context.
741 DeclContext *const DC = CurContext;
742
743 // C++17 [dcl.dcl]/8:
744 // The decl-specifier-seq shall contain only the type-specifier auto
745 // and cv-qualifiers.
746 // C++2a [dcl.dcl]/8:
747 // If decl-specifier-seq contains any decl-specifier other than static,
748 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
749 auto &DS = D.getDeclSpec();
750 {
751 SmallVector<StringRef, 8> BadSpecifiers;
752 SmallVector<SourceLocation, 8> BadSpecifierLocs;
753 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
754 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
755 if (auto SCS = DS.getStorageClassSpec()) {
756 if (SCS == DeclSpec::SCS_static) {
757 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
758 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
759 } else {
760 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
761 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
762 }
763 }
764 if (auto TSCS = DS.getThreadStorageClassSpec()) {
765 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
766 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
767 }
768 if (DS.hasConstexprSpecifier()) {
769 BadSpecifiers.push_back(
770 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
771 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
772 }
773 if (DS.isInlineSpecified()) {
774 BadSpecifiers.push_back("inline");
775 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
776 }
777 if (!BadSpecifiers.empty()) {
778 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
779 Err << (int)BadSpecifiers.size()
780 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
781 // Don't add FixItHints to remove the specifiers; we do still respect
782 // them when building the underlying variable.
783 for (auto Loc : BadSpecifierLocs)
784 Err << SourceRange(Loc, Loc);
785 } else if (!CPlusPlus20Specifiers.empty()) {
786 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
787 getLangOpts().CPlusPlus20
788 ? diag::warn_cxx17_compat_decomp_decl_spec
789 : diag::ext_decomp_decl_spec);
790 Warn << (int)CPlusPlus20Specifiers.size()
791 << llvm::join(CPlusPlus20Specifiers.begin(),
792 CPlusPlus20Specifiers.end(), " ");
793 for (auto Loc : CPlusPlus20SpecifierLocs)
794 Warn << SourceRange(Loc, Loc);
795 }
796 // We can't recover from it being declared as a typedef.
797 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
798 return nullptr;
799 }
800
801 // C++2a [dcl.struct.bind]p1:
802 // A cv that includes volatile is deprecated
803 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
804 getLangOpts().CPlusPlus20)
805 Diag(DS.getVolatileSpecLoc(),
806 diag::warn_deprecated_volatile_structured_binding);
807
808 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
809 QualType R = TInfo->getType();
810
811 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
812 UPPC_DeclarationType))
813 D.setInvalidType();
814
815 // The syntax only allows a single ref-qualifier prior to the decomposition
816 // declarator. No other declarator chunks are permitted. Also check the type
817 // specifier here.
818 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
819 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
820 (D.getNumTypeObjects() == 1 &&
821 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
822 Diag(Decomp.getLSquareLoc(),
823 (D.hasGroupingParens() ||
824 (D.getNumTypeObjects() &&
825 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
826 ? diag::err_decomp_decl_parens
827 : diag::err_decomp_decl_type)
828 << R;
829
830 // In most cases, there's no actual problem with an explicitly-specified
831 // type, but a function type won't work here, and ActOnVariableDeclarator
832 // shouldn't be called for such a type.
833 if (R->isFunctionType())
834 D.setInvalidType();
835 }
836
837 // Build the BindingDecls.
838 SmallVector<BindingDecl*, 8> Bindings;
839
840 // Build the BindingDecls.
841 for (auto &B : D.getDecompositionDeclarator().bindings()) {
842 // Check for name conflicts.
843 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
844 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
845 ForVisibleRedeclaration);
846 LookupName(Previous, S,
847 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
848
849 // It's not permitted to shadow a template parameter name.
850 if (Previous.isSingleResult() &&
851 Previous.getFoundDecl()->isTemplateParameter()) {
852 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
853 Previous.getFoundDecl());
854 Previous.clear();
855 }
856
857 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
858
859 // Find the shadowed declaration before filtering for scope.
860 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
861 ? getShadowedDeclaration(BD, Previous)
862 : nullptr;
863
864 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
865 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
866 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
867 /*AllowInlineNamespace*/false);
868
869 if (!Previous.empty()) {
870 auto *Old = Previous.getRepresentativeDecl();
871 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
872 Diag(Old->getLocation(), diag::note_previous_definition);
873 } else if (ShadowedDecl && !D.isRedeclaration()) {
874 CheckShadow(BD, ShadowedDecl, Previous);
875 }
876 PushOnScopeChains(BD, S, true);
877 Bindings.push_back(BD);
878 ParsingInitForAutoVars.insert(BD);
879 }
880
881 // There are no prior lookup results for the variable itself, because it
882 // is unnamed.
883 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
884 Decomp.getLSquareLoc());
885 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
886 ForVisibleRedeclaration);
887
888 // Build the variable that holds the non-decomposed object.
889 bool AddToScope = true;
890 NamedDecl *New =
891 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
892 MultiTemplateParamsArg(), AddToScope, Bindings);
893 if (AddToScope) {
894 S->AddDecl(New);
895 CurContext->addHiddenDecl(New);
896 }
897
898 if (isInOpenMPDeclareTargetContext())
899 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
900
901 return New;
902}
903
904static bool checkSimpleDecomposition(
905 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
906 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
907 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
908 if ((int64_t)Bindings.size() != NumElems) {
909 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
910 << DecompType << (unsigned)Bindings.size()
911 << (unsigned)NumElems.getLimitedValue(UINT_MAX(2147483647 *2U +1U))
912 << toString(NumElems, 10) << (NumElems < Bindings.size());
913 return true;
914 }
915
916 unsigned I = 0;
917 for (auto *B : Bindings) {
918 SourceLocation Loc = B->getLocation();
919 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
920 if (E.isInvalid())
921 return true;
922 E = GetInit(Loc, E.get(), I++);
923 if (E.isInvalid())
924 return true;
925 B->setBinding(ElemType, E.get());
926 }
927
928 return false;
929}
930
931static bool checkArrayLikeDecomposition(Sema &S,
932 ArrayRef<BindingDecl *> Bindings,
933 ValueDecl *Src, QualType DecompType,
934 const llvm::APSInt &NumElems,
935 QualType ElemType) {
936 return checkSimpleDecomposition(
937 S, Bindings, Src, DecompType, NumElems, ElemType,
938 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
939 ExprResult E = S.ActOnIntegerConstant(Loc, I);
940 if (E.isInvalid())
941 return ExprError();
942 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
943 });
944}
945
946static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
947 ValueDecl *Src, QualType DecompType,
948 const ConstantArrayType *CAT) {
949 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
950 llvm::APSInt(CAT->getSize()),
951 CAT->getElementType());
952}
953
954static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
955 ValueDecl *Src, QualType DecompType,
956 const VectorType *VT) {
957 return checkArrayLikeDecomposition(
958 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
959 S.Context.getQualifiedType(VT->getElementType(),
960 DecompType.getQualifiers()));
961}
962
963static bool checkComplexDecomposition(Sema &S,
964 ArrayRef<BindingDecl *> Bindings,
965 ValueDecl *Src, QualType DecompType,
966 const ComplexType *CT) {
967 return checkSimpleDecomposition(
968 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
969 S.Context.getQualifiedType(CT->getElementType(),
970 DecompType.getQualifiers()),
971 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
972 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
973 });
974}
975
976static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
977 TemplateArgumentListInfo &Args,
978 const TemplateParameterList *Params) {
979 SmallString<128> SS;
980 llvm::raw_svector_ostream OS(SS);
981 bool First = true;
982 unsigned I = 0;
983 for (auto &Arg : Args.arguments()) {
984 if (!First)
985 OS << ", ";
986 Arg.getArgument().print(
987 PrintingPolicy, OS,
988 TemplateParameterList::shouldIncludeTypeForArgument(Params, I));
989 First = false;
990 I++;
991 }
992 return std::string(OS.str());
993}
994
995static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
996 SourceLocation Loc, StringRef Trait,
997 TemplateArgumentListInfo &Args,
998 unsigned DiagID) {
999 auto DiagnoseMissing = [&] {
1000 if (DiagID)
1001 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1002 Args, /*Params*/ nullptr);
1003 return true;
1004 };
1005
1006 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1007 NamespaceDecl *Std = S.getStdNamespace();
1008 if (!Std)
1009 return DiagnoseMissing();
1010
1011 // Look up the trait itself, within namespace std. We can diagnose various
1012 // problems with this lookup even if we've been asked to not diagnose a
1013 // missing specialization, because this can only fail if the user has been
1014 // declaring their own names in namespace std or we don't support the
1015 // standard library implementation in use.
1016 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1017 Loc, Sema::LookupOrdinaryName);
1018 if (!S.LookupQualifiedName(Result, Std))
1019 return DiagnoseMissing();
1020 if (Result.isAmbiguous())
1021 return true;
1022
1023 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1024 if (!TraitTD) {
1025 Result.suppressDiagnostics();
1026 NamedDecl *Found = *Result.begin();
1027 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1028 S.Diag(Found->getLocation(), diag::note_declared_at);
1029 return true;
1030 }
1031
1032 // Build the template-id.
1033 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1034 if (TraitTy.isNull())
1035 return true;
1036 if (!S.isCompleteType(Loc, TraitTy)) {
1037 if (DiagID)
1038 S.RequireCompleteType(
1039 Loc, TraitTy, DiagID,
1040 printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1041 TraitTD->getTemplateParameters()));
1042 return true;
1043 }
1044
1045 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1046 assert(RD && "specialization of class template is not a class?")(static_cast <bool> (RD && "specialization of class template is not a class?"
) ? void (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 1046, __extension__ __PRETTY_FUNCTION__))
;
1047
1048 // Look up the member of the trait type.
1049 S.LookupQualifiedName(TraitMemberLookup, RD);
1050 return TraitMemberLookup.isAmbiguous();
1051}
1052
1053static TemplateArgumentLoc
1054getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1055 uint64_t I) {
1056 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1057 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1058}
1059
1060static TemplateArgumentLoc
1061getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1062 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1063}
1064
1065namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1066
1067static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1068 llvm::APSInt &Size) {
1069 EnterExpressionEvaluationContext ContextRAII(
1070 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1071
1072 DeclarationName Value = S.PP.getIdentifierInfo("value");
1073 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1074
1075 // Form template argument list for tuple_size<T>.
1076 TemplateArgumentListInfo Args(Loc, Loc);
1077 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1078
1079 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1080 // it's not tuple-like.
1081 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1082 R.empty())
1083 return IsTupleLike::NotTupleLike;
1084
1085 // If we get this far, we've committed to the tuple interpretation, but
1086 // we can still fail if there actually isn't a usable ::value.
1087
1088 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1089 LookupResult &R;
1090 TemplateArgumentListInfo &Args;
1091 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1092 : R(R), Args(Args) {}
1093 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1094 SourceLocation Loc) override {
1095 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1096 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1097 /*Params*/ nullptr);
1098 }
1099 } Diagnoser(R, Args);
1100
1101 ExprResult E =
1102 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1103 if (E.isInvalid())
1104 return IsTupleLike::Error;
1105
1106 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1107 if (E.isInvalid())
1108 return IsTupleLike::Error;
1109
1110 return IsTupleLike::TupleLike;
1111}
1112
1113/// \return std::tuple_element<I, T>::type.
1114static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1115 unsigned I, QualType T) {
1116 // Form template argument list for tuple_element<I, T>.
1117 TemplateArgumentListInfo Args(Loc, Loc);
1118 Args.addArgument(
1119 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1120 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1121
1122 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1123 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1124 if (lookupStdTypeTraitMember(
1125 S, R, Loc, "tuple_element", Args,
1126 diag::err_decomp_decl_std_tuple_element_not_specialized))
1127 return QualType();
1128
1129 auto *TD = R.getAsSingle<TypeDecl>();
1130 if (!TD) {
1131 R.suppressDiagnostics();
1132 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1133 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1134 /*Params*/ nullptr);
1135 if (!R.empty())
1136 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1137 return QualType();
1138 }
1139
1140 return S.Context.getTypeDeclType(TD);
1141}
1142
1143namespace {
1144struct InitializingBinding {
1145 Sema &S;
1146 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1147 Sema::CodeSynthesisContext Ctx;
1148 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1149 Ctx.PointOfInstantiation = BD->getLocation();
1150 Ctx.Entity = BD;
1151 S.pushCodeSynthesisContext(Ctx);
1152 }
1153 ~InitializingBinding() {
1154 S.popCodeSynthesisContext();
1155 }
1156};
1157}
1158
1159static bool checkTupleLikeDecomposition(Sema &S,
1160 ArrayRef<BindingDecl *> Bindings,
1161 VarDecl *Src, QualType DecompType,
1162 const llvm::APSInt &TupleSize) {
1163 if ((int64_t)Bindings.size() != TupleSize) {
1164 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1165 << DecompType << (unsigned)Bindings.size()
1166 << (unsigned)TupleSize.getLimitedValue(UINT_MAX(2147483647 *2U +1U))
1167 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1168 return true;
1169 }
1170
1171 if (Bindings.empty())
1172 return false;
1173
1174 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1175
1176 // [dcl.decomp]p3:
1177 // The unqualified-id get is looked up in the scope of E by class member
1178 // access lookup ...
1179 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1180 bool UseMemberGet = false;
1181 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1182 if (auto *RD = DecompType->getAsCXXRecordDecl())
1183 S.LookupQualifiedName(MemberGet, RD);
1184 if (MemberGet.isAmbiguous())
1185 return true;
1186 // ... and if that finds at least one declaration that is a function
1187 // template whose first template parameter is a non-type parameter ...
1188 for (NamedDecl *D : MemberGet) {
1189 if (FunctionTemplateDecl *FTD =
1190 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1191 TemplateParameterList *TPL = FTD->getTemplateParameters();
1192 if (TPL->size() != 0 &&
1193 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1194 // ... the initializer is e.get<i>().
1195 UseMemberGet = true;
1196 break;
1197 }
1198 }
1199 }
1200 }
1201
1202 unsigned I = 0;
1203 for (auto *B : Bindings) {
1204 InitializingBinding InitContext(S, B);
1205 SourceLocation Loc = B->getLocation();
1206
1207 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1208 if (E.isInvalid())
1209 return true;
1210
1211 // e is an lvalue if the type of the entity is an lvalue reference and
1212 // an xvalue otherwise
1213 if (!Src->getType()->isLValueReferenceType())
1214 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1215 E.get(), nullptr, VK_XValue,
1216 FPOptionsOverride());
1217
1218 TemplateArgumentListInfo Args(Loc, Loc);
1219 Args.addArgument(
1220 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1221
1222 if (UseMemberGet) {
1223 // if [lookup of member get] finds at least one declaration, the
1224 // initializer is e.get<i-1>().
1225 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1226 CXXScopeSpec(), SourceLocation(), nullptr,
1227 MemberGet, &Args, nullptr);
1228 if (E.isInvalid())
1229 return true;
1230
1231 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1232 } else {
1233 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1234 // in the associated namespaces.
1235 Expr *Get = UnresolvedLookupExpr::Create(
1236 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1237 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1238 UnresolvedSetIterator(), UnresolvedSetIterator());
1239
1240 Expr *Arg = E.get();
1241 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1242 }
1243 if (E.isInvalid())
1244 return true;
1245 Expr *Init = E.get();
1246
1247 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1248 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1249 if (T.isNull())
1250 return true;
1251
1252 // each vi is a variable of type "reference to T" initialized with the
1253 // initializer, where the reference is an lvalue reference if the
1254 // initializer is an lvalue and an rvalue reference otherwise
1255 QualType RefType =
1256 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1257 if (RefType.isNull())
1258 return true;
1259 auto *RefVD = VarDecl::Create(
1260 S.Context, Src->getDeclContext(), Loc, Loc,
1261 B->getDeclName().getAsIdentifierInfo(), RefType,
1262 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1263 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1264 RefVD->setTSCSpec(Src->getTSCSpec());
1265 RefVD->setImplicit();
1266 if (Src->isInlineSpecified())
1267 RefVD->setInlineSpecified();
1268 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1269
1270 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1271 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1272 InitializationSequence Seq(S, Entity, Kind, Init);
1273 E = Seq.Perform(S, Entity, Kind, Init);
1274 if (E.isInvalid())
1275 return true;
1276 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1277 if (E.isInvalid())
1278 return true;
1279 RefVD->setInit(E.get());
1280 S.CheckCompleteVariableDeclaration(RefVD);
1281
1282 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1283 DeclarationNameInfo(B->getDeclName(), Loc),
1284 RefVD);
1285 if (E.isInvalid())
1286 return true;
1287
1288 B->setBinding(T, E.get());
1289 I++;
1290 }
1291
1292 return false;
1293}
1294
1295/// Find the base class to decompose in a built-in decomposition of a class type.
1296/// This base class search is, unfortunately, not quite like any other that we
1297/// perform anywhere else in C++.
1298static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1299 const CXXRecordDecl *RD,
1300 CXXCastPath &BasePath) {
1301 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1302 CXXBasePath &Path) {
1303 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1304 };
1305
1306 const CXXRecordDecl *ClassWithFields = nullptr;
1307 AccessSpecifier AS = AS_public;
1308 if (RD->hasDirectFields())
1309 // [dcl.decomp]p4:
1310 // Otherwise, all of E's non-static data members shall be public direct
1311 // members of E ...
1312 ClassWithFields = RD;
1313 else {
1314 // ... or of ...
1315 CXXBasePaths Paths;
1316 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1317 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1318 // If no classes have fields, just decompose RD itself. (This will work
1319 // if and only if zero bindings were provided.)
1320 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1321 }
1322
1323 CXXBasePath *BestPath = nullptr;
1324 for (auto &P : Paths) {
1325 if (!BestPath)
1326 BestPath = &P;
1327 else if (!S.Context.hasSameType(P.back().Base->getType(),
1328 BestPath->back().Base->getType())) {
1329 // ... the same ...
1330 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1331 << false << RD << BestPath->back().Base->getType()
1332 << P.back().Base->getType();
1333 return DeclAccessPair();
1334 } else if (P.Access < BestPath->Access) {
1335 BestPath = &P;
1336 }
1337 }
1338
1339 // ... unambiguous ...
1340 QualType BaseType = BestPath->back().Base->getType();
1341 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1342 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1343 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1344 return DeclAccessPair();
1345 }
1346
1347 // ... [accessible, implied by other rules] base class of E.
1348 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1349 *BestPath, diag::err_decomp_decl_inaccessible_base);
1350 AS = BestPath->Access;
1351
1352 ClassWithFields = BaseType->getAsCXXRecordDecl();
1353 S.BuildBasePathArray(Paths, BasePath);
1354 }
1355
1356 // The above search did not check whether the selected class itself has base
1357 // classes with fields, so check that now.
1358 CXXBasePaths Paths;
1359 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1360 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1361 << (ClassWithFields == RD) << RD << ClassWithFields
1362 << Paths.front().back().Base->getType();
1363 return DeclAccessPair();
1364 }
1365
1366 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1367}
1368
1369static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1370 ValueDecl *Src, QualType DecompType,
1371 const CXXRecordDecl *OrigRD) {
1372 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1373 diag::err_incomplete_type))
1374 return true;
1375
1376 CXXCastPath BasePath;
1377 DeclAccessPair BasePair =
1378 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1379 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1380 if (!RD)
1381 return true;
1382 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1383 DecompType.getQualifiers());
1384
1385 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1386 unsigned NumFields =
1387 std::count_if(RD->field_begin(), RD->field_end(),
1388 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1389 assert(Bindings.size() != NumFields)(static_cast <bool> (Bindings.size() != NumFields) ? void
(0) : __assert_fail ("Bindings.size() != NumFields", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 1389, __extension__ __PRETTY_FUNCTION__))
;
1390 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1391 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1392 << (NumFields < Bindings.size());
1393 return true;
1394 };
1395
1396 // all of E's non-static data members shall be [...] well-formed
1397 // when named as e.name in the context of the structured binding,
1398 // E shall not have an anonymous union member, ...
1399 unsigned I = 0;
1400 for (auto *FD : RD->fields()) {
1401 if (FD->isUnnamedBitfield())
1402 continue;
1403
1404 // All the non-static data members are required to be nameable, so they
1405 // must all have names.
1406 if (!FD->getDeclName()) {
1407 if (RD->isLambda()) {
1408 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1409 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1410 return true;
1411 }
1412
1413 if (FD->isAnonymousStructOrUnion()) {
1414 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1415 << DecompType << FD->getType()->isUnionType();
1416 S.Diag(FD->getLocation(), diag::note_declared_at);
1417 return true;
1418 }
1419
1420 // FIXME: Are there any other ways we could have an anonymous member?
1421 }
1422
1423 // We have a real field to bind.
1424 if (I >= Bindings.size())
1425 return DiagnoseBadNumberOfBindings();
1426 auto *B = Bindings[I++];
1427 SourceLocation Loc = B->getLocation();
1428
1429 // The field must be accessible in the context of the structured binding.
1430 // We already checked that the base class is accessible.
1431 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1432 // const_cast here.
1433 S.CheckStructuredBindingMemberAccess(
1434 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1435 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1436 BasePair.getAccess(), FD->getAccess())));
1437
1438 // Initialize the binding to Src.FD.
1439 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1440 if (E.isInvalid())
1441 return true;
1442 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1443 VK_LValue, &BasePath);
1444 if (E.isInvalid())
1445 return true;
1446 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1447 CXXScopeSpec(), FD,
1448 DeclAccessPair::make(FD, FD->getAccess()),
1449 DeclarationNameInfo(FD->getDeclName(), Loc));
1450 if (E.isInvalid())
1451 return true;
1452
1453 // If the type of the member is T, the referenced type is cv T, where cv is
1454 // the cv-qualification of the decomposition expression.
1455 //
1456 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1457 // 'const' to the type of the field.
1458 Qualifiers Q = DecompType.getQualifiers();
1459 if (FD->isMutable())
1460 Q.removeConst();
1461 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1462 }
1463
1464 if (I != Bindings.size())
1465 return DiagnoseBadNumberOfBindings();
1466
1467 return false;
1468}
1469
1470void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1471 QualType DecompType = DD->getType();
1472
1473 // If the type of the decomposition is dependent, then so is the type of
1474 // each binding.
1475 if (DecompType->isDependentType()) {
1476 for (auto *B : DD->bindings())
1477 B->setType(Context.DependentTy);
1478 return;
1479 }
1480
1481 DecompType = DecompType.getNonReferenceType();
1482 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1483
1484 // C++1z [dcl.decomp]/2:
1485 // If E is an array type [...]
1486 // As an extension, we also support decomposition of built-in complex and
1487 // vector types.
1488 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1489 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1490 DD->setInvalidDecl();
1491 return;
1492 }
1493 if (auto *VT = DecompType->getAs<VectorType>()) {
1494 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1495 DD->setInvalidDecl();
1496 return;
1497 }
1498 if (auto *CT = DecompType->getAs<ComplexType>()) {
1499 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1500 DD->setInvalidDecl();
1501 return;
1502 }
1503
1504 // C++1z [dcl.decomp]/3:
1505 // if the expression std::tuple_size<E>::value is a well-formed integral
1506 // constant expression, [...]
1507 llvm::APSInt TupleSize(32);
1508 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1509 case IsTupleLike::Error:
1510 DD->setInvalidDecl();
1511 return;
1512
1513 case IsTupleLike::TupleLike:
1514 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1515 DD->setInvalidDecl();
1516 return;
1517
1518 case IsTupleLike::NotTupleLike:
1519 break;
1520 }
1521
1522 // C++1z [dcl.dcl]/8:
1523 // [E shall be of array or non-union class type]
1524 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1525 if (!RD || RD->isUnion()) {
1526 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1527 << DD << !RD << DecompType;
1528 DD->setInvalidDecl();
1529 return;
1530 }
1531
1532 // C++1z [dcl.decomp]/4:
1533 // all of E's non-static data members shall be [...] direct members of
1534 // E or of the same unambiguous public base class of E, ...
1535 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1536 DD->setInvalidDecl();
1537}
1538
1539/// Merge the exception specifications of two variable declarations.
1540///
1541/// This is called when there's a redeclaration of a VarDecl. The function
1542/// checks if the redeclaration might have an exception specification and
1543/// validates compatibility and merges the specs if necessary.
1544void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1545 // Shortcut if exceptions are disabled.
1546 if (!getLangOpts().CXXExceptions)
1547 return;
1548
1549 assert(Context.hasSameType(New->getType(), Old->getType()) &&(static_cast <bool> (Context.hasSameType(New->getType
(), Old->getType()) && "Should only be called if types are otherwise the same."
) ? void (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 1550, __extension__ __PRETTY_FUNCTION__))
1550 "Should only be called if types are otherwise the same.")(static_cast <bool> (Context.hasSameType(New->getType
(), Old->getType()) && "Should only be called if types are otherwise the same."
) ? void (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 1550, __extension__ __PRETTY_FUNCTION__))
;
1551
1552 QualType NewType = New->getType();
1553 QualType OldType = Old->getType();
1554
1555 // We're only interested in pointers and references to functions, as well
1556 // as pointers to member functions.
1557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1558 NewType = R->getPointeeType();
1559 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1560 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1561 NewType = P->getPointeeType();
1562 OldType = OldType->castAs<PointerType>()->getPointeeType();
1563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1564 NewType = M->getPointeeType();
1565 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1566 }
1567
1568 if (!NewType->isFunctionProtoType())
1569 return;
1570
1571 // There's lots of special cases for functions. For function pointers, system
1572 // libraries are hopefully not as broken so that we don't need these
1573 // workarounds.
1574 if (CheckEquivalentExceptionSpec(
1575 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1576 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1577 New->setInvalidDecl();
1578 }
1579}
1580
1581/// CheckCXXDefaultArguments - Verify that the default arguments for a
1582/// function declaration are well-formed according to C++
1583/// [dcl.fct.default].
1584void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1585 unsigned NumParams = FD->getNumParams();
1586 unsigned ParamIdx = 0;
1587
1588 // This checking doesn't make sense for explicit specializations; their
1589 // default arguments are determined by the declaration we're specializing,
1590 // not by FD.
1591 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1592 return;
1593 if (auto *FTD = FD->getDescribedFunctionTemplate())
1594 if (FTD->isMemberSpecialization())
1595 return;
1596
1597 // Find first parameter with a default argument
1598 for (; ParamIdx < NumParams; ++ParamIdx) {
1599 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1600 if (Param->hasDefaultArg())
1601 break;
1602 }
1603
1604 // C++20 [dcl.fct.default]p4:
1605 // In a given function declaration, each parameter subsequent to a parameter
1606 // with a default argument shall have a default argument supplied in this or
1607 // a previous declaration, unless the parameter was expanded from a
1608 // parameter pack, or shall be a function parameter pack.
1609 for (; ParamIdx < NumParams; ++ParamIdx) {
1610 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1611 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1612 !(CurrentInstantiationScope &&
1613 CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1614 if (Param->isInvalidDecl())
1615 /* We already complained about this parameter. */;
1616 else if (Param->getIdentifier())
1617 Diag(Param->getLocation(),
1618 diag::err_param_default_argument_missing_name)
1619 << Param->getIdentifier();
1620 else
1621 Diag(Param->getLocation(),
1622 diag::err_param_default_argument_missing);
1623 }
1624 }
1625}
1626
1627/// Check that the given type is a literal type. Issue a diagnostic if not,
1628/// if Kind is Diagnose.
1629/// \return \c true if a problem has been found (and optionally diagnosed).
1630template <typename... Ts>
1631static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1632 SourceLocation Loc, QualType T, unsigned DiagID,
1633 Ts &&...DiagArgs) {
1634 if (T->isDependentType())
1635 return false;
1636
1637 switch (Kind) {
1638 case Sema::CheckConstexprKind::Diagnose:
1639 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1640 std::forward<Ts>(DiagArgs)...);
1641
1642 case Sema::CheckConstexprKind::CheckValid:
1643 return !T->isLiteralType(SemaRef.Context);
1644 }
1645
1646 llvm_unreachable("unknown CheckConstexprKind")::llvm::llvm_unreachable_internal("unknown CheckConstexprKind"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 1646)
;
1647}
1648
1649/// Determine whether a destructor cannot be constexpr due to
1650static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1651 const CXXDestructorDecl *DD,
1652 Sema::CheckConstexprKind Kind) {
1653 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1654 const CXXRecordDecl *RD =
1655 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1656 if (!RD || RD->hasConstexprDestructor())
1657 return true;
1658
1659 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1660 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1661 << static_cast<int>(DD->getConstexprKind()) << !FD
1662 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1663 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1664 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1665 }
1666 return false;
1667 };
1668
1669 const CXXRecordDecl *RD = DD->getParent();
1670 for (const CXXBaseSpecifier &B : RD->bases())
1671 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1672 return false;
1673 for (const FieldDecl *FD : RD->fields())
1674 if (!Check(FD->getLocation(), FD->getType(), FD))
1675 return false;
1676 return true;
1677}
1678
1679/// Check whether a function's parameter types are all literal types. If so,
1680/// return true. If not, produce a suitable diagnostic and return false.
1681static bool CheckConstexprParameterTypes(Sema &SemaRef,
1682 const FunctionDecl *FD,
1683 Sema::CheckConstexprKind Kind) {
1684 unsigned ArgIndex = 0;
1685 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1686 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1687 e = FT->param_type_end();
1688 i != e; ++i, ++ArgIndex) {
1689 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1690 SourceLocation ParamLoc = PD->getLocation();
1691 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1692 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1693 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1694 FD->isConsteval()))
1695 return false;
1696 }
1697 return true;
1698}
1699
1700/// Check whether a function's return type is a literal type. If so, return
1701/// true. If not, produce a suitable diagnostic and return false.
1702static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1703 Sema::CheckConstexprKind Kind) {
1704 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1705 diag::err_constexpr_non_literal_return,
1706 FD->isConsteval()))
1707 return false;
1708 return true;
1709}
1710
1711/// Get diagnostic %select index for tag kind for
1712/// record diagnostic message.
1713/// WARNING: Indexes apply to particular diagnostics only!
1714///
1715/// \returns diagnostic %select index.
1716static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1717 switch (Tag) {
1718 case TTK_Struct: return 0;
1719 case TTK_Interface: return 1;
1720 case TTK_Class: return 2;
1721 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 1721)
;
1722 }
1723}
1724
1725static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1726 Stmt *Body,
1727 Sema::CheckConstexprKind Kind);
1728
1729// Check whether a function declaration satisfies the requirements of a
1730// constexpr function definition or a constexpr constructor definition. If so,
1731// return true. If not, produce appropriate diagnostics (unless asked not to by
1732// Kind) and return false.
1733//
1734// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1735bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1736 CheckConstexprKind Kind) {
1737 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1738 if (MD && MD->isInstance()) {
1739 // C++11 [dcl.constexpr]p4:
1740 // The definition of a constexpr constructor shall satisfy the following
1741 // constraints:
1742 // - the class shall not have any virtual base classes;
1743 //
1744 // FIXME: This only applies to constructors and destructors, not arbitrary
1745 // member functions.
1746 const CXXRecordDecl *RD = MD->getParent();
1747 if (RD->getNumVBases()) {
1748 if (Kind == CheckConstexprKind::CheckValid)
1749 return false;
1750
1751 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1752 << isa<CXXConstructorDecl>(NewFD)
1753 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1754 for (const auto &I : RD->vbases())
1755 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1756 << I.getSourceRange();
1757 return false;
1758 }
1759 }
1760
1761 if (!isa<CXXConstructorDecl>(NewFD)) {
1762 // C++11 [dcl.constexpr]p3:
1763 // The definition of a constexpr function shall satisfy the following
1764 // constraints:
1765 // - it shall not be virtual; (removed in C++20)
1766 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1767 if (Method && Method->isVirtual()) {
1768 if (getLangOpts().CPlusPlus20) {
1769 if (Kind == CheckConstexprKind::Diagnose)
1770 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1771 } else {
1772 if (Kind == CheckConstexprKind::CheckValid)
1773 return false;
1774
1775 Method = Method->getCanonicalDecl();
1776 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1777
1778 // If it's not obvious why this function is virtual, find an overridden
1779 // function which uses the 'virtual' keyword.
1780 const CXXMethodDecl *WrittenVirtual = Method;
1781 while (!WrittenVirtual->isVirtualAsWritten())
1782 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1783 if (WrittenVirtual != Method)
1784 Diag(WrittenVirtual->getLocation(),
1785 diag::note_overridden_virtual_function);
1786 return false;
1787 }
1788 }
1789
1790 // - its return type shall be a literal type;
1791 if (!CheckConstexprReturnType(*this, NewFD, Kind))
1792 return false;
1793 }
1794
1795 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1796 // A destructor can be constexpr only if the defaulted destructor could be;
1797 // we don't need to check the members and bases if we already know they all
1798 // have constexpr destructors.
1799 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1800 if (Kind == CheckConstexprKind::CheckValid)
1801 return false;
1802 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1803 return false;
1804 }
1805 }
1806
1807 // - each of its parameter types shall be a literal type;
1808 if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1809 return false;
1810
1811 Stmt *Body = NewFD->getBody();
1812 assert(Body &&(static_cast <bool> (Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? void (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 1813, __extension__ __PRETTY_FUNCTION__))
1813 "CheckConstexprFunctionDefinition called on function with no body")(static_cast <bool> (Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? void (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 1813, __extension__ __PRETTY_FUNCTION__))
;
1814 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1815}
1816
1817/// Check the given declaration statement is legal within a constexpr function
1818/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1819///
1820/// \return true if the body is OK (maybe only as an extension), false if we
1821/// have diagnosed a problem.
1822static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1823 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1824 Sema::CheckConstexprKind Kind) {
1825 // C++11 [dcl.constexpr]p3 and p4:
1826 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1827 // contain only
1828 for (const auto *DclIt : DS->decls()) {
1829 switch (DclIt->getKind()) {
1830 case Decl::StaticAssert:
1831 case Decl::Using:
1832 case Decl::UsingShadow:
1833 case Decl::UsingDirective:
1834 case Decl::UnresolvedUsingTypename:
1835 case Decl::UnresolvedUsingValue:
1836 case Decl::UsingEnum:
1837 // - static_assert-declarations
1838 // - using-declarations,
1839 // - using-directives,
1840 // - using-enum-declaration
1841 continue;
1842
1843 case Decl::Typedef:
1844 case Decl::TypeAlias: {
1845 // - typedef declarations and alias-declarations that do not define
1846 // classes or enumerations,
1847 const auto *TN = cast<TypedefNameDecl>(DclIt);
1848 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1849 // Don't allow variably-modified types in constexpr functions.
1850 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1853 << TL.getSourceRange() << TL.getType()
1854 << isa<CXXConstructorDecl>(Dcl);
1855 }
1856 return false;
1857 }
1858 continue;
1859 }
1860
1861 case Decl::Enum:
1862 case Decl::CXXRecord:
1863 // C++1y allows types to be defined, not just declared.
1864 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1865 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866 SemaRef.Diag(DS->getBeginLoc(),
1867 SemaRef.getLangOpts().CPlusPlus14
1868 ? diag::warn_cxx11_compat_constexpr_type_definition
1869 : diag::ext_constexpr_type_definition)
1870 << isa<CXXConstructorDecl>(Dcl);
1871 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1872 return false;
1873 }
1874 }
1875 continue;
1876
1877 case Decl::EnumConstant:
1878 case Decl::IndirectField:
1879 case Decl::ParmVar:
1880 // These can only appear with other declarations which are banned in
1881 // C++11 and permitted in C++1y, so ignore them.
1882 continue;
1883
1884 case Decl::Var:
1885 case Decl::Decomposition: {
1886 // C++1y [dcl.constexpr]p3 allows anything except:
1887 // a definition of a variable of non-literal type or of static or
1888 // thread storage duration or [before C++2a] for which no
1889 // initialization is performed.
1890 const auto *VD = cast<VarDecl>(DclIt);
1891 if (VD->isThisDeclarationADefinition()) {
1892 if (VD->isStaticLocal()) {
1893 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1894 SemaRef.Diag(VD->getLocation(),
1895 diag::err_constexpr_local_var_static)
1896 << isa<CXXConstructorDecl>(Dcl)
1897 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1898 }
1899 return false;
1900 }
1901 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1902 diag::err_constexpr_local_var_non_literal_type,
1903 isa<CXXConstructorDecl>(Dcl)))
1904 return false;
1905 if (!VD->getType()->isDependentType() &&
1906 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1907 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1908 SemaRef.Diag(
1909 VD->getLocation(),
1910 SemaRef.getLangOpts().CPlusPlus20
1911 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1912 : diag::ext_constexpr_local_var_no_init)
1913 << isa<CXXConstructorDecl>(Dcl);
1914 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1915 return false;
1916 }
1917 continue;
1918 }
1919 }
1920 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1921 SemaRef.Diag(VD->getLocation(),
1922 SemaRef.getLangOpts().CPlusPlus14
1923 ? diag::warn_cxx11_compat_constexpr_local_var
1924 : diag::ext_constexpr_local_var)
1925 << isa<CXXConstructorDecl>(Dcl);
1926 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1927 return false;
1928 }
1929 continue;
1930 }
1931
1932 case Decl::NamespaceAlias:
1933 case Decl::Function:
1934 // These are disallowed in C++11 and permitted in C++1y. Allow them
1935 // everywhere as an extension.
1936 if (!Cxx1yLoc.isValid())
1937 Cxx1yLoc = DS->getBeginLoc();
1938 continue;
1939
1940 default:
1941 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1942 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1943 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1944 }
1945 return false;
1946 }
1947 }
1948
1949 return true;
1950}
1951
1952/// Check that the given field is initialized within a constexpr constructor.
1953///
1954/// \param Dcl The constexpr constructor being checked.
1955/// \param Field The field being checked. This may be a member of an anonymous
1956/// struct or union nested within the class being checked.
1957/// \param Inits All declarations, including anonymous struct/union members and
1958/// indirect members, for which any initialization was provided.
1959/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1960/// multiple notes for different members to the same error.
1961/// \param Kind Whether we're diagnosing a constructor as written or determining
1962/// whether the formal requirements are satisfied.
1963/// \return \c false if we're checking for validity and the constructor does
1964/// not satisfy the requirements on a constexpr constructor.
1965static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1966 const FunctionDecl *Dcl,
1967 FieldDecl *Field,
1968 llvm::SmallSet<Decl*, 16> &Inits,
1969 bool &Diagnosed,
1970 Sema::CheckConstexprKind Kind) {
1971 // In C++20 onwards, there's nothing to check for validity.
1972 if (Kind == Sema::CheckConstexprKind::CheckValid &&
1973 SemaRef.getLangOpts().CPlusPlus20)
1974 return true;
1975
1976 if (Field->isInvalidDecl())
1977 return true;
1978
1979 if (Field->isUnnamedBitfield())
1980 return true;
1981
1982 // Anonymous unions with no variant members and empty anonymous structs do not
1983 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1984 // indirect fields don't need initializing.
1985 if (Field->isAnonymousStructOrUnion() &&
1986 (Field->getType()->isUnionType()
1987 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1988 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1989 return true;
1990
1991 if (!Inits.count(Field)) {
1992 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1993 if (!Diagnosed) {
1994 SemaRef.Diag(Dcl->getLocation(),
1995 SemaRef.getLangOpts().CPlusPlus20
1996 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1997 : diag::ext_constexpr_ctor_missing_init);
1998 Diagnosed = true;
1999 }
2000 SemaRef.Diag(Field->getLocation(),
2001 diag::note_constexpr_ctor_missing_init);
2002 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2003 return false;
2004 }
2005 } else if (Field->isAnonymousStructOrUnion()) {
2006 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2007 for (auto *I : RD->fields())
2008 // If an anonymous union contains an anonymous struct of which any member
2009 // is initialized, all members must be initialized.
2010 if (!RD->isUnion() || Inits.count(I))
2011 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2012 Kind))
2013 return false;
2014 }
2015 return true;
2016}
2017
2018/// Check the provided statement is allowed in a constexpr function
2019/// definition.
2020static bool
2021CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2022 SmallVectorImpl<SourceLocation> &ReturnStmts,
2023 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2024 Sema::CheckConstexprKind Kind) {
2025 // - its function-body shall be [...] a compound-statement that contains only
2026 switch (S->getStmtClass()) {
2027 case Stmt::NullStmtClass:
2028 // - null statements,
2029 return true;
2030
2031 case Stmt::DeclStmtClass:
2032 // - static_assert-declarations
2033 // - using-declarations,
2034 // - using-directives,
2035 // - typedef declarations and alias-declarations that do not define
2036 // classes or enumerations,
2037 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2038 return false;
2039 return true;
2040
2041 case Stmt::ReturnStmtClass:
2042 // - and exactly one return statement;
2043 if (isa<CXXConstructorDecl>(Dcl)) {
2044 // C++1y allows return statements in constexpr constructors.
2045 if (!Cxx1yLoc.isValid())
2046 Cxx1yLoc = S->getBeginLoc();
2047 return true;
2048 }
2049
2050 ReturnStmts.push_back(S->getBeginLoc());
2051 return true;
2052
2053 case Stmt::CompoundStmtClass: {
2054 // C++1y allows compound-statements.
2055 if (!Cxx1yLoc.isValid())
2056 Cxx1yLoc = S->getBeginLoc();
2057
2058 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2059 for (auto *BodyIt : CompStmt->body()) {
2060 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2061 Cxx1yLoc, Cxx2aLoc, Kind))
2062 return false;
2063 }
2064 return true;
2065 }
2066
2067 case Stmt::AttributedStmtClass:
2068 if (!Cxx1yLoc.isValid())
2069 Cxx1yLoc = S->getBeginLoc();
2070 return true;
2071
2072 case Stmt::IfStmtClass: {
2073 // C++1y allows if-statements.
2074 if (!Cxx1yLoc.isValid())
2075 Cxx1yLoc = S->getBeginLoc();
2076
2077 IfStmt *If = cast<IfStmt>(S);
2078 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2079 Cxx1yLoc, Cxx2aLoc, Kind))
2080 return false;
2081 if (If->getElse() &&
2082 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2083 Cxx1yLoc, Cxx2aLoc, Kind))
2084 return false;
2085 return true;
2086 }
2087
2088 case Stmt::WhileStmtClass:
2089 case Stmt::DoStmtClass:
2090 case Stmt::ForStmtClass:
2091 case Stmt::CXXForRangeStmtClass:
2092 case Stmt::ContinueStmtClass:
2093 // C++1y allows all of these. We don't allow them as extensions in C++11,
2094 // because they don't make sense without variable mutation.
2095 if (!SemaRef.getLangOpts().CPlusPlus14)
2096 break;
2097 if (!Cxx1yLoc.isValid())
2098 Cxx1yLoc = S->getBeginLoc();
2099 for (Stmt *SubStmt : S->children())
2100 if (SubStmt &&
2101 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2102 Cxx1yLoc, Cxx2aLoc, Kind))
2103 return false;
2104 return true;
2105
2106 case Stmt::SwitchStmtClass:
2107 case Stmt::CaseStmtClass:
2108 case Stmt::DefaultStmtClass:
2109 case Stmt::BreakStmtClass:
2110 // C++1y allows switch-statements, and since they don't need variable
2111 // mutation, we can reasonably allow them in C++11 as an extension.
2112 if (!Cxx1yLoc.isValid())
2113 Cxx1yLoc = S->getBeginLoc();
2114 for (Stmt *SubStmt : S->children())
2115 if (SubStmt &&
2116 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2117 Cxx1yLoc, Cxx2aLoc, Kind))
2118 return false;
2119 return true;
2120
2121 case Stmt::GCCAsmStmtClass:
2122 case Stmt::MSAsmStmtClass:
2123 // C++2a allows inline assembly statements.
2124 case Stmt::CXXTryStmtClass:
2125 if (Cxx2aLoc.isInvalid())
2126 Cxx2aLoc = S->getBeginLoc();
2127 for (Stmt *SubStmt : S->children()) {
2128 if (SubStmt &&
2129 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2130 Cxx1yLoc, Cxx2aLoc, Kind))
2131 return false;
2132 }
2133 return true;
2134
2135 case Stmt::CXXCatchStmtClass:
2136 // Do not bother checking the language mode (already covered by the
2137 // try block check).
2138 if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2139 cast<CXXCatchStmt>(S)->getHandlerBlock(),
2140 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2141 return false;
2142 return true;
2143
2144 default:
2145 if (!isa<Expr>(S))
2146 break;
2147
2148 // C++1y allows expression-statements.
2149 if (!Cxx1yLoc.isValid())
2150 Cxx1yLoc = S->getBeginLoc();
2151 return true;
2152 }
2153
2154 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2155 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2156 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2157 }
2158 return false;
2159}
2160
2161/// Check the body for the given constexpr function declaration only contains
2162/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2163///
2164/// \return true if the body is OK, false if we have found or diagnosed a
2165/// problem.
2166static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2167 Stmt *Body,
2168 Sema::CheckConstexprKind Kind) {
2169 SmallVector<SourceLocation, 4> ReturnStmts;
2170
2171 if (isa<CXXTryStmt>(Body)) {
2172 // C++11 [dcl.constexpr]p3:
2173 // The definition of a constexpr function shall satisfy the following
2174 // constraints: [...]
2175 // - its function-body shall be = delete, = default, or a
2176 // compound-statement
2177 //
2178 // C++11 [dcl.constexpr]p4:
2179 // In the definition of a constexpr constructor, [...]
2180 // - its function-body shall not be a function-try-block;
2181 //
2182 // This restriction is lifted in C++2a, as long as inner statements also
2183 // apply the general constexpr rules.
2184 switch (Kind) {
2185 case Sema::CheckConstexprKind::CheckValid:
2186 if (!SemaRef.getLangOpts().CPlusPlus20)
2187 return false;
2188 break;
2189
2190 case Sema::CheckConstexprKind::Diagnose:
2191 SemaRef.Diag(Body->getBeginLoc(),
2192 !SemaRef.getLangOpts().CPlusPlus20
2193 ? diag::ext_constexpr_function_try_block_cxx20
2194 : diag::warn_cxx17_compat_constexpr_function_try_block)
2195 << isa<CXXConstructorDecl>(Dcl);
2196 break;
2197 }
2198 }
2199
2200 // - its function-body shall be [...] a compound-statement that contains only
2201 // [... list of cases ...]
2202 //
2203 // Note that walking the children here is enough to properly check for
2204 // CompoundStmt and CXXTryStmt body.
2205 SourceLocation Cxx1yLoc, Cxx2aLoc;
2206 for (Stmt *SubStmt : Body->children()) {
2207 if (SubStmt &&
2208 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2209 Cxx1yLoc, Cxx2aLoc, Kind))
2210 return false;
2211 }
2212
2213 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2214 // If this is only valid as an extension, report that we don't satisfy the
2215 // constraints of the current language.
2216 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2217 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2218 return false;
2219 } else if (Cxx2aLoc.isValid()) {
2220 SemaRef.Diag(Cxx2aLoc,
2221 SemaRef.getLangOpts().CPlusPlus20
2222 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2223 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2224 << isa<CXXConstructorDecl>(Dcl);
2225 } else if (Cxx1yLoc.isValid()) {
2226 SemaRef.Diag(Cxx1yLoc,
2227 SemaRef.getLangOpts().CPlusPlus14
2228 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2229 : diag::ext_constexpr_body_invalid_stmt)
2230 << isa<CXXConstructorDecl>(Dcl);
2231 }
2232
2233 if (const CXXConstructorDecl *Constructor
2234 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2235 const CXXRecordDecl *RD = Constructor->getParent();
2236 // DR1359:
2237 // - every non-variant non-static data member and base class sub-object
2238 // shall be initialized;
2239 // DR1460:
2240 // - if the class is a union having variant members, exactly one of them
2241 // shall be initialized;
2242 if (RD->isUnion()) {
2243 if (Constructor->getNumCtorInitializers() == 0 &&
2244 RD->hasVariantMembers()) {
2245 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2246 SemaRef.Diag(
2247 Dcl->getLocation(),
2248 SemaRef.getLangOpts().CPlusPlus20
2249 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2250 : diag::ext_constexpr_union_ctor_no_init);
2251 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2252 return false;
2253 }
2254 }
2255 } else if (!Constructor->isDependentContext() &&
2256 !Constructor->isDelegatingConstructor()) {
2257 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases")(static_cast <bool> (RD->getNumVBases() == 0 &&
"constexpr ctor with virtual bases") ? void (0) : __assert_fail
("RD->getNumVBases() == 0 && \"constexpr ctor with virtual bases\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 2257, __extension__ __PRETTY_FUNCTION__))
;
2258
2259 // Skip detailed checking if we have enough initializers, and we would
2260 // allow at most one initializer per member.
2261 bool AnyAnonStructUnionMembers = false;
2262 unsigned Fields = 0;
2263 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2264 E = RD->field_end(); I != E; ++I, ++Fields) {
2265 if (I->isAnonymousStructOrUnion()) {
2266 AnyAnonStructUnionMembers = true;
2267 break;
2268 }
2269 }
2270 // DR1460:
2271 // - if the class is a union-like class, but is not a union, for each of
2272 // its anonymous union members having variant members, exactly one of
2273 // them shall be initialized;
2274 if (AnyAnonStructUnionMembers ||
2275 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2276 // Check initialization of non-static data members. Base classes are
2277 // always initialized so do not need to be checked. Dependent bases
2278 // might not have initializers in the member initializer list.
2279 llvm::SmallSet<Decl*, 16> Inits;
2280 for (const auto *I: Constructor->inits()) {
2281 if (FieldDecl *FD = I->getMember())
2282 Inits.insert(FD);
2283 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2284 Inits.insert(ID->chain_begin(), ID->chain_end());
2285 }
2286
2287 bool Diagnosed = false;
2288 for (auto *I : RD->fields())
2289 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2290 Kind))
2291 return false;
2292 }
2293 }
2294 } else {
2295 if (ReturnStmts.empty()) {
2296 // C++1y doesn't require constexpr functions to contain a 'return'
2297 // statement. We still do, unless the return type might be void, because
2298 // otherwise if there's no return statement, the function cannot
2299 // be used in a core constant expression.
2300 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2301 (Dcl->getReturnType()->isVoidType() ||
2302 Dcl->getReturnType()->isDependentType());
2303 switch (Kind) {
2304 case Sema::CheckConstexprKind::Diagnose:
2305 SemaRef.Diag(Dcl->getLocation(),
2306 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2307 : diag::err_constexpr_body_no_return)
2308 << Dcl->isConsteval();
2309 if (!OK)
2310 return false;
2311 break;
2312
2313 case Sema::CheckConstexprKind::CheckValid:
2314 // The formal requirements don't include this rule in C++14, even
2315 // though the "must be able to produce a constant expression" rules
2316 // still imply it in some cases.
2317 if (!SemaRef.getLangOpts().CPlusPlus14)
2318 return false;
2319 break;
2320 }
2321 } else if (ReturnStmts.size() > 1) {
2322 switch (Kind) {
2323 case Sema::CheckConstexprKind::Diagnose:
2324 SemaRef.Diag(
2325 ReturnStmts.back(),
2326 SemaRef.getLangOpts().CPlusPlus14
2327 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2328 : diag::ext_constexpr_body_multiple_return);
2329 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2330 SemaRef.Diag(ReturnStmts[I],
2331 diag::note_constexpr_body_previous_return);
2332 break;
2333
2334 case Sema::CheckConstexprKind::CheckValid:
2335 if (!SemaRef.getLangOpts().CPlusPlus14)
2336 return false;
2337 break;
2338 }
2339 }
2340 }
2341
2342 // C++11 [dcl.constexpr]p5:
2343 // if no function argument values exist such that the function invocation
2344 // substitution would produce a constant expression, the program is
2345 // ill-formed; no diagnostic required.
2346 // C++11 [dcl.constexpr]p3:
2347 // - every constructor call and implicit conversion used in initializing the
2348 // return value shall be one of those allowed in a constant expression.
2349 // C++11 [dcl.constexpr]p4:
2350 // - every constructor involved in initializing non-static data members and
2351 // base class sub-objects shall be a constexpr constructor.
2352 //
2353 // Note that this rule is distinct from the "requirements for a constexpr
2354 // function", so is not checked in CheckValid mode.
2355 SmallVector<PartialDiagnosticAt, 8> Diags;
2356 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2357 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2358 SemaRef.Diag(Dcl->getLocation(),
2359 diag::ext_constexpr_function_never_constant_expr)
2360 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2361 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2362 SemaRef.Diag(Diags[I].first, Diags[I].second);
2363 // Don't return false here: we allow this for compatibility in
2364 // system headers.
2365 }
2366
2367 return true;
2368}
2369
2370/// Get the class that is directly named by the current context. This is the
2371/// class for which an unqualified-id in this scope could name a constructor
2372/// or destructor.
2373///
2374/// If the scope specifier denotes a class, this will be that class.
2375/// If the scope specifier is empty, this will be the class whose
2376/// member-specification we are currently within. Otherwise, there
2377/// is no such class.
2378CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2379 assert(getLangOpts().CPlusPlus && "No class names in C!")(static_cast <bool> (getLangOpts().CPlusPlus &&
"No class names in C!") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 2379, __extension__ __PRETTY_FUNCTION__))
;
2380
2381 if (SS && SS->isInvalid())
2382 return nullptr;
2383
2384 if (SS && SS->isNotEmpty()) {
2385 DeclContext *DC = computeDeclContext(*SS, true);
2386 return dyn_cast_or_null<CXXRecordDecl>(DC);
2387 }
2388
2389 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2390}
2391
2392/// isCurrentClassName - Determine whether the identifier II is the
2393/// name of the class type currently being defined. In the case of
2394/// nested classes, this will only return true if II is the name of
2395/// the innermost class.
2396bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2397 const CXXScopeSpec *SS) {
2398 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2399 return CurDecl && &II == CurDecl->getIdentifier();
2400}
2401
2402/// Determine whether the identifier II is a typo for the name of
2403/// the class type currently being defined. If so, update it to the identifier
2404/// that should have been used.
2405bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2406 assert(getLangOpts().CPlusPlus && "No class names in C!")(static_cast <bool> (getLangOpts().CPlusPlus &&
"No class names in C!") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 2406, __extension__ __PRETTY_FUNCTION__))
;
2407
2408 if (!getLangOpts().SpellChecking)
2409 return false;
2410
2411 CXXRecordDecl *CurDecl;
2412 if (SS && SS->isSet() && !SS->isInvalid()) {
2413 DeclContext *DC = computeDeclContext(*SS, true);
2414 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2415 } else
2416 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2417
2418 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2419 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2420 < II->getLength()) {
2421 II = CurDecl->getIdentifier();
2422 return true;
2423 }
2424
2425 return false;
2426}
2427
2428/// Determine whether the given class is a base class of the given
2429/// class, including looking at dependent bases.
2430static bool findCircularInheritance(const CXXRecordDecl *Class,
2431 const CXXRecordDecl *Current) {
2432 SmallVector<const CXXRecordDecl*, 8> Queue;
2433
2434 Class = Class->getCanonicalDecl();
2435 while (true) {
2436 for (const auto &I : Current->bases()) {
2437 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2438 if (!Base)
2439 continue;
2440
2441 Base = Base->getDefinition();
2442 if (!Base)
2443 continue;
2444
2445 if (Base->getCanonicalDecl() == Class)
2446 return true;
2447
2448 Queue.push_back(Base);
2449 }
2450
2451 if (Queue.empty())
2452 return false;
2453
2454 Current = Queue.pop_back_val();
2455 }
2456
2457 return false;
2458}
2459
2460/// Check the validity of a C++ base class specifier.
2461///
2462/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2463/// and returns NULL otherwise.
2464CXXBaseSpecifier *
2465Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2466 SourceRange SpecifierRange,
2467 bool Virtual, AccessSpecifier Access,
2468 TypeSourceInfo *TInfo,
2469 SourceLocation EllipsisLoc) {
2470 QualType BaseType = TInfo->getType();
2471 if (BaseType->containsErrors()) {
2472 // Already emitted a diagnostic when parsing the error type.
2473 return nullptr;
2474 }
2475 // C++ [class.union]p1:
2476 // A union shall not have base classes.
2477 if (Class->isUnion()) {
2478 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2479 << SpecifierRange;
2480 return nullptr;
2481 }
2482
2483 if (EllipsisLoc.isValid() &&
2484 !TInfo->getType()->containsUnexpandedParameterPack()) {
2485 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2486 << TInfo->getTypeLoc().getSourceRange();
2487 EllipsisLoc = SourceLocation();
2488 }
2489
2490 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2491
2492 if (BaseType->isDependentType()) {
2493 // Make sure that we don't have circular inheritance among our dependent
2494 // bases. For non-dependent bases, the check for completeness below handles
2495 // this.
2496 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2497 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2498 ((BaseDecl = BaseDecl->getDefinition()) &&
2499 findCircularInheritance(Class, BaseDecl))) {
2500 Diag(BaseLoc, diag::err_circular_inheritance)
2501 << BaseType << Context.getTypeDeclType(Class);
2502
2503 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2504 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2505 << BaseType;
2506
2507 return nullptr;
2508 }
2509 }
2510
2511 // Make sure that we don't make an ill-formed AST where the type of the
2512 // Class is non-dependent and its attached base class specifier is an
2513 // dependent type, which violates invariants in many clang code paths (e.g.
2514 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2515 // explicitly mark the Class decl invalid. The diagnostic was already
2516 // emitted.
2517 if (!Class->getTypeForDecl()->isDependentType())
2518 Class->setInvalidDecl();
2519 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2520 Class->getTagKind() == TTK_Class,
2521 Access, TInfo, EllipsisLoc);
2522 }
2523
2524 // Base specifiers must be record types.
2525 if (!BaseType->isRecordType()) {
2526 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2527 return nullptr;
2528 }
2529
2530 // C++ [class.union]p1:
2531 // A union shall not be used as a base class.
2532 if (BaseType->isUnionType()) {
2533 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2534 return nullptr;
2535 }
2536
2537 // For the MS ABI, propagate DLL attributes to base class templates.
2538 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2539 if (Attr *ClassAttr = getDLLAttr(Class)) {
2540 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2541 BaseType->getAsCXXRecordDecl())) {
2542 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2543 BaseLoc);
2544 }
2545 }
2546 }
2547
2548 // C++ [class.derived]p2:
2549 // The class-name in a base-specifier shall not be an incompletely
2550 // defined class.
2551 if (RequireCompleteType(BaseLoc, BaseType,
2552 diag::err_incomplete_base_class, SpecifierRange)) {
2553 Class->setInvalidDecl();
2554 return nullptr;
2555 }
2556
2557 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2558 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2559 assert(BaseDecl && "Record type has no declaration")(static_cast <bool> (BaseDecl && "Record type has no declaration"
) ? void (0) : __assert_fail ("BaseDecl && \"Record type has no declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 2559, __extension__ __PRETTY_FUNCTION__))
;
2560 BaseDecl = BaseDecl->getDefinition();
2561 assert(BaseDecl && "Base type is not incomplete, but has no definition")(static_cast <bool> (BaseDecl && "Base type is not incomplete, but has no definition"
) ? void (0) : __assert_fail ("BaseDecl && \"Base type is not incomplete, but has no definition\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 2561, __extension__ __PRETTY_FUNCTION__))
;
2562 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2563 assert(CXXBaseDecl && "Base type is not a C++ type")(static_cast <bool> (CXXBaseDecl && "Base type is not a C++ type"
) ? void (0) : __assert_fail ("CXXBaseDecl && \"Base type is not a C++ type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 2563, __extension__ __PRETTY_FUNCTION__))
;
2564
2565 // Microsoft docs say:
2566 // "If a base-class has a code_seg attribute, derived classes must have the
2567 // same attribute."
2568 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2569 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2570 if ((DerivedCSA || BaseCSA) &&
2571 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2572 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2573 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2574 << CXXBaseDecl;
2575 return nullptr;
2576 }
2577
2578 // A class which contains a flexible array member is not suitable for use as a
2579 // base class:
2580 // - If the layout determines that a base comes before another base,
2581 // the flexible array member would index into the subsequent base.
2582 // - If the layout determines that base comes before the derived class,
2583 // the flexible array member would index into the derived class.
2584 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2585 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2586 << CXXBaseDecl->getDeclName();
2587 return nullptr;
2588 }
2589
2590 // C++ [class]p3:
2591 // If a class is marked final and it appears as a base-type-specifier in
2592 // base-clause, the program is ill-formed.
2593 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2594 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2595 << CXXBaseDecl->getDeclName()
2596 << FA->isSpelledAsSealed();
2597 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2598 << CXXBaseDecl->getDeclName() << FA->getRange();
2599 return nullptr;
2600 }
2601
2602 if (BaseDecl->isInvalidDecl())
2603 Class->setInvalidDecl();
2604
2605 // Create the base specifier.
2606 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2607 Class->getTagKind() == TTK_Class,
2608 Access, TInfo, EllipsisLoc);
2609}
2610
2611/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2612/// one entry in the base class list of a class specifier, for
2613/// example:
2614/// class foo : public bar, virtual private baz {
2615/// 'public bar' and 'virtual private baz' are each base-specifiers.
2616BaseResult
2617Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2618 ParsedAttributes &Attributes,
2619 bool Virtual, AccessSpecifier Access,
2620 ParsedType basetype, SourceLocation BaseLoc,
2621 SourceLocation EllipsisLoc) {
2622 if (!classdecl)
2623 return true;
2624
2625 AdjustDeclIfTemplate(classdecl);
2626 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2627 if (!Class)
2628 return true;
2629
2630 // We haven't yet attached the base specifiers.
2631 Class->setIsParsingBaseSpecifiers();
2632
2633 // We do not support any C++11 attributes on base-specifiers yet.
2634 // Diagnose any attributes we see.
2635 for (const ParsedAttr &AL : Attributes) {
2636 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2637 continue;
2638 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2639 ? (unsigned)diag::warn_unknown_attribute_ignored
2640 : (unsigned)diag::err_base_specifier_attribute)
2641 << AL << AL.getRange();
2642 }
2643
2644 TypeSourceInfo *TInfo = nullptr;
2645 GetTypeFromParser(basetype, &TInfo);
2646
2647 if (EllipsisLoc.isInvalid() &&
2648 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2649 UPPC_BaseType))
2650 return true;
2651
2652 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2653 Virtual, Access, TInfo,
2654 EllipsisLoc))
2655 return BaseSpec;
2656 else
2657 Class->setInvalidDecl();
2658
2659 return true;
2660}
2661
2662/// Use small set to collect indirect bases. As this is only used
2663/// locally, there's no need to abstract the small size parameter.
2664typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2665
2666/// Recursively add the bases of Type. Don't add Type itself.
2667static void
2668NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2669 const QualType &Type)
2670{
2671 // Even though the incoming type is a base, it might not be
2672 // a class -- it could be a template parm, for instance.
2673 if (auto Rec = Type->getAs<RecordType>()) {
2674 auto Decl = Rec->getAsCXXRecordDecl();
2675
2676 // Iterate over its bases.
2677 for (const auto &BaseSpec : Decl->bases()) {
2678 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2679 .getUnqualifiedType();
2680 if (Set.insert(Base).second)
2681 // If we've not already seen it, recurse.
2682 NoteIndirectBases(Context, Set, Base);
2683 }
2684 }
2685}
2686
2687/// Performs the actual work of attaching the given base class
2688/// specifiers to a C++ class.
2689bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2690 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2691 if (Bases.empty())
2692 return false;
2693
2694 // Used to keep track of which base types we have already seen, so
2695 // that we can properly diagnose redundant direct base types. Note
2696 // that the key is always the unqualified canonical type of the base
2697 // class.
2698 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2699
2700 // Used to track indirect bases so we can see if a direct base is
2701 // ambiguous.
2702 IndirectBaseSet IndirectBaseTypes;
2703
2704 // Copy non-redundant base specifiers into permanent storage.
2705 unsigned NumGoodBases = 0;
2706 bool Invalid = false;
2707 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2708 QualType NewBaseType
2709 = Context.getCanonicalType(Bases[idx]->getType());
2710 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2711
2712 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2713 if (KnownBase) {
2714 // C++ [class.mi]p3:
2715 // A class shall not be specified as a direct base class of a
2716 // derived class more than once.
2717 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2718 << KnownBase->getType() << Bases[idx]->getSourceRange();
2719
2720 // Delete the duplicate base class specifier; we're going to
2721 // overwrite its pointer later.
2722 Context.Deallocate(Bases[idx]);
2723
2724 Invalid = true;
2725 } else {
2726 // Okay, add this new base class.
2727 KnownBase = Bases[idx];
2728 Bases[NumGoodBases++] = Bases[idx];
2729
2730 // Note this base's direct & indirect bases, if there could be ambiguity.
2731 if (Bases.size() > 1)
2732 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2733
2734 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2735 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2736 if (Class->isInterface() &&
2737 (!RD->isInterfaceLike() ||
2738 KnownBase->getAccessSpecifier() != AS_public)) {
2739 // The Microsoft extension __interface does not permit bases that
2740 // are not themselves public interfaces.
2741 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2742 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2743 << RD->getSourceRange();
2744 Invalid = true;
2745 }
2746 if (RD->hasAttr<WeakAttr>())
2747 Class->addAttr(WeakAttr::CreateImplicit(Context));
2748 }
2749 }
2750 }
2751
2752 // Attach the remaining base class specifiers to the derived class.
2753 Class->setBases(Bases.data(), NumGoodBases);
2754
2755 // Check that the only base classes that are duplicate are virtual.
2756 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2757 // Check whether this direct base is inaccessible due to ambiguity.
2758 QualType BaseType = Bases[idx]->getType();
2759
2760 // Skip all dependent types in templates being used as base specifiers.
2761 // Checks below assume that the base specifier is a CXXRecord.
2762 if (BaseType->isDependentType())
2763 continue;
2764
2765 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2766 .getUnqualifiedType();
2767
2768 if (IndirectBaseTypes.count(CanonicalBase)) {
2769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2770 /*DetectVirtual=*/true);
2771 bool found
2772 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2773 assert(found)(static_cast <bool> (found) ? void (0) : __assert_fail (
"found", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 2773, __extension__ __PRETTY_FUNCTION__))
;
2774 (void)found;
2775
2776 if (Paths.isAmbiguous(CanonicalBase))
2777 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2778 << BaseType << getAmbiguousPathsDisplayString(Paths)
2779 << Bases[idx]->getSourceRange();
2780 else
2781 assert(Bases[idx]->isVirtual())(static_cast <bool> (Bases[idx]->isVirtual()) ? void
(0) : __assert_fail ("Bases[idx]->isVirtual()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 2781, __extension__ __PRETTY_FUNCTION__))
;
2782 }
2783
2784 // Delete the base class specifier, since its data has been copied
2785 // into the CXXRecordDecl.
2786 Context.Deallocate(Bases[idx]);
2787 }
2788
2789 return Invalid;
2790}
2791
2792/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2793/// class, after checking whether there are any duplicate base
2794/// classes.
2795void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2796 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2797 if (!ClassDecl || Bases.empty())
2798 return;
2799
2800 AdjustDeclIfTemplate(ClassDecl);
2801 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2802}
2803
2804/// Determine whether the type \p Derived is a C++ class that is
2805/// derived from the type \p Base.
2806bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2807 if (!getLangOpts().CPlusPlus)
2808 return false;
2809
2810 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2811 if (!DerivedRD)
2812 return false;
2813
2814 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2815 if (!BaseRD)
2816 return false;
2817
2818 // If either the base or the derived type is invalid, don't try to
2819 // check whether one is derived from the other.
2820 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2821 return false;
2822
2823 // FIXME: In a modules build, do we need the entire path to be visible for us
2824 // to be able to use the inheritance relationship?
2825 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2826 return false;
2827
2828 return DerivedRD->isDerivedFrom(BaseRD);
2829}
2830
2831/// Determine whether the type \p Derived is a C++ class that is
2832/// derived from the type \p Base.
2833bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2834 CXXBasePaths &Paths) {
2835 if (!getLangOpts().CPlusPlus)
2836 return false;
2837
2838 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2839 if (!DerivedRD)
2840 return false;
2841
2842 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2843 if (!BaseRD)
2844 return false;
2845
2846 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2847 return false;
2848
2849 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2850}
2851
2852static void BuildBasePathArray(const CXXBasePath &Path,
2853 CXXCastPath &BasePathArray) {
2854 // We first go backward and check if we have a virtual base.
2855 // FIXME: It would be better if CXXBasePath had the base specifier for
2856 // the nearest virtual base.
2857 unsigned Start = 0;
2858 for (unsigned I = Path.size(); I != 0; --I) {
2859 if (Path[I - 1].Base->isVirtual()) {
2860 Start = I - 1;
2861 break;
2862 }
2863 }
2864
2865 // Now add all bases.
2866 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2867 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2868}
2869
2870
2871void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2872 CXXCastPath &BasePathArray) {
2873 assert(BasePathArray.empty() && "Base path array must be empty!")(static_cast <bool> (BasePathArray.empty() && "Base path array must be empty!"
) ? void (0) : __assert_fail ("BasePathArray.empty() && \"Base path array must be empty!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 2873, __extension__ __PRETTY_FUNCTION__))
;
2874 assert(Paths.isRecordingPaths() && "Must record paths!")(static_cast <bool> (Paths.isRecordingPaths() &&
"Must record paths!") ? void (0) : __assert_fail ("Paths.isRecordingPaths() && \"Must record paths!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 2874, __extension__ __PRETTY_FUNCTION__))
;
2875 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2876}
2877/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2878/// conversion (where Derived and Base are class types) is
2879/// well-formed, meaning that the conversion is unambiguous (and
2880/// that all of the base classes are accessible). Returns true
2881/// and emits a diagnostic if the code is ill-formed, returns false
2882/// otherwise. Loc is the location where this routine should point to
2883/// if there is an error, and Range is the source range to highlight
2884/// if there is an error.
2885///
2886/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2887/// diagnostic for the respective type of error will be suppressed, but the
2888/// check for ill-formed code will still be performed.
2889bool
2890Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2891 unsigned InaccessibleBaseID,
2892 unsigned AmbiguousBaseConvID,
2893 SourceLocation Loc, SourceRange Range,
2894 DeclarationName Name,
2895 CXXCastPath *BasePath,
2896 bool IgnoreAccess) {
2897 // First, determine whether the path from Derived to Base is
2898 // ambiguous. This is slightly more expensive than checking whether
2899 // the Derived to Base conversion exists, because here we need to
2900 // explore multiple paths to determine if there is an ambiguity.
2901 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2902 /*DetectVirtual=*/false);
2903 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2904 if (!DerivationOkay)
2905 return true;
2906
2907 const CXXBasePath *Path = nullptr;
2908 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2909 Path = &Paths.front();
2910
2911 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2912 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2913 // user to access such bases.
2914 if (!Path && getLangOpts().MSVCCompat) {
2915 for (const CXXBasePath &PossiblePath : Paths) {
2916 if (PossiblePath.size() == 1) {
2917 Path = &PossiblePath;
2918 if (AmbiguousBaseConvID)
2919 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2920 << Base << Derived << Range;
2921 break;
2922 }
2923 }
2924 }
2925
2926 if (Path) {
2927 if (!IgnoreAccess) {
2928 // Check that the base class can be accessed.
2929 switch (
2930 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2931 case AR_inaccessible:
2932 return true;
2933 case AR_accessible:
2934 case AR_dependent:
2935 case AR_delayed:
2936 break;
2937 }
2938 }
2939
2940 // Build a base path if necessary.
2941 if (BasePath)
2942 ::BuildBasePathArray(*Path, *BasePath);
2943 return false;
2944 }
2945
2946 if (AmbiguousBaseConvID) {
2947 // We know that the derived-to-base conversion is ambiguous, and
2948 // we're going to produce a diagnostic. Perform the derived-to-base
2949 // search just one more time to compute all of the possible paths so
2950 // that we can print them out. This is more expensive than any of
2951 // the previous derived-to-base checks we've done, but at this point
2952 // performance isn't as much of an issue.
2953 Paths.clear();
2954 Paths.setRecordingPaths(true);
2955 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2956 assert(StillOkay && "Can only be used with a derived-to-base conversion")(static_cast <bool> (StillOkay && "Can only be used with a derived-to-base conversion"
) ? void (0) : __assert_fail ("StillOkay && \"Can only be used with a derived-to-base conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 2956, __extension__ __PRETTY_FUNCTION__))
;
2957 (void)StillOkay;
2958
2959 // Build up a textual representation of the ambiguous paths, e.g.,
2960 // D -> B -> A, that will be used to illustrate the ambiguous
2961 // conversions in the diagnostic. We only print one of the paths
2962 // to each base class subobject.
2963 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2964
2965 Diag(Loc, AmbiguousBaseConvID)
2966 << Derived << Base << PathDisplayStr << Range << Name;
2967 }
2968 return true;
2969}
2970
2971bool
2972Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2973 SourceLocation Loc, SourceRange Range,
2974 CXXCastPath *BasePath,
2975 bool IgnoreAccess) {
2976 return CheckDerivedToBaseConversion(
2977 Derived, Base, diag::err_upcast_to_inaccessible_base,
2978 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2979 BasePath, IgnoreAccess);
2980}
2981
2982
2983/// Builds a string representing ambiguous paths from a
2984/// specific derived class to different subobjects of the same base
2985/// class.
2986///
2987/// This function builds a string that can be used in error messages
2988/// to show the different paths that one can take through the
2989/// inheritance hierarchy to go from the derived class to different
2990/// subobjects of a base class. The result looks something like this:
2991/// @code
2992/// struct D -> struct B -> struct A
2993/// struct D -> struct C -> struct A
2994/// @endcode
2995std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2996 std::string PathDisplayStr;
2997 std::set<unsigned> DisplayedPaths;
2998 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2999 Path != Paths.end(); ++Path) {
3000 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3001 // We haven't displayed a path to this particular base
3002 // class subobject yet.
3003 PathDisplayStr += "\n ";
3004 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3005 for (CXXBasePath::const_iterator Element = Path->begin();
3006 Element != Path->end(); ++Element)
3007 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3008 }
3009 }
3010
3011 return PathDisplayStr;
3012}
3013
3014//===----------------------------------------------------------------------===//
3015// C++ class member Handling
3016//===----------------------------------------------------------------------===//
3017
3018/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3019bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3020 SourceLocation ColonLoc,
3021 const ParsedAttributesView &Attrs) {
3022 assert(Access != AS_none && "Invalid kind for syntactic access specifier!")(static_cast <bool> (Access != AS_none && "Invalid kind for syntactic access specifier!"
) ? void (0) : __assert_fail ("Access != AS_none && \"Invalid kind for syntactic access specifier!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3022, __extension__ __PRETTY_FUNCTION__))
;
3023 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3024 ASLoc, ColonLoc);
3025 CurContext->addHiddenDecl(ASDecl);
3026 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3027}
3028
3029/// CheckOverrideControl - Check C++11 override control semantics.
3030void Sema::CheckOverrideControl(NamedDecl *D) {
3031 if (D->isInvalidDecl())
3032 return;
3033
3034 // We only care about "override" and "final" declarations.
3035 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3036 return;
3037
3038 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3039
3040 // We can't check dependent instance methods.
3041 if (MD && MD->isInstance() &&
3042 (MD->getParent()->hasAnyDependentBases() ||
3043 MD->getType()->isDependentType()))
3044 return;
3045
3046 if (MD && !MD->isVirtual()) {
3047 // If we have a non-virtual method, check if if hides a virtual method.
3048 // (In that case, it's most likely the method has the wrong type.)
3049 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3050 FindHiddenVirtualMethods(MD, OverloadedMethods);
3051
3052 if (!OverloadedMethods.empty()) {
3053 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3054 Diag(OA->getLocation(),
3055 diag::override_keyword_hides_virtual_member_function)
3056 << "override" << (OverloadedMethods.size() > 1);
3057 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3058 Diag(FA->getLocation(),
3059 diag::override_keyword_hides_virtual_member_function)
3060 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3061 << (OverloadedMethods.size() > 1);
3062 }
3063 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3064 MD->setInvalidDecl();
3065 return;
3066 }
3067 // Fall through into the general case diagnostic.
3068 // FIXME: We might want to attempt typo correction here.
3069 }
3070
3071 if (!MD || !MD->isVirtual()) {
3072 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3073 Diag(OA->getLocation(),
3074 diag::override_keyword_only_allowed_on_virtual_member_functions)
3075 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3076 D->dropAttr<OverrideAttr>();
3077 }
3078 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3079 Diag(FA->getLocation(),
3080 diag::override_keyword_only_allowed_on_virtual_member_functions)
3081 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3082 << FixItHint::CreateRemoval(FA->getLocation());
3083 D->dropAttr<FinalAttr>();
3084 }
3085 return;
3086 }
3087
3088 // C++11 [class.virtual]p5:
3089 // If a function is marked with the virt-specifier override and
3090 // does not override a member function of a base class, the program is
3091 // ill-formed.
3092 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3093 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3094 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3095 << MD->getDeclName();
3096}
3097
3098void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3099 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3100 return;
3101 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3102 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3103 return;
3104
3105 SourceLocation Loc = MD->getLocation();
3106 SourceLocation SpellingLoc = Loc;
3107 if (getSourceManager().isMacroArgExpansion(Loc))
3108 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3109 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3110 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3111 return;
3112
3113 if (MD->size_overridden_methods() > 0) {
3114 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3115 unsigned DiagID =
3116 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3117 ? DiagInconsistent
3118 : DiagSuggest;
3119 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3120 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3121 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3122 };
3123 if (isa<CXXDestructorDecl>(MD))
3124 EmitDiag(
3125 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3126 diag::warn_suggest_destructor_marked_not_override_overriding);
3127 else
3128 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3129 diag::warn_suggest_function_marked_not_override_overriding);
3130 }
3131}
3132
3133/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3134/// function overrides a virtual member function marked 'final', according to
3135/// C++11 [class.virtual]p4.
3136bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3137 const CXXMethodDecl *Old) {
3138 FinalAttr *FA = Old->getAttr<FinalAttr>();
3139 if (!FA)
3140 return false;
3141
3142 Diag(New->getLocation(), diag::err_final_function_overridden)
3143 << New->getDeclName()
3144 << FA->isSpelledAsSealed();
3145 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3146 return true;
3147}
3148
3149static bool InitializationHasSideEffects(const FieldDecl &FD) {
3150 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3151 // FIXME: Destruction of ObjC lifetime types has side-effects.
3152 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3153 return !RD->isCompleteDefinition() ||
3154 !RD->hasTrivialDefaultConstructor() ||
3155 !RD->hasTrivialDestructor();
3156 return false;
3157}
3158
3159static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3160 ParsedAttributesView::const_iterator Itr =
3161 llvm::find_if(list, [](const ParsedAttr &AL) {
3162 return AL.isDeclspecPropertyAttribute();
3163 });
3164 if (Itr != list.end())
3165 return &*Itr;
3166 return nullptr;
3167}
3168
3169// Check if there is a field shadowing.
3170void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3171 DeclarationName FieldName,
3172 const CXXRecordDecl *RD,
3173 bool DeclIsField) {
3174 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3175 return;
3176
3177 // To record a shadowed field in a base
3178 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3179 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3180 CXXBasePath &Path) {
3181 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3182 // Record an ambiguous path directly
3183 if (Bases.find(Base) != Bases.end())
3184 return true;
3185 for (const auto Field : Base->lookup(FieldName)) {
3186 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3187 Field->getAccess() != AS_private) {
3188 assert(Field->getAccess() != AS_none)(static_cast <bool> (Field->getAccess() != AS_none) ?
void (0) : __assert_fail ("Field->getAccess() != AS_none"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3188, __extension__ __PRETTY_FUNCTION__))
;
3189 assert(Bases.find(Base) == Bases.end())(static_cast <bool> (Bases.find(Base) == Bases.end()) ?
void (0) : __assert_fail ("Bases.find(Base) == Bases.end()",
"/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3189, __extension__ __PRETTY_FUNCTION__))
;
3190 Bases[Base] = Field;
3191 return true;
3192 }
3193 }
3194 return false;
3195 };
3196
3197 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3198 /*DetectVirtual=*/true);
3199 if (!RD->lookupInBases(FieldShadowed, Paths))
3200 return;
3201
3202 for (const auto &P : Paths) {
3203 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3204 auto It = Bases.find(Base);
3205 // Skip duplicated bases
3206 if (It == Bases.end())
3207 continue;
3208 auto BaseField = It->second;
3209 assert(BaseField->getAccess() != AS_private)(static_cast <bool> (BaseField->getAccess() != AS_private
) ? void (0) : __assert_fail ("BaseField->getAccess() != AS_private"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3209, __extension__ __PRETTY_FUNCTION__))
;
3210 if (AS_none !=
3211 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3212 Diag(Loc, diag::warn_shadow_field)
3213 << FieldName << RD << Base << DeclIsField;
3214 Diag(BaseField->getLocation(), diag::note_shadow_field);
3215 Bases.erase(It);
3216 }
3217 }
3218}
3219
3220/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3221/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3222/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3223/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3224/// present (but parsing it has been deferred).
3225NamedDecl *
3226Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3227 MultiTemplateParamsArg TemplateParameterLists,
3228 Expr *BW, const VirtSpecifiers &VS,
3229 InClassInitStyle InitStyle) {
3230 const DeclSpec &DS = D.getDeclSpec();
3231 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3232 DeclarationName Name = NameInfo.getName();
3233 SourceLocation Loc = NameInfo.getLoc();
3234
3235 // For anonymous bitfields, the location should point to the type.
3236 if (Loc.isInvalid())
3237 Loc = D.getBeginLoc();
3238
3239 Expr *BitWidth = static_cast<Expr*>(BW);
3240
3241 assert(isa<CXXRecordDecl>(CurContext))(static_cast <bool> (isa<CXXRecordDecl>(CurContext
)) ? void (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3241, __extension__ __PRETTY_FUNCTION__))
;
3242 assert(!DS.isFriendSpecified())(static_cast <bool> (!DS.isFriendSpecified()) ? void (0
) : __assert_fail ("!DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3242, __extension__ __PRETTY_FUNCTION__))
;
3243
3244 bool isFunc = D.isDeclarationOfFunction();
3245 const ParsedAttr *MSPropertyAttr =
3246 getMSPropertyAttr(D.getDeclSpec().getAttributes());
3247
3248 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3249 // The Microsoft extension __interface only permits public member functions
3250 // and prohibits constructors, destructors, operators, non-public member
3251 // functions, static methods and data members.
3252 unsigned InvalidDecl;
3253 bool ShowDeclName = true;
3254 if (!isFunc &&
3255 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3256 InvalidDecl = 0;
3257 else if (!isFunc)
3258 InvalidDecl = 1;
3259 else if (AS != AS_public)
3260 InvalidDecl = 2;
3261 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3262 InvalidDecl = 3;
3263 else switch (Name.getNameKind()) {
3264 case DeclarationName::CXXConstructorName:
3265 InvalidDecl = 4;
3266 ShowDeclName = false;
3267 break;
3268
3269 case DeclarationName::CXXDestructorName:
3270 InvalidDecl = 5;
3271 ShowDeclName = false;
3272 break;
3273
3274 case DeclarationName::CXXOperatorName:
3275 case DeclarationName::CXXConversionFunctionName:
3276 InvalidDecl = 6;
3277 break;
3278
3279 default:
3280 InvalidDecl = 0;
3281 break;
3282 }
3283
3284 if (InvalidDecl) {
3285 if (ShowDeclName)
3286 Diag(Loc, diag::err_invalid_member_in_interface)
3287 << (InvalidDecl-1) << Name;
3288 else
3289 Diag(Loc, diag::err_invalid_member_in_interface)
3290 << (InvalidDecl-1) << "";
3291 return nullptr;
3292 }
3293 }
3294
3295 // C++ 9.2p6: A member shall not be declared to have automatic storage
3296 // duration (auto, register) or with the extern storage-class-specifier.
3297 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3298 // data members and cannot be applied to names declared const or static,
3299 // and cannot be applied to reference members.
3300 switch (DS.getStorageClassSpec()) {
3301 case DeclSpec::SCS_unspecified:
3302 case DeclSpec::SCS_typedef:
3303 case DeclSpec::SCS_static:
3304 break;
3305 case DeclSpec::SCS_mutable:
3306 if (isFunc) {
3307 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3308
3309 // FIXME: It would be nicer if the keyword was ignored only for this
3310 // declarator. Otherwise we could get follow-up errors.
3311 D.getMutableDeclSpec().ClearStorageClassSpecs();
3312 }
3313 break;
3314 default:
3315 Diag(DS.getStorageClassSpecLoc(),
3316 diag::err_storageclass_invalid_for_member);
3317 D.getMutableDeclSpec().ClearStorageClassSpecs();
3318 break;
3319 }
3320
3321 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3322 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3323 !isFunc);
3324
3325 if (DS.hasConstexprSpecifier() && isInstField) {
3326 SemaDiagnosticBuilder B =
3327 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3328 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3329 if (InitStyle == ICIS_NoInit) {
3330 B << 0 << 0;
3331 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3332 B << FixItHint::CreateRemoval(ConstexprLoc);
3333 else {
3334 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3335 D.getMutableDeclSpec().ClearConstexprSpec();
3336 const char *PrevSpec;
3337 unsigned DiagID;
3338 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3339 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3340 (void)Failed;
3341 assert(!Failed && "Making a constexpr member const shouldn't fail")(static_cast <bool> (!Failed && "Making a constexpr member const shouldn't fail"
) ? void (0) : __assert_fail ("!Failed && \"Making a constexpr member const shouldn't fail\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3341, __extension__ __PRETTY_FUNCTION__))
;
3342 }
3343 } else {
3344 B << 1;
3345 const char *PrevSpec;
3346 unsigned DiagID;
3347 if (D.getMutableDeclSpec().SetStorageClassSpec(
3348 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3349 Context.getPrintingPolicy())) {
3350 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_mutable && "This is the only DeclSpec that should fail to be applied"
) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3351, __extension__ __PRETTY_FUNCTION__))
3351 "This is the only DeclSpec that should fail to be applied")(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_mutable && "This is the only DeclSpec that should fail to be applied"
) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3351, __extension__ __PRETTY_FUNCTION__))
;
3352 B << 1;
3353 } else {
3354 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3355 isInstField = false;
3356 }
3357 }
3358 }
3359
3360 NamedDecl *Member;
3361 if (isInstField) {
3362 CXXScopeSpec &SS = D.getCXXScopeSpec();
3363
3364 // Data members must have identifiers for names.
3365 if (!Name.isIdentifier()) {
3366 Diag(Loc, diag::err_bad_variable_name)
3367 << Name;
3368 return nullptr;
3369 }
3370
3371 IdentifierInfo *II = Name.getAsIdentifierInfo();
3372
3373 // Member field could not be with "template" keyword.
3374 // So TemplateParameterLists should be empty in this case.
3375 if (TemplateParameterLists.size()) {
3376 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3377 if (TemplateParams->size()) {
3378 // There is no such thing as a member field template.
3379 Diag(D.getIdentifierLoc(), diag::err_template_member)
3380 << II
3381 << SourceRange(TemplateParams->getTemplateLoc(),
3382 TemplateParams->getRAngleLoc());
3383 } else {
3384 // There is an extraneous 'template<>' for this member.
3385 Diag(TemplateParams->getTemplateLoc(),
3386 diag::err_template_member_noparams)
3387 << II
3388 << SourceRange(TemplateParams->getTemplateLoc(),
3389 TemplateParams->getRAngleLoc());
3390 }
3391 return nullptr;
3392 }
3393
3394 if (SS.isSet() && !SS.isInvalid()) {
3395 // The user provided a superfluous scope specifier inside a class
3396 // definition:
3397 //
3398 // class X {
3399 // int X::member;
3400 // };
3401 if (DeclContext *DC = computeDeclContext(SS, false))
3402 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3403 D.getName().getKind() ==
3404 UnqualifiedIdKind::IK_TemplateId);
3405 else
3406 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3407 << Name << SS.getRange();
3408
3409 SS.clear();
3410 }
3411
3412 if (MSPropertyAttr) {
3413 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3414 BitWidth, InitStyle, AS, *MSPropertyAttr);
3415 if (!Member)
3416 return nullptr;
3417 isInstField = false;
3418 } else {
3419 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3420 BitWidth, InitStyle, AS);
3421 if (!Member)
3422 return nullptr;
3423 }
3424
3425 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3426 } else {
3427 Member = HandleDeclarator(S, D, TemplateParameterLists);
3428 if (!Member)
3429 return nullptr;
3430
3431 // Non-instance-fields can't have a bitfield.
3432 if (BitWidth) {
3433 if (Member->isInvalidDecl()) {
3434 // don't emit another diagnostic.
3435 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3436 // C++ 9.6p3: A bit-field shall not be a static member.
3437 // "static member 'A' cannot be a bit-field"
3438 Diag(Loc, diag::err_static_not_bitfield)
3439 << Name << BitWidth->getSourceRange();
3440 } else if (isa<TypedefDecl>(Member)) {
3441 // "typedef member 'x' cannot be a bit-field"
3442 Diag(Loc, diag::err_typedef_not_bitfield)
3443 << Name << BitWidth->getSourceRange();
3444 } else {
3445 // A function typedef ("typedef int f(); f a;").
3446 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3447 Diag(Loc, diag::err_not_integral_type_bitfield)
3448 << Name << cast<ValueDecl>(Member)->getType()
3449 << BitWidth->getSourceRange();
3450 }
3451
3452 BitWidth = nullptr;
3453 Member->setInvalidDecl();
3454 }
3455
3456 NamedDecl *NonTemplateMember = Member;
3457 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3458 NonTemplateMember = FunTmpl->getTemplatedDecl();
3459 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3460 NonTemplateMember = VarTmpl->getTemplatedDecl();
3461
3462 Member->setAccess(AS);
3463
3464 // If we have declared a member function template or static data member
3465 // template, set the access of the templated declaration as well.
3466 if (NonTemplateMember != Member)
3467 NonTemplateMember->setAccess(AS);
3468
3469 // C++ [temp.deduct.guide]p3:
3470 // A deduction guide [...] for a member class template [shall be
3471 // declared] with the same access [as the template].
3472 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3473 auto *TD = DG->getDeducedTemplate();
3474 // Access specifiers are only meaningful if both the template and the
3475 // deduction guide are from the same scope.
3476 if (AS != TD->getAccess() &&
3477 TD->getDeclContext()->getRedeclContext()->Equals(
3478 DG->getDeclContext()->getRedeclContext())) {
3479 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3480 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3481 << TD->getAccess();
3482 const AccessSpecDecl *LastAccessSpec = nullptr;
3483 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3484 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3485 LastAccessSpec = AccessSpec;
3486 }
3487 assert(LastAccessSpec && "differing access with no access specifier")(static_cast <bool> (LastAccessSpec && "differing access with no access specifier"
) ? void (0) : __assert_fail ("LastAccessSpec && \"differing access with no access specifier\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3487, __extension__ __PRETTY_FUNCTION__))
;
3488 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3489 << AS;
3490 }
3491 }
3492 }
3493
3494 if (VS.isOverrideSpecified())
3495 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3496 AttributeCommonInfo::AS_Keyword));
3497 if (VS.isFinalSpecified())
3498 Member->addAttr(FinalAttr::Create(
3499 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3500 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3501
3502 if (VS.getLastLocation().isValid()) {
3503 // Update the end location of a method that has a virt-specifiers.
3504 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3505 MD->setRangeEnd(VS.getLastLocation());
3506 }
3507
3508 CheckOverrideControl(Member);
3509
3510 assert((Name || isInstField) && "No identifier for non-field ?")(static_cast <bool> ((Name || isInstField) && "No identifier for non-field ?"
) ? void (0) : __assert_fail ("(Name || isInstField) && \"No identifier for non-field ?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3510, __extension__ __PRETTY_FUNCTION__))
;
3511
3512 if (isInstField) {
3513 FieldDecl *FD = cast<FieldDecl>(Member);
3514 FieldCollector->Add(FD);
3515
3516 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3517 // Remember all explicit private FieldDecls that have a name, no side
3518 // effects and are not part of a dependent type declaration.
3519 if (!FD->isImplicit() && FD->getDeclName() &&
3520 FD->getAccess() == AS_private &&
3521 !FD->hasAttr<UnusedAttr>() &&
3522 !FD->getParent()->isDependentContext() &&
3523 !InitializationHasSideEffects(*FD))
3524 UnusedPrivateFields.insert(FD);
3525 }
3526 }
3527
3528 return Member;
3529}
3530
3531namespace {
3532 class UninitializedFieldVisitor
3533 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3534 Sema &S;
3535 // List of Decls to generate a warning on. Also remove Decls that become
3536 // initialized.
3537 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3538 // List of base classes of the record. Classes are removed after their
3539 // initializers.
3540 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3541 // Vector of decls to be removed from the Decl set prior to visiting the
3542 // nodes. These Decls may have been initialized in the prior initializer.
3543 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3544 // If non-null, add a note to the warning pointing back to the constructor.
3545 const CXXConstructorDecl *Constructor;
3546 // Variables to hold state when processing an initializer list. When
3547 // InitList is true, special case initialization of FieldDecls matching
3548 // InitListFieldDecl.
3549 bool InitList;
3550 FieldDecl *InitListFieldDecl;
3551 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3552
3553 public:
3554 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3555 UninitializedFieldVisitor(Sema &S,
3556 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3557 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3558 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3559 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3560
3561 // Returns true if the use of ME is not an uninitialized use.
3562 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3563 bool CheckReferenceOnly) {
3564 llvm::SmallVector<FieldDecl*, 4> Fields;
3565 bool ReferenceField = false;
3566 while (ME) {
3567 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3568 if (!FD)
3569 return false;
3570 Fields.push_back(FD);
3571 if (FD->getType()->isReferenceType())
3572 ReferenceField = true;
3573 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3574 }
3575
3576 // Binding a reference to an uninitialized field is not an
3577 // uninitialized use.
3578 if (CheckReferenceOnly && !ReferenceField)
3579 return true;
3580
3581 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3582 // Discard the first field since it is the field decl that is being
3583 // initialized.
3584 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3585 UsedFieldIndex.push_back((*I)->getFieldIndex());
3586 }
3587
3588 for (auto UsedIter = UsedFieldIndex.begin(),
3589 UsedEnd = UsedFieldIndex.end(),
3590 OrigIter = InitFieldIndex.begin(),
3591 OrigEnd = InitFieldIndex.end();
3592 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3593 if (*UsedIter < *OrigIter)
3594 return true;
3595 if (*UsedIter > *OrigIter)
3596 break;
3597 }
3598
3599 return false;
3600 }
3601
3602 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3603 bool AddressOf) {
3604 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3605 return;
3606
3607 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3608 // or union.
3609 MemberExpr *FieldME = ME;
3610
3611 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3612
3613 Expr *Base = ME;
3614 while (MemberExpr *SubME =
3615 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3616
3617 if (isa<VarDecl>(SubME->getMemberDecl()))
3618 return;
3619
3620 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3621 if (!FD->isAnonymousStructOrUnion())
3622 FieldME = SubME;
3623
3624 if (!FieldME->getType().isPODType(S.Context))
3625 AllPODFields = false;
3626
3627 Base = SubME->getBase();
3628 }
3629
3630 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3631 Visit(Base);
3632 return;
3633 }
3634
3635 if (AddressOf && AllPODFields)
3636 return;
3637
3638 ValueDecl* FoundVD = FieldME->getMemberDecl();
3639
3640 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3641 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3642 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3643 }
3644
3645 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3646 QualType T = BaseCast->getType();
3647 if (T->isPointerType() &&
3648 BaseClasses.count(T->getPointeeType())) {
3649 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3650 << T->getPointeeType() << FoundVD;
3651 }
3652 }
3653 }
3654
3655 if (!Decls.count(FoundVD))
3656 return;
3657
3658 const bool IsReference = FoundVD->getType()->isReferenceType();
3659
3660 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3661 // Special checking for initializer lists.
3662 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3663 return;
3664 }
3665 } else {
3666 // Prevent double warnings on use of unbounded references.
3667 if (CheckReferenceOnly && !IsReference)
3668 return;
3669 }
3670
3671 unsigned diag = IsReference
3672 ? diag::warn_reference_field_is_uninit
3673 : diag::warn_field_is_uninit;
3674 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3675 if (Constructor)
3676 S.Diag(Constructor->getLocation(),
3677 diag::note_uninit_in_this_constructor)
3678 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3679
3680 }
3681
3682 void HandleValue(Expr *E, bool AddressOf) {
3683 E = E->IgnoreParens();
3684
3685 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3686 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3687 AddressOf /*AddressOf*/);
3688 return;
3689 }
3690
3691 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3692 Visit(CO->getCond());
3693 HandleValue(CO->getTrueExpr(), AddressOf);
3694 HandleValue(CO->getFalseExpr(), AddressOf);
3695 return;
3696 }
3697
3698 if (BinaryConditionalOperator *BCO =
3699 dyn_cast<BinaryConditionalOperator>(E)) {
3700 Visit(BCO->getCond());
3701 HandleValue(BCO->getFalseExpr(), AddressOf);
3702 return;
3703 }
3704
3705 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3706 HandleValue(OVE->getSourceExpr(), AddressOf);
3707 return;
3708 }
3709
3710 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3711 switch (BO->getOpcode()) {
3712 default:
3713 break;
3714 case(BO_PtrMemD):
3715 case(BO_PtrMemI):
3716 HandleValue(BO->getLHS(), AddressOf);
3717 Visit(BO->getRHS());
3718 return;
3719 case(BO_Comma):
3720 Visit(BO->getLHS());
3721 HandleValue(BO->getRHS(), AddressOf);
3722 return;
3723 }
3724 }
3725
3726 Visit(E);
3727 }
3728
3729 void CheckInitListExpr(InitListExpr *ILE) {
3730 InitFieldIndex.push_back(0);
3731 for (auto Child : ILE->children()) {
3732 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3733 CheckInitListExpr(SubList);
3734 } else {
3735 Visit(Child);
3736 }
3737 ++InitFieldIndex.back();
3738 }
3739 InitFieldIndex.pop_back();
3740 }
3741
3742 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3743 FieldDecl *Field, const Type *BaseClass) {
3744 // Remove Decls that may have been initialized in the previous
3745 // initializer.
3746 for (ValueDecl* VD : DeclsToRemove)
3747 Decls.erase(VD);
3748 DeclsToRemove.clear();
3749
3750 Constructor = FieldConstructor;
3751 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3752
3753 if (ILE && Field) {
3754 InitList = true;
3755 InitListFieldDecl = Field;
3756 InitFieldIndex.clear();
3757 CheckInitListExpr(ILE);
3758 } else {
3759 InitList = false;
3760 Visit(E);
3761 }
3762
3763 if (Field)
3764 Decls.erase(Field);
3765 if (BaseClass)
3766 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3767 }
3768
3769 void VisitMemberExpr(MemberExpr *ME) {
3770 // All uses of unbounded reference fields will warn.
3771 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3772 }
3773
3774 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3775 if (E->getCastKind() == CK_LValueToRValue) {
3776 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3777 return;
3778 }
3779
3780 Inherited::VisitImplicitCastExpr(E);
3781 }
3782
3783 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3784 if (E->getConstructor()->isCopyConstructor()) {
3785 Expr *ArgExpr = E->getArg(0);
3786 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3787 if (ILE->getNumInits() == 1)
3788 ArgExpr = ILE->getInit(0);
3789 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3790 if (ICE->getCastKind() == CK_NoOp)
3791 ArgExpr = ICE->getSubExpr();
3792 HandleValue(ArgExpr, false /*AddressOf*/);
3793 return;
3794 }
3795 Inherited::VisitCXXConstructExpr(E);
3796 }
3797
3798 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3799 Expr *Callee = E->getCallee();
3800 if (isa<MemberExpr>(Callee)) {
3801 HandleValue(Callee, false /*AddressOf*/);
3802 for (auto Arg : E->arguments())
3803 Visit(Arg);
3804 return;
3805 }
3806
3807 Inherited::VisitCXXMemberCallExpr(E);
3808 }
3809
3810 void VisitCallExpr(CallExpr *E) {
3811 // Treat std::move as a use.
3812 if (E->isCallToStdMove()) {
3813 HandleValue(E->getArg(0), /*AddressOf=*/false);
3814 return;
3815 }
3816
3817 Inherited::VisitCallExpr(E);
3818 }
3819
3820 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3821 Expr *Callee = E->getCallee();
3822
3823 if (isa<UnresolvedLookupExpr>(Callee))
3824 return Inherited::VisitCXXOperatorCallExpr(E);
3825
3826 Visit(Callee);
3827 for (auto Arg : E->arguments())
3828 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3829 }
3830
3831 void VisitBinaryOperator(BinaryOperator *E) {
3832 // If a field assignment is detected, remove the field from the
3833 // uninitiailized field set.
3834 if (E->getOpcode() == BO_Assign)
3835 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3836 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3837 if (!FD->getType()->isReferenceType())
3838 DeclsToRemove.push_back(FD);
3839
3840 if (E->isCompoundAssignmentOp()) {
3841 HandleValue(E->getLHS(), false /*AddressOf*/);
3842 Visit(E->getRHS());
3843 return;
3844 }
3845
3846 Inherited::VisitBinaryOperator(E);
3847 }
3848
3849 void VisitUnaryOperator(UnaryOperator *E) {
3850 if (E->isIncrementDecrementOp()) {
3851 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3852 return;
3853 }
3854 if (E->getOpcode() == UO_AddrOf) {
3855 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3856 HandleValue(ME->getBase(), true /*AddressOf*/);
3857 return;
3858 }
3859 }
3860
3861 Inherited::VisitUnaryOperator(E);
3862 }
3863 };
3864
3865 // Diagnose value-uses of fields to initialize themselves, e.g.
3866 // foo(foo)
3867 // where foo is not also a parameter to the constructor.
3868 // Also diagnose across field uninitialized use such as
3869 // x(y), y(x)
3870 // TODO: implement -Wuninitialized and fold this into that framework.
3871 static void DiagnoseUninitializedFields(
3872 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3873
3874 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3875 Constructor->getLocation())) {
3876 return;
3877 }
3878
3879 if (Constructor->isInvalidDecl())
3880 return;
3881
3882 const CXXRecordDecl *RD = Constructor->getParent();
3883
3884 if (RD->isDependentContext())
3885 return;
3886
3887 // Holds fields that are uninitialized.
3888 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3889
3890 // At the beginning, all fields are uninitialized.
3891 for (auto *I : RD->decls()) {
3892 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3893 UninitializedFields.insert(FD);
3894 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3895 UninitializedFields.insert(IFD->getAnonField());
3896 }
3897 }
3898
3899 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3900 for (auto I : RD->bases())
3901 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3902
3903 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3904 return;
3905
3906 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3907 UninitializedFields,
3908 UninitializedBaseClasses);
3909
3910 for (const auto *FieldInit : Constructor->inits()) {
3911 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3912 break;
3913
3914 Expr *InitExpr = FieldInit->getInit();
3915 if (!InitExpr)
3916 continue;
3917
3918 if (CXXDefaultInitExpr *Default =
3919 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3920 InitExpr = Default->getExpr();
3921 if (!InitExpr)
3922 continue;
3923 // In class initializers will point to the constructor.
3924 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3925 FieldInit->getAnyMember(),
3926 FieldInit->getBaseClass());
3927 } else {
3928 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3929 FieldInit->getAnyMember(),
3930 FieldInit->getBaseClass());
3931 }
3932 }
3933 }
3934} // namespace
3935
3936/// Enter a new C++ default initializer scope. After calling this, the
3937/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3938/// parsing or instantiating the initializer failed.
3939void Sema::ActOnStartCXXInClassMemberInitializer() {
3940 // Create a synthetic function scope to represent the call to the constructor
3941 // that notionally surrounds a use of this initializer.
3942 PushFunctionScope();
3943}
3944
3945void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3946 if (!D.isFunctionDeclarator())
3947 return;
3948 auto &FTI = D.getFunctionTypeInfo();
3949 if (!FTI.Params)
3950 return;
3951 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3952 FTI.NumParams)) {
3953 auto *ParamDecl = cast<NamedDecl>(Param.Param);
3954 if (ParamDecl->getDeclName())
3955 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3956 }
3957}
3958
3959ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3960 return ActOnRequiresClause(ConstraintExpr);
3961}
3962
3963ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
3964 if (ConstraintExpr.isInvalid())
3965 return ExprError();
3966
3967 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
3968 if (ConstraintExpr.isInvalid())
3969 return ExprError();
3970
3971 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
3972 UPPC_RequiresClause))
3973 return ExprError();
3974
3975 return ConstraintExpr;
3976}
3977
3978/// This is invoked after parsing an in-class initializer for a
3979/// non-static C++ class member, and after instantiating an in-class initializer
3980/// in a class template. Such actions are deferred until the class is complete.
3981void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3982 SourceLocation InitLoc,
3983 Expr *InitExpr) {
3984 // Pop the notional constructor scope we created earlier.
3985 PopFunctionScopeInfo(nullptr, D);
3986
3987 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3988 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&(static_cast <bool> ((isa<MSPropertyDecl>(D) || FD
->getInClassInitStyle() != ICIS_NoInit) && "must set init style when field is created"
) ? void (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3989, __extension__ __PRETTY_FUNCTION__))
3989 "must set init style when field is created")(static_cast <bool> ((isa<MSPropertyDecl>(D) || FD
->getInClassInitStyle() != ICIS_NoInit) && "must set init style when field is created"
) ? void (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 3989, __extension__ __PRETTY_FUNCTION__))
;
3990
3991 if (!InitExpr) {
3992 D->setInvalidDecl();
3993 if (FD)
3994 FD->removeInClassInitializer();
3995 return;
3996 }
3997
3998 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3999 FD->setInvalidDecl();
4000 FD->removeInClassInitializer();
4001 return;
4002 }
4003
4004 ExprResult Init = InitExpr;
4005 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4006 InitializedEntity Entity =
4007 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4008 InitializationKind Kind =
4009 FD->getInClassInitStyle() == ICIS_ListInit
4010 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4011 InitExpr->getBeginLoc(),
4012 InitExpr->getEndLoc())
4013 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4014 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4015 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4016 if (Init.isInvalid()) {
4017 FD->setInvalidDecl();
4018 return;
4019 }
4020 }
4021
4022 // C++11 [class.base.init]p7:
4023 // The initialization of each base and member constitutes a
4024 // full-expression.
4025 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4026 if (Init.isInvalid()) {
4027 FD->setInvalidDecl();
4028 return;
4029 }
4030
4031 InitExpr = Init.get();
4032
4033 FD->setInClassInitializer(InitExpr);
4034}
4035
4036/// Find the direct and/or virtual base specifiers that
4037/// correspond to the given base type, for use in base initialization
4038/// within a constructor.
4039static bool FindBaseInitializer(Sema &SemaRef,
4040 CXXRecordDecl *ClassDecl,
4041 QualType BaseType,
4042 const CXXBaseSpecifier *&DirectBaseSpec,
4043 const CXXBaseSpecifier *&VirtualBaseSpec) {
4044 // First, check for a direct base class.
4045 DirectBaseSpec = nullptr;
4046 for (const auto &Base : ClassDecl->bases()) {
4047 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4048 // We found a direct base of this type. That's what we're
4049 // initializing.
4050 DirectBaseSpec = &Base;
4051 break;
4052 }
4053 }
4054
4055 // Check for a virtual base class.
4056 // FIXME: We might be able to short-circuit this if we know in advance that
4057 // there are no virtual bases.
4058 VirtualBaseSpec = nullptr;
4059 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4060 // We haven't found a base yet; search the class hierarchy for a
4061 // virtual base class.
4062 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4063 /*DetectVirtual=*/false);
4064 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4065 SemaRef.Context.getTypeDeclType(ClassDecl),
4066 BaseType, Paths)) {
4067 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4068 Path != Paths.end(); ++Path) {
4069 if (Path->back().Base->isVirtual()) {
4070 VirtualBaseSpec = Path->back().Base;
4071 break;
4072 }
4073 }
4074 }
4075 }
4076
4077 return DirectBaseSpec || VirtualBaseSpec;
4078}
4079
4080/// Handle a C++ member initializer using braced-init-list syntax.
4081MemInitResult
4082Sema::ActOnMemInitializer(Decl *ConstructorD,
4083 Scope *S,
4084 CXXScopeSpec &SS,
4085 IdentifierInfo *MemberOrBase,
4086 ParsedType TemplateTypeTy,
4087 const DeclSpec &DS,
4088 SourceLocation IdLoc,
4089 Expr *InitList,
4090 SourceLocation EllipsisLoc) {
4091 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1
Calling 'Sema::BuildMemInitializer'
4092 DS, IdLoc, InitList,
4093 EllipsisLoc);
4094}
4095
4096/// Handle a C++ member initializer using parentheses syntax.
4097MemInitResult
4098Sema::ActOnMemInitializer(Decl *ConstructorD,
4099 Scope *S,
4100 CXXScopeSpec &SS,
4101 IdentifierInfo *MemberOrBase,
4102 ParsedType TemplateTypeTy,
4103 const DeclSpec &DS,
4104 SourceLocation IdLoc,
4105 SourceLocation LParenLoc,
4106 ArrayRef<Expr *> Args,
4107 SourceLocation RParenLoc,
4108 SourceLocation EllipsisLoc) {
4109 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4110 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4111 DS, IdLoc, List, EllipsisLoc);
4112}
4113
4114namespace {
4115
4116// Callback to only accept typo corrections that can be a valid C++ member
4117// intializer: either a non-static field member or a base class.
4118class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4119public:
4120 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4121 : ClassDecl(ClassDecl) {}
4122
4123 bool ValidateCandidate(const TypoCorrection &candidate) override {
4124 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4125 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4126 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4127 return isa<TypeDecl>(ND);
4128 }
4129 return false;
4130 }
4131
4132 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4133 return std::make_unique<MemInitializerValidatorCCC>(*this);
4134 }
4135
4136private:
4137 CXXRecordDecl *ClassDecl;
4138};
4139
4140}
4141
4142ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4143 CXXScopeSpec &SS,
4144 ParsedType TemplateTypeTy,
4145 IdentifierInfo *MemberOrBase) {
4146 if (SS.getScopeRep() || TemplateTypeTy)
4147 return nullptr;
4148 for (auto *D : ClassDecl->lookup(MemberOrBase))
4149 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4150 return cast<ValueDecl>(D);
4151 return nullptr;
4152}
4153
4154/// Handle a C++ member initializer.
4155MemInitResult
4156Sema::BuildMemInitializer(Decl *ConstructorD,
4157 Scope *S,
4158 CXXScopeSpec &SS,
4159 IdentifierInfo *MemberOrBase,
4160 ParsedType TemplateTypeTy,
4161 const DeclSpec &DS,
4162 SourceLocation IdLoc,
4163 Expr *Init,
4164 SourceLocation EllipsisLoc) {
4165 ExprResult Res = CorrectDelayedTyposInExpr(Init);
4166 if (!Res.isUsable())
2
Calling 'ActionResult::isUsable'
5
Returning from 'ActionResult::isUsable'
6
Taking false branch
4167 return true;
4168 Init = Res.get();
4169
4170 if (!ConstructorD)
7
Assuming 'ConstructorD' is non-null
8
Taking false branch
4171 return true;
4172
4173 AdjustDeclIfTemplate(ConstructorD);
4174
4175 CXXConstructorDecl *Constructor
4176 = dyn_cast<CXXConstructorDecl>(ConstructorD);
9
Assuming 'ConstructorD' is a 'CXXConstructorDecl'
4177 if (!Constructor
9.1
'Constructor' is non-null
9.1
'Constructor' is non-null
9.1
'Constructor' is non-null
9.1
'Constructor' is non-null
9.1
'Constructor' is non-null
) {
10
Taking false branch
4178 // The user wrote a constructor initializer on a function that is
4179 // not a C++ constructor. Ignore the error for now, because we may
4180 // have more member initializers coming; we'll diagnose it just
4181 // once in ActOnMemInitializers.
4182 return true;
4183 }
4184
4185 CXXRecordDecl *ClassDecl = Constructor->getParent();
4186
4187 // C++ [class.base.init]p2:
4188 // Names in a mem-initializer-id are looked up in the scope of the
4189 // constructor's class and, if not found in that scope, are looked
4190 // up in the scope containing the constructor's definition.
4191 // [Note: if the constructor's class contains a member with the
4192 // same name as a direct or virtual base class of the class, a
4193 // mem-initializer-id naming the member or base class and composed
4194 // of a single identifier refers to the class member. A
4195 // mem-initializer-id for the hidden base class may be specified
4196 // using a qualified name. ]
4197
4198 // Look for a member, first.
4199 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
11
Assuming 'Member' is null
12
Taking false branch
4200 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4201 if (EllipsisLoc.isValid())
4202 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4203 << MemberOrBase
4204 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4205
4206 return BuildMemberInitializer(Member, Init, IdLoc);
4207 }
4208 // It didn't name a member, so see if it names a class.
4209 QualType BaseType;
4210 TypeSourceInfo *TInfo = nullptr;
4211
4212 if (TemplateTypeTy) {
13
Calling 'OpaquePtr::operator bool'
16
Returning from 'OpaquePtr::operator bool'
17
Taking false branch
4213 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4214 if (BaseType.isNull())
4215 return true;
4216 } else if (DS.getTypeSpecType() == TST_decltype) {
18
Assuming the condition is false
19
Taking false branch
4217 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4218 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
20
Assuming the condition is false
21
Taking false branch
4219 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4220 return true;
4221 } else {
4222 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4223 LookupParsedName(R, S, &SS);
4224
4225 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
22
'TyD' initialized here
4226 if (!TyD) {
23
Assuming 'TyD' is null
24
Assuming pointer value is null
25
Taking true branch
4227 if (R.isAmbiguous()) return true;
26
Assuming the condition is false
27
Taking false branch
4228
4229 // We don't want access-control diagnostics here.
4230 R.suppressDiagnostics();
4231
4232 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
28
Calling 'CXXScopeSpec::isSet'
31
Returning from 'CXXScopeSpec::isSet'
32
Assuming the condition is true
33
Taking true branch
4233 bool NotUnknownSpecialization = false;
4234 DeclContext *DC = computeDeclContext(SS, false);
4235 if (CXXRecordDecl *Record
34.1
'Record' is null
34.1
'Record' is null
34.1
'Record' is null
34.1
'Record' is null
34.1
'Record' is null
= dyn_cast_or_null<CXXRecordDecl>(DC))
34
Assuming null pointer is passed into cast
35
Taking false branch
4236 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4237
4238 if (!NotUnknownSpecialization
35.1
'NotUnknownSpecialization' is false
35.1
'NotUnknownSpecialization' is false
35.1
'NotUnknownSpecialization' is false
35.1
'NotUnknownSpecialization' is false
35.1
'NotUnknownSpecialization' is false
) {
36
Taking true branch
4239 // When the scope specifier can refer to a member of an unknown
4240 // specialization, we take it as a type name.
4241 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4242 SS.getWithLocInContext(Context),
4243 *MemberOrBase, IdLoc);
4244 if (BaseType.isNull())
37
Calling 'QualType::isNull'
43
Returning from 'QualType::isNull'
44
Taking false branch
4245 return true;
4246
4247 TInfo = Context.CreateTypeSourceInfo(BaseType);
4248 DependentNameTypeLoc TL =
4249 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4250 if (!TL.isNull()) {
45
Taking false branch
4251 TL.setNameLoc(IdLoc);
4252 TL.setElaboratedKeywordLoc(SourceLocation());
4253 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4254 }
4255
4256 R.clear();
4257 R.setLookupName(MemberOrBase);
4258 }
4259 }
4260
4261 // If no results were found, try to correct typos.
4262 TypoCorrection Corr;
4263 MemInitializerValidatorCCC CCC(ClassDecl);
4264 if (R.empty() && BaseType.isNull() &&
46
Assuming the condition is false
47
Taking false branch
4265 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4266 CCC, CTK_ErrorRecovery, ClassDecl))) {
4267 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4268 // We have found a non-static data member with a similar
4269 // name to what was typed; complain and initialize that
4270 // member.
4271 diagnoseTypo(Corr,
4272 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4273 << MemberOrBase << true);
4274 return BuildMemberInitializer(Member, Init, IdLoc);
4275 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4276 const CXXBaseSpecifier *DirectBaseSpec;
4277 const CXXBaseSpecifier *VirtualBaseSpec;
4278 if (FindBaseInitializer(*this, ClassDecl,
4279 Context.getTypeDeclType(Type),
4280 DirectBaseSpec, VirtualBaseSpec)) {
4281 // We have found a direct or virtual base class with a
4282 // similar name to what was typed; complain and initialize
4283 // that base class.
4284 diagnoseTypo(Corr,
4285 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4286 << MemberOrBase << false,
4287 PDiag() /*Suppress note, we provide our own.*/);
4288
4289 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4290 : VirtualBaseSpec;
4291 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4292 << BaseSpec->getType() << BaseSpec->getSourceRange();
4293
4294 TyD = Type;
4295 }
4296 }
4297 }
4298
4299 if (!TyD
47.1
'TyD' is null
47.1
'TyD' is null
47.1
'TyD' is null
47.1
'TyD' is null
47.1
'TyD' is null
&& BaseType.isNull()) {
48
Calling 'QualType::isNull'
54
Returning from 'QualType::isNull'
55
Taking false branch
4300 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4301 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4302 return true;
4303 }
4304 }
4305
4306 if (BaseType.isNull()) {
56
Calling 'QualType::isNull'
62
Returning from 'QualType::isNull'
63
Taking true branch
4307 BaseType = Context.getTypeDeclType(TyD);
4308 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
64
Called C++ object pointer is null
4309 if (SS.isSet()) {
4310 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4311 BaseType);
4312 TInfo = Context.CreateTypeSourceInfo(BaseType);
4313 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4314 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4315 TL.setElaboratedKeywordLoc(SourceLocation());
4316 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4317 }
4318 }
4319 }
4320
4321 if (!TInfo)
4322 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4323
4324 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4325}
4326
4327MemInitResult
4328Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4329 SourceLocation IdLoc) {
4330 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4331 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4332 assert((DirectMember || IndirectMember) &&(static_cast <bool> ((DirectMember || IndirectMember) &&
"Member must be a FieldDecl or IndirectFieldDecl") ? void (0
) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 4333, __extension__ __PRETTY_FUNCTION__))
4333 "Member must be a FieldDecl or IndirectFieldDecl")(static_cast <bool> ((DirectMember || IndirectMember) &&
"Member must be a FieldDecl or IndirectFieldDecl") ? void (0
) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 4333, __extension__ __PRETTY_FUNCTION__))
;
4334
4335 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4336 return true;
4337
4338 if (Member->isInvalidDecl())
4339 return true;
4340
4341 MultiExprArg Args;
4342 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4343 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4344 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4345 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4346 } else {
4347 // Template instantiation doesn't reconstruct ParenListExprs for us.
4348 Args = Init;
4349 }
4350
4351 SourceRange InitRange = Init->getSourceRange();
4352
4353 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4354 // Can't check initialization for a member of dependent type or when
4355 // any of the arguments are type-dependent expressions.
4356 DiscardCleanupsInEvaluationContext();
4357 } else {
4358 bool InitList = false;
4359 if (isa<InitListExpr>(Init)) {
4360 InitList = true;
4361 Args = Init;
4362 }
4363
4364 // Initialize the member.
4365 InitializedEntity MemberEntity =
4366 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4367 : InitializedEntity::InitializeMember(IndirectMember,
4368 nullptr);
4369 InitializationKind Kind =
4370 InitList ? InitializationKind::CreateDirectList(
4371 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4372 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4373 InitRange.getEnd());
4374
4375 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4376 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4377 nullptr);
4378 if (MemberInit.isInvalid())
4379 return true;
4380
4381 // C++11 [class.base.init]p7:
4382 // The initialization of each base and member constitutes a
4383 // full-expression.
4384 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4385 /*DiscardedValue*/ false);
4386 if (MemberInit.isInvalid())
4387 return true;
4388
4389 Init = MemberInit.get();
4390 }
4391
4392 if (DirectMember) {
4393 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4394 InitRange.getBegin(), Init,
4395 InitRange.getEnd());
4396 } else {
4397 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4398 InitRange.getBegin(), Init,
4399 InitRange.getEnd());
4400 }
4401}
4402
4403MemInitResult
4404Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4405 CXXRecordDecl *ClassDecl) {
4406 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4407 if (!LangOpts.CPlusPlus11)
4408 return Diag(NameLoc, diag::err_delegating_ctor)
4409 << TInfo->getTypeLoc().getLocalSourceRange();
4410 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4411
4412 bool InitList = true;
4413 MultiExprArg Args = Init;
4414 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4415 InitList = false;
4416 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4417 }
4418
4419 SourceRange InitRange = Init->getSourceRange();
4420 // Initialize the object.
4421 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4422 QualType(ClassDecl->getTypeForDecl(), 0));
4423 InitializationKind Kind =
4424 InitList ? InitializationKind::CreateDirectList(
4425 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4426 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4427 InitRange.getEnd());
4428 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4429 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4430 Args, nullptr);
4431 if (DelegationInit.isInvalid())
4432 return true;
4433
4434 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&(static_cast <bool> (cast<CXXConstructExpr>(DelegationInit
.get())->getConstructor() && "Delegating constructor with no target?"
) ? void (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 4435, __extension__ __PRETTY_FUNCTION__))
4435 "Delegating constructor with no target?")(static_cast <bool> (cast<CXXConstructExpr>(DelegationInit
.get())->getConstructor() && "Delegating constructor with no target?"
) ? void (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 4435, __extension__ __PRETTY_FUNCTION__))
;
4436
4437 // C++11 [class.base.init]p7:
4438 // The initialization of each base and member constitutes a
4439 // full-expression.
4440 DelegationInit = ActOnFinishFullExpr(
4441 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4442 if (DelegationInit.isInvalid())
4443 return true;
4444
4445 // If we are in a dependent context, template instantiation will
4446 // perform this type-checking again. Just save the arguments that we
4447 // received in a ParenListExpr.
4448 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4449 // of the information that we have about the base
4450 // initializer. However, deconstructing the ASTs is a dicey process,
4451 // and this approach is far more likely to get the corner cases right.
4452 if (CurContext->isDependentContext())
4453 DelegationInit = Init;
4454
4455 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4456 DelegationInit.getAs<Expr>(),
4457 InitRange.getEnd());
4458}
4459
4460MemInitResult
4461Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4462 Expr *Init, CXXRecordDecl *ClassDecl,
4463 SourceLocation EllipsisLoc) {
4464 SourceLocation BaseLoc
4465 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4466
4467 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4468 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4469 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4470
4471 // C++ [class.base.init]p2:
4472 // [...] Unless the mem-initializer-id names a nonstatic data
4473 // member of the constructor's class or a direct or virtual base
4474 // of that class, the mem-initializer is ill-formed. A
4475 // mem-initializer-list can initialize a base class using any
4476 // name that denotes that base class type.
4477 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4478
4479 SourceRange InitRange = Init->getSourceRange();
4480 if (EllipsisLoc.isValid()) {
4481 // This is a pack expansion.
4482 if (!BaseType->containsUnexpandedParameterPack()) {
4483 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4484 << SourceRange(BaseLoc, InitRange.getEnd());
4485
4486 EllipsisLoc = SourceLocation();
4487 }
4488 } else {
4489 // Check for any unexpanded parameter packs.
4490 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4491 return true;
4492
4493 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4494 return true;
4495 }
4496
4497 // Check for direct and virtual base classes.
4498 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4499 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4500 if (!Dependent) {
4501 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4502 BaseType))
4503 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4504
4505 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4506 VirtualBaseSpec);
4507
4508 // C++ [base.class.init]p2:
4509 // Unless the mem-initializer-id names a nonstatic data member of the
4510 // constructor's class or a direct or virtual base of that class, the
4511 // mem-initializer is ill-formed.
4512 if (!DirectBaseSpec && !VirtualBaseSpec) {
4513 // If the class has any dependent bases, then it's possible that
4514 // one of those types will resolve to the same type as
4515 // BaseType. Therefore, just treat this as a dependent base
4516 // class initialization. FIXME: Should we try to check the
4517 // initialization anyway? It seems odd.
4518 if (ClassDecl->hasAnyDependentBases())
4519 Dependent = true;
4520 else
4521 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4522 << BaseType << Context.getTypeDeclType(ClassDecl)
4523 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4524 }
4525 }
4526
4527 if (Dependent) {
4528 DiscardCleanupsInEvaluationContext();
4529
4530 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4531 /*IsVirtual=*/false,
4532 InitRange.getBegin(), Init,
4533 InitRange.getEnd(), EllipsisLoc);
4534 }
4535
4536 // C++ [base.class.init]p2:
4537 // If a mem-initializer-id is ambiguous because it designates both
4538 // a direct non-virtual base class and an inherited virtual base
4539 // class, the mem-initializer is ill-formed.
4540 if (DirectBaseSpec && VirtualBaseSpec)
4541 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4542 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4543
4544 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4545 if (!BaseSpec)
4546 BaseSpec = VirtualBaseSpec;
4547
4548 // Initialize the base.
4549 bool InitList = true;
4550 MultiExprArg Args = Init;
4551 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4552 InitList = false;
4553 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4554 }
4555
4556 InitializedEntity BaseEntity =
4557 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4558 InitializationKind Kind =
4559 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4560 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4561 InitRange.getEnd());
4562 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4563 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4564 if (BaseInit.isInvalid())
4565 return true;
4566
4567 // C++11 [class.base.init]p7:
4568 // The initialization of each base and member constitutes a
4569 // full-expression.
4570 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4571 /*DiscardedValue*/ false);
4572 if (BaseInit.isInvalid())
4573 return true;
4574
4575 // If we are in a dependent context, template instantiation will
4576 // perform this type-checking again. Just save the arguments that we
4577 // received in a ParenListExpr.
4578 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4579 // of the information that we have about the base
4580 // initializer. However, deconstructing the ASTs is a dicey process,
4581 // and this approach is far more likely to get the corner cases right.
4582 if (CurContext->isDependentContext())
4583 BaseInit = Init;
4584
4585 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4586 BaseSpec->isVirtual(),
4587 InitRange.getBegin(),
4588 BaseInit.getAs<Expr>(),
4589 InitRange.getEnd(), EllipsisLoc);
4590}
4591
4592// Create a static_cast\<T&&>(expr).
4593static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4594 if (T.isNull()) T = E->getType();
4595 QualType TargetType = SemaRef.BuildReferenceType(
4596 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4597 SourceLocation ExprLoc = E->getBeginLoc();
4598 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4599 TargetType, ExprLoc);
4600
4601 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4602 SourceRange(ExprLoc, ExprLoc),
4603 E->getSourceRange()).get();
4604}
4605
4606/// ImplicitInitializerKind - How an implicit base or member initializer should
4607/// initialize its base or member.
4608enum ImplicitInitializerKind {
4609 IIK_Default,
4610 IIK_Copy,
4611 IIK_Move,
4612 IIK_Inherit
4613};
4614
4615static bool
4616BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4617 ImplicitInitializerKind ImplicitInitKind,
4618 CXXBaseSpecifier *BaseSpec,
4619 bool IsInheritedVirtualBase,
4620 CXXCtorInitializer *&CXXBaseInit) {
4621 InitializedEntity InitEntity
4622 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4623 IsInheritedVirtualBase);
4624
4625 ExprResult BaseInit;
4626
4627 switch (ImplicitInitKind) {
4628 case IIK_Inherit:
4629 case IIK_Default: {
4630 InitializationKind InitKind
4631 = InitializationKind::CreateDefault(Constructor->getLocation());
4632 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4633 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4634 break;
4635 }
4636
4637 case IIK_Move:
4638 case IIK_Copy: {
4639 bool Moving = ImplicitInitKind == IIK_Move;
4640 ParmVarDecl *Param = Constructor->getParamDecl(0);
4641 QualType ParamType = Param->getType().getNonReferenceType();
4642
4643 Expr *CopyCtorArg =
4644 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4645 SourceLocation(), Param, false,
4646 Constructor->getLocation(), ParamType,
4647 VK_LValue, nullptr);
4648
4649 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4650
4651 // Cast to the base class to avoid ambiguities.
4652 QualType ArgTy =
4653 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4654 ParamType.getQualifiers());
4655
4656 if (Moving) {
4657 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4658 }
4659
4660 CXXCastPath BasePath;
4661 BasePath.push_back(BaseSpec);
4662 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4663 CK_UncheckedDerivedToBase,
4664 Moving ? VK_XValue : VK_LValue,
4665 &BasePath).get();
4666
4667 InitializationKind InitKind
4668 = InitializationKind::CreateDirect(Constructor->getLocation(),
4669 SourceLocation(), SourceLocation());
4670 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4671 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4672 break;
4673 }
4674 }
4675
4676 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4677 if (BaseInit.isInvalid())
4678 return true;
4679
4680 CXXBaseInit =
4681 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4682 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4683 SourceLocation()),
4684 BaseSpec->isVirtual(),
4685 SourceLocation(),
4686 BaseInit.getAs<Expr>(),
4687 SourceLocation(),
4688 SourceLocation());
4689
4690 return false;
4691}
4692
4693static bool RefersToRValueRef(Expr *MemRef) {
4694 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4695 return Referenced->getType()->isRValueReferenceType();
4696}
4697
4698static bool
4699BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4700 ImplicitInitializerKind ImplicitInitKind,
4701 FieldDecl *Field, IndirectFieldDecl *Indirect,
4702 CXXCtorInitializer *&CXXMemberInit) {
4703 if (Field->isInvalidDecl())
4704 return true;
4705
4706 SourceLocation Loc = Constructor->getLocation();
4707
4708 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4709 bool Moving = ImplicitInitKind == IIK_Move;
4710 ParmVarDecl *Param = Constructor->getParamDecl(0);
4711 QualType ParamType = Param->getType().getNonReferenceType();
4712
4713 // Suppress copying zero-width bitfields.
4714 if (Field->isZeroLengthBitField(SemaRef.Context))
4715 return false;
4716
4717 Expr *MemberExprBase =
4718 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4719 SourceLocation(), Param, false,
4720 Loc, ParamType, VK_LValue, nullptr);
4721
4722 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4723
4724 if (Moving) {
4725 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4726 }
4727
4728 // Build a reference to this field within the parameter.
4729 CXXScopeSpec SS;
4730 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4731 Sema::LookupMemberName);
4732 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4733 : cast<ValueDecl>(Field), AS_public);
4734 MemberLookup.resolveKind();
4735 ExprResult CtorArg
4736 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4737 ParamType, Loc,
4738 /*IsArrow=*/false,
4739 SS,
4740 /*TemplateKWLoc=*/SourceLocation(),
4741 /*FirstQualifierInScope=*/nullptr,
4742 MemberLookup,
4743 /*TemplateArgs=*/nullptr,
4744 /*S*/nullptr);
4745 if (CtorArg.isInvalid())
4746 return true;
4747
4748 // C++11 [class.copy]p15:
4749 // - if a member m has rvalue reference type T&&, it is direct-initialized
4750 // with static_cast<T&&>(x.m);
4751 if (RefersToRValueRef(CtorArg.get())) {
4752 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4753 }
4754
4755 InitializedEntity Entity =
4756 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4757 /*Implicit*/ true)
4758 : InitializedEntity::InitializeMember(Field, nullptr,
4759 /*Implicit*/ true);
4760
4761 // Direct-initialize to use the copy constructor.
4762 InitializationKind InitKind =
4763 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4764
4765 Expr *CtorArgE = CtorArg.getAs<Expr>();
4766 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4767 ExprResult MemberInit =
4768 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4769 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4770 if (MemberInit.isInvalid())
4771 return true;
4772
4773 if (Indirect)
4774 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4775 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4776 else
4777 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4778 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4779 return false;
4780 }
4781
4782 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(static_cast <bool> ((ImplicitInitKind == IIK_Default ||
ImplicitInitKind == IIK_Inherit) && "Unhandled implicit init kind!"
) ? void (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 4783, __extension__ __PRETTY_FUNCTION__))
4783 "Unhandled implicit init kind!")(static_cast <bool> ((ImplicitInitKind == IIK_Default ||
ImplicitInitKind == IIK_Inherit) && "Unhandled implicit init kind!"
) ? void (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 4783, __extension__ __PRETTY_FUNCTION__))
;
4784
4785 QualType FieldBaseElementType =
4786 SemaRef.Context.getBaseElementType(Field->getType());
4787
4788 if (FieldBaseElementType->isRecordType()) {
4789 InitializedEntity InitEntity =
4790 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4791 /*Implicit*/ true)
4792 : InitializedEntity::InitializeMember(Field, nullptr,
4793 /*Implicit*/ true);
4794 InitializationKind InitKind =
4795 InitializationKind::CreateDefault(Loc);
4796
4797 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4798 ExprResult MemberInit =
4799 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4800
4801 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4802 if (MemberInit.isInvalid())
4803 return true;
4804
4805 if (Indirect)
4806 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4807 Indirect, Loc,
4808 Loc,
4809 MemberInit.get(),
4810 Loc);
4811 else
4812 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4813 Field, Loc, Loc,
4814 MemberInit.get(),
4815 Loc);
4816 return false;
4817 }
4818
4819 if (!Field->getParent()->isUnion()) {
4820 if (FieldBaseElementType->isReferenceType()) {
4821 SemaRef.Diag(Constructor->getLocation(),
4822 diag::err_uninitialized_member_in_ctor)
4823 << (int)Constructor->isImplicit()
4824 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4825 << 0 << Field->getDeclName();
4826 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4827 return true;
4828 }
4829
4830 if (FieldBaseElementType.isConstQualified()) {
4831 SemaRef.Diag(Constructor->getLocation(),
4832 diag::err_uninitialized_member_in_ctor)
4833 << (int)Constructor->isImplicit()
4834 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4835 << 1 << Field->getDeclName();
4836 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4837 return true;
4838 }
4839 }
4840
4841 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4842 // ARC and Weak:
4843 // Default-initialize Objective-C pointers to NULL.
4844 CXXMemberInit
4845 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4846 Loc, Loc,
4847 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4848 Loc);
4849 return false;
4850 }
4851
4852 // Nothing to initialize.
4853 CXXMemberInit = nullptr;
4854 return false;
4855}
4856
4857namespace {
4858struct BaseAndFieldInfo {
4859 Sema &S;
4860 CXXConstructorDecl *Ctor;
4861 bool AnyErrorsInInits;
4862 ImplicitInitializerKind IIK;
4863 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4864 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4865 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4866
4867 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4868 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4869 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4870 if (Ctor->getInheritedConstructor())
4871 IIK = IIK_Inherit;
4872 else if (Generated && Ctor->isCopyConstructor())
4873 IIK = IIK_Copy;
4874 else if (Generated && Ctor->isMoveConstructor())
4875 IIK = IIK_Move;
4876 else
4877 IIK = IIK_Default;
4878 }
4879
4880 bool isImplicitCopyOrMove() const {
4881 switch (IIK) {
4882 case IIK_Copy:
4883 case IIK_Move:
4884 return true;
4885
4886 case IIK_Default:
4887 case IIK_Inherit:
4888 return false;
4889 }
4890
4891 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 4891)
;
4892 }
4893
4894 bool addFieldInitializer(CXXCtorInitializer *Init) {
4895 AllToInit.push_back(Init);
4896
4897 // Check whether this initializer makes the field "used".
4898 if (Init->getInit()->HasSideEffects(S.Context))
4899 S.UnusedPrivateFields.remove(Init->getAnyMember());
4900
4901 return false;
4902 }
4903
4904 bool isInactiveUnionMember(FieldDecl *Field) {
4905 RecordDecl *Record = Field->getParent();
4906 if (!Record->isUnion())
4907 return false;
4908
4909 if (FieldDecl *Active =
4910 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4911 return Active != Field->getCanonicalDecl();
4912
4913 // In an implicit copy or move constructor, ignore any in-class initializer.
4914 if (isImplicitCopyOrMove())
4915 return true;
4916
4917 // If there's no explicit initialization, the field is active only if it
4918 // has an in-class initializer...
4919 if (Field->hasInClassInitializer())
4920 return false;
4921 // ... or it's an anonymous struct or union whose class has an in-class
4922 // initializer.
4923 if (!Field->isAnonymousStructOrUnion())
4924 return true;
4925 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4926 return !FieldRD->hasInClassInitializer();
4927 }
4928
4929 /// Determine whether the given field is, or is within, a union member
4930 /// that is inactive (because there was an initializer given for a different
4931 /// member of the union, or because the union was not initialized at all).
4932 bool isWithinInactiveUnionMember(FieldDecl *Field,
4933 IndirectFieldDecl *Indirect) {
4934 if (!Indirect)
4935 return isInactiveUnionMember(Field);
4936
4937 for (auto *C : Indirect->chain()) {
4938 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4939 if (Field && isInactiveUnionMember(Field))
4940 return true;
4941 }
4942 return false;
4943 }
4944};
4945}
4946
4947/// Determine whether the given type is an incomplete or zero-lenfgth
4948/// array type.
4949static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4950 if (T->isIncompleteArrayType())
4951 return true;
4952
4953 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4954 if (!ArrayT->getSize())
4955 return true;
4956
4957 T = ArrayT->getElementType();
4958 }
4959
4960 return false;
4961}
4962
4963static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4964 FieldDecl *Field,
4965 IndirectFieldDecl *Indirect = nullptr) {
4966 if (Field->isInvalidDecl())
4967 return false;
4968
4969 // Overwhelmingly common case: we have a direct initializer for this field.
4970 if (CXXCtorInitializer *Init =
4971 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4972 return Info.addFieldInitializer(Init);
4973
4974 // C++11 [class.base.init]p8:
4975 // if the entity is a non-static data member that has a
4976 // brace-or-equal-initializer and either
4977 // -- the constructor's class is a union and no other variant member of that
4978 // union is designated by a mem-initializer-id or
4979 // -- the constructor's class is not a union, and, if the entity is a member
4980 // of an anonymous union, no other member of that union is designated by
4981 // a mem-initializer-id,
4982 // the entity is initialized as specified in [dcl.init].
4983 //
4984 // We also apply the same rules to handle anonymous structs within anonymous
4985 // unions.
4986 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4987 return false;
4988
4989 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4990 ExprResult DIE =
4991 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4992 if (DIE.isInvalid())
4993 return true;
4994
4995 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4996 SemaRef.checkInitializerLifetime(Entity, DIE.get());
4997
4998 CXXCtorInitializer *Init;
4999 if (Indirect)
5000 Init = new (SemaRef.Context)
5001 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5002 SourceLocation(), DIE.get(), SourceLocation());
5003 else
5004 Init = new (SemaRef.Context)
5005 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5006 SourceLocation(), DIE.get(), SourceLocation());
5007 return Info.addFieldInitializer(Init);
5008 }
5009
5010 // Don't initialize incomplete or zero-length arrays.
5011 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5012 return false;
5013
5014 // Don't try to build an implicit initializer if there were semantic
5015 // errors in any of the initializers (and therefore we might be
5016 // missing some that the user actually wrote).
5017 if (Info.AnyErrorsInInits)
5018 return false;
5019
5020 CXXCtorInitializer *Init = nullptr;
5021 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5022 Indirect, Init))
5023 return true;
5024
5025 if (!Init)
5026 return false;
5027
5028 return Info.addFieldInitializer(Init);
5029}
5030
5031bool
5032Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5033 CXXCtorInitializer *Initializer) {
5034 assert(Initializer->isDelegatingInitializer())(static_cast <bool> (Initializer->isDelegatingInitializer
()) ? void (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 5034, __extension__ __PRETTY_FUNCTION__))
;
5035 Constructor->setNumCtorInitializers(1);
5036 CXXCtorInitializer **initializer =
5037 new (Context) CXXCtorInitializer*[1];
5038 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5039 Constructor->setCtorInitializers(initializer);
5040
5041 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5042 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5043 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5044 }
5045
5046 DelegatingCtorDecls.push_back(Constructor);
5047
5048 DiagnoseUninitializedFields(*this, Constructor);
5049
5050 return false;
5051}
5052
5053bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5054 ArrayRef<CXXCtorInitializer *> Initializers) {
5055 if (Constructor->isDependentContext()) {
5056 // Just store the initializers as written, they will be checked during
5057 // instantiation.
5058 if (!Initializers.empty()) {
5059 Constructor->setNumCtorInitializers(Initializers.size());
5060 CXXCtorInitializer **baseOrMemberInitializers =
5061 new (Context) CXXCtorInitializer*[Initializers.size()];
5062 memcpy(baseOrMemberInitializers, Initializers.data(),
5063 Initializers.size() * sizeof(CXXCtorInitializer*));
5064 Constructor->setCtorInitializers(baseOrMemberInitializers);
5065 }
5066
5067 // Let template instantiation know whether we had errors.
5068 if (AnyErrors)
5069 Constructor->setInvalidDecl();
5070
5071 return false;
5072 }
5073
5074 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5075
5076 // We need to build the initializer AST according to order of construction
5077 // and not what user specified in the Initializers list.
5078 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5079 if (!ClassDecl)
5080 return true;
5081
5082 bool HadError = false;
5083
5084 for (unsigned i = 0; i < Initializers.size(); i++) {
5085 CXXCtorInitializer *Member = Initializers[i];
5086
5087 if (Member->isBaseInitializer())
5088 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5089 else {
5090 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5091
5092 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5093 for (auto *C : F->chain()) {
5094 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5095 if (FD && FD->getParent()->isUnion())
5096 Info.ActiveUnionMember.insert(std::make_pair(
5097 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5098 }
5099 } else if (FieldDecl *FD = Member->getMember()) {
5100 if (FD->getParent()->isUnion())
5101 Info.ActiveUnionMember.insert(std::make_pair(
5102 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5103 }
5104 }
5105 }
5106
5107 // Keep track of the direct virtual bases.
5108 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5109 for (auto &I : ClassDecl->bases()) {
5110 if (I.isVirtual())
5111 DirectVBases.insert(&I);
5112 }
5113
5114 // Push virtual bases before others.
5115 for (auto &VBase : ClassDecl->vbases()) {
5116 if (CXXCtorInitializer *Value
5117 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5118 // [class.base.init]p7, per DR257:
5119 // A mem-initializer where the mem-initializer-id names a virtual base
5120 // class is ignored during execution of a constructor of any class that
5121 // is not the most derived class.
5122 if (ClassDecl->isAbstract()) {
5123 // FIXME: Provide a fixit to remove the base specifier. This requires
5124 // tracking the location of the associated comma for a base specifier.
5125 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5126 << VBase.getType() << ClassDecl;
5127 DiagnoseAbstractType(ClassDecl);
5128 }
5129
5130 Info.AllToInit.push_back(Value);
5131 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5132 // [class.base.init]p8, per DR257:
5133 // If a given [...] base class is not named by a mem-initializer-id
5134 // [...] and the entity is not a virtual base class of an abstract
5135 // class, then [...] the entity is default-initialized.
5136 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5137 CXXCtorInitializer *CXXBaseInit;
5138 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5139 &VBase, IsInheritedVirtualBase,
5140 CXXBaseInit)) {
5141 HadError = true;
5142 continue;
5143 }
5144
5145 Info.AllToInit.push_back(CXXBaseInit);
5146 }
5147 }
5148
5149 // Non-virtual bases.
5150 for (auto &Base : ClassDecl->bases()) {
5151 // Virtuals are in the virtual base list and already constructed.
5152 if (Base.isVirtual())
5153 continue;
5154
5155 if (CXXCtorInitializer *Value
5156 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5157 Info.AllToInit.push_back(Value);
5158 } else if (!AnyErrors) {
5159 CXXCtorInitializer *CXXBaseInit;
5160 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5161 &Base, /*IsInheritedVirtualBase=*/false,
5162 CXXBaseInit)) {
5163 HadError = true;
5164 continue;
5165 }
5166
5167 Info.AllToInit.push_back(CXXBaseInit);
5168 }
5169 }
5170
5171 // Fields.
5172 for (auto *Mem : ClassDecl->decls()) {
5173 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5174 // C++ [class.bit]p2:
5175 // A declaration for a bit-field that omits the identifier declares an
5176 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5177 // initialized.
5178 if (F->isUnnamedBitfield())
5179 continue;
5180
5181 // If we're not generating the implicit copy/move constructor, then we'll
5182 // handle anonymous struct/union fields based on their individual
5183 // indirect fields.
5184 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5185 continue;
5186
5187 if (CollectFieldInitializer(*this, Info, F))
5188 HadError = true;
5189 continue;
5190 }
5191
5192 // Beyond this point, we only consider default initialization.
5193 if (Info.isImplicitCopyOrMove())
5194 continue;
5195
5196 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5197 if (F->getType()->isIncompleteArrayType()) {
5198 assert(ClassDecl->hasFlexibleArrayMember() &&(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 5199, __extension__ __PRETTY_FUNCTION__))
5199 "Incomplete array type is not valid")(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 5199, __extension__ __PRETTY_FUNCTION__))
;
5200 continue;
5201 }
5202
5203 // Initialize each field of an anonymous struct individually.
5204 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5205 HadError = true;
5206
5207 continue;
5208 }
5209 }
5210
5211 unsigned NumInitializers = Info.AllToInit.size();
5212 if (NumInitializers > 0) {
5213 Constructor->setNumCtorInitializers(NumInitializers);
5214 CXXCtorInitializer **baseOrMemberInitializers =
5215 new (Context) CXXCtorInitializer*[NumInitializers];
5216 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5217 NumInitializers * sizeof(CXXCtorInitializer*));
5218 Constructor->setCtorInitializers(baseOrMemberInitializers);
5219
5220 // Constructors implicitly reference the base and member
5221 // destructors.
5222 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5223 Constructor->getParent());
5224 }
5225
5226 return HadError;
5227}
5228
5229static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5230 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5231 const RecordDecl *RD = RT->getDecl();
5232 if (RD->isAnonymousStructOrUnion()) {
5233 for (auto *Field : RD->fields())
5234 PopulateKeysForFields(Field, IdealInits);
5235 return;
5236 }
5237 }
5238 IdealInits.push_back(Field->getCanonicalDecl());
5239}
5240
5241static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5242 return Context.getCanonicalType(BaseType).getTypePtr();
5243}
5244
5245static const void *GetKeyForMember(ASTContext &Context,
5246 CXXCtorInitializer *Member) {
5247 if (!Member->isAnyMemberInitializer())
5248 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5249
5250 return Member->getAnyMember()->getCanonicalDecl();
5251}
5252
5253static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5254 const CXXCtorInitializer *Previous,
5255 const CXXCtorInitializer *Current) {
5256 if (Previous->isAnyMemberInitializer())
5257 Diag << 0 << Previous->getAnyMember();
5258 else
5259 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5260
5261 if (Current->isAnyMemberInitializer())
5262 Diag << 0 << Current->getAnyMember();
5263 else
5264 Diag << 1 << Current->getTypeSourceInfo()->getType();
5265}
5266
5267static void DiagnoseBaseOrMemInitializerOrder(
5268 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5269 ArrayRef<CXXCtorInitializer *> Inits) {
5270 if (Constructor->getDeclContext()->isDependentContext())
5271 return;
5272
5273 // Don't check initializers order unless the warning is enabled at the
5274 // location of at least one initializer.
5275 bool ShouldCheckOrder = false;
5276 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5277 CXXCtorInitializer *Init = Inits[InitIndex];
5278 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5279 Init->getSourceLocation())) {
5280 ShouldCheckOrder = true;
5281 break;
5282 }
5283 }
5284 if (!ShouldCheckOrder)
5285 return;
5286
5287 // Build the list of bases and members in the order that they'll
5288 // actually be initialized. The explicit initializers should be in
5289 // this same order but may be missing things.
5290 SmallVector<const void*, 32> IdealInitKeys;
5291
5292 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5293
5294 // 1. Virtual bases.
5295 for (const auto &VBase : ClassDecl->vbases())
5296 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5297
5298 // 2. Non-virtual bases.
5299 for (const auto &Base : ClassDecl->bases()) {
5300 if (Base.isVirtual())
5301 continue;
5302 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5303 }
5304
5305 // 3. Direct fields.
5306 for (auto *Field : ClassDecl->fields()) {
5307 if (Field->isUnnamedBitfield())
5308 continue;
5309
5310 PopulateKeysForFields(Field, IdealInitKeys);
5311 }
5312
5313 unsigned NumIdealInits = IdealInitKeys.size();
5314 unsigned IdealIndex = 0;
5315
5316 // Track initializers that are in an incorrect order for either a warning or
5317 // note if multiple ones occur.
5318 SmallVector<unsigned> WarnIndexes;
5319 // Correlates the index of an initializer in the init-list to the index of
5320 // the field/base in the class.
5321 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5322
5323 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5324 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5325
5326 // Scan forward to try to find this initializer in the idealized
5327 // initializers list.
5328 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5329 if (InitKey == IdealInitKeys[IdealIndex])
5330 break;
5331
5332 // If we didn't find this initializer, it must be because we
5333 // scanned past it on a previous iteration. That can only
5334 // happen if we're out of order; emit a warning.
5335 if (IdealIndex == NumIdealInits && InitIndex) {
5336 WarnIndexes.push_back(InitIndex);
5337
5338 // Move back to the initializer's location in the ideal list.
5339 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5340 if (InitKey == IdealInitKeys[IdealIndex])
5341 break;
5342
5343 assert(IdealIndex < NumIdealInits &&(static_cast <bool> (IdealIndex < NumIdealInits &&
"initializer not found in initializer list") ? void (0) : __assert_fail
("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 5344, __extension__ __PRETTY_FUNCTION__))
5344 "initializer not found in initializer list")(static_cast <bool> (IdealIndex < NumIdealInits &&
"initializer not found in initializer list") ? void (0) : __assert_fail
("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 5344, __extension__ __PRETTY_FUNCTION__))
;
5345 }
5346 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5347 }
5348
5349 if (WarnIndexes.empty())
5350 return;
5351
5352 // Sort based on the ideal order, first in the pair.
5353 llvm::sort(CorrelatedInitOrder,
5354 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
5355
5356 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5357 // emit the diagnostic before we can try adding notes.
5358 {
5359 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5360 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5361 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5362 : diag::warn_some_initializers_out_of_order);
5363
5364 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5365 if (CorrelatedInitOrder[I].second == I)
5366 continue;
5367 // Ideally we would be using InsertFromRange here, but clang doesn't
5368 // appear to handle InsertFromRange correctly when the source range is
5369 // modified by another fix-it.
5370 D << FixItHint::CreateReplacement(
5371 Inits[I]->getSourceRange(),
5372 Lexer::getSourceText(
5373 CharSourceRange::getTokenRange(
5374 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5375 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5376 }
5377
5378 // If there is only 1 item out of order, the warning expects the name and
5379 // type of each being added to it.
5380 if (WarnIndexes.size() == 1) {
5381 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5382 Inits[WarnIndexes.front()]);
5383 return;
5384 }
5385 }
5386 // More than 1 item to warn, create notes letting the user know which ones
5387 // are bad.
5388 for (unsigned WarnIndex : WarnIndexes) {
5389 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5390 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5391 diag::note_initializer_out_of_order);
5392 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5393 D << PrevInit->getSourceRange();
5394 }
5395}
5396
5397namespace {
5398bool CheckRedundantInit(Sema &S,
5399 CXXCtorInitializer *Init,
5400 CXXCtorInitializer *&PrevInit) {
5401 if (!PrevInit) {
5402 PrevInit = Init;
5403 return false;
5404 }
5405
5406 if (FieldDecl *Field = Init->getAnyMember())
5407 S.Diag(Init->getSourceLocation(),
5408 diag::err_multiple_mem_initialization)
5409 << Field->getDeclName()
5410 << Init->getSourceRange();
5411 else {
5412 const Type *BaseClass = Init->getBaseClass();
5413 assert(BaseClass && "neither field nor base")(static_cast <bool> (BaseClass && "neither field nor base"
) ? void (0) : __assert_fail ("BaseClass && \"neither field nor base\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 5413, __extension__ __PRETTY_FUNCTION__))
;
5414 S.Diag(Init->getSourceLocation(),
5415 diag::err_multiple_base_initialization)
5416 << QualType(BaseClass, 0)
5417 << Init->getSourceRange();
5418 }
5419 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5420 << 0 << PrevInit->getSourceRange();
5421
5422 return true;
5423}
5424
5425typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5426typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5427
5428bool CheckRedundantUnionInit(Sema &S,
5429 CXXCtorInitializer *Init,
5430 RedundantUnionMap &Unions) {
5431 FieldDecl *Field = Init->getAnyMember();
5432 RecordDecl *Parent = Field->getParent();
5433 NamedDecl *Child = Field;
5434
5435 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5436 if (Parent->isUnion()) {
5437 UnionEntry &En = Unions[Parent];
5438 if (En.first && En.first != Child) {
5439 S.Diag(Init->getSourceLocation(),
5440 diag::err_multiple_mem_union_initialization)
5441 << Field->getDeclName()
5442 << Init->getSourceRange();
5443 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5444 << 0 << En.second->getSourceRange();
5445 return true;
5446 }
5447 if (!En.first) {
5448 En.first = Child;
5449 En.second = Init;
5450 }
5451 if (!Parent->isAnonymousStructOrUnion())
5452 return false;
5453 }
5454
5455 Child = Parent;
5456 Parent = cast<RecordDecl>(Parent->getDeclContext());
5457 }
5458
5459 return false;
5460}
5461} // namespace
5462
5463/// ActOnMemInitializers - Handle the member initializers for a constructor.
5464void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5465 SourceLocation ColonLoc,
5466 ArrayRef<CXXCtorInitializer*> MemInits,
5467 bool AnyErrors) {
5468 if (!ConstructorDecl)
5469 return;
5470
5471 AdjustDeclIfTemplate(ConstructorDecl);
5472
5473 CXXConstructorDecl *Constructor
5474 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5475
5476 if (!Constructor) {
5477 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5478 return;
5479 }
5480
5481 // Mapping for the duplicate initializers check.
5482 // For member initializers, this is keyed with a FieldDecl*.
5483 // For base initializers, this is keyed with a Type*.
5484 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5485
5486 // Mapping for the inconsistent anonymous-union initializers check.
5487 RedundantUnionMap MemberUnions;
5488
5489 bool HadError = false;
5490 for (unsigned i = 0; i < MemInits.size(); i++) {
5491 CXXCtorInitializer *Init = MemInits[i];
5492
5493 // Set the source order index.
5494 Init->setSourceOrder(i);
5495
5496 if (Init->isAnyMemberInitializer()) {
5497 const void *Key = GetKeyForMember(Context, Init);
5498 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5499 CheckRedundantUnionInit(*this, Init, MemberUnions))
5500 HadError = true;
5501 } else if (Init->isBaseInitializer()) {
5502 const void *Key = GetKeyForMember(Context, Init);
5503 if (CheckRedundantInit(*this, Init, Members[Key]))
5504 HadError = true;
5505 } else {
5506 assert(Init->isDelegatingInitializer())(static_cast <bool> (Init->isDelegatingInitializer()
) ? void (0) : __assert_fail ("Init->isDelegatingInitializer()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 5506, __extension__ __PRETTY_FUNCTION__))
;
5507 // This must be the only initializer
5508 if (MemInits.size() != 1) {
5509 Diag(Init->getSourceLocation(),
5510 diag::err_delegating_initializer_alone)
5511 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5512 // We will treat this as being the only initializer.
5513 }
5514 SetDelegatingInitializer(Constructor, MemInits[i]);
5515 // Return immediately as the initializer is set.
5516 return;
5517 }
5518 }
5519
5520 if (HadError)
5521 return;
5522
5523 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5524
5525 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5526
5527 DiagnoseUninitializedFields(*this, Constructor);
5528}
5529
5530void
5531Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5532 CXXRecordDecl *ClassDecl) {
5533 // Ignore dependent contexts. Also ignore unions, since their members never
5534 // have destructors implicitly called.
5535 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5536 return;
5537
5538 // FIXME: all the access-control diagnostics are positioned on the
5539 // field/base declaration. That's probably good; that said, the
5540 // user might reasonably want to know why the destructor is being
5541 // emitted, and we currently don't say.
5542
5543 // Non-static data members.
5544 for (auto *Field : ClassDecl->fields()) {
5545 if (Field->isInvalidDecl())
5546 continue;
5547
5548 // Don't destroy incomplete or zero-length arrays.
5549 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5550 continue;
5551
5552 QualType FieldType = Context.getBaseElementType(Field->getType());
5553
5554 const RecordType* RT = FieldType->getAs<RecordType>();
5555 if (!RT)
5556 continue;
5557
5558 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5559 if (FieldClassDecl->isInvalidDecl())
5560 continue;
5561 if (FieldClassDecl->hasIrrelevantDestructor())
5562 continue;
5563 // The destructor for an implicit anonymous union member is never invoked.
5564 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5565 continue;
5566
5567 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5568 assert(Dtor && "No dtor found for FieldClassDecl!")(static_cast <bool> (Dtor && "No dtor found for FieldClassDecl!"
) ? void (0) : __assert_fail ("Dtor && \"No dtor found for FieldClassDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 5568, __extension__ __PRETTY_FUNCTION__))
;
5569 CheckDestructorAccess(Field->getLocation(), Dtor,
5570 PDiag(diag::err_access_dtor_field)
5571 << Field->getDeclName()
5572 << FieldType);
5573
5574 MarkFunctionReferenced(Location, Dtor);
5575 DiagnoseUseOfDecl(Dtor, Location);
5576 }
5577
5578 // We only potentially invoke the destructors of potentially constructed
5579 // subobjects.
5580 bool VisitVirtualBases = !ClassDecl->isAbstract();
5581
5582 // If the destructor exists and has already been marked used in the MS ABI,
5583 // then virtual base destructors have already been checked and marked used.
5584 // Skip checking them again to avoid duplicate diagnostics.
5585 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5586 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5587 if (Dtor && Dtor->isUsed())
5588 VisitVirtualBases = false;
5589 }
5590
5591 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5592
5593 // Bases.
5594 for (const auto &Base : ClassDecl->bases()) {
5595 const RecordType *RT = Base.getType()->getAs<RecordType>();
5596 if (!RT)
5597 continue;
5598
5599 // Remember direct virtual bases.
5600 if (Base.isVirtual()) {
5601 if (!VisitVirtualBases)
5602 continue;
5603 DirectVirtualBases.insert(RT);
5604 }
5605
5606 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5607 // If our base class is invalid, we probably can't get its dtor anyway.
5608 if (BaseClassDecl->isInvalidDecl())
5609 continue;
5610 if (BaseClassDecl->hasIrrelevantDestructor())
5611 continue;
5612
5613 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5614 assert(Dtor && "No dtor found for BaseClassDecl!")(static_cast <bool> (Dtor && "No dtor found for BaseClassDecl!"
) ? void (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 5614, __extension__ __PRETTY_FUNCTION__))
;
5615
5616 // FIXME: caret should be on the start of the class name
5617 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5618 PDiag(diag::err_access_dtor_base)
5619 << Base.getType() << Base.getSourceRange(),
5620 Context.getTypeDeclType(ClassDecl));
5621
5622 MarkFunctionReferenced(Location, Dtor);
5623 DiagnoseUseOfDecl(Dtor, Location);
5624 }
5625
5626 if (VisitVirtualBases)
5627 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5628 &DirectVirtualBases);
5629}
5630
5631void Sema::MarkVirtualBaseDestructorsReferenced(
5632 SourceLocation Location, CXXRecordDecl *ClassDecl,
5633 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5634 // Virtual bases.
5635 for (const auto &VBase : ClassDecl->vbases()) {
5636 // Bases are always records in a well-formed non-dependent class.
5637 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5638
5639 // Ignore already visited direct virtual bases.
5640 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5641 continue;
5642
5643 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5644 // If our base class is invalid, we probably can't get its dtor anyway.
5645 if (BaseClassDecl->isInvalidDecl())
5646 continue;
5647 if (BaseClassDecl->hasIrrelevantDestructor())
5648 continue;
5649
5650 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5651 assert(Dtor && "No dtor found for BaseClassDecl!")(static_cast <bool> (Dtor && "No dtor found for BaseClassDecl!"
) ? void (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 5651, __extension__ __PRETTY_FUNCTION__))
;
5652 if (CheckDestructorAccess(
5653 ClassDecl->getLocation(), Dtor,
5654 PDiag(diag::err_access_dtor_vbase)
5655 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5656 Context.getTypeDeclType(ClassDecl)) ==
5657 AR_accessible) {
5658 CheckDerivedToBaseConversion(
5659 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5660 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5661 SourceRange(), DeclarationName(), nullptr);
5662 }
5663
5664 MarkFunctionReferenced(Location, Dtor);
5665 DiagnoseUseOfDecl(Dtor, Location);
5666 }
5667}
5668
5669void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5670 if (!CDtorDecl)
5671 return;
5672
5673 if (CXXConstructorDecl *Constructor
5674 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5675 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5676 DiagnoseUninitializedFields(*this, Constructor);
5677 }
5678}
5679
5680bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5681 if (!getLangOpts().CPlusPlus)
5682 return false;
5683
5684 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5685 if (!RD)
5686 return false;
5687
5688 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5689 // class template specialization here, but doing so breaks a lot of code.
5690
5691 // We can't answer whether something is abstract until it has a
5692 // definition. If it's currently being defined, we'll walk back
5693 // over all the declarations when we have a full definition.
5694 const CXXRecordDecl *Def = RD->getDefinition();
5695 if (!Def || Def->isBeingDefined())
5696 return false;
5697
5698 return RD->isAbstract();
5699}
5700
5701bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5702 TypeDiagnoser &Diagnoser) {
5703 if (!isAbstractType(Loc, T))
5704 return false;
5705
5706 T = Context.getBaseElementType(T);
5707 Diagnoser.diagnose(*this, Loc, T);
5708 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5709 return true;
5710}
5711
5712void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5713 // Check if we've already emitted the list of pure virtual functions
5714 // for this class.
5715 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5716 return;
5717
5718 // If the diagnostic is suppressed, don't emit the notes. We're only
5719 // going to emit them once, so try to attach them to a diagnostic we're
5720 // actually going to show.
5721 if (Diags.isLastDiagnosticIgnored())
5722 return;
5723
5724 CXXFinalOverriderMap FinalOverriders;
5725 RD->getFinalOverriders(FinalOverriders);
5726
5727 // Keep a set of seen pure methods so we won't diagnose the same method
5728 // more than once.
5729 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5730
5731 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5732 MEnd = FinalOverriders.end();
5733 M != MEnd;
5734 ++M) {
5735 for (OverridingMethods::iterator SO = M->second.begin(),
5736 SOEnd = M->second.end();
5737 SO != SOEnd; ++SO) {
5738 // C++ [class.abstract]p4:
5739 // A class is abstract if it contains or inherits at least one
5740 // pure virtual function for which the final overrider is pure
5741 // virtual.
5742
5743 //
5744 if (SO->second.size() != 1)
5745 continue;
5746
5747 if (!SO->second.front().Method->isPure())
5748 continue;
5749
5750 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5751 continue;
5752
5753 Diag(SO->second.front().Method->getLocation(),
5754 diag::note_pure_virtual_function)
5755 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5756 }
5757 }
5758
5759 if (!PureVirtualClassDiagSet)
5760 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5761 PureVirtualClassDiagSet->insert(RD);
5762}
5763
5764namespace {
5765struct AbstractUsageInfo {
5766 Sema &S;
5767 CXXRecordDecl *Record;
5768 CanQualType AbstractType;
5769 bool Invalid;
5770
5771 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5772 : S(S), Record(Record),
5773 AbstractType(S.Context.getCanonicalType(
5774 S.Context.getTypeDeclType(Record))),
5775 Invalid(false) {}
5776
5777 void DiagnoseAbstractType() {
5778 if (Invalid) return;
5779 S.DiagnoseAbstractType(Record);
5780 Invalid = true;
5781 }
5782
5783 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5784};
5785
5786struct CheckAbstractUsage {
5787 AbstractUsageInfo &Info;
5788 const NamedDecl *Ctx;
5789
5790 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5791 : Info(Info), Ctx(Ctx) {}
5792
5793 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5794 switch (TL.getTypeLocClass()) {
5795#define ABSTRACT_TYPELOC(CLASS, PARENT)
5796#define TYPELOC(CLASS, PARENT) \
5797 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5798#include "clang/AST/TypeLocNodes.def"
5799 }
5800 }
5801
5802 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5803 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5804 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5805 if (!TL.getParam(I))
5806 continue;
5807
5808 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5809 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5810 }
5811 }
5812
5813 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5814 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5815 }
5816
5817 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5818 // Visit the type parameters from a permissive context.
5819 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5820 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5821 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5822 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5823 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5824 // TODO: other template argument types?
5825 }
5826 }
5827
5828 // Visit pointee types from a permissive context.
5829#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5830 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5831 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5832 }
5833 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5834 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5835 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5836 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5837 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5838
5839 /// Handle all the types we haven't given a more specific
5840 /// implementation for above.
5841 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5842 // Every other kind of type that we haven't called out already
5843 // that has an inner type is either (1) sugar or (2) contains that
5844 // inner type in some way as a subobject.
5845 if (TypeLoc Next = TL.getNextTypeLoc())
5846 return Visit(Next, Sel);
5847
5848 // If there's no inner type and we're in a permissive context,
5849 // don't diagnose.
5850 if (Sel == Sema::AbstractNone) return;
5851
5852 // Check whether the type matches the abstract type.
5853 QualType T = TL.getType();
5854 if (T->isArrayType()) {
5855 Sel = Sema::AbstractArrayType;
5856 T = Info.S.Context.getBaseElementType(T);
5857 }
5858 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5859 if (CT != Info.AbstractType) return;
5860
5861 // It matched; do some magic.
5862 if (Sel == Sema::AbstractArrayType) {
5863 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5864 << T << TL.getSourceRange();
5865 } else {
5866 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5867 << Sel << T << TL.getSourceRange();
5868 }
5869 Info.DiagnoseAbstractType();
5870 }
5871};
5872
5873void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5874 Sema::AbstractDiagSelID Sel) {
5875 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5876}
5877
5878}
5879
5880/// Check for invalid uses of an abstract type in a method declaration.
5881static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5882 CXXMethodDecl *MD) {
5883 // No need to do the check on definitions, which require that
5884 // the return/param types be complete.
5885 if (MD->doesThisDeclarationHaveABody())
5886 return;
5887
5888 // For safety's sake, just ignore it if we don't have type source
5889 // information. This should never happen for non-implicit methods,
5890 // but...
5891 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5892 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5893}
5894
5895/// Check for invalid uses of an abstract type within a class definition.
5896static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5897 CXXRecordDecl *RD) {
5898 for (auto *D : RD->decls()) {
5899 if (D->isImplicit()) continue;
5900
5901 // Methods and method templates.
5902 if (isa<CXXMethodDecl>(D)) {
5903 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5904 } else if (isa<FunctionTemplateDecl>(D)) {
5905 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5906 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5907
5908 // Fields and static variables.
5909 } else if (isa<FieldDecl>(D)) {
5910 FieldDecl *FD = cast<FieldDecl>(D);
5911 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5912 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5913 } else if (isa<VarDecl>(D)) {
5914 VarDecl *VD = cast<VarDecl>(D);
5915 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5916 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5917
5918 // Nested classes and class templates.
5919 } else if (isa<CXXRecordDecl>(D)) {
5920 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5921 } else if (isa<ClassTemplateDecl>(D)) {
5922 CheckAbstractClassUsage(Info,
5923 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5924 }
5925 }
5926}
5927
5928static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5929 Attr *ClassAttr = getDLLAttr(Class);
5930 if (!ClassAttr)
5931 return;
5932
5933 assert(ClassAttr->getKind() == attr::DLLExport)(static_cast <bool> (ClassAttr->getKind() == attr::DLLExport
) ? void (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 5933, __extension__ __PRETTY_FUNCTION__))
;
5934
5935 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5936
5937 if (TSK == TSK_ExplicitInstantiationDeclaration)
5938 // Don't go any further if this is just an explicit instantiation
5939 // declaration.
5940 return;
5941
5942 // Add a context note to explain how we got to any diagnostics produced below.
5943 struct MarkingClassDllexported {
5944 Sema &S;
5945 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5946 SourceLocation AttrLoc)
5947 : S(S) {
5948 Sema::CodeSynthesisContext Ctx;
5949 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5950 Ctx.PointOfInstantiation = AttrLoc;
5951 Ctx.Entity = Class;
5952 S.pushCodeSynthesisContext(Ctx);
5953 }
5954 ~MarkingClassDllexported() {
5955 S.popCodeSynthesisContext();
5956 }
5957 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5958
5959 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5960 S.MarkVTableUsed(Class->getLocation(), Class, true);
5961
5962 for (Decl *Member : Class->decls()) {
5963 // Defined static variables that are members of an exported base
5964 // class must be marked export too.
5965 auto *VD = dyn_cast<VarDecl>(Member);
5966 if (VD && Member->getAttr<DLLExportAttr>() &&
5967 VD->getStorageClass() == SC_Static &&
5968 TSK == TSK_ImplicitInstantiation)
5969 S.MarkVariableReferenced(VD->getLocation(), VD);
5970
5971 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5972 if (!MD)
5973 continue;
5974
5975 if (Member->getAttr<DLLExportAttr>()) {
5976 if (MD->isUserProvided()) {
5977 // Instantiate non-default class member functions ...
5978
5979 // .. except for certain kinds of template specializations.
5980 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5981 continue;
5982
5983 S.MarkFunctionReferenced(Class->getLocation(), MD);
5984
5985 // The function will be passed to the consumer when its definition is
5986 // encountered.
5987 } else if (MD->isExplicitlyDefaulted()) {
5988 // Synthesize and instantiate explicitly defaulted methods.
5989 S.MarkFunctionReferenced(Class->getLocation(), MD);
5990
5991 if (TSK != TSK_ExplicitInstantiationDefinition) {
5992 // Except for explicit instantiation defs, we will not see the
5993 // definition again later, so pass it to the consumer now.
5994 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5995 }
5996 } else if (!MD->isTrivial() ||
5997 MD->isCopyAssignmentOperator() ||
5998 MD->isMoveAssignmentOperator()) {
5999 // Synthesize and instantiate non-trivial implicit methods, and the copy
6000 // and move assignment operators. The latter are exported even if they
6001 // are trivial, because the address of an operator can be taken and
6002 // should compare equal across libraries.
6003 S.MarkFunctionReferenced(Class->getLocation(), MD);
6004
6005 // There is no later point when we will see the definition of this
6006 // function, so pass it to the consumer now.
6007 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6008 }
6009 }
6010 }
6011}
6012
6013static void checkForMultipleExportedDefaultConstructors(Sema &S,
6014 CXXRecordDecl *Class) {
6015 // Only the MS ABI has default constructor closures, so we don't need to do
6016 // this semantic checking anywhere else.
6017 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6018 return;
6019
6020 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6021 for (Decl *Member : Class->decls()) {
6022 // Look for exported default constructors.
6023 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6024 if (!CD || !CD->isDefaultConstructor())
6025 continue;
6026 auto *Attr = CD->getAttr<DLLExportAttr>();
6027 if (!Attr)
6028 continue;
6029
6030 // If the class is non-dependent, mark the default arguments as ODR-used so
6031 // that we can properly codegen the constructor closure.
6032 if (!Class->isDependentContext()) {
6033 for (ParmVarDecl *PD : CD->parameters()) {
6034 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6035 S.DiscardCleanupsInEvaluationContext();
6036 }
6037 }
6038
6039 if (LastExportedDefaultCtor) {
6040 S.Diag(LastExportedDefaultCtor->getLocation(),
6041 diag::err_attribute_dll_ambiguous_default_ctor)
6042 << Class;
6043 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6044 << CD->getDeclName();
6045 return;
6046 }
6047 LastExportedDefaultCtor = CD;
6048 }
6049}
6050
6051static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6052 CXXRecordDecl *Class) {
6053 bool ErrorReported = false;
6054 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6055 ClassTemplateDecl *TD) {
6056 if (ErrorReported)
6057 return;
6058 S.Diag(TD->getLocation(),
6059 diag::err_cuda_device_builtin_surftex_cls_template)
6060 << /*surface*/ 0 << TD;
6061 ErrorReported = true;
6062 };
6063
6064 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6065 if (!TD) {
6066 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6067 if (!SD) {
6068 S.Diag(Class->getLocation(),
6069 diag::err_cuda_device_builtin_surftex_ref_decl)
6070 << /*surface*/ 0 << Class;
6071 S.Diag(Class->getLocation(),
6072 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6073 << Class;
6074 return;
6075 }
6076 TD = SD->getSpecializedTemplate();
6077 }
6078
6079 TemplateParameterList *Params = TD->getTemplateParameters();
6080 unsigned N = Params->size();
6081
6082 if (N != 2) {
6083 reportIllegalClassTemplate(S, TD);
6084 S.Diag(TD->getLocation(),
6085 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6086 << TD << 2;
6087 }
6088 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6089 reportIllegalClassTemplate(S, TD);
6090 S.Diag(TD->getLocation(),
6091 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6092 << TD << /*1st*/ 0 << /*type*/ 0;
6093 }
6094 if (N > 1) {
6095 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6096 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6097 reportIllegalClassTemplate(S, TD);
6098 S.Diag(TD->getLocation(),
6099 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6100 << TD << /*2nd*/ 1 << /*integer*/ 1;
6101 }
6102 }
6103}
6104
6105static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6106 CXXRecordDecl *Class) {
6107 bool ErrorReported = false;
6108 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6109 ClassTemplateDecl *TD) {
6110 if (ErrorReported)
6111 return;
6112 S.Diag(TD->getLocation(),
6113 diag::err_cuda_device_builtin_surftex_cls_template)
6114 << /*texture*/ 1 << TD;
6115 ErrorReported = true;
6116 };
6117
6118 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6119 if (!TD) {
6120 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6121 if (!SD) {
6122 S.Diag(Class->getLocation(),
6123 diag::err_cuda_device_builtin_surftex_ref_decl)
6124 << /*texture*/ 1 << Class;
6125 S.Diag(Class->getLocation(),
6126 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6127 << Class;
6128 return;
6129 }
6130 TD = SD->getSpecializedTemplate();
6131 }
6132
6133 TemplateParameterList *Params = TD->getTemplateParameters();
6134 unsigned N = Params->size();
6135
6136 if (N != 3) {
6137 reportIllegalClassTemplate(S, TD);
6138 S.Diag(TD->getLocation(),
6139 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6140 << TD << 3;
6141 }
6142 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6143 reportIllegalClassTemplate(S, TD);
6144 S.Diag(TD->getLocation(),
6145 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6146 << TD << /*1st*/ 0 << /*type*/ 0;
6147 }
6148 if (N > 1) {
6149 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6150 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6151 reportIllegalClassTemplate(S, TD);
6152 S.Diag(TD->getLocation(),
6153 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6154 << TD << /*2nd*/ 1 << /*integer*/ 1;
6155 }
6156 }
6157 if (N > 2) {
6158 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6159 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6160 reportIllegalClassTemplate(S, TD);
6161 S.Diag(TD->getLocation(),
6162 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6163 << TD << /*3rd*/ 2 << /*integer*/ 1;
6164 }
6165 }
6166}
6167
6168void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6169 // Mark any compiler-generated routines with the implicit code_seg attribute.
6170 for (auto *Method : Class->methods()) {
6171 if (Method->isUserProvided())
6172 continue;
6173 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6174 Method->addAttr(A);
6175 }
6176}
6177
6178/// Check class-level dllimport/dllexport attribute.
6179void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6180 Attr *ClassAttr = getDLLAttr(Class);
6181
6182 // MSVC inherits DLL attributes to partial class template specializations.
6183 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6184 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6185 if (Attr *TemplateAttr =
6186 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6187 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6188 A->setInherited(true);
6189 ClassAttr = A;
6190 }
6191 }
6192 }
6193
6194 if (!ClassAttr)
6195 return;
6196
6197 if (!Class->isExternallyVisible()) {
6198 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6199 << Class << ClassAttr;
6200 return;
6201 }
6202
6203 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6204 !ClassAttr->isInherited()) {
6205 // Diagnose dll attributes on members of class with dll attribute.
6206 for (Decl *Member : Class->decls()) {
6207 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6208 continue;
6209 InheritableAttr *MemberAttr = getDLLAttr(Member);
6210 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6211 continue;
6212
6213 Diag(MemberAttr->getLocation(),
6214 diag::err_attribute_dll_member_of_dll_class)
6215 << MemberAttr << ClassAttr;
6216 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6217 Member->setInvalidDecl();
6218 }
6219 }
6220
6221 if (Class->getDescribedClassTemplate())
6222 // Don't inherit dll attribute until the template is instantiated.
6223 return;
6224
6225 // The class is either imported or exported.
6226 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6227
6228 // Check if this was a dllimport attribute propagated from a derived class to
6229 // a base class template specialization. We don't apply these attributes to
6230 // static data members.
6231 const bool PropagatedImport =
6232 !ClassExported &&
6233 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6234
6235 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6236
6237 // Ignore explicit dllexport on explicit class template instantiation
6238 // declarations, except in MinGW mode.
6239 if (ClassExported && !ClassAttr->isInherited() &&
6240 TSK == TSK_ExplicitInstantiationDeclaration &&
6241 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6242 Class->dropAttr<DLLExportAttr>();
6243 return;
6244 }
6245
6246 // Force declaration of implicit members so they can inherit the attribute.
6247 ForceDeclarationOfImplicitMembers(Class);
6248
6249 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6250 // seem to be true in practice?
6251
6252 for (Decl *Member : Class->decls()) {
6253 VarDecl *VD = dyn_cast<VarDecl>(Member);
6254 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6255
6256 // Only methods and static fields inherit the attributes.
6257 if (!VD && !MD)
6258 continue;
6259
6260 if (MD) {
6261 // Don't process deleted methods.
6262 if (MD->isDeleted())
6263 continue;
6264
6265 if (MD->isInlined()) {
6266 // MinGW does not import or export inline methods. But do it for
6267 // template instantiations.
6268 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6269 TSK != TSK_ExplicitInstantiationDeclaration &&
6270 TSK != TSK_ExplicitInstantiationDefinition)
6271 continue;
6272
6273 // MSVC versions before 2015 don't export the move assignment operators
6274 // and move constructor, so don't attempt to import/export them if
6275 // we have a definition.
6276 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6277 if ((MD->isMoveAssignmentOperator() ||
6278 (Ctor && Ctor->isMoveConstructor())) &&
6279 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6280 continue;
6281
6282 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6283 // operator is exported anyway.
6284 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6285 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6286 continue;
6287 }
6288 }
6289
6290 // Don't apply dllimport attributes to static data members of class template
6291 // instantiations when the attribute is propagated from a derived class.
6292 if (VD && PropagatedImport)
6293 continue;
6294
6295 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6296 continue;
6297
6298 if (!getDLLAttr(Member)) {
6299 InheritableAttr *NewAttr = nullptr;
6300
6301 // Do not export/import inline function when -fno-dllexport-inlines is
6302 // passed. But add attribute for later local static var check.
6303 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6304 TSK != TSK_ExplicitInstantiationDeclaration &&
6305 TSK != TSK_ExplicitInstantiationDefinition) {
6306 if (ClassExported) {
6307 NewAttr = ::new (getASTContext())
6308 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6309 } else {
6310 NewAttr = ::new (getASTContext())
6311 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6312 }
6313 } else {
6314 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6315 }
6316
6317 NewAttr->setInherited(true);
6318 Member->addAttr(NewAttr);
6319
6320 if (MD) {
6321 // Propagate DLLAttr to friend re-declarations of MD that have already
6322 // been constructed.
6323 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6324 FD = FD->getPreviousDecl()) {
6325 if (FD->getFriendObjectKind() == Decl::FOK_None)
6326 continue;
6327 assert(!getDLLAttr(FD) &&(static_cast <bool> (!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? void (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 6328, __extension__ __PRETTY_FUNCTION__))
6328 "friend re-decl should not already have a DLLAttr")(static_cast <bool> (!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? void (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 6328, __extension__ __PRETTY_FUNCTION__))
;
6329 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6330 NewAttr->setInherited(true);
6331 FD->addAttr(NewAttr);
6332 }
6333 }
6334 }
6335 }
6336
6337 if (ClassExported)
6338 DelayedDllExportClasses.push_back(Class);
6339}
6340
6341/// Perform propagation of DLL attributes from a derived class to a
6342/// templated base class for MS compatibility.
6343void Sema::propagateDLLAttrToBaseClassTemplate(
6344 CXXRecordDecl *Class, Attr *ClassAttr,
6345 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6346 if (getDLLAttr(
6347 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6348 // If the base class template has a DLL attribute, don't try to change it.
6349 return;
6350 }
6351
6352 auto TSK = BaseTemplateSpec->getSpecializationKind();
6353 if (!getDLLAttr(BaseTemplateSpec) &&
6354 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6355 TSK == TSK_ImplicitInstantiation)) {
6356 // The template hasn't been instantiated yet (or it has, but only as an
6357 // explicit instantiation declaration or implicit instantiation, which means
6358 // we haven't codegenned any members yet), so propagate the attribute.
6359 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6360 NewAttr->setInherited(true);
6361 BaseTemplateSpec->addAttr(NewAttr);
6362
6363 // If this was an import, mark that we propagated it from a derived class to
6364 // a base class template specialization.
6365 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6366 ImportAttr->setPropagatedToBaseTemplate();
6367
6368 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6369 // needs to be run again to work see the new attribute. Otherwise this will
6370 // get run whenever the template is instantiated.
6371 if (TSK != TSK_Undeclared)
6372 checkClassLevelDLLAttribute(BaseTemplateSpec);
6373
6374 return;
6375 }
6376
6377 if (getDLLAttr(BaseTemplateSpec)) {
6378 // The template has already been specialized or instantiated with an
6379 // attribute, explicitly or through propagation. We should not try to change
6380 // it.
6381 return;
6382 }
6383
6384 // The template was previously instantiated or explicitly specialized without
6385 // a dll attribute, It's too late for us to add an attribute, so warn that
6386 // this is unsupported.
6387 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6388 << BaseTemplateSpec->isExplicitSpecialization();
6389 Diag(ClassAttr->getLocation(), diag::note_attribute);
6390 if (BaseTemplateSpec->isExplicitSpecialization()) {
6391 Diag(BaseTemplateSpec->getLocation(),
6392 diag::note_template_class_explicit_specialization_was_here)
6393 << BaseTemplateSpec;
6394 } else {
6395 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6396 diag::note_template_class_instantiation_was_here)
6397 << BaseTemplateSpec;
6398 }
6399}
6400
6401/// Determine the kind of defaulting that would be done for a given function.
6402///
6403/// If the function is both a default constructor and a copy / move constructor
6404/// (due to having a default argument for the first parameter), this picks
6405/// CXXDefaultConstructor.
6406///
6407/// FIXME: Check that case is properly handled by all callers.
6408Sema::DefaultedFunctionKind
6409Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6410 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6411 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6412 if (Ctor->isDefaultConstructor())
6413 return Sema::CXXDefaultConstructor;
6414
6415 if (Ctor->isCopyConstructor())
6416 return Sema::CXXCopyConstructor;
6417
6418 if (Ctor->isMoveConstructor())
6419 return Sema::CXXMoveConstructor;
6420 }
6421
6422 if (MD->isCopyAssignmentOperator())
6423 return Sema::CXXCopyAssignment;
6424
6425 if (MD->isMoveAssignmentOperator())
6426 return Sema::CXXMoveAssignment;
6427
6428 if (isa<CXXDestructorDecl>(FD))
6429 return Sema::CXXDestructor;
6430 }
6431
6432 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6433 case OO_EqualEqual:
6434 return DefaultedComparisonKind::Equal;
6435
6436 case OO_ExclaimEqual:
6437 return DefaultedComparisonKind::NotEqual;
6438
6439 case OO_Spaceship:
6440 // No point allowing this if <=> doesn't exist in the current language mode.
6441 if (!getLangOpts().CPlusPlus20)
6442 break;
6443 return DefaultedComparisonKind::ThreeWay;
6444
6445 case OO_Less:
6446 case OO_LessEqual:
6447 case OO_Greater:
6448 case OO_GreaterEqual:
6449 // No point allowing this if <=> doesn't exist in the current language mode.
6450 if (!getLangOpts().CPlusPlus20)
6451 break;
6452 return DefaultedComparisonKind::Relational;
6453
6454 default:
6455 break;
6456 }
6457
6458 // Not defaultable.
6459 return DefaultedFunctionKind();
6460}
6461
6462static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6463 SourceLocation DefaultLoc) {
6464 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6465 if (DFK.isComparison())
6466 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6467
6468 switch (DFK.asSpecialMember()) {
6469 case Sema::CXXDefaultConstructor:
6470 S.DefineImplicitDefaultConstructor(DefaultLoc,
6471 cast<CXXConstructorDecl>(FD));
6472 break;
6473 case Sema::CXXCopyConstructor:
6474 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6475 break;
6476 case Sema::CXXCopyAssignment:
6477 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6478 break;
6479 case Sema::CXXDestructor:
6480 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6481 break;
6482 case Sema::CXXMoveConstructor:
6483 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6484 break;
6485 case Sema::CXXMoveAssignment:
6486 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6487 break;
6488 case Sema::CXXInvalid:
6489 llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 6489)
;
6490 }
6491}
6492
6493/// Determine whether a type is permitted to be passed or returned in
6494/// registers, per C++ [class.temporary]p3.
6495static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6496 TargetInfo::CallingConvKind CCK) {
6497 if (D->isDependentType() || D->isInvalidDecl())
6498 return false;
6499
6500 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6501 // The PS4 platform ABI follows the behavior of Clang 3.2.
6502 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6503 return !D->hasNonTrivialDestructorForCall() &&
6504 !D->hasNonTrivialCopyConstructorForCall();
6505
6506 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6507 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6508 bool DtorIsTrivialForCall = false;
6509
6510 // If a class has at least one non-deleted, trivial copy constructor, it
6511 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6512 //
6513 // Note: This permits classes with non-trivial copy or move ctors to be
6514 // passed in registers, so long as they *also* have a trivial copy ctor,
6515 // which is non-conforming.
6516 if (D->needsImplicitCopyConstructor()) {
6517 if (!D->defaultedCopyConstructorIsDeleted()) {
6518 if (D->hasTrivialCopyConstructor())
6519 CopyCtorIsTrivial = true;
6520 if (D->hasTrivialCopyConstructorForCall())
6521 CopyCtorIsTrivialForCall = true;
6522 }
6523 } else {
6524 for (const CXXConstructorDecl *CD : D->ctors()) {
6525 if (CD->isCopyConstructor() && !CD->isDeleted()) {
6526 if (CD->isTrivial())
6527 CopyCtorIsTrivial = true;
6528 if (CD->isTrivialForCall())
6529 CopyCtorIsTrivialForCall = true;
6530 }
6531 }
6532 }
6533
6534 if (D->needsImplicitDestructor()) {
6535 if (!D->defaultedDestructorIsDeleted() &&
6536 D->hasTrivialDestructorForCall())
6537 DtorIsTrivialForCall = true;
6538 } else if (const auto *DD = D->getDestructor()) {
6539 if (!DD->isDeleted() && DD->isTrivialForCall())
6540 DtorIsTrivialForCall = true;
6541 }
6542
6543 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6544 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6545 return true;
6546
6547 // If a class has a destructor, we'd really like to pass it indirectly
6548 // because it allows us to elide copies. Unfortunately, MSVC makes that
6549 // impossible for small types, which it will pass in a single register or
6550 // stack slot. Most objects with dtors are large-ish, so handle that early.
6551 // We can't call out all large objects as being indirect because there are
6552 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6553 // how we pass large POD types.
6554
6555 // Note: This permits small classes with nontrivial destructors to be
6556 // passed in registers, which is non-conforming.
6557 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6558 uint64_t TypeSize = isAArch64 ? 128 : 64;
6559
6560 if (CopyCtorIsTrivial &&
6561 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6562 return true;
6563 return false;
6564 }
6565
6566 // Per C++ [class.temporary]p3, the relevant condition is:
6567 // each copy constructor, move constructor, and destructor of X is
6568 // either trivial or deleted, and X has at least one non-deleted copy
6569 // or move constructor
6570 bool HasNonDeletedCopyOrMove = false;
6571
6572 if (D->needsImplicitCopyConstructor() &&
6573 !D->defaultedCopyConstructorIsDeleted()) {
6574 if (!D->hasTrivialCopyConstructorForCall())
6575 return false;
6576 HasNonDeletedCopyOrMove = true;
6577 }
6578
6579 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6580 !D->defaultedMoveConstructorIsDeleted()) {
6581 if (!D->hasTrivialMoveConstructorForCall())
6582 return false;
6583 HasNonDeletedCopyOrMove = true;
6584 }
6585
6586 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6587 !D->hasTrivialDestructorForCall())
6588 return false;
6589
6590 for (const CXXMethodDecl *MD : D->methods()) {
6591 if (MD->isDeleted())
6592 continue;
6593
6594 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6595 if (CD && CD->isCopyOrMoveConstructor())
6596 HasNonDeletedCopyOrMove = true;
6597 else if (!isa<CXXDestructorDecl>(MD))
6598 continue;
6599
6600 if (!MD->isTrivialForCall())
6601 return false;
6602 }
6603
6604 return HasNonDeletedCopyOrMove;
6605}
6606
6607/// Report an error regarding overriding, along with any relevant
6608/// overridden methods.
6609///
6610/// \param DiagID the primary error to report.
6611/// \param MD the overriding method.
6612static bool
6613ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6614 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6615 bool IssuedDiagnostic = false;
6616 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6617 if (Report(O)) {
6618 if (!IssuedDiagnostic) {
6619 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6620 IssuedDiagnostic = true;
6621 }
6622 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6623 }
6624 }
6625 return IssuedDiagnostic;
6626}
6627
6628/// Perform semantic checks on a class definition that has been
6629/// completing, introducing implicitly-declared members, checking for
6630/// abstract types, etc.
6631///
6632/// \param S The scope in which the class was parsed. Null if we didn't just
6633/// parse a class definition.
6634/// \param Record The completed class.
6635void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6636 if (!Record)
6637 return;
6638
6639 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6640 AbstractUsageInfo Info(*this, Record);
6641 CheckAbstractClassUsage(Info, Record);
6642 }
6643
6644 // If this is not an aggregate type and has no user-declared constructor,
6645 // complain about any non-static data members of reference or const scalar
6646 // type, since they will never get initializers.
6647 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6648 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6649 !Record->isLambda()) {
6650 bool Complained = false;
6651 for (const auto *F : Record->fields()) {
6652 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6653 continue;
6654
6655 if (F->getType()->isReferenceType() ||
6656 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6657 if (!Complained) {
6658 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6659 << Record->getTagKind() << Record;
6660 Complained = true;
6661 }
6662
6663 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6664 << F->getType()->isReferenceType()
6665 << F->getDeclName();
6666 }
6667 }
6668 }
6669
6670 if (Record->getIdentifier()) {
6671 // C++ [class.mem]p13:
6672 // If T is the name of a class, then each of the following shall have a
6673 // name different from T:
6674 // - every member of every anonymous union that is a member of class T.
6675 //
6676 // C++ [class.mem]p14:
6677 // In addition, if class T has a user-declared constructor (12.1), every
6678 // non-static data member of class T shall have a name different from T.
6679 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6680 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6681 ++I) {
6682 NamedDecl *D = (*I)->getUnderlyingDecl();
6683 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6684 Record->hasUserDeclaredConstructor()) ||
6685 isa<IndirectFieldDecl>(D)) {
6686 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6687 << D->getDeclName();
6688 break;
6689 }
6690 }
6691 }
6692
6693 // Warn if the class has virtual methods but non-virtual public destructor.
6694 if (Record->isPolymorphic() && !Record->isDependentType()) {
6695 CXXDestructorDecl *dtor = Record->getDestructor();
6696 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6697 !Record->hasAttr<FinalAttr>())
6698 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6699 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6700 }
6701
6702 if (Record->isAbstract()) {
6703 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6704 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6705 << FA->isSpelledAsSealed();
6706 DiagnoseAbstractType(Record);
6707 }
6708 }
6709
6710 // Warn if the class has a final destructor but is not itself marked final.
6711 if (!Record->hasAttr<FinalAttr>()) {
6712 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6713 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6714 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6715 << FA->isSpelledAsSealed()
6716 << FixItHint::CreateInsertion(
6717 getLocForEndOfToken(Record->getLocation()),
6718 (FA->isSpelledAsSealed() ? " sealed" : " final"));
6719 Diag(Record->getLocation(),
6720 diag::note_final_dtor_non_final_class_silence)
6721 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6722 }
6723 }
6724 }
6725
6726 // See if trivial_abi has to be dropped.
6727 if (Record->hasAttr<TrivialABIAttr>())
6728 checkIllFormedTrivialABIStruct(*Record);
6729
6730 // Set HasTrivialSpecialMemberForCall if the record has attribute
6731 // "trivial_abi".
6732 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6733
6734 if (HasTrivialABI)
6735 Record->setHasTrivialSpecialMemberForCall();
6736
6737 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6738 // We check these last because they can depend on the properties of the
6739 // primary comparison functions (==, <=>).
6740 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6741
6742 // Perform checks that can't be done until we know all the properties of a
6743 // member function (whether it's defaulted, deleted, virtual, overriding,
6744 // ...).
6745 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6746 // A static function cannot override anything.
6747 if (MD->getStorageClass() == SC_Static) {
6748 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6749 [](const CXXMethodDecl *) { return true; }))
6750 return;
6751 }
6752
6753 // A deleted function cannot override a non-deleted function and vice
6754 // versa.
6755 if (ReportOverrides(*this,
6756 MD->isDeleted() ? diag::err_deleted_override
6757 : diag::err_non_deleted_override,
6758 MD, [&](const CXXMethodDecl *V) {
6759 return MD->isDeleted() != V->isDeleted();
6760 })) {
6761 if (MD->isDefaulted() && MD->isDeleted())
6762 // Explain why this defaulted function was deleted.
6763 DiagnoseDeletedDefaultedFunction(MD);
6764 return;
6765 }
6766
6767 // A consteval function cannot override a non-consteval function and vice
6768 // versa.
6769 if (ReportOverrides(*this,
6770 MD->isConsteval() ? diag::err_consteval_override
6771 : diag::err_non_consteval_override,
6772 MD, [&](const CXXMethodDecl *V) {
6773 return MD->isConsteval() != V->isConsteval();
6774 })) {
6775 if (MD->isDefaulted() && MD->isDeleted())
6776 // Explain why this defaulted function was deleted.
6777 DiagnoseDeletedDefaultedFunction(MD);
6778 return;
6779 }
6780 };
6781
6782 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6783 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6784 return false;
6785
6786 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6787 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6788 DFK.asComparison() == DefaultedComparisonKind::Relational) {
6789 DefaultedSecondaryComparisons.push_back(FD);
6790 return true;
6791 }
6792
6793 CheckExplicitlyDefaultedFunction(S, FD);
6794 return false;
6795 };
6796
6797 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6798 // Check whether the explicitly-defaulted members are valid.
6799 bool Incomplete = CheckForDefaultedFunction(M);
6800
6801 // Skip the rest of the checks for a member of a dependent class.
6802 if (Record->isDependentType())
6803 return;
6804
6805 // For an explicitly defaulted or deleted special member, we defer
6806 // determining triviality until the class is complete. That time is now!
6807 CXXSpecialMember CSM = getSpecialMember(M);
6808 if (!M->isImplicit() && !M->isUserProvided()) {
6809 if (CSM != CXXInvalid) {
6810 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6811 // Inform the class that we've finished declaring this member.
6812 Record->finishedDefaultedOrDeletedMember(M);
6813 M->setTrivialForCall(
6814 HasTrivialABI ||
6815 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6816 Record->setTrivialForCallFlags(M);
6817 }
6818 }
6819
6820 // Set triviality for the purpose of calls if this is a user-provided
6821 // copy/move constructor or destructor.
6822 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6823 CSM == CXXDestructor) && M->isUserProvided()) {
6824 M->setTrivialForCall(HasTrivialABI);
6825 Record->setTrivialForCallFlags(M);
6826 }
6827
6828 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6829 M->hasAttr<DLLExportAttr>()) {
6830 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6831 M->isTrivial() &&
6832 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6833 CSM == CXXDestructor))
6834 M->dropAttr<DLLExportAttr>();
6835
6836 if (M->hasAttr<DLLExportAttr>()) {
6837 // Define after any fields with in-class initializers have been parsed.
6838 DelayedDllExportMemberFunctions.push_back(M);
6839 }
6840 }
6841
6842 // Define defaulted constexpr virtual functions that override a base class
6843 // function right away.
6844 // FIXME: We can defer doing this until the vtable is marked as used.
6845 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6846 DefineDefaultedFunction(*this, M, M->getLocation());
6847
6848 if (!Incomplete)
6849 CheckCompletedMemberFunction(M);
6850 };
6851
6852 // Check the destructor before any other member function. We need to
6853 // determine whether it's trivial in order to determine whether the claas
6854 // type is a literal type, which is a prerequisite for determining whether
6855 // other special member functions are valid and whether they're implicitly
6856 // 'constexpr'.
6857 if (CXXDestructorDecl *Dtor = Record->getDestructor())
6858 CompleteMemberFunction(Dtor);
6859
6860 bool HasMethodWithOverrideControl = false,
6861 HasOverridingMethodWithoutOverrideControl = false;
6862 for (auto *D : Record->decls()) {
6863 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6864 // FIXME: We could do this check for dependent types with non-dependent
6865 // bases.
6866 if (!Record->isDependentType()) {
6867 // See if a method overloads virtual methods in a base
6868 // class without overriding any.
6869 if (!M->isStatic())
6870 DiagnoseHiddenVirtualMethods(M);
6871 if (M->hasAttr<OverrideAttr>())
6872 HasMethodWithOverrideControl = true;
6873 else if (M->size_overridden_methods() > 0)
6874 HasOverridingMethodWithoutOverrideControl = true;
6875 }
6876
6877 if (!isa<CXXDestructorDecl>(M))
6878 CompleteMemberFunction(M);
6879 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6880 CheckForDefaultedFunction(
6881 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6882 }
6883 }
6884
6885 if (HasOverridingMethodWithoutOverrideControl) {
6886 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6887 for (auto *M : Record->methods())
6888 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6889 }
6890
6891 // Check the defaulted secondary comparisons after any other member functions.
6892 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6893 CheckExplicitlyDefaultedFunction(S, FD);
6894
6895 // If this is a member function, we deferred checking it until now.
6896 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6897 CheckCompletedMemberFunction(MD);
6898 }
6899
6900 // ms_struct is a request to use the same ABI rules as MSVC. Check
6901 // whether this class uses any C++ features that are implemented
6902 // completely differently in MSVC, and if so, emit a diagnostic.
6903 // That diagnostic defaults to an error, but we allow projects to
6904 // map it down to a warning (or ignore it). It's a fairly common
6905 // practice among users of the ms_struct pragma to mass-annotate
6906 // headers, sweeping up a bunch of types that the project doesn't
6907 // really rely on MSVC-compatible layout for. We must therefore
6908 // support "ms_struct except for C++ stuff" as a secondary ABI.
6909 // Don't emit this diagnostic if the feature was enabled as a
6910 // language option (as opposed to via a pragma or attribute), as
6911 // the option -mms-bitfields otherwise essentially makes it impossible
6912 // to build C++ code, unless this diagnostic is turned off.
6913 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6914 (Record->isPolymorphic() || Record->getNumBases())) {
6915 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6916 }
6917
6918 checkClassLevelDLLAttribute(Record);
6919 checkClassLevelCodeSegAttribute(Record);
6920
6921 bool ClangABICompat4 =
6922 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6923 TargetInfo::CallingConvKind CCK =
6924 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6925 bool CanPass = canPassInRegisters(*this, Record, CCK);
6926
6927 // Do not change ArgPassingRestrictions if it has already been set to
6928 // APK_CanNeverPassInRegs.
6929 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6930 Record->setArgPassingRestrictions(CanPass
6931 ? RecordDecl::APK_CanPassInRegs
6932 : RecordDecl::APK_CannotPassInRegs);
6933
6934 // If canPassInRegisters returns true despite the record having a non-trivial
6935 // destructor, the record is destructed in the callee. This happens only when
6936 // the record or one of its subobjects has a field annotated with trivial_abi
6937 // or a field qualified with ObjC __strong/__weak.
6938 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6939 Record->setParamDestroyedInCallee(true);
6940 else if (Record->hasNonTrivialDestructor())
6941 Record->setParamDestroyedInCallee(CanPass);
6942
6943 if (getLangOpts().ForceEmitVTables) {
6944 // If we want to emit all the vtables, we need to mark it as used. This
6945 // is especially required for cases like vtable assumption loads.
6946 MarkVTableUsed(Record->getInnerLocStart(), Record);
6947 }
6948
6949 if (getLangOpts().CUDA) {
6950 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6951 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6952 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6953 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6954 }
6955}
6956
6957/// Look up the special member function that would be called by a special
6958/// member function for a subobject of class type.
6959///
6960/// \param Class The class type of the subobject.
6961/// \param CSM The kind of special member function.
6962/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6963/// \param ConstRHS True if this is a copy operation with a const object
6964/// on its RHS, that is, if the argument to the outer special member
6965/// function is 'const' and this is not a field marked 'mutable'.
6966static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6967 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6968 unsigned FieldQuals, bool ConstRHS) {
6969 unsigned LHSQuals = 0;
6970 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6971 LHSQuals = FieldQuals;
6972
6973 unsigned RHSQuals = FieldQuals;
6974 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6975 RHSQuals = 0;
6976 else if (ConstRHS)
6977 RHSQuals |= Qualifiers::Const;
6978
6979 return S.LookupSpecialMember(Class, CSM,
6980 RHSQuals & Qualifiers::Const,
6981 RHSQuals & Qualifiers::Volatile,
6982 false,
6983 LHSQuals & Qualifiers::Const,
6984 LHSQuals & Qualifiers::Volatile);
6985}
6986
6987class Sema::InheritedConstructorInfo {
6988 Sema &S;
6989 SourceLocation UseLoc;
6990
6991 /// A mapping from the base classes through which the constructor was
6992 /// inherited to the using shadow declaration in that base class (or a null
6993 /// pointer if the constructor was declared in that base class).
6994 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6995 InheritedFromBases;
6996
6997public:
6998 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6999 ConstructorUsingShadowDecl *Shadow)
7000 : S(S), UseLoc(UseLoc) {
7001 bool DiagnosedMultipleConstructedBases = false;
7002 CXXRecordDecl *ConstructedBase = nullptr;
7003 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7004
7005 // Find the set of such base class subobjects and check that there's a
7006 // unique constructed subobject.
7007 for (auto *D : Shadow->redecls()) {
7008 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7009 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7010 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7011
7012 InheritedFromBases.insert(
7013 std::make_pair(DNominatedBase->getCanonicalDecl(),
7014 DShadow->getNominatedBaseClassShadowDecl()));
7015 if (DShadow->constructsVirtualBase())
7016 InheritedFromBases.insert(
7017 std::make_pair(DConstructedBase->getCanonicalDecl(),
7018 DShadow->getConstructedBaseClassShadowDecl()));
7019 else
7020 assert(DNominatedBase == DConstructedBase)(static_cast <bool> (DNominatedBase == DConstructedBase
) ? void (0) : __assert_fail ("DNominatedBase == DConstructedBase"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7020, __extension__ __PRETTY_FUNCTION__))
;
7021
7022 // [class.inhctor.init]p2:
7023 // If the constructor was inherited from multiple base class subobjects
7024 // of type B, the program is ill-formed.
7025 if (!ConstructedBase) {
7026 ConstructedBase = DConstructedBase;
7027 ConstructedBaseIntroducer = D->getIntroducer();
7028 } else if (ConstructedBase != DConstructedBase &&
7029 !Shadow->isInvalidDecl()) {
7030 if (!DiagnosedMultipleConstructedBases) {
7031 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7032 << Shadow->getTargetDecl();
7033 S.Diag(ConstructedBaseIntroducer->getLocation(),
7034 diag::note_ambiguous_inherited_constructor_using)
7035 << ConstructedBase;
7036 DiagnosedMultipleConstructedBases = true;
7037 }
7038 S.Diag(D->getIntroducer()->getLocation(),
7039 diag::note_ambiguous_inherited_constructor_using)
7040 << DConstructedBase;
7041 }
7042 }
7043
7044 if (DiagnosedMultipleConstructedBases)
7045 Shadow->setInvalidDecl();
7046 }
7047
7048 /// Find the constructor to use for inherited construction of a base class,
7049 /// and whether that base class constructor inherits the constructor from a
7050 /// virtual base class (in which case it won't actually invoke it).
7051 std::pair<CXXConstructorDecl *, bool>
7052 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7053 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7054 if (It == InheritedFromBases.end())
7055 return std::make_pair(nullptr, false);
7056
7057 // This is an intermediary class.
7058 if (It->second)
7059 return std::make_pair(
7060 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7061 It->second->constructsVirtualBase());
7062
7063 // This is the base class from which the constructor was inherited.
7064 return std::make_pair(Ctor, false);
7065 }
7066};
7067
7068/// Is the special member function which would be selected to perform the
7069/// specified operation on the specified class type a constexpr constructor?
7070static bool
7071specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7072 Sema::CXXSpecialMember CSM, unsigned Quals,
7073 bool ConstRHS,
7074 CXXConstructorDecl *InheritedCtor = nullptr,
7075 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7076 // If we're inheriting a constructor, see if we need to call it for this base
7077 // class.
7078 if (InheritedCtor) {
7079 assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor
) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7079, __extension__ __PRETTY_FUNCTION__))
;
7080 auto BaseCtor =
7081 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7082 if (BaseCtor)
7083 return BaseCtor->isConstexpr();
7084 }
7085
7086 if (CSM == Sema::CXXDefaultConstructor)
7087 return ClassDecl->hasConstexprDefaultConstructor();
7088 if (CSM == Sema::CXXDestructor)
7089 return ClassDecl->hasConstexprDestructor();
7090
7091 Sema::SpecialMemberOverloadResult SMOR =
7092 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7093 if (!SMOR.getMethod())
7094 // A constructor we wouldn't select can't be "involved in initializing"
7095 // anything.
7096 return true;
7097 return SMOR.getMethod()->isConstexpr();
7098}
7099
7100/// Determine whether the specified special member function would be constexpr
7101/// if it were implicitly defined.
7102static bool defaultedSpecialMemberIsConstexpr(
7103 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7104 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7105 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7106 if (!S.getLangOpts().CPlusPlus11)
7107 return false;
7108
7109 // C++11 [dcl.constexpr]p4:
7110 // In the definition of a constexpr constructor [...]
7111 bool Ctor = true;
7112 switch (CSM) {
7113 case Sema::CXXDefaultConstructor:
7114 if (Inherited)
7115 break;
7116 // Since default constructor lookup is essentially trivial (and cannot
7117 // involve, for instance, template instantiation), we compute whether a
7118 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7119 //
7120 // This is important for performance; we need to know whether the default
7121 // constructor is constexpr to determine whether the type is a literal type.
7122 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7123
7124 case Sema::CXXCopyConstructor:
7125 case Sema::CXXMoveConstructor:
7126 // For copy or move constructors, we need to perform overload resolution.
7127 break;
7128
7129 case Sema::CXXCopyAssignment:
7130 case Sema::CXXMoveAssignment:
7131 if (!S.getLangOpts().CPlusPlus14)
7132 return false;
7133 // In C++1y, we need to perform overload resolution.
7134 Ctor = false;
7135 break;
7136
7137 case Sema::CXXDestructor:
7138 return ClassDecl->defaultedDestructorIsConstexpr();
7139
7140 case Sema::CXXInvalid:
7141 return false;
7142 }
7143
7144 // -- if the class is a non-empty union, or for each non-empty anonymous
7145 // union member of a non-union class, exactly one non-static data member
7146 // shall be initialized; [DR1359]
7147 //
7148 // If we squint, this is guaranteed, since exactly one non-static data member
7149 // will be initialized (if the constructor isn't deleted), we just don't know
7150 // which one.
7151 if (Ctor && ClassDecl->isUnion())
7152 return CSM == Sema::CXXDefaultConstructor
7153 ? ClassDecl->hasInClassInitializer() ||
7154 !ClassDecl->hasVariantMembers()
7155 : true;
7156
7157 // -- the class shall not have any virtual base classes;
7158 if (Ctor && ClassDecl->getNumVBases())
7159 return false;
7160
7161 // C++1y [class.copy]p26:
7162 // -- [the class] is a literal type, and
7163 if (!Ctor && !ClassDecl->isLiteral())
7164 return false;
7165
7166 // -- every constructor involved in initializing [...] base class
7167 // sub-objects shall be a constexpr constructor;
7168 // -- the assignment operator selected to copy/move each direct base
7169 // class is a constexpr function, and
7170 for (const auto &B : ClassDecl->bases()) {
7171 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7172 if (!BaseType) continue;
7173
7174 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7175 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7176 InheritedCtor, Inherited))
7177 return false;
7178 }
7179
7180 // -- every constructor involved in initializing non-static data members
7181 // [...] shall be a constexpr constructor;
7182 // -- every non-static data member and base class sub-object shall be
7183 // initialized
7184 // -- for each non-static data member of X that is of class type (or array
7185 // thereof), the assignment operator selected to copy/move that member is
7186 // a constexpr function
7187 for (const auto *F : ClassDecl->fields()) {
7188 if (F->isInvalidDecl())
7189 continue;
7190 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7191 continue;
7192 QualType BaseType = S.Context.getBaseElementType(F->getType());
7193 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7194 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7195 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7196 BaseType.getCVRQualifiers(),
7197 ConstArg && !F->isMutable()))
7198 return false;
7199 } else if (CSM == Sema::CXXDefaultConstructor) {
7200 return false;
7201 }
7202 }
7203
7204 // All OK, it's constexpr!
7205 return true;
7206}
7207
7208namespace {
7209/// RAII object to register a defaulted function as having its exception
7210/// specification computed.
7211struct ComputingExceptionSpec {
7212 Sema &S;
7213
7214 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7215 : S(S) {
7216 Sema::CodeSynthesisContext Ctx;
7217 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7218 Ctx.PointOfInstantiation = Loc;
7219 Ctx.Entity = FD;
7220 S.pushCodeSynthesisContext(Ctx);
7221 }
7222 ~ComputingExceptionSpec() {
7223 S.popCodeSynthesisContext();
7224 }
7225};
7226}
7227
7228static Sema::ImplicitExceptionSpecification
7229ComputeDefaultedSpecialMemberExceptionSpec(
7230 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7231 Sema::InheritedConstructorInfo *ICI);
7232
7233static Sema::ImplicitExceptionSpecification
7234ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7235 FunctionDecl *FD,
7236 Sema::DefaultedComparisonKind DCK);
7237
7238static Sema::ImplicitExceptionSpecification
7239computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7240 auto DFK = S.getDefaultedFunctionKind(FD);
7241 if (DFK.isSpecialMember())
7242 return ComputeDefaultedSpecialMemberExceptionSpec(
7243 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7244 if (DFK.isComparison())
7245 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7246 DFK.asComparison());
7247
7248 auto *CD = cast<CXXConstructorDecl>(FD);
7249 assert(CD->getInheritedConstructor() &&(static_cast <bool> (CD->getInheritedConstructor() &&
"only defaulted functions and inherited constructors have implicit "
"exception specs") ? void (0) : __assert_fail ("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7251, __extension__ __PRETTY_FUNCTION__))
7250 "only defaulted functions and inherited constructors have implicit "(static_cast <bool> (CD->getInheritedConstructor() &&
"only defaulted functions and inherited constructors have implicit "
"exception specs") ? void (0) : __assert_fail ("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7251, __extension__ __PRETTY_FUNCTION__))
7251 "exception specs")(static_cast <bool> (CD->getInheritedConstructor() &&
"only defaulted functions and inherited constructors have implicit "
"exception specs") ? void (0) : __assert_fail ("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7251, __extension__ __PRETTY_FUNCTION__))
;
7252 Sema::InheritedConstructorInfo ICI(
7253 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7254 return ComputeDefaultedSpecialMemberExceptionSpec(
7255 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7256}
7257
7258static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7259 CXXMethodDecl *MD) {
7260 FunctionProtoType::ExtProtoInfo EPI;
7261
7262 // Build an exception specification pointing back at this member.
7263 EPI.ExceptionSpec.Type = EST_Unevaluated;
7264 EPI.ExceptionSpec.SourceDecl = MD;
7265
7266 // Set the calling convention to the default for C++ instance methods.
7267 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7268 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7269 /*IsCXXMethod=*/true));
7270 return EPI;
7271}
7272
7273void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7274 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7275 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7276 return;
7277
7278 // Evaluate the exception specification.
7279 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7280 auto ESI = IES.getExceptionSpec();
7281
7282 // Update the type of the special member to use it.
7283 UpdateExceptionSpec(FD, ESI);
7284}
7285
7286void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7287 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted")(static_cast <bool> (FD->isExplicitlyDefaulted() &&
"not explicitly-defaulted") ? void (0) : __assert_fail ("FD->isExplicitlyDefaulted() && \"not explicitly-defaulted\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7287, __extension__ __PRETTY_FUNCTION__))
;
7288
7289 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7290 if (!DefKind) {
7291 assert(FD->getDeclContext()->isDependentContext())(static_cast <bool> (FD->getDeclContext()->isDependentContext
()) ? void (0) : __assert_fail ("FD->getDeclContext()->isDependentContext()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7291, __extension__ __PRETTY_FUNCTION__))
;
7292 return;
7293 }
7294
7295 if (DefKind.isComparison())
7296 UnusedPrivateFields.clear();
7297
7298 if (DefKind.isSpecialMember()
7299 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7300 DefKind.asSpecialMember())
7301 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7302 FD->setInvalidDecl();
7303}
7304
7305bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7306 CXXSpecialMember CSM) {
7307 CXXRecordDecl *RD = MD->getParent();
7308
7309 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&(static_cast <bool> (MD->isExplicitlyDefaulted() &&
CSM != CXXInvalid && "not an explicitly-defaulted special member"
) ? void (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7310, __extension__ __PRETTY_FUNCTION__))
7310 "not an explicitly-defaulted special member")(static_cast <bool> (MD->isExplicitlyDefaulted() &&
CSM != CXXInvalid && "not an explicitly-defaulted special member"
) ? void (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7310, __extension__ __PRETTY_FUNCTION__))
;
7311
7312 // Defer all checking for special members of a dependent type.
7313 if (RD->isDependentType())
7314 return false;
7315
7316 // Whether this was the first-declared instance of the constructor.
7317 // This affects whether we implicitly add an exception spec and constexpr.
7318 bool First = MD == MD->getCanonicalDecl();
7319
7320 bool HadError = false;
7321
7322 // C++11 [dcl.fct.def.default]p1:
7323 // A function that is explicitly defaulted shall
7324 // -- be a special member function [...] (checked elsewhere),
7325 // -- have the same type (except for ref-qualifiers, and except that a
7326 // copy operation can take a non-const reference) as an implicit
7327 // declaration, and
7328 // -- not have default arguments.
7329 // C++2a changes the second bullet to instead delete the function if it's
7330 // defaulted on its first declaration, unless it's "an assignment operator,
7331 // and its return type differs or its parameter type is not a reference".
7332 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7333 bool ShouldDeleteForTypeMismatch = false;
7334 unsigned ExpectedParams = 1;
7335 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7336 ExpectedParams = 0;
7337 if (MD->getNumParams() != ExpectedParams) {
7338 // This checks for default arguments: a copy or move constructor with a
7339 // default argument is classified as a default constructor, and assignment
7340 // operations and destructors can't have default arguments.
7341 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7342 << CSM << MD->getSourceRange();
7343 HadError = true;
7344 } else if (MD->isVariadic()) {
7345 if (DeleteOnTypeMismatch)
7346 ShouldDeleteForTypeMismatch = true;
7347 else {
7348 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7349 << CSM << MD->getSourceRange();
7350 HadError = true;
7351 }
7352 }
7353
7354 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7355
7356 bool CanHaveConstParam = false;
7357 if (CSM == CXXCopyConstructor)
7358 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7359 else if (CSM == CXXCopyAssignment)
7360 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7361
7362 QualType ReturnType = Context.VoidTy;
7363 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7364 // Check for return type matching.
7365 ReturnType = Type->getReturnType();
7366
7367 QualType DeclType = Context.getTypeDeclType(RD);
7368 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7369 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7370
7371 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7372 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7373 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7374 HadError = true;
7375 }
7376
7377 // A defaulted special member cannot have cv-qualifiers.
7378 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7379 if (DeleteOnTypeMismatch)
7380 ShouldDeleteForTypeMismatch = true;
7381 else {
7382 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7383 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7384 HadError = true;
7385 }
7386 }
7387 }
7388
7389 // Check for parameter type matching.
7390 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7391 bool HasConstParam = false;
7392 if (ExpectedParams && ArgType->isReferenceType()) {
7393 // Argument must be reference to possibly-const T.
7394 QualType ReferentType = ArgType->getPointeeType();
7395 HasConstParam = ReferentType.isConstQualified();
7396
7397 if (ReferentType.isVolatileQualified()) {
7398 if (DeleteOnTypeMismatch)
7399 ShouldDeleteForTypeMismatch = true;
7400 else {
7401 Diag(MD->getLocation(),
7402 diag::err_defaulted_special_member_volatile_param) << CSM;
7403 HadError = true;
7404 }
7405 }
7406
7407 if (HasConstParam && !CanHaveConstParam) {
7408 if (DeleteOnTypeMismatch)
7409 ShouldDeleteForTypeMismatch = true;
7410 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7411 Diag(MD->getLocation(),
7412 diag::err_defaulted_special_member_copy_const_param)
7413 << (CSM == CXXCopyAssignment);
7414 // FIXME: Explain why this special member can't be const.
7415 HadError = true;
7416 } else {
7417 Diag(MD->getLocation(),
7418 diag::err_defaulted_special_member_move_const_param)
7419 << (CSM == CXXMoveAssignment);
7420 HadError = true;
7421 }
7422 }
7423 } else if (ExpectedParams) {
7424 // A copy assignment operator can take its argument by value, but a
7425 // defaulted one cannot.
7426 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument")(static_cast <bool> (CSM == CXXCopyAssignment &&
"unexpected non-ref argument") ? void (0) : __assert_fail ("CSM == CXXCopyAssignment && \"unexpected non-ref argument\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7426, __extension__ __PRETTY_FUNCTION__))
;
7427 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7428 HadError = true;
7429 }
7430
7431 // C++11 [dcl.fct.def.default]p2:
7432 // An explicitly-defaulted function may be declared constexpr only if it
7433 // would have been implicitly declared as constexpr,
7434 // Do not apply this rule to members of class templates, since core issue 1358
7435 // makes such functions always instantiate to constexpr functions. For
7436 // functions which cannot be constexpr (for non-constructors in C++11 and for
7437 // destructors in C++14 and C++17), this is checked elsewhere.
7438 //
7439 // FIXME: This should not apply if the member is deleted.
7440 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7441 HasConstParam);
7442 if ((getLangOpts().CPlusPlus20 ||
7443 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7444 : isa<CXXConstructorDecl>(MD))) &&
7445 MD->isConstexpr() && !Constexpr &&
7446 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7447 Diag(MD->getBeginLoc(), MD->isConsteval()
7448 ? diag::err_incorrect_defaulted_consteval
7449 : diag::err_incorrect_defaulted_constexpr)
7450 << CSM;
7451 // FIXME: Explain why the special member can't be constexpr.
7452 HadError = true;
7453 }
7454
7455 if (First) {
7456 // C++2a [dcl.fct.def.default]p3:
7457 // If a function is explicitly defaulted on its first declaration, it is
7458 // implicitly considered to be constexpr if the implicit declaration
7459 // would be.
7460 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7461 ? ConstexprSpecKind::Consteval
7462 : ConstexprSpecKind::Constexpr)
7463 : ConstexprSpecKind::Unspecified);
7464
7465 if (!Type->hasExceptionSpec()) {
7466 // C++2a [except.spec]p3:
7467 // If a declaration of a function does not have a noexcept-specifier
7468 // [and] is defaulted on its first declaration, [...] the exception
7469 // specification is as specified below
7470 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7471 EPI.ExceptionSpec.Type = EST_Unevaluated;
7472 EPI.ExceptionSpec.SourceDecl = MD;
7473 MD->setType(Context.getFunctionType(ReturnType,
7474 llvm::makeArrayRef(&ArgType,
7475 ExpectedParams),
7476 EPI));
7477 }
7478 }
7479
7480 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7481 if (First) {
7482 SetDeclDeleted(MD, MD->getLocation());
7483 if (!inTemplateInstantiation() && !HadError) {
7484 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7485 if (ShouldDeleteForTypeMismatch) {
7486 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7487 } else {
7488 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7489 }
7490 }
7491 if (ShouldDeleteForTypeMismatch && !HadError) {
7492 Diag(MD->getLocation(),
7493 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7494 }
7495 } else {
7496 // C++11 [dcl.fct.def.default]p4:
7497 // [For a] user-provided explicitly-defaulted function [...] if such a
7498 // function is implicitly defined as deleted, the program is ill-formed.
7499 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7500 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl")(static_cast <bool> (!ShouldDeleteForTypeMismatch &&
"deleted non-first decl") ? void (0) : __assert_fail ("!ShouldDeleteForTypeMismatch && \"deleted non-first decl\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7500, __extension__ __PRETTY_FUNCTION__))
;
7501 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7502 HadError = true;
7503 }
7504 }
7505
7506 return HadError;
7507}
7508
7509namespace {
7510/// Helper class for building and checking a defaulted comparison.
7511///
7512/// Defaulted functions are built in two phases:
7513///
7514/// * First, the set of operations that the function will perform are
7515/// identified, and some of them are checked. If any of the checked
7516/// operations is invalid in certain ways, the comparison function is
7517/// defined as deleted and no body is built.
7518/// * Then, if the function is not defined as deleted, the body is built.
7519///
7520/// This is accomplished by performing two visitation steps over the eventual
7521/// body of the function.
7522template<typename Derived, typename ResultList, typename Result,
7523 typename Subobject>
7524class DefaultedComparisonVisitor {
7525public:
7526 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7527
7528 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7529 DefaultedComparisonKind DCK)
7530 : S(S), RD(RD), FD(FD), DCK(DCK) {
7531 if (auto *Info = FD->getDefaultedFunctionInfo()) {
7532 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7533 // UnresolvedSet to avoid this copy.
7534 Fns.assign(Info->getUnqualifiedLookups().begin(),
7535 Info->getUnqualifiedLookups().end());
7536 }
7537 }
7538
7539 ResultList visit() {
7540 // The type of an lvalue naming a parameter of this function.
7541 QualType ParamLvalType =
7542 FD->getParamDecl(0)->getType().getNonReferenceType();
7543
7544 ResultList Results;
7545
7546 switch (DCK) {
7547 case DefaultedComparisonKind::None:
7548 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7548)
;
7549
7550 case DefaultedComparisonKind::Equal:
7551 case DefaultedComparisonKind::ThreeWay:
7552 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7553 return Results;
7554
7555 case DefaultedComparisonKind::NotEqual:
7556 case DefaultedComparisonKind::Relational:
7557 Results.add(getDerived().visitExpandedSubobject(
7558 ParamLvalType, getDerived().getCompleteObject()));
7559 return Results;
7560 }
7561 llvm_unreachable("")::llvm::llvm_unreachable_internal("", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7561)
;
7562 }
7563
7564protected:
7565 Derived &getDerived() { return static_cast<Derived&>(*this); }
7566
7567 /// Visit the expanded list of subobjects of the given type, as specified in
7568 /// C++2a [class.compare.default].
7569 ///
7570 /// \return \c true if the ResultList object said we're done, \c false if not.
7571 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7572 Qualifiers Quals) {
7573 // C++2a [class.compare.default]p4:
7574 // The direct base class subobjects of C
7575 for (CXXBaseSpecifier &Base : Record->bases())
7576 if (Results.add(getDerived().visitSubobject(
7577 S.Context.getQualifiedType(Base.getType(), Quals),
7578 getDerived().getBase(&Base))))
7579 return true;
7580
7581 // followed by the non-static data members of C
7582 for (FieldDecl *Field : Record->fields()) {
7583 // Recursively expand anonymous structs.
7584 if (Field->isAnonymousStructOrUnion()) {
7585 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7586 Quals))
7587 return true;
7588 continue;
7589 }
7590
7591 // Figure out the type of an lvalue denoting this field.
7592 Qualifiers FieldQuals = Quals;
7593 if (Field->isMutable())
7594 FieldQuals.removeConst();
7595 QualType FieldType =
7596 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7597
7598 if (Results.add(getDerived().visitSubobject(
7599 FieldType, getDerived().getField(Field))))
7600 return true;
7601 }
7602
7603 // form a list of subobjects.
7604 return false;
7605 }
7606
7607 Result visitSubobject(QualType Type, Subobject Subobj) {
7608 // In that list, any subobject of array type is recursively expanded
7609 const ArrayType *AT = S.Context.getAsArrayType(Type);
7610 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7611 return getDerived().visitSubobjectArray(CAT->getElementType(),
7612 CAT->getSize(), Subobj);
7613 return getDerived().visitExpandedSubobject(Type, Subobj);
7614 }
7615
7616 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7617 Subobject Subobj) {
7618 return getDerived().visitSubobject(Type, Subobj);
7619 }
7620
7621protected:
7622 Sema &S;
7623 CXXRecordDecl *RD;
7624 FunctionDecl *FD;
7625 DefaultedComparisonKind DCK;
7626 UnresolvedSet<16> Fns;
7627};
7628
7629/// Information about a defaulted comparison, as determined by
7630/// DefaultedComparisonAnalyzer.
7631struct DefaultedComparisonInfo {
7632 bool Deleted = false;
7633 bool Constexpr = true;
7634 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7635
7636 static DefaultedComparisonInfo deleted() {
7637 DefaultedComparisonInfo Deleted;
7638 Deleted.Deleted = true;
7639 return Deleted;
7640 }
7641
7642 bool add(const DefaultedComparisonInfo &R) {
7643 Deleted |= R.Deleted;
7644 Constexpr &= R.Constexpr;
7645 Category = commonComparisonType(Category, R.Category);
7646 return Deleted;
7647 }
7648};
7649
7650/// An element in the expanded list of subobjects of a defaulted comparison, as
7651/// specified in C++2a [class.compare.default]p4.
7652struct DefaultedComparisonSubobject {
7653 enum { CompleteObject, Member, Base } Kind;
7654 NamedDecl *Decl;
7655 SourceLocation Loc;
7656};
7657
7658/// A visitor over the notional body of a defaulted comparison that determines
7659/// whether that body would be deleted or constexpr.
7660class DefaultedComparisonAnalyzer
7661 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7662 DefaultedComparisonInfo,
7663 DefaultedComparisonInfo,
7664 DefaultedComparisonSubobject> {
7665public:
7666 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7667
7668private:
7669 DiagnosticKind Diagnose;
7670
7671public:
7672 using Base = DefaultedComparisonVisitor;
7673 using Result = DefaultedComparisonInfo;
7674 using Subobject = DefaultedComparisonSubobject;
7675
7676 friend Base;
7677
7678 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7679 DefaultedComparisonKind DCK,
7680 DiagnosticKind Diagnose = NoDiagnostics)
7681 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7682
7683 Result visit() {
7684 if ((DCK == DefaultedComparisonKind::Equal ||
7685 DCK == DefaultedComparisonKind::ThreeWay) &&
7686 RD->hasVariantMembers()) {
7687 // C++2a [class.compare.default]p2 [P2002R0]:
7688 // A defaulted comparison operator function for class C is defined as
7689 // deleted if [...] C has variant members.
7690 if (Diagnose == ExplainDeleted) {
7691 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7692 << FD << RD->isUnion() << RD;
7693 }
7694 return Result::deleted();
7695 }
7696
7697 return Base::visit();
7698 }
7699
7700private:
7701 Subobject getCompleteObject() {
7702 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7703 }
7704
7705 Subobject getBase(CXXBaseSpecifier *Base) {
7706 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7707 Base->getBaseTypeLoc()};
7708 }
7709
7710 Subobject getField(FieldDecl *Field) {
7711 return Subobject{Subobject::Member, Field, Field->getLocation()};
7712 }
7713
7714 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7715 // C++2a [class.compare.default]p2 [P2002R0]:
7716 // A defaulted <=> or == operator function for class C is defined as
7717 // deleted if any non-static data member of C is of reference type
7718 if (Type->isReferenceType()) {
7719 if (Diagnose == ExplainDeleted) {
7720 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7721 << FD << RD;
7722 }
7723 return Result::deleted();
7724 }
7725
7726 // [...] Let xi be an lvalue denoting the ith element [...]
7727 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7728 Expr *Args[] = {&Xi, &Xi};
7729
7730 // All operators start by trying to apply that same operator recursively.
7731 OverloadedOperatorKind OO = FD->getOverloadedOperator();
7732 assert(OO != OO_None && "not an overloaded operator!")(static_cast <bool> (OO != OO_None && "not an overloaded operator!"
) ? void (0) : __assert_fail ("OO != OO_None && \"not an overloaded operator!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7732, __extension__ __PRETTY_FUNCTION__))
;
7733 return visitBinaryOperator(OO, Args, Subobj);
7734 }
7735
7736 Result
7737 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7738 Subobject Subobj,
7739 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7740 // Note that there is no need to consider rewritten candidates here if
7741 // we've already found there is no viable 'operator<=>' candidate (and are
7742 // considering synthesizing a '<=>' from '==' and '<').
7743 OverloadCandidateSet CandidateSet(
7744 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7745 OverloadCandidateSet::OperatorRewriteInfo(
7746 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7747
7748 /// C++2a [class.compare.default]p1 [P2002R0]:
7749 /// [...] the defaulted function itself is never a candidate for overload
7750 /// resolution [...]
7751 CandidateSet.exclude(FD);
7752
7753 if (Args[0]->getType()->isOverloadableType())
7754 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7755 else
7756 // FIXME: We determine whether this is a valid expression by checking to
7757 // see if there's a viable builtin operator candidate for it. That isn't
7758 // really what the rules ask us to do, but should give the right results.
7759 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7760
7761 Result R;
7762
7763 OverloadCandidateSet::iterator Best;
7764 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7765 case OR_Success: {
7766 // C++2a [class.compare.secondary]p2 [P2002R0]:
7767 // The operator function [...] is defined as deleted if [...] the
7768 // candidate selected by overload resolution is not a rewritten
7769 // candidate.
7770 if ((DCK == DefaultedComparisonKind::NotEqual ||
7771 DCK == DefaultedComparisonKind::Relational) &&
7772 !Best->RewriteKind) {
7773 if (Diagnose == ExplainDeleted) {
7774 S.Diag(Best->Function->getLocation(),
7775 diag::note_defaulted_comparison_not_rewritten_callee)
7776 << FD;
7777 }
7778 return Result::deleted();
7779 }
7780
7781 // Throughout C++2a [class.compare]: if overload resolution does not
7782 // result in a usable function, the candidate function is defined as
7783 // deleted. This requires that we selected an accessible function.
7784 //
7785 // Note that this only considers the access of the function when named
7786 // within the type of the subobject, and not the access path for any
7787 // derived-to-base conversion.
7788 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7789 if (ArgClass && Best->FoundDecl.getDecl() &&
7790 Best->FoundDecl.getDecl()->isCXXClassMember()) {
7791 QualType ObjectType = Subobj.Kind == Subobject::Member
7792 ? Args[0]->getType()
7793 : S.Context.getRecordType(RD);
7794 if (!S.isMemberAccessibleForDeletion(
7795 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7796 Diagnose == ExplainDeleted
7797 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7798 << FD << Subobj.Kind << Subobj.Decl
7799 : S.PDiag()))
7800 return Result::deleted();
7801 }
7802
7803 bool NeedsDeducing =
7804 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7805
7806 if (FunctionDecl *BestFD = Best->Function) {
7807 // C++2a [class.compare.default]p3 [P2002R0]:
7808 // A defaulted comparison function is constexpr-compatible if
7809 // [...] no overlod resolution performed [...] results in a
7810 // non-constexpr function.
7811 assert(!BestFD->isDeleted() && "wrong overload resolution result")(static_cast <bool> (!BestFD->isDeleted() &&
"wrong overload resolution result") ? void (0) : __assert_fail
("!BestFD->isDeleted() && \"wrong overload resolution result\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7811, __extension__ __PRETTY_FUNCTION__))
;
7812 // If it's not constexpr, explain why not.
7813 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7814 if (Subobj.Kind != Subobject::CompleteObject)
7815 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7816 << Subobj.Kind << Subobj.Decl;
7817 S.Diag(BestFD->getLocation(),
7818 diag::note_defaulted_comparison_not_constexpr_here);
7819 // Bail out after explaining; we don't want any more notes.
7820 return Result::deleted();
7821 }
7822 R.Constexpr &= BestFD->isConstexpr();
7823
7824 if (NeedsDeducing) {
7825 // If any callee has an undeduced return type, deduce it now.
7826 // FIXME: It's not clear how a failure here should be handled. For
7827 // now, we produce an eager diagnostic, because that is forward
7828 // compatible with most (all?) other reasonable options.
7829 if (BestFD->getReturnType()->isUndeducedType() &&
7830 S.DeduceReturnType(BestFD, FD->getLocation(),
7831 /*Diagnose=*/false)) {
7832 // Don't produce a duplicate error when asked to explain why the
7833 // comparison is deleted: we diagnosed that when initially checking
7834 // the defaulted operator.
7835 if (Diagnose == NoDiagnostics) {
7836 S.Diag(
7837 FD->getLocation(),
7838 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7839 << Subobj.Kind << Subobj.Decl;
7840 S.Diag(
7841 Subobj.Loc,
7842 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7843 << Subobj.Kind << Subobj.Decl;
7844 S.Diag(BestFD->getLocation(),
7845 diag::note_defaulted_comparison_cannot_deduce_callee)
7846 << Subobj.Kind << Subobj.Decl;
7847 }
7848 return Result::deleted();
7849 }
7850 auto *Info = S.Context.CompCategories.lookupInfoForType(
7851 BestFD->getCallResultType());
7852 if (!Info) {
7853 if (Diagnose == ExplainDeleted) {
7854 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7855 << Subobj.Kind << Subobj.Decl
7856 << BestFD->getCallResultType().withoutLocalFastQualifiers();
7857 S.Diag(BestFD->getLocation(),
7858 diag::note_defaulted_comparison_cannot_deduce_callee)
7859 << Subobj.Kind << Subobj.Decl;
7860 }
7861 return Result::deleted();
7862 }
7863 R.Category = Info->Kind;
7864 }
7865 } else {
7866 QualType T = Best->BuiltinParamTypes[0];
7867 assert(T == Best->BuiltinParamTypes[1] &&(static_cast <bool> (T == Best->BuiltinParamTypes[1]
&& "builtin comparison for different types?") ? void
(0) : __assert_fail ("T == Best->BuiltinParamTypes[1] && \"builtin comparison for different types?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7868, __extension__ __PRETTY_FUNCTION__))
7868 "builtin comparison for different types?")(static_cast <bool> (T == Best->BuiltinParamTypes[1]
&& "builtin comparison for different types?") ? void
(0) : __assert_fail ("T == Best->BuiltinParamTypes[1] && \"builtin comparison for different types?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7868, __extension__ __PRETTY_FUNCTION__))
;
7869 assert(Best->BuiltinParamTypes[2].isNull() &&(static_cast <bool> (Best->BuiltinParamTypes[2].isNull
() && "invalid builtin comparison") ? void (0) : __assert_fail
("Best->BuiltinParamTypes[2].isNull() && \"invalid builtin comparison\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7870, __extension__ __PRETTY_FUNCTION__))
7870 "invalid builtin comparison")(static_cast <bool> (Best->BuiltinParamTypes[2].isNull
() && "invalid builtin comparison") ? void (0) : __assert_fail
("Best->BuiltinParamTypes[2].isNull() && \"invalid builtin comparison\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7870, __extension__ __PRETTY_FUNCTION__))
;
7871
7872 if (NeedsDeducing) {
7873 Optional<ComparisonCategoryType> Cat =
7874 getComparisonCategoryForBuiltinCmp(T);
7875 assert(Cat && "no category for builtin comparison?")(static_cast <bool> (Cat && "no category for builtin comparison?"
) ? void (0) : __assert_fail ("Cat && \"no category for builtin comparison?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 7875, __extension__ __PRETTY_FUNCTION__))
;
7876 R.Category = *Cat;
7877 }
7878 }
7879
7880 // Note that we might be rewriting to a different operator. That call is
7881 // not considered until we come to actually build the comparison function.
7882 break;
7883 }
7884
7885 case OR_Ambiguous:
7886 if (Diagnose == ExplainDeleted) {
7887 unsigned Kind = 0;
7888 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7889 Kind = OO == OO_EqualEqual ? 1 : 2;
7890 CandidateSet.NoteCandidates(
7891 PartialDiagnosticAt(
7892 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7893 << FD << Kind << Subobj.Kind << Subobj.Decl),
7894 S, OCD_AmbiguousCandidates, Args);
7895 }
7896 R = Result::deleted();
7897 break;
7898
7899 case OR_Deleted:
7900 if (Diagnose == ExplainDeleted) {
7901 if ((DCK == DefaultedComparisonKind::NotEqual ||
7902 DCK == DefaultedComparisonKind::Relational) &&
7903 !Best->RewriteKind) {
7904 S.Diag(Best->Function->getLocation(),
7905 diag::note_defaulted_comparison_not_rewritten_callee)
7906 << FD;
7907 } else {
7908 S.Diag(Subobj.Loc,
7909 diag::note_defaulted_comparison_calls_deleted)
7910 << FD << Subobj.Kind << Subobj.Decl;
7911 S.NoteDeletedFunction(Best->Function);
7912 }
7913 }
7914 R = Result::deleted();
7915 break;
7916
7917 case OR_No_Viable_Function:
7918 // If there's no usable candidate, we're done unless we can rewrite a
7919 // '<=>' in terms of '==' and '<'.
7920 if (OO == OO_Spaceship &&
7921 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7922 // For any kind of comparison category return type, we need a usable
7923 // '==' and a usable '<'.
7924 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7925 &CandidateSet)))
7926 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7927 break;
7928 }
7929
7930 if (Diagnose == ExplainDeleted) {
7931 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7932 << FD << Subobj.Kind << Subobj.Decl;
7933
7934 // For a three-way comparison, list both the candidates for the
7935 // original operator and the candidates for the synthesized operator.
7936 if (SpaceshipCandidates) {
7937 SpaceshipCandidates->NoteCandidates(
7938 S, Args,
7939 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7940 Args, FD->getLocation()));
7941 S.Diag(Subobj.Loc,
7942 diag::note_defaulted_comparison_no_viable_function_synthesized)
7943 << (OO == OO_EqualEqual ? 0 : 1);
7944 }
7945
7946 CandidateSet.NoteCandidates(
7947 S, Args,
7948 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7949 FD->getLocation()));
7950 }
7951 R = Result::deleted();
7952 break;
7953 }
7954
7955 return R;
7956 }
7957};
7958
7959/// A list of statements.
7960struct StmtListResult {
7961 bool IsInvalid = false;
7962 llvm::SmallVector<Stmt*, 16> Stmts;
7963
7964 bool add(const StmtResult &S) {
7965 IsInvalid |= S.isInvalid();
7966 if (IsInvalid)
7967 return true;
7968 Stmts.push_back(S.get());
7969 return false;
7970 }
7971};
7972
7973/// A visitor over the notional body of a defaulted comparison that synthesizes
7974/// the actual body.
7975class DefaultedComparisonSynthesizer
7976 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7977 StmtListResult, StmtResult,
7978 std::pair<ExprResult, ExprResult>> {
7979 SourceLocation Loc;
7980 unsigned ArrayDepth = 0;
7981
7982public:
7983 using Base = DefaultedComparisonVisitor;
7984 using ExprPair = std::pair<ExprResult, ExprResult>;
7985
7986 friend Base;
7987
7988 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7989 DefaultedComparisonKind DCK,
7990 SourceLocation BodyLoc)
7991 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7992
7993 /// Build a suitable function body for this defaulted comparison operator.
7994 StmtResult build() {
7995 Sema::CompoundScopeRAII CompoundScope(S);
7996
7997 StmtListResult Stmts = visit();
7998 if (Stmts.IsInvalid)
7999 return StmtError();
8000
8001 ExprResult RetVal;
8002 switch (DCK) {
8003 case DefaultedComparisonKind::None:
8004 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8004)
;
8005
8006 case DefaultedComparisonKind::Equal: {
8007 // C++2a [class.eq]p3:
8008 // [...] compar[e] the corresponding elements [...] until the first
8009 // index i where xi == yi yields [...] false. If no such index exists,
8010 // V is true. Otherwise, V is false.
8011 //
8012 // Join the comparisons with '&&'s and return the result. Use a right
8013 // fold (traversing the conditions right-to-left), because that
8014 // short-circuits more naturally.
8015 auto OldStmts = std::move(Stmts.Stmts);
8016 Stmts.Stmts.clear();
8017 ExprResult CmpSoFar;
8018 // Finish a particular comparison chain.
8019 auto FinishCmp = [&] {
8020 if (Expr *Prior = CmpSoFar.get()) {
8021 // Convert the last expression to 'return ...;'
8022 if (RetVal.isUnset() && Stmts.Stmts.empty())
8023 RetVal = CmpSoFar;
8024 // Convert any prior comparison to 'if (!(...)) return false;'
8025 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8026 return true;
8027 CmpSoFar = ExprResult();
8028 }
8029 return false;
8030 };
8031 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8032 Expr *E = dyn_cast<Expr>(EAsStmt);
8033 if (!E) {
8034 // Found an array comparison.
8035 if (FinishCmp() || Stmts.add(EAsStmt))
8036 return StmtError();
8037 continue;
8038 }
8039
8040 if (CmpSoFar.isUnset()) {
8041 CmpSoFar = E;
8042 continue;
8043 }
8044 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8045 if (CmpSoFar.isInvalid())
8046 return StmtError();
8047 }
8048 if (FinishCmp())
8049 return StmtError();
8050 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8051 // If no such index exists, V is true.
8052 if (RetVal.isUnset())
8053 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8054 break;
8055 }
8056
8057 case DefaultedComparisonKind::ThreeWay: {
8058 // Per C++2a [class.spaceship]p3, as a fallback add:
8059 // return static_cast<R>(std::strong_ordering::equal);
8060 QualType StrongOrdering = S.CheckComparisonCategoryType(
8061 ComparisonCategoryType::StrongOrdering, Loc,
8062 Sema::ComparisonCategoryUsage::DefaultedOperator);
8063 if (StrongOrdering.isNull())
8064 return StmtError();
8065 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8066 .getValueInfo(ComparisonCategoryResult::Equal)
8067 ->VD;
8068 RetVal = getDecl(EqualVD);
8069 if (RetVal.isInvalid())
8070 return StmtError();
8071 RetVal = buildStaticCastToR(RetVal.get());
8072 break;
8073 }
8074
8075 case DefaultedComparisonKind::NotEqual:
8076 case DefaultedComparisonKind::Relational:
8077 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8078 break;
8079 }
8080
8081 // Build the final return statement.
8082 if (RetVal.isInvalid())
8083 return StmtError();
8084 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8085 if (ReturnStmt.isInvalid())
8086 return StmtError();
8087 Stmts.Stmts.push_back(ReturnStmt.get());
8088
8089 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8090 }
8091
8092private:
8093 ExprResult getDecl(ValueDecl *VD) {
8094 return S.BuildDeclarationNameExpr(
8095 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8096 }
8097
8098 ExprResult getParam(unsigned I) {
8099 ParmVarDecl *PD = FD->getParamDecl(I);
8100 return getDecl(PD);
8101 }
8102
8103 ExprPair getCompleteObject() {
8104 unsigned Param = 0;
8105 ExprResult LHS;
8106 if (isa<CXXMethodDecl>(FD)) {
8107 // LHS is '*this'.
8108 LHS = S.ActOnCXXThis(Loc);
8109 if (!LHS.isInvalid())
8110 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8111 } else {
8112 LHS = getParam(Param++);
8113 }
8114 ExprResult RHS = getParam(Param++);
8115 assert(Param == FD->getNumParams())(static_cast <bool> (Param == FD->getNumParams()) ? void
(0) : __assert_fail ("Param == FD->getNumParams()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8115, __extension__ __PRETTY_FUNCTION__))
;
8116 return {LHS, RHS};
8117 }
8118
8119 ExprPair getBase(CXXBaseSpecifier *Base) {
8120 ExprPair Obj = getCompleteObject();
8121 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8122 return {ExprError(), ExprError()};
8123 CXXCastPath Path = {Base};
8124 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8125 CK_DerivedToBase, VK_LValue, &Path),
8126 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8127 CK_DerivedToBase, VK_LValue, &Path)};
8128 }
8129
8130 ExprPair getField(FieldDecl *Field) {
8131 ExprPair Obj = getCompleteObject();
8132 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8133 return {ExprError(), ExprError()};
8134
8135 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8136 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8137 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8138 CXXScopeSpec(), Field, Found, NameInfo),
8139 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8140 CXXScopeSpec(), Field, Found, NameInfo)};
8141 }
8142
8143 // FIXME: When expanding a subobject, register a note in the code synthesis
8144 // stack to say which subobject we're comparing.
8145
8146 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8147 if (Cond.isInvalid())
8148 return StmtError();
8149
8150 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8151 if (NotCond.isInvalid())
8152 return StmtError();
8153
8154 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8155 assert(!False.isInvalid() && "should never fail")(static_cast <bool> (!False.isInvalid() && "should never fail"
) ? void (0) : __assert_fail ("!False.isInvalid() && \"should never fail\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8155, __extension__ __PRETTY_FUNCTION__))
;
8156 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8157 if (ReturnFalse.isInvalid())
8158 return StmtError();
8159
8160 return S.ActOnIfStmt(Loc, false, Loc, nullptr,
8161 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8162 Sema::ConditionKind::Boolean),
8163 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8164 }
8165
8166 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8167 ExprPair Subobj) {
8168 QualType SizeType = S.Context.getSizeType();
8169 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8170
8171 // Build 'size_t i$n = 0'.
8172 IdentifierInfo *IterationVarName = nullptr;
8173 {
8174 SmallString<8> Str;
8175 llvm::raw_svector_ostream OS(Str);
8176 OS << "i" << ArrayDepth;
8177 IterationVarName = &S.Context.Idents.get(OS.str());
8178 }
8179 VarDecl *IterationVar = VarDecl::Create(
8180 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8181 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8182 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8183 IterationVar->setInit(
8184 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8185 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8186
8187 auto IterRef = [&] {
8188 ExprResult Ref = S.BuildDeclarationNameExpr(
8189 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8190 IterationVar);
8191 assert(!Ref.isInvalid() && "can't reference our own variable?")(static_cast <bool> (!Ref.isInvalid() && "can't reference our own variable?"
) ? void (0) : __assert_fail ("!Ref.isInvalid() && \"can't reference our own variable?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8191, __extension__ __PRETTY_FUNCTION__))
;
8192 return Ref.get();
8193 };
8194
8195 // Build 'i$n != Size'.
8196 ExprResult Cond = S.CreateBuiltinBinOp(
8197 Loc, BO_NE, IterRef(),
8198 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8199 assert(!Cond.isInvalid() && "should never fail")(static_cast <bool> (!Cond.isInvalid() && "should never fail"
) ? void (0) : __assert_fail ("!Cond.isInvalid() && \"should never fail\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8199, __extension__ __PRETTY_FUNCTION__))
;
8200
8201 // Build '++i$n'.
8202 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8203 assert(!Inc.isInvalid() && "should never fail")(static_cast <bool> (!Inc.isInvalid() && "should never fail"
) ? void (0) : __assert_fail ("!Inc.isInvalid() && \"should never fail\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8203, __extension__ __PRETTY_FUNCTION__))
;
8204
8205 // Build 'a[i$n]' and 'b[i$n]'.
8206 auto Index = [&](ExprResult E) {
8207 if (E.isInvalid())
8208 return ExprError();
8209 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8210 };
8211 Subobj.first = Index(Subobj.first);
8212 Subobj.second = Index(Subobj.second);
8213
8214 // Compare the array elements.
8215 ++ArrayDepth;
8216 StmtResult Substmt = visitSubobject(Type, Subobj);
8217 --ArrayDepth;
8218
8219 if (Substmt.isInvalid())
8220 return StmtError();
8221
8222 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8223 // For outer levels or for an 'operator<=>' we already have a suitable
8224 // statement that returns as necessary.
8225 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8226 assert(DCK == DefaultedComparisonKind::Equal &&(static_cast <bool> (DCK == DefaultedComparisonKind::Equal
&& "should have non-expression statement") ? void (0
) : __assert_fail ("DCK == DefaultedComparisonKind::Equal && \"should have non-expression statement\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8227, __extension__ __PRETTY_FUNCTION__))
8227 "should have non-expression statement")(static_cast <bool> (DCK == DefaultedComparisonKind::Equal
&& "should have non-expression statement") ? void (0
) : __assert_fail ("DCK == DefaultedComparisonKind::Equal && \"should have non-expression statement\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8227, __extension__ __PRETTY_FUNCTION__))
;
8228 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8229 if (Substmt.isInvalid())
8230 return StmtError();
8231 }
8232
8233 // Build 'for (...) ...'
8234 return S.ActOnForStmt(Loc, Loc, Init,
8235 S.ActOnCondition(nullptr, Loc, Cond.get(),
8236 Sema::ConditionKind::Boolean),
8237 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8238 Substmt.get());
8239 }
8240
8241 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8242 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8243 return StmtError();
8244
8245 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8246 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8247 ExprResult Op;
8248 if (Type->isOverloadableType())
8249 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8250 Obj.second.get(), /*PerformADL=*/true,
8251 /*AllowRewrittenCandidates=*/true, FD);
8252 else
8253 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8254 if (Op.isInvalid())
8255 return StmtError();
8256
8257 switch (DCK) {
8258 case DefaultedComparisonKind::None:
8259 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8259)
;
8260
8261 case DefaultedComparisonKind::Equal:
8262 // Per C++2a [class.eq]p2, each comparison is individually contextually
8263 // converted to bool.
8264 Op = S.PerformContextuallyConvertToBool(Op.get());
8265 if (Op.isInvalid())
8266 return StmtError();
8267 return Op.get();
8268
8269 case DefaultedComparisonKind::ThreeWay: {
8270 // Per C++2a [class.spaceship]p3, form:
8271 // if (R cmp = static_cast<R>(op); cmp != 0)
8272 // return cmp;
8273 QualType R = FD->getReturnType();
8274 Op = buildStaticCastToR(Op.get());
8275 if (Op.isInvalid())
8276 return StmtError();
8277
8278 // R cmp = ...;
8279 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8280 VarDecl *VD =
8281 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8282 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8283 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8284 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8285
8286 // cmp != 0
8287 ExprResult VDRef = getDecl(VD);
8288 if (VDRef.isInvalid())
8289 return StmtError();
8290 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8291 Expr *Zero =
8292 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8293 ExprResult Comp;
8294 if (VDRef.get()->getType()->isOverloadableType())
8295 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8296 true, FD);
8297 else
8298 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8299 if (Comp.isInvalid())
8300 return StmtError();
8301 Sema::ConditionResult Cond = S.ActOnCondition(
8302 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8303 if (Cond.isInvalid())
8304 return StmtError();
8305
8306 // return cmp;
8307 VDRef = getDecl(VD);
8308 if (VDRef.isInvalid())
8309 return StmtError();
8310 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8311 if (ReturnStmt.isInvalid())
8312 return StmtError();
8313
8314 // if (...)
8315 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc,
8316 ReturnStmt.get(),
8317 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8318 }
8319
8320 case DefaultedComparisonKind::NotEqual:
8321 case DefaultedComparisonKind::Relational:
8322 // C++2a [class.compare.secondary]p2:
8323 // Otherwise, the operator function yields x @ y.
8324 return Op.get();
8325 }
8326 llvm_unreachable("")::llvm::llvm_unreachable_internal("", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8326)
;
8327 }
8328
8329 /// Build "static_cast<R>(E)".
8330 ExprResult buildStaticCastToR(Expr *E) {
8331 QualType R = FD->getReturnType();
8332 assert(!R->isUndeducedType() && "type should have been deduced already")(static_cast <bool> (!R->isUndeducedType() &&
"type should have been deduced already") ? void (0) : __assert_fail
("!R->isUndeducedType() && \"type should have been deduced already\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8332, __extension__ __PRETTY_FUNCTION__))
;
8333
8334 // Don't bother forming a no-op cast in the common case.
8335 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8336 return E;
8337 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8338 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8339 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8340 }
8341};
8342}
8343
8344/// Perform the unqualified lookups that might be needed to form a defaulted
8345/// comparison function for the given operator.
8346static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8347 UnresolvedSetImpl &Operators,
8348 OverloadedOperatorKind Op) {
8349 auto Lookup = [&](OverloadedOperatorKind OO) {
8350 Self.LookupOverloadedOperatorName(OO, S, Operators);
8351 };
8352
8353 // Every defaulted operator looks up itself.
8354 Lookup(Op);
8355 // ... and the rewritten form of itself, if any.
8356 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8357 Lookup(ExtraOp);
8358
8359 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8360 // synthesize a three-way comparison from '<' and '=='. In a dependent
8361 // context, we also need to look up '==' in case we implicitly declare a
8362 // defaulted 'operator=='.
8363 if (Op == OO_Spaceship) {
8364 Lookup(OO_ExclaimEqual);
8365 Lookup(OO_Less);
8366 Lookup(OO_EqualEqual);
8367 }
8368}
8369
8370bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8371 DefaultedComparisonKind DCK) {
8372 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison")(static_cast <bool> (DCK != DefaultedComparisonKind::None
&& "not a defaulted comparison") ? void (0) : __assert_fail
("DCK != DefaultedComparisonKind::None && \"not a defaulted comparison\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8372, __extension__ __PRETTY_FUNCTION__))
;
8373
8374 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8375 assert(RD && "defaulted comparison is not defaulted in a class")(static_cast <bool> (RD && "defaulted comparison is not defaulted in a class"
) ? void (0) : __assert_fail ("RD && \"defaulted comparison is not defaulted in a class\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8375, __extension__ __PRETTY_FUNCTION__))
;
8376
8377 // Perform any unqualified lookups we're going to need to default this
8378 // function.
8379 if (S) {
8380 UnresolvedSet<32> Operators;
8381 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8382 FD->getOverloadedOperator());
8383 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8384 Context, Operators.pairs()));
8385 }
8386
8387 // C++2a [class.compare.default]p1:
8388 // A defaulted comparison operator function for some class C shall be a
8389 // non-template function declared in the member-specification of C that is
8390 // -- a non-static const member of C having one parameter of type
8391 // const C&, or
8392 // -- a friend of C having two parameters of type const C& or two
8393 // parameters of type C.
8394 QualType ExpectedParmType1 = Context.getRecordType(RD);
8395 QualType ExpectedParmType2 =
8396 Context.getLValueReferenceType(ExpectedParmType1.withConst());
8397 if (isa<CXXMethodDecl>(FD))
8398 ExpectedParmType1 = ExpectedParmType2;
8399 for (const ParmVarDecl *Param : FD->parameters()) {
8400 if (!Param->getType()->isDependentType() &&
8401 !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8402 !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8403 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8404 // corresponding defaulted 'operator<=>' already.
8405 if (!FD->isImplicit()) {
8406 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8407 << (int)DCK << Param->getType() << ExpectedParmType1
8408 << !isa<CXXMethodDecl>(FD)
8409 << ExpectedParmType2 << Param->getSourceRange();
8410 }
8411 return true;
8412 }
8413 }
8414 if (FD->getNumParams() == 2 &&
8415 !Context.hasSameType(FD->getParamDecl(0)->getType(),
8416 FD->getParamDecl(1)->getType())) {
8417 if (!FD->isImplicit()) {
8418 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8419 << (int)DCK
8420 << FD->getParamDecl(0)->getType()
8421 << FD->getParamDecl(0)->getSourceRange()
8422 << FD->getParamDecl(1)->getType()
8423 << FD->getParamDecl(1)->getSourceRange();
8424 }
8425 return true;
8426 }
8427
8428 // ... non-static const member ...
8429 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8430 assert(!MD->isStatic() && "comparison function cannot be a static member")(static_cast <bool> (!MD->isStatic() && "comparison function cannot be a static member"
) ? void (0) : __assert_fail ("!MD->isStatic() && \"comparison function cannot be a static member\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8430, __extension__ __PRETTY_FUNCTION__))
;
8431 if (!MD->isConst()) {
8432 SourceLocation InsertLoc;
8433 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8434 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8435 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8436 // corresponding defaulted 'operator<=>' already.
8437 if (!MD->isImplicit()) {
8438 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8439 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8440 }
8441
8442 // Add the 'const' to the type to recover.
8443 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8444 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8445 EPI.TypeQuals.addConst();
8446 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8447 FPT->getParamTypes(), EPI));
8448 }
8449 } else {
8450 // A non-member function declared in a class must be a friend.
8451 assert(FD->getFriendObjectKind() && "expected a friend declaration")(static_cast <bool> (FD->getFriendObjectKind() &&
"expected a friend declaration") ? void (0) : __assert_fail (
"FD->getFriendObjectKind() && \"expected a friend declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8451, __extension__ __PRETTY_FUNCTION__))
;
8452 }
8453
8454 // C++2a [class.eq]p1, [class.rel]p1:
8455 // A [defaulted comparison other than <=>] shall have a declared return
8456 // type bool.
8457 if (DCK != DefaultedComparisonKind::ThreeWay &&
8458 !FD->getDeclaredReturnType()->isDependentType() &&
8459 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8460 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8461 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8462 << FD->getReturnTypeSourceRange();
8463 return true;
8464 }
8465 // C++2a [class.spaceship]p2 [P2002R0]:
8466 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8467 // R shall not contain a placeholder type.
8468 if (DCK == DefaultedComparisonKind::ThreeWay &&
8469 FD->getDeclaredReturnType()->getContainedDeducedType() &&
8470 !Context.hasSameType(FD->getDeclaredReturnType(),
8471 Context.getAutoDeductType())) {
8472 Diag(FD->getLocation(),
8473 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8474 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8475 << FD->getReturnTypeSourceRange();
8476 return true;
8477 }
8478
8479 // For a defaulted function in a dependent class, defer all remaining checks
8480 // until instantiation.
8481 if (RD->isDependentType())
8482 return false;
8483
8484 // Determine whether the function should be defined as deleted.
8485 DefaultedComparisonInfo Info =
8486 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8487
8488 bool First = FD == FD->getCanonicalDecl();
8489
8490 // If we want to delete the function, then do so; there's nothing else to
8491 // check in that case.
8492 if (Info.Deleted) {
8493 if (!First) {
8494 // C++11 [dcl.fct.def.default]p4:
8495 // [For a] user-provided explicitly-defaulted function [...] if such a
8496 // function is implicitly defined as deleted, the program is ill-formed.
8497 //
8498 // This is really just a consequence of the general rule that you can
8499 // only delete a function on its first declaration.
8500 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8501 << FD->isImplicit() << (int)DCK;
8502 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8503 DefaultedComparisonAnalyzer::ExplainDeleted)
8504 .visit();
8505 return true;
8506 }
8507
8508 SetDeclDeleted(FD, FD->getLocation());
8509 if (!inTemplateInstantiation() && !FD->isImplicit()) {
8510 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8511 << (int)DCK;
8512 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8513 DefaultedComparisonAnalyzer::ExplainDeleted)
8514 .visit();
8515 }
8516 return false;
8517 }
8518
8519 // C++2a [class.spaceship]p2:
8520 // The return type is deduced as the common comparison type of R0, R1, ...
8521 if (DCK == DefaultedComparisonKind::ThreeWay &&
8522 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8523 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8524 if (RetLoc.isInvalid())
8525 RetLoc = FD->getBeginLoc();
8526 // FIXME: Should we really care whether we have the complete type and the
8527 // 'enumerator' constants here? A forward declaration seems sufficient.
8528 QualType Cat = CheckComparisonCategoryType(
8529 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8530 if (Cat.isNull())
8531 return true;
8532 Context.adjustDeducedFunctionResultType(
8533 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8534 }
8535
8536 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8537 // An explicitly-defaulted function that is not defined as deleted may be
8538 // declared constexpr or consteval only if it is constexpr-compatible.
8539 // C++2a [class.compare.default]p3 [P2002R0]:
8540 // A defaulted comparison function is constexpr-compatible if it satisfies
8541 // the requirements for a constexpr function [...]
8542 // The only relevant requirements are that the parameter and return types are
8543 // literal types. The remaining conditions are checked by the analyzer.
8544 if (FD->isConstexpr()) {
8545 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8546 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8547 !Info.Constexpr) {
8548 Diag(FD->getBeginLoc(),
8549 diag::err_incorrect_defaulted_comparison_constexpr)
8550 << FD->isImplicit() << (int)DCK << FD->isConsteval();
8551 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8552 DefaultedComparisonAnalyzer::ExplainConstexpr)
8553 .visit();
8554 }
8555 }
8556
8557 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8558 // If a constexpr-compatible function is explicitly defaulted on its first
8559 // declaration, it is implicitly considered to be constexpr.
8560 // FIXME: Only applying this to the first declaration seems problematic, as
8561 // simple reorderings can affect the meaning of the program.
8562 if (First && !FD->isConstexpr() && Info.Constexpr)
8563 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8564
8565 // C++2a [except.spec]p3:
8566 // If a declaration of a function does not have a noexcept-specifier
8567 // [and] is defaulted on its first declaration, [...] the exception
8568 // specification is as specified below
8569 if (FD->getExceptionSpecType() == EST_None) {
8570 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8571 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8572 EPI.ExceptionSpec.Type = EST_Unevaluated;
8573 EPI.ExceptionSpec.SourceDecl = FD;
8574 FD->setType(Context.getFunctionType(FPT->getReturnType(),
8575 FPT->getParamTypes(), EPI));
8576 }
8577
8578 return false;
8579}
8580
8581void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8582 FunctionDecl *Spaceship) {
8583 Sema::CodeSynthesisContext Ctx;
8584 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8585 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8586 Ctx.Entity = Spaceship;
8587 pushCodeSynthesisContext(Ctx);
8588
8589 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8590 EqualEqual->setImplicit();
8591
8592 popCodeSynthesisContext();
8593}
8594
8595void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8596 DefaultedComparisonKind DCK) {
8597 assert(FD->isDefaulted() && !FD->isDeleted() &&(static_cast <bool> (FD->isDefaulted() && !FD
->isDeleted() && !FD->doesThisDeclarationHaveABody
()) ? void (0) : __assert_fail ("FD->isDefaulted() && !FD->isDeleted() && !FD->doesThisDeclarationHaveABody()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8598, __extension__ __PRETTY_FUNCTION__))
8598 !FD->doesThisDeclarationHaveABody())(static_cast <bool> (FD->isDefaulted() && !FD
->isDeleted() && !FD->doesThisDeclarationHaveABody
()) ? void (0) : __assert_fail ("FD->isDefaulted() && !FD->isDeleted() && !FD->doesThisDeclarationHaveABody()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8598, __extension__ __PRETTY_FUNCTION__))
;
8599 if (FD->willHaveBody() || FD->isInvalidDecl())
8600 return;
8601
8602 SynthesizedFunctionScope Scope(*this, FD);
8603
8604 // Add a context note for diagnostics produced after this point.
8605 Scope.addContextNote(UseLoc);
8606
8607 {
8608 // Build and set up the function body.
8609 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8610 SourceLocation BodyLoc =
8611 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8612 StmtResult Body =
8613 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8614 if (Body.isInvalid()) {
8615 FD->setInvalidDecl();
8616 return;
8617 }
8618 FD->setBody(Body.get());
8619 FD->markUsed(Context);
8620 }
8621
8622 // The exception specification is needed because we are defining the
8623 // function. Note that this will reuse the body we just built.
8624 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8625
8626 if (ASTMutationListener *L = getASTMutationListener())
8627 L->CompletedImplicitDefinition(FD);
8628}
8629
8630static Sema::ImplicitExceptionSpecification
8631ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8632 FunctionDecl *FD,
8633 Sema::DefaultedComparisonKind DCK) {
8634 ComputingExceptionSpec CES(S, FD, Loc);
8635 Sema::ImplicitExceptionSpecification ExceptSpec(S);
8636
8637 if (FD->isInvalidDecl())
8638 return ExceptSpec;
8639
8640 // The common case is that we just defined the comparison function. In that
8641 // case, just look at whether the body can throw.
8642 if (FD->hasBody()) {
8643 ExceptSpec.CalledStmt(FD->getBody());
8644 } else {
8645 // Otherwise, build a body so we can check it. This should ideally only
8646 // happen when we're not actually marking the function referenced. (This is
8647 // only really important for efficiency: we don't want to build and throw
8648 // away bodies for comparison functions more than we strictly need to.)
8649
8650 // Pretend to synthesize the function body in an unevaluated context.
8651 // Note that we can't actually just go ahead and define the function here:
8652 // we are not permitted to mark its callees as referenced.
8653 Sema::SynthesizedFunctionScope Scope(S, FD);
8654 EnterExpressionEvaluationContext Context(
8655 S, Sema::ExpressionEvaluationContext::Unevaluated);
8656
8657 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8658 SourceLocation BodyLoc =
8659 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8660 StmtResult Body =
8661 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8662 if (!Body.isInvalid())
8663 ExceptSpec.CalledStmt(Body.get());
8664
8665 // FIXME: Can we hold onto this body and just transform it to potentially
8666 // evaluated when we're asked to define the function rather than rebuilding
8667 // it? Either that, or we should only build the bits of the body that we
8668 // need (the expressions, not the statements).
8669 }
8670
8671 return ExceptSpec;
8672}
8673
8674void Sema::CheckDelayedMemberExceptionSpecs() {
8675 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8676 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8677
8678 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8679 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8680
8681 // Perform any deferred checking of exception specifications for virtual
8682 // destructors.
8683 for (auto &Check : Overriding)
8684 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8685
8686 // Perform any deferred checking of exception specifications for befriended
8687 // special members.
8688 for (auto &Check : Equivalent)
8689 CheckEquivalentExceptionSpec(Check.second, Check.first);
8690}
8691
8692namespace {
8693/// CRTP base class for visiting operations performed by a special member
8694/// function (or inherited constructor).
8695template<typename Derived>
8696struct SpecialMemberVisitor {
8697 Sema &S;
8698 CXXMethodDecl *MD;
8699 Sema::CXXSpecialMember CSM;
8700 Sema::InheritedConstructorInfo *ICI;
8701
8702 // Properties of the special member, computed for convenience.
8703 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8704
8705 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8706 Sema::InheritedConstructorInfo *ICI)
8707 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8708 switch (CSM) {
8709 case Sema::CXXDefaultConstructor:
8710 case Sema::CXXCopyConstructor:
8711 case Sema::CXXMoveConstructor:
8712 IsConstructor = true;
8713 break;
8714 case Sema::CXXCopyAssignment:
8715 case Sema::CXXMoveAssignment:
8716 IsAssignment = true;
8717 break;
8718 case Sema::CXXDestructor:
8719 break;
8720 case Sema::CXXInvalid:
8721 llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8721)
;
8722 }
8723
8724 if (MD->getNumParams()) {
8725 if (const ReferenceType *RT =
8726 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8727 ConstArg = RT->getPointeeType().isConstQualified();
8728 }
8729 }
8730
8731 Derived &getDerived() { return static_cast<Derived&>(*this); }
8732
8733 /// Is this a "move" special member?
8734 bool isMove() const {
8735 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8736 }
8737
8738 /// Look up the corresponding special member in the given class.
8739 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8740 unsigned Quals, bool IsMutable) {
8741 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8742 ConstArg && !IsMutable);
8743 }
8744
8745 /// Look up the constructor for the specified base class to see if it's
8746 /// overridden due to this being an inherited constructor.
8747 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8748 if (!ICI)
8749 return {};
8750 assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor
) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 8750, __extension__ __PRETTY_FUNCTION__))
;
8751 auto *BaseCtor =
8752 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8753 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8754 return MD;
8755 return {};
8756 }
8757
8758 /// A base or member subobject.
8759 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8760
8761 /// Get the location to use for a subobject in diagnostics.
8762 static SourceLocation getSubobjectLoc(Subobject Subobj) {
8763 // FIXME: For an indirect virtual base, the direct base leading to
8764 // the indirect virtual base would be a more useful choice.
8765 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8766 return B->getBaseTypeLoc();
8767 else
8768 return Subobj.get<FieldDecl*>()->getLocation();
8769 }
8770
8771 enum BasesToVisit {
8772 /// Visit all non-virtual (direct) bases.
8773 VisitNonVirtualBases,
8774 /// Visit all direct bases, virtual or not.
8775 VisitDirectBases,
8776 /// Visit all non-virtual bases, and all virtual bases if the class
8777 /// is not abstract.
8778 VisitPotentiallyConstructedBases,
8779 /// Visit all direct or virtual bases.
8780 VisitAllBases
8781 };
8782
8783 // Visit the bases and members of the class.
8784 bool visit(BasesToVisit Bases) {
8785 CXXRecordDecl *RD = MD->getParent();
8786
8787 if (Bases == VisitPotentiallyConstructedBases)
8788 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8789
8790 for (auto &B : RD->bases())
8791 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8792 getDerived().visitBase(&B))
8793 return true;
8794
8795 if (Bases == VisitAllBases)
8796 for (auto &B : RD->vbases())
8797 if (getDerived().visitBase(&B))
8798 return true;
8799
8800 for (auto *F : RD->fields())
8801 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8802 getDerived().visitField(F))
8803 return true;
8804
8805 return false;
8806 }
8807};
8808}
8809
8810namespace {
8811struct SpecialMemberDeletionInfo
8812 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8813 bool Diagnose;
8814
8815 SourceLocation Loc;
8816
8817 bool AllFieldsAreConst;
8818
8819 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8820 Sema::CXXSpecialMember CSM,
8821 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8822 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8823 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8824
8825 bool inUnion() const { return MD->getParent()->isUnion(); }
8826
8827 Sema::CXXSpecialMember getEffectiveCSM() {
8828 return ICI ? Sema::CXXInvalid : CSM;
8829 }
8830
8831 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8832
8833 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8834 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8835
8836 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8837 bool shouldDeleteForField(FieldDecl *FD);
8838 bool shouldDeleteForAllConstMembers();
8839
8840 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8841 unsigned Quals);
8842 bool shouldDeleteForSubobjectCall(Subobject Subobj,
8843 Sema::SpecialMemberOverloadResult SMOR,
8844 bool IsDtorCallInCtor);
8845
8846 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8847};
8848}
8849
8850/// Is the given special member inaccessible when used on the given
8851/// sub-object.
8852bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8853 CXXMethodDecl *target) {
8854 /// If we're operating on a base class, the object type is the
8855 /// type of this special member.
8856 QualType objectTy;
8857 AccessSpecifier access = target->getAccess();
8858 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8859 objectTy = S.Context.getTypeDeclType(MD->getParent());
8860 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8861
8862 // If we're operating on a field, the object type is the type of the field.
8863 } else {
8864 objectTy = S.Context.getTypeDeclType(target->getParent());
8865 }
8866
8867 return S.isMemberAccessibleForDeletion(
8868 target->getParent(), DeclAccessPair::make(target, access), objectTy);
8869}
8870
8871/// Check whether we should delete a special member due to the implicit
8872/// definition containing a call to a special member of a subobject.
8873bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8874 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8875 bool IsDtorCallInCtor) {
8876 CXXMethodDecl *Decl = SMOR.getMethod();
8877 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8878
8879 int DiagKind = -1;
8880
8881 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8882 DiagKind = !Decl ? 0 : 1;
8883 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8884 DiagKind = 2;
8885 else if (!isAccessible(Subobj, Decl))
8886 DiagKind = 3;
8887 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8888 !Decl->isTrivial()) {
8889 // A member of a union must have a trivial corresponding special member.
8890 // As a weird special case, a destructor call from a union's constructor
8891 // must be accessible and non-deleted, but need not be trivial. Such a
8892 // destructor is never actually called, but is semantically checked as
8893 // if it were.
8894 DiagKind = 4;
8895 }
8896
8897 if (DiagKind == -1)
8898 return false;
8899
8900 if (Diagnose) {
8901 if (Field) {
8902 S.Diag(Field->getLocation(),
8903 diag::note_deleted_special_member_class_subobject)
8904 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8905 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8906 } else {
8907 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8908 S.Diag(Base->getBeginLoc(),
8909 diag::note_deleted_special_member_class_subobject)
8910 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8911 << Base->getType() << DiagKind << IsDtorCallInCtor
8912 << /*IsObjCPtr*/false;
8913 }
8914
8915 if (DiagKind == 1)
8916 S.NoteDeletedFunction(Decl);
8917 // FIXME: Explain inaccessibility if DiagKind == 3.
8918 }
8919
8920 return true;
8921}
8922
8923/// Check whether we should delete a special member function due to having a
8924/// direct or virtual base class or non-static data member of class type M.
8925bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8926 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8927 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8928 bool IsMutable = Field && Field->isMutable();
8929
8930 // C++11 [class.ctor]p5:
8931 // -- any direct or virtual base class, or non-static data member with no
8932 // brace-or-equal-initializer, has class type M (or array thereof) and
8933 // either M has no default constructor or overload resolution as applied
8934 // to M's default constructor results in an ambiguity or in a function
8935 // that is deleted or inaccessible
8936 // C++11 [class.copy]p11, C++11 [class.copy]p23:
8937 // -- a direct or virtual base class B that cannot be copied/moved because
8938 // overload resolution, as applied to B's corresponding special member,
8939 // results in an ambiguity or a function that is deleted or inaccessible
8940 // from the defaulted special member
8941 // C++11 [class.dtor]p5:
8942 // -- any direct or virtual base class [...] has a type with a destructor
8943 // that is deleted or inaccessible
8944 if (!(CSM == Sema::CXXDefaultConstructor &&
8945 Field && Field->hasInClassInitializer()) &&
8946 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8947 false))
8948 return true;
8949
8950 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8951 // -- any direct or virtual base class or non-static data member has a
8952 // type with a destructor that is deleted or inaccessible
8953 if (IsConstructor) {
8954 Sema::SpecialMemberOverloadResult SMOR =
8955 S.LookupSpecialMember(Class, Sema::CXXDestructor,
8956 false, false, false, false, false);
8957 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8958 return true;
8959 }
8960
8961 return false;
8962}
8963
8964bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8965 FieldDecl *FD, QualType FieldType) {
8966 // The defaulted special functions are defined as deleted if this is a variant
8967 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8968 // type under ARC.
8969 if (!FieldType.hasNonTrivialObjCLifetime())
8970 return false;
8971
8972 // Don't make the defaulted default constructor defined as deleted if the
8973 // member has an in-class initializer.
8974 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8975 return false;
8976
8977 if (Diagnose) {
8978 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8979 S.Diag(FD->getLocation(),
8980 diag::note_deleted_special_member_class_subobject)
8981 << getEffectiveCSM() << ParentClass << /*IsField*/true
8982 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8983 }
8984
8985 return true;
8986}
8987
8988/// Check whether we should delete a special member function due to the class
8989/// having a particular direct or virtual base class.
8990bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8991 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8992 // If program is correct, BaseClass cannot be null, but if it is, the error
8993 // must be reported elsewhere.
8994 if (!BaseClass)
8995 return false;
8996 // If we have an inheriting constructor, check whether we're calling an
8997 // inherited constructor instead of a default constructor.
8998 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8999 if (auto *BaseCtor = SMOR.getMethod()) {
9000 // Note that we do not check access along this path; other than that,
9001 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9002 // FIXME: Check that the base has a usable destructor! Sink this into
9003 // shouldDeleteForClassSubobject.
9004 if (BaseCtor->isDeleted() && Diagnose) {
9005 S.Diag(Base->getBeginLoc(),
9006 diag::note_deleted_special_member_class_subobject)
9007 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9008 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9009 << /*IsObjCPtr*/false;
9010 S.NoteDeletedFunction(BaseCtor);
9011 }
9012 return BaseCtor->isDeleted();
9013 }
9014 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9015}
9016
9017/// Check whether we should delete a special member function due to the class
9018/// having a particular non-static data member.
9019bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9020 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9021 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9022
9023 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9024 return true;
9025
9026 if (CSM == Sema::CXXDefaultConstructor) {
9027 // For a default constructor, all references must be initialized in-class
9028 // and, if a union, it must have a non-const member.
9029 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9030 if (Diagnose)
9031 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9032 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9033 return true;
9034 }
9035 // C++11 [class.ctor]p5: any non-variant non-static data member of
9036 // const-qualified type (or array thereof) with no
9037 // brace-or-equal-initializer does not have a user-provided default
9038 // constructor.
9039 if (!inUnion() && FieldType.isConstQualified() &&
9040 !FD->hasInClassInitializer() &&
9041 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
9042 if (Diagnose)
9043 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9044 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9045 return true;
9046 }
9047
9048 if (inUnion() && !FieldType.isConstQualified())
9049 AllFieldsAreConst = false;
9050 } else if (CSM == Sema::CXXCopyConstructor) {
9051 // For a copy constructor, data members must not be of rvalue reference
9052 // type.
9053 if (FieldType->isRValueReferenceType()) {
9054 if (Diagnose)
9055 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9056 << MD->getParent() << FD << FieldType;
9057 return true;
9058 }
9059 } else if (IsAssignment) {
9060 // For an assignment operator, data members must not be of reference type.
9061 if (FieldType->isReferenceType()) {
9062 if (Diagnose)
9063 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9064 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9065 return true;
9066 }
9067 if (!FieldRecord && FieldType.isConstQualified()) {
9068 // C++11 [class.copy]p23:
9069 // -- a non-static data member of const non-class type (or array thereof)
9070 if (Diagnose)
9071 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9072 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9073 return true;
9074 }
9075 }
9076
9077 if (FieldRecord) {
9078 // Some additional restrictions exist on the variant members.
9079 if (!inUnion() && FieldRecord->isUnion() &&
9080 FieldRecord->isAnonymousStructOrUnion()) {
9081 bool AllVariantFieldsAreConst = true;
9082
9083 // FIXME: Handle anonymous unions declared within anonymous unions.
9084 for (auto *UI : FieldRecord->fields()) {
9085 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9086
9087 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9088 return true;
9089
9090 if (!UnionFieldType.isConstQualified())
9091 AllVariantFieldsAreConst = false;
9092
9093 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9094 if (UnionFieldRecord &&
9095 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9096 UnionFieldType.getCVRQualifiers()))
9097 return true;
9098 }
9099
9100 // At least one member in each anonymous union must be non-const
9101 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9102 !FieldRecord->field_empty()) {
9103 if (Diagnose)
9104 S.Diag(FieldRecord->getLocation(),
9105 diag::note_deleted_default_ctor_all_const)
9106 << !!ICI << MD->getParent() << /*anonymous union*/1;
9107 return true;
9108 }
9109
9110 // Don't check the implicit member of the anonymous union type.
9111 // This is technically non-conformant, but sanity demands it.
9112 return false;
9113 }
9114
9115 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9116 FieldType.getCVRQualifiers()))
9117 return true;
9118 }
9119
9120 return false;
9121}
9122
9123/// C++11 [class.ctor] p5:
9124/// A defaulted default constructor for a class X is defined as deleted if
9125/// X is a union and all of its variant members are of const-qualified type.
9126bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9127 // This is a silly definition, because it gives an empty union a deleted
9128 // default constructor. Don't do that.
9129 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9130 bool AnyFields = false;
9131 for (auto *F : MD->getParent()->fields())
9132 if ((AnyFields = !F->isUnnamedBitfield()))
9133 break;
9134 if (!AnyFields)
9135 return false;
9136 if (Diagnose)
9137 S.Diag(MD->getParent()->getLocation(),
9138 diag::note_deleted_default_ctor_all_const)
9139 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9140 return true;
9141 }
9142 return false;
9143}
9144
9145/// Determine whether a defaulted special member function should be defined as
9146/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9147/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9148bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9149 InheritedConstructorInfo *ICI,
9150 bool Diagnose) {
9151 if (MD->isInvalidDecl())
9152 return false;
9153 CXXRecordDecl *RD = MD->getParent();
9154 assert(!RD->isDependentType() && "do deletion after instantiation")(static_cast <bool> (!RD->isDependentType() &&
"do deletion after instantiation") ? void (0) : __assert_fail
("!RD->isDependentType() && \"do deletion after instantiation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9154, __extension__ __PRETTY_FUNCTION__))
;
9155 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9156 return false;
9157
9158 // C++11 [expr.lambda.prim]p19:
9159 // The closure type associated with a lambda-expression has a
9160 // deleted (8.4.3) default constructor and a deleted copy
9161 // assignment operator.
9162 // C++2a adds back these operators if the lambda has no lambda-capture.
9163 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9164 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9165 if (Diagnose)
9166 Diag(RD->getLocation(), diag::note_lambda_decl);
9167 return true;
9168 }
9169
9170 // For an anonymous struct or union, the copy and assignment special members
9171 // will never be used, so skip the check. For an anonymous union declared at
9172 // namespace scope, the constructor and destructor are used.
9173 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9174 RD->isAnonymousStructOrUnion())
9175 return false;
9176
9177 // C++11 [class.copy]p7, p18:
9178 // If the class definition declares a move constructor or move assignment
9179 // operator, an implicitly declared copy constructor or copy assignment
9180 // operator is defined as deleted.
9181 if (MD->isImplicit() &&
9182 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9183 CXXMethodDecl *UserDeclaredMove = nullptr;
9184
9185 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9186 // deletion of the corresponding copy operation, not both copy operations.
9187 // MSVC 2015 has adopted the standards conforming behavior.
9188 bool DeletesOnlyMatchingCopy =
9189 getLangOpts().MSVCCompat &&
9190 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9191
9192 if (RD->hasUserDeclaredMoveConstructor() &&
9193 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9194 if (!Diagnose) return true;
9195
9196 // Find any user-declared move constructor.
9197 for (auto *I : RD->ctors()) {
9198 if (I->isMoveConstructor()) {
9199 UserDeclaredMove = I;
9200 break;
9201 }
9202 }
9203 assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail
("UserDeclaredMove", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9203, __extension__ __PRETTY_FUNCTION__))
;
9204 } else if (RD->hasUserDeclaredMoveAssignment() &&
9205 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9206 if (!Diagnose) return true;
9207
9208 // Find any user-declared move assignment operator.
9209 for (auto *I : RD->methods()) {
9210 if (I->isMoveAssignmentOperator()) {
9211 UserDeclaredMove = I;
9212 break;
9213 }
9214 }
9215 assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail
("UserDeclaredMove", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9215, __extension__ __PRETTY_FUNCTION__))
;
9216 }
9217
9218 if (UserDeclaredMove) {
9219 Diag(UserDeclaredMove->getLocation(),
9220 diag::note_deleted_copy_user_declared_move)
9221 << (CSM == CXXCopyAssignment) << RD
9222 << UserDeclaredMove->isMoveAssignmentOperator();
9223 return true;
9224 }
9225 }
9226
9227 // Do access control from the special member function
9228 ContextRAII MethodContext(*this, MD);
9229
9230 // C++11 [class.dtor]p5:
9231 // -- for a virtual destructor, lookup of the non-array deallocation function
9232 // results in an ambiguity or in a function that is deleted or inaccessible
9233 if (CSM == CXXDestructor && MD->isVirtual()) {
9234 FunctionDecl *OperatorDelete = nullptr;
9235 DeclarationName Name =
9236 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9237 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9238 OperatorDelete, /*Diagnose*/false)) {
9239 if (Diagnose)
9240 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9241 return true;
9242 }
9243 }
9244
9245 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9246
9247 // Per DR1611, do not consider virtual bases of constructors of abstract
9248 // classes, since we are not going to construct them.
9249 // Per DR1658, do not consider virtual bases of destructors of abstract
9250 // classes either.
9251 // Per DR2180, for assignment operators we only assign (and thus only
9252 // consider) direct bases.
9253 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9254 : SMI.VisitPotentiallyConstructedBases))
9255 return true;
9256
9257 if (SMI.shouldDeleteForAllConstMembers())
9258 return true;
9259
9260 if (getLangOpts().CUDA) {
9261 // We should delete the special member in CUDA mode if target inference
9262 // failed.
9263 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9264 // is treated as certain special member, which may not reflect what special
9265 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9266 // expects CSM to match MD, therefore recalculate CSM.
9267 assert(ICI || CSM == getSpecialMember(MD))(static_cast <bool> (ICI || CSM == getSpecialMember(MD)
) ? void (0) : __assert_fail ("ICI || CSM == getSpecialMember(MD)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9267, __extension__ __PRETTY_FUNCTION__))
;
9268 auto RealCSM = CSM;
9269 if (ICI)
9270 RealCSM = getSpecialMember(MD);
9271
9272 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9273 SMI.ConstArg, Diagnose);
9274 }
9275
9276 return false;
9277}
9278
9279void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9280 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9281 assert(DFK && "not a defaultable function")(static_cast <bool> (DFK && "not a defaultable function"
) ? void (0) : __assert_fail ("DFK && \"not a defaultable function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9281, __extension__ __PRETTY_FUNCTION__))
;
9282 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted")(static_cast <bool> (FD->isDefaulted() && FD
->isDeleted() && "not defaulted and deleted") ? void
(0) : __assert_fail ("FD->isDefaulted() && FD->isDeleted() && \"not defaulted and deleted\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9282, __extension__ __PRETTY_FUNCTION__))
;
9283
9284 if (DFK.isSpecialMember()) {
9285 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9286 nullptr, /*Diagnose=*/true);
9287 } else {
9288 DefaultedComparisonAnalyzer(
9289 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9290 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9291 .visit();
9292 }
9293}
9294
9295/// Perform lookup for a special member of the specified kind, and determine
9296/// whether it is trivial. If the triviality can be determined without the
9297/// lookup, skip it. This is intended for use when determining whether a
9298/// special member of a containing object is trivial, and thus does not ever
9299/// perform overload resolution for default constructors.
9300///
9301/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9302/// member that was most likely to be intended to be trivial, if any.
9303///
9304/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9305/// determine whether the special member is trivial.
9306static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9307 Sema::CXXSpecialMember CSM, unsigned Quals,
9308 bool ConstRHS,
9309 Sema::TrivialABIHandling TAH,
9310 CXXMethodDecl **Selected) {
9311 if (Selected)
9312 *Selected = nullptr;
9313
9314 switch (CSM) {
9315 case Sema::CXXInvalid:
9316 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9316)
;
9317
9318 case Sema::CXXDefaultConstructor:
9319 // C++11 [class.ctor]p5:
9320 // A default constructor is trivial if:
9321 // - all the [direct subobjects] have trivial default constructors
9322 //
9323 // Note, no overload resolution is performed in this case.
9324 if (RD->hasTrivialDefaultConstructor())
9325 return true;
9326
9327 if (Selected) {
9328 // If there's a default constructor which could have been trivial, dig it
9329 // out. Otherwise, if there's any user-provided default constructor, point
9330 // to that as an example of why there's not a trivial one.
9331 CXXConstructorDecl *DefCtor = nullptr;
9332 if (RD->needsImplicitDefaultConstructor())
9333 S.DeclareImplicitDefaultConstructor(RD);
9334 for (auto *CI : RD->ctors()) {
9335 if (!CI->isDefaultConstructor())
9336 continue;
9337 DefCtor = CI;
9338 if (!DefCtor->isUserProvided())
9339 break;
9340 }
9341
9342 *Selected = DefCtor;
9343 }
9344
9345 return false;
9346
9347 case Sema::CXXDestructor:
9348 // C++11 [class.dtor]p5:
9349 // A destructor is trivial if:
9350 // - all the direct [subobjects] have trivial destructors
9351 if (RD->hasTrivialDestructor() ||
9352 (TAH == Sema::TAH_ConsiderTrivialABI &&
9353 RD->hasTrivialDestructorForCall()))
9354 return true;
9355
9356 if (Selected) {
9357 if (RD->needsImplicitDestructor())
9358 S.DeclareImplicitDestructor(RD);
9359 *Selected = RD->getDestructor();
9360 }
9361
9362 return false;
9363
9364 case Sema::CXXCopyConstructor:
9365 // C++11 [class.copy]p12:
9366 // A copy constructor is trivial if:
9367 // - the constructor selected to copy each direct [subobject] is trivial
9368 if (RD->hasTrivialCopyConstructor() ||
9369 (TAH == Sema::TAH_ConsiderTrivialABI &&
9370 RD->hasTrivialCopyConstructorForCall())) {
9371 if (Quals == Qualifiers::Const)
9372 // We must either select the trivial copy constructor or reach an
9373 // ambiguity; no need to actually perform overload resolution.
9374 return true;
9375 } else if (!Selected) {
9376 return false;
9377 }
9378 // In C++98, we are not supposed to perform overload resolution here, but we
9379 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9380 // cases like B as having a non-trivial copy constructor:
9381 // struct A { template<typename T> A(T&); };
9382 // struct B { mutable A a; };
9383 goto NeedOverloadResolution;
9384
9385 case Sema::CXXCopyAssignment:
9386 // C++11 [class.copy]p25:
9387 // A copy assignment operator is trivial if:
9388 // - the assignment operator selected to copy each direct [subobject] is
9389 // trivial
9390 if (RD->hasTrivialCopyAssignment()) {
9391 if (Quals == Qualifiers::Const)
9392 return true;
9393 } else if (!Selected) {
9394 return false;
9395 }
9396 // In C++98, we are not supposed to perform overload resolution here, but we
9397 // treat that as a language defect.
9398 goto NeedOverloadResolution;
9399
9400 case Sema::CXXMoveConstructor:
9401 case Sema::CXXMoveAssignment:
9402 NeedOverloadResolution:
9403 Sema::SpecialMemberOverloadResult SMOR =
9404 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9405
9406 // The standard doesn't describe how to behave if the lookup is ambiguous.
9407 // We treat it as not making the member non-trivial, just like the standard
9408 // mandates for the default constructor. This should rarely matter, because
9409 // the member will also be deleted.
9410 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9411 return true;
9412
9413 if (!SMOR.getMethod()) {
9414 assert(SMOR.getKind() ==(static_cast <bool> (SMOR.getKind() == Sema::SpecialMemberOverloadResult
::NoMemberOrDeleted) ? void (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9415, __extension__ __PRETTY_FUNCTION__))
9415 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)(static_cast <bool> (SMOR.getKind() == Sema::SpecialMemberOverloadResult
::NoMemberOrDeleted) ? void (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9415, __extension__ __PRETTY_FUNCTION__))
;
9416 return false;
9417 }
9418
9419 // We deliberately don't check if we found a deleted special member. We're
9420 // not supposed to!
9421 if (Selected)
9422 *Selected = SMOR.getMethod();
9423
9424 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9425 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9426 return SMOR.getMethod()->isTrivialForCall();
9427 return SMOR.getMethod()->isTrivial();
9428 }
9429
9430 llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9430)
;
9431}
9432
9433static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9434 for (auto *CI : RD->ctors())
9435 if (!CI->isImplicit())
9436 return CI;
9437
9438 // Look for constructor templates.
9439 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9440 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9441 if (CXXConstructorDecl *CD =
9442 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9443 return CD;
9444 }
9445
9446 return nullptr;
9447}
9448
9449/// The kind of subobject we are checking for triviality. The values of this
9450/// enumeration are used in diagnostics.
9451enum TrivialSubobjectKind {
9452 /// The subobject is a base class.
9453 TSK_BaseClass,
9454 /// The subobject is a non-static data member.
9455 TSK_Field,
9456 /// The object is actually the complete object.
9457 TSK_CompleteObject
9458};
9459
9460/// Check whether the special member selected for a given type would be trivial.
9461static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9462 QualType SubType, bool ConstRHS,
9463 Sema::CXXSpecialMember CSM,
9464 TrivialSubobjectKind Kind,
9465 Sema::TrivialABIHandling TAH, bool Diagnose) {
9466 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9467 if (!SubRD)
9468 return true;
9469
9470 CXXMethodDecl *Selected;
9471 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9472 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9473 return true;
9474
9475 if (Diagnose) {
9476 if (ConstRHS)
9477 SubType.addConst();
9478
9479 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9480 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9481 << Kind << SubType.getUnqualifiedType();
9482 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9483 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9484 } else if (!Selected)
9485 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9486 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9487 else if (Selected->isUserProvided()) {
9488 if (Kind == TSK_CompleteObject)
9489 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9490 << Kind << SubType.getUnqualifiedType() << CSM;
9491 else {
9492 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9493 << Kind << SubType.getUnqualifiedType() << CSM;
9494 S.Diag(Selected->getLocation(), diag::note_declared_at);
9495 }
9496 } else {
9497 if (Kind != TSK_CompleteObject)
9498 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9499 << Kind << SubType.getUnqualifiedType() << CSM;
9500
9501 // Explain why the defaulted or deleted special member isn't trivial.
9502 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9503 Diagnose);
9504 }
9505 }
9506
9507 return false;
9508}
9509
9510/// Check whether the members of a class type allow a special member to be
9511/// trivial.
9512static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9513 Sema::CXXSpecialMember CSM,
9514 bool ConstArg,
9515 Sema::TrivialABIHandling TAH,
9516 bool Diagnose) {
9517 for (const auto *FI : RD->fields()) {
9518 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9519 continue;
9520
9521 QualType FieldType = S.Context.getBaseElementType(FI->getType());
9522
9523 // Pretend anonymous struct or union members are members of this class.
9524 if (FI->isAnonymousStructOrUnion()) {
9525 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9526 CSM, ConstArg, TAH, Diagnose))
9527 return false;
9528 continue;
9529 }
9530
9531 // C++11 [class.ctor]p5:
9532 // A default constructor is trivial if [...]
9533 // -- no non-static data member of its class has a
9534 // brace-or-equal-initializer
9535 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9536 if (Diagnose)
9537 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9538 << FI;
9539 return false;
9540 }
9541
9542 // Objective C ARC 4.3.5:
9543 // [...] nontrivally ownership-qualified types are [...] not trivially
9544 // default constructible, copy constructible, move constructible, copy
9545 // assignable, move assignable, or destructible [...]
9546 if (FieldType.hasNonTrivialObjCLifetime()) {
9547 if (Diagnose)
9548 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9549 << RD << FieldType.getObjCLifetime();
9550 return false;
9551 }
9552
9553 bool ConstRHS = ConstArg && !FI->isMutable();
9554 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9555 CSM, TSK_Field, TAH, Diagnose))
9556 return false;
9557 }
9558
9559 return true;
9560}
9561
9562/// Diagnose why the specified class does not have a trivial special member of
9563/// the given kind.
9564void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9565 QualType Ty = Context.getRecordType(RD);
9566
9567 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9568 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9569 TSK_CompleteObject, TAH_IgnoreTrivialABI,
9570 /*Diagnose*/true);
9571}
9572
9573/// Determine whether a defaulted or deleted special member function is trivial,
9574/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9575/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9576bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9577 TrivialABIHandling TAH, bool Diagnose) {
9578 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough")(static_cast <bool> (!MD->isUserProvided() &&
CSM != CXXInvalid && "not special enough") ? void (0
) : __assert_fail ("!MD->isUserProvided() && CSM != CXXInvalid && \"not special enough\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9578, __extension__ __PRETTY_FUNCTION__))
;
9579
9580 CXXRecordDecl *RD = MD->getParent();
9581
9582 bool ConstArg = false;
9583
9584 // C++11 [class.copy]p12, p25: [DR1593]
9585 // A [special member] is trivial if [...] its parameter-type-list is
9586 // equivalent to the parameter-type-list of an implicit declaration [...]
9587 switch (CSM) {
9588 case CXXDefaultConstructor:
9589 case CXXDestructor:
9590 // Trivial default constructors and destructors cannot have parameters.
9591 break;
9592
9593 case CXXCopyConstructor:
9594 case CXXCopyAssignment: {
9595 // Trivial copy operations always have const, non-volatile parameter types.
9596 ConstArg = true;
9597 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9598 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9599 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9600 if (Diagnose)
9601 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9602 << Param0->getSourceRange() << Param0->getType()
9603 << Context.getLValueReferenceType(
9604 Context.getRecordType(RD).withConst());
9605 return false;
9606 }
9607 break;
9608 }
9609
9610 case CXXMoveConstructor:
9611 case CXXMoveAssignment: {
9612 // Trivial move operations always have non-cv-qualified parameters.
9613 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9614 const RValueReferenceType *RT =
9615 Param0->getType()->getAs<RValueReferenceType>();
9616 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9617 if (Diagnose)
9618 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9619 << Param0->getSourceRange() << Param0->getType()
9620 << Context.getRValueReferenceType(Context.getRecordType(RD));
9621 return false;
9622 }
9623 break;
9624 }
9625
9626 case CXXInvalid:
9627 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9627)
;
9628 }
9629
9630 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9631 if (Diagnose)
9632 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9633 diag::note_nontrivial_default_arg)
9634 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9635 return false;
9636 }
9637 if (MD->isVariadic()) {
9638 if (Diagnose)
9639 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9640 return false;
9641 }
9642
9643 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9644 // A copy/move [constructor or assignment operator] is trivial if
9645 // -- the [member] selected to copy/move each direct base class subobject
9646 // is trivial
9647 //
9648 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9649 // A [default constructor or destructor] is trivial if
9650 // -- all the direct base classes have trivial [default constructors or
9651 // destructors]
9652 for (const auto &BI : RD->bases())
9653 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9654 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9655 return false;
9656
9657 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9658 // A copy/move [constructor or assignment operator] for a class X is
9659 // trivial if
9660 // -- for each non-static data member of X that is of class type (or array
9661 // thereof), the constructor selected to copy/move that member is
9662 // trivial
9663 //
9664 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9665 // A [default constructor or destructor] is trivial if
9666 // -- for all of the non-static data members of its class that are of class
9667 // type (or array thereof), each such class has a trivial [default
9668 // constructor or destructor]
9669 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9670 return false;
9671
9672 // C++11 [class.dtor]p5:
9673 // A destructor is trivial if [...]
9674 // -- the destructor is not virtual
9675 if (CSM == CXXDestructor && MD->isVirtual()) {
9676 if (Diagnose)
9677 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9678 return false;
9679 }
9680
9681 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9682 // A [special member] for class X is trivial if [...]
9683 // -- class X has no virtual functions and no virtual base classes
9684 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9685 if (!Diagnose)
9686 return false;
9687
9688 if (RD->getNumVBases()) {
9689 // Check for virtual bases. We already know that the corresponding
9690 // member in all bases is trivial, so vbases must all be direct.
9691 CXXBaseSpecifier &BS = *RD->vbases_begin();
9692 assert(BS.isVirtual())(static_cast <bool> (BS.isVirtual()) ? void (0) : __assert_fail
("BS.isVirtual()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9692, __extension__ __PRETTY_FUNCTION__))
;
9693 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9694 return false;
9695 }
9696
9697 // Must have a virtual method.
9698 for (const auto *MI : RD->methods()) {
9699 if (MI->isVirtual()) {
9700 SourceLocation MLoc = MI->getBeginLoc();
9701 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9702 return false;
9703 }
9704 }
9705
9706 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-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9706)
;
9707 }
9708
9709 // Looks like it's trivial!
9710 return true;
9711}
9712
9713namespace {
9714struct FindHiddenVirtualMethod {
9715 Sema *S;
9716 CXXMethodDecl *Method;
9717 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9718 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9719
9720private:
9721 /// Check whether any most overridden method from MD in Methods
9722 static bool CheckMostOverridenMethods(
9723 const CXXMethodDecl *MD,
9724 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9725 if (MD->size_overridden_methods() == 0)
9726 return Methods.count(MD->getCanonicalDecl());
9727 for (const CXXMethodDecl *O : MD->overridden_methods())
9728 if (CheckMostOverridenMethods(O, Methods))
9729 return true;
9730 return false;
9731 }
9732
9733public:
9734 /// Member lookup function that determines whether a given C++
9735 /// method overloads virtual methods in a base class without overriding any,
9736 /// to be used with CXXRecordDecl::lookupInBases().
9737 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9738 RecordDecl *BaseRecord =
9739 Specifier->getType()->castAs<RecordType>()->getDecl();
9740
9741 DeclarationName Name = Method->getDeclName();
9742 assert(Name.getNameKind() == DeclarationName::Identifier)(static_cast <bool> (Name.getNameKind() == DeclarationName
::Identifier) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::Identifier"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 9742, __extension__ __PRETTY_FUNCTION__))
;
9743
9744 bool foundSameNameMethod = false;
9745 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9746 for (Path.Decls = BaseRecord->lookup(Name).begin();
9747 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9748 NamedDecl *D = *Path.Decls;
9749 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9750 MD = MD->getCanonicalDecl();
9751 foundSameNameMethod = true;
9752 // Interested only in hidden virtual methods.
9753 if (!MD->isVirtual())
9754 continue;
9755 // If the method we are checking overrides a method from its base
9756 // don't warn about the other overloaded methods. Clang deviates from
9757 // GCC by only diagnosing overloads of inherited virtual functions that
9758 // do not override any other virtual functions in the base. GCC's
9759 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9760 // function from a base class. These cases may be better served by a
9761 // warning (not specific to virtual functions) on call sites when the
9762 // call would select a different function from the base class, were it
9763 // visible.
9764 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9765 if (!S->IsOverload(Method, MD, false))
9766 return true;
9767 // Collect the overload only if its hidden.
9768 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9769 overloadedMethods.push_back(MD);
9770 }
9771 }
9772
9773 if (foundSameNameMethod)
9774 OverloadedMethods.append(overloadedMethods.begin(),
9775 overloadedMethods.end());
9776 return foundSameNameMethod;
9777 }
9778};
9779} // end anonymous namespace
9780
9781/// Add the most overriden methods from MD to Methods
9782static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9783 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9784 if (MD->size_overridden_methods() == 0)
9785 Methods.insert(MD->getCanonicalDecl());
9786 else
9787 for (const CXXMethodDecl *O : MD->overridden_methods())
9788 AddMostOverridenMethods(O, Methods);
9789}
9790
9791/// Check if a method overloads virtual methods in a base class without
9792/// overriding any.
9793void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9794 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9795 if (!MD->getDeclName().isIdentifier())
9796 return;
9797
9798 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9799 /*bool RecordPaths=*/false,
9800 /*bool DetectVirtual=*/false);
9801 FindHiddenVirtualMethod FHVM;
9802 FHVM.Method = MD;
9803 FHVM.S = this;
9804
9805 // Keep the base methods that were overridden or introduced in the subclass
9806 // by 'using' in a set. A base method not in this set is hidden.
9807 CXXRecordDecl *DC = MD->getParent();
9808 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9809 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9810 NamedDecl *ND = *I;
9811 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9812 ND = shad->getTargetDecl();
9813 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9814 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9815 }
9816
9817 if (DC->lookupInBases(FHVM, Paths))
9818 OverloadedMethods = FHVM.OverloadedMethods;
9819}
9820
9821void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9822 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9823 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9824 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9825 PartialDiagnostic PD = PDiag(
9826 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9827 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9828 Diag(overloadedMD->getLocation(), PD);
9829 }
9830}
9831
9832/// Diagnose methods which overload virtual methods in a base class
9833/// without overriding any.
9834void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9835 if (MD->isInvalidDecl())
9836 return;
9837
9838 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9839 return;
9840
9841 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9842 FindHiddenVirtualMethods(MD, OverloadedMethods);
9843 if (!OverloadedMethods.empty()) {
9844 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9845 << MD << (OverloadedMethods.size() > 1);
9846
9847 NoteHiddenVirtualMethods(MD, OverloadedMethods);
9848 }
9849}
9850
9851void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9852 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9853 // No diagnostics if this is a template instantiation.
9854 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9855 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9856 diag::ext_cannot_use_trivial_abi) << &RD;
9857 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9858 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9859 }
9860 RD.dropAttr<TrivialABIAttr>();
9861 };
9862
9863 // Ill-formed if the copy and move constructors are deleted.
9864 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9865 // If the type is dependent, then assume it might have
9866 // implicit copy or move ctor because we won't know yet at this point.
9867 if (RD.isDependentType())
9868 return true;
9869 if (RD.needsImplicitCopyConstructor() &&
9870 !RD.defaultedCopyConstructorIsDeleted())
9871 return true;
9872 if (RD.needsImplicitMoveConstructor() &&
9873 !RD.defaultedMoveConstructorIsDeleted())
9874 return true;
9875 for (const CXXConstructorDecl *CD : RD.ctors())
9876 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9877 return true;
9878 return false;
9879 };
9880
9881 if (!HasNonDeletedCopyOrMoveConstructor()) {
9882 PrintDiagAndRemoveAttr(0);
9883 return;
9884 }
9885
9886 // Ill-formed if the struct has virtual functions.
9887 if (RD.isPolymorphic()) {
9888 PrintDiagAndRemoveAttr(1);
9889 return;
9890 }
9891
9892 for (const auto &B : RD.bases()) {
9893 // Ill-formed if the base class is non-trivial for the purpose of calls or a
9894 // virtual base.
9895 if (!B.getType()->isDependentType() &&
9896 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9897 PrintDiagAndRemoveAttr(2);
9898 return;
9899 }
9900
9901 if (B.isVirtual()) {
9902 PrintDiagAndRemoveAttr(3);
9903 return;
9904 }
9905 }
9906
9907 for (const auto *FD : RD.fields()) {
9908 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9909 // non-trivial for the purpose of calls.
9910 QualType FT = FD->getType();
9911 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9912 PrintDiagAndRemoveAttr(4);
9913 return;
9914 }
9915
9916 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9917 if (!RT->isDependentType() &&
9918 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9919 PrintDiagAndRemoveAttr(5);
9920 return;
9921 }
9922 }
9923}
9924
9925void Sema::ActOnFinishCXXMemberSpecification(
9926 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9927 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9928 if (!TagDecl)
9929 return;
9930
9931 AdjustDeclIfTemplate(TagDecl);
9932
9933 for (const ParsedAttr &AL : AttrList) {
9934 if (AL.getKind() != ParsedAttr::AT_Visibility)
9935 continue;
9936 AL.setInvalid();
9937 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9938 }
9939
9940 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9941 // strict aliasing violation!
9942 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9943 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9944
9945 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9946}
9947
9948/// Find the equality comparison functions that should be implicitly declared
9949/// in a given class definition, per C++2a [class.compare.default]p3.
9950static void findImplicitlyDeclaredEqualityComparisons(
9951 ASTContext &Ctx, CXXRecordDecl *RD,
9952 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9953 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9954 if (!RD->lookup(EqEq).empty())
9955 // Member operator== explicitly declared: no implicit operator==s.
9956 return;
9957
9958 // Traverse friends looking for an '==' or a '<=>'.
9959 for (FriendDecl *Friend : RD->friends()) {
9960 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9961 if (!FD) continue;
9962
9963 if (FD->getOverloadedOperator() == OO_EqualEqual) {
9964 // Friend operator== explicitly declared: no implicit operator==s.
9965 Spaceships.clear();
9966 return;
9967 }
9968
9969 if (FD->getOverloadedOperator() == OO_Spaceship &&
9970 FD->isExplicitlyDefaulted())
9971 Spaceships.push_back(FD);
9972 }
9973
9974 // Look for members named 'operator<=>'.
9975 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9976 for (NamedDecl *ND : RD->lookup(Cmp)) {
9977 // Note that we could find a non-function here (either a function template
9978 // or a using-declaration). Neither case results in an implicit
9979 // 'operator=='.
9980 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9981 if (FD->isExplicitlyDefaulted())
9982 Spaceships.push_back(FD);
9983 }
9984}
9985
9986/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9987/// special functions, such as the default constructor, copy
9988/// constructor, or destructor, to the given C++ class (C++
9989/// [special]p1). This routine can only be executed just before the
9990/// definition of the class is complete.
9991void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9992 // Don't add implicit special members to templated classes.
9993 // FIXME: This means unqualified lookups for 'operator=' within a class
9994 // template don't work properly.
9995 if (!ClassDecl->isDependentType()) {
9996 if (ClassDecl->needsImplicitDefaultConstructor()) {
9997 ++getASTContext().NumImplicitDefaultConstructors;
9998
9999 if (ClassDecl->hasInheritedConstructor())
10000 DeclareImplicitDefaultConstructor(ClassDecl);
10001 }
10002
10003 if (ClassDecl->needsImplicitCopyConstructor()) {
10004 ++getASTContext().NumImplicitCopyConstructors;
10005
10006 // If the properties or semantics of the copy constructor couldn't be
10007 // determined while the class was being declared, force a declaration
10008 // of it now.
10009 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10010 ClassDecl->hasInheritedConstructor())
10011 DeclareImplicitCopyConstructor(ClassDecl);
10012 // For the MS ABI we need to know whether the copy ctor is deleted. A
10013 // prerequisite for deleting the implicit copy ctor is that the class has
10014 // a move ctor or move assignment that is either user-declared or whose
10015 // semantics are inherited from a subobject. FIXME: We should provide a
10016 // more direct way for CodeGen to ask whether the constructor was deleted.
10017 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10018 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10019 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10020 ClassDecl->hasUserDeclaredMoveAssignment() ||
10021 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10022 DeclareImplicitCopyConstructor(ClassDecl);
10023 }
10024
10025 if (getLangOpts().CPlusPlus11 &&
10026 ClassDecl->needsImplicitMoveConstructor()) {
10027 ++getASTContext().NumImplicitMoveConstructors;
10028
10029 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10030 ClassDecl->hasInheritedConstructor())
10031 DeclareImplicitMoveConstructor(ClassDecl);
10032 }
10033
10034 if (ClassDecl->needsImplicitCopyAssignment()) {
10035 ++getASTContext().NumImplicitCopyAssignmentOperators;
10036
10037 // If we have a dynamic class, then the copy assignment operator may be
10038 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10039 // it shows up in the right place in the vtable and that we diagnose
10040 // problems with the implicit exception specification.
10041 if (ClassDecl->isDynamicClass() ||
10042 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10043 ClassDecl->hasInheritedAssignment())
10044 DeclareImplicitCopyAssignment(ClassDecl);
10045 }
10046
10047 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10048 ++getASTContext().NumImplicitMoveAssignmentOperators;
10049
10050 // Likewise for the move assignment operator.
10051 if (ClassDecl->isDynamicClass() ||
10052 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10053 ClassDecl->hasInheritedAssignment())
10054 DeclareImplicitMoveAssignment(ClassDecl);
10055 }
10056
10057 if (ClassDecl->needsImplicitDestructor()) {
10058 ++getASTContext().NumImplicitDestructors;
10059
10060 // If we have a dynamic class, then the destructor may be virtual, so we
10061 // have to declare the destructor immediately. This ensures that, e.g., it
10062 // shows up in the right place in the vtable and that we diagnose problems
10063 // with the implicit exception specification.
10064 if (ClassDecl->isDynamicClass() ||
10065 ClassDecl->needsOverloadResolutionForDestructor())
10066 DeclareImplicitDestructor(ClassDecl);
10067 }
10068 }
10069
10070 // C++2a [class.compare.default]p3:
10071 // If the member-specification does not explicitly declare any member or
10072 // friend named operator==, an == operator function is declared implicitly
10073 // for each defaulted three-way comparison operator function defined in
10074 // the member-specification
10075 // FIXME: Consider doing this lazily.
10076 // We do this during the initial parse for a class template, not during
10077 // instantiation, so that we can handle unqualified lookups for 'operator=='
10078 // when parsing the template.
10079 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10080 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10081 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10082 DefaultedSpaceships);
10083 for (auto *FD : DefaultedSpaceships)
10084 DeclareImplicitEqualityComparison(ClassDecl, FD);
10085 }
10086}
10087
10088unsigned
10089Sema::ActOnReenterTemplateScope(Decl *D,
10090 llvm::function_ref<Scope *()> EnterScope) {
10091 if (!D)
10092 return 0;
10093 AdjustDeclIfTemplate(D);
10094
10095 // In order to get name lookup right, reenter template scopes in order from
10096 // outermost to innermost.
10097 SmallVector<TemplateParameterList *, 4> ParameterLists;
10098 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10099
10100 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10101 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10102 ParameterLists.push_back(DD->getTemplateParameterList(i));
10103
10104 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10105 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10106 ParameterLists.push_back(FTD->getTemplateParameters());
10107 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10108 LookupDC = VD->getDeclContext();
10109
10110 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10111 ParameterLists.push_back(VTD->getTemplateParameters());
10112 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10113 ParameterLists.push_back(PSD->getTemplateParameters());
10114 }
10115 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10116 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10117 ParameterLists.push_back(TD->getTemplateParameterList(i));
10118
10119 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10120 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10121 ParameterLists.push_back(CTD->getTemplateParameters());
10122 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10123 ParameterLists.push_back(PSD->getTemplateParameters());
10124 }
10125 }
10126 // FIXME: Alias declarations and concepts.
10127
10128 unsigned Count = 0;
10129 Scope *InnermostTemplateScope = nullptr;
10130 for (TemplateParameterList *Params : ParameterLists) {
10131 // Ignore explicit specializations; they don't contribute to the template
10132 // depth.
10133 if (Params->size() == 0)
10134 continue;
10135
10136 InnermostTemplateScope = EnterScope();
10137 for (NamedDecl *Param : *Params) {
10138 if (Param->getDeclName()) {
10139 InnermostTemplateScope->AddDecl(Param);
10140 IdResolver.AddDecl(Param);
10141 }
10142 }
10143 ++Count;
10144 }
10145
10146 // Associate the new template scopes with the corresponding entities.
10147 if (InnermostTemplateScope) {
10148 assert(LookupDC && "no enclosing DeclContext for template lookup")(static_cast <bool> (LookupDC && "no enclosing DeclContext for template lookup"
) ? void (0) : __assert_fail ("LookupDC && \"no enclosing DeclContext for template lookup\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 10148, __extension__ __PRETTY_FUNCTION__))
;
10149 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10150 }
10151
10152 return Count;
10153}
10154
10155void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10156 if (!RecordD) return;
10157 AdjustDeclIfTemplate(RecordD);
10158 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10159 PushDeclContext(S, Record);
10160}
10161
10162void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10163 if (!RecordD) return;
10164 PopDeclContext();
10165}
10166
10167/// This is used to implement the constant expression evaluation part of the
10168/// attribute enable_if extension. There is nothing in standard C++ which would
10169/// require reentering parameters.
10170void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10171 if (!Param)
10172 return;
10173
10174 S->AddDecl(Param);
10175 if (Param->getDeclName())
10176 IdResolver.AddDecl(Param);
10177}
10178
10179/// ActOnStartDelayedCXXMethodDeclaration - We have completed
10180/// parsing a top-level (non-nested) C++ class, and we are now
10181/// parsing those parts of the given Method declaration that could
10182/// not be parsed earlier (C++ [class.mem]p2), such as default
10183/// arguments. This action should enter the scope of the given
10184/// Method declaration as if we had just parsed the qualified method
10185/// name. However, it should not bring the parameters into scope;
10186/// that will be performed by ActOnDelayedCXXMethodParameter.
10187void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10188}
10189
10190/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10191/// C++ method declaration. We're (re-)introducing the given
10192/// function parameter into scope for use in parsing later parts of
10193/// the method declaration. For example, we could see an
10194/// ActOnParamDefaultArgument event for this parameter.
10195void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10196 if (!ParamD)
10197 return;
10198
10199 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10200
10201 S->AddDecl(Param);
10202 if (Param->getDeclName())
10203 IdResolver.AddDecl(Param);
10204}
10205
10206/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10207/// processing the delayed method declaration for Method. The method
10208/// declaration is now considered finished. There may be a separate
10209/// ActOnStartOfFunctionDef action later (not necessarily
10210/// immediately!) for this method, if it was also defined inside the
10211/// class body.
10212void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10213 if (!MethodD)
10214 return;
10215
10216 AdjustDeclIfTemplate(MethodD);
10217
10218 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10219
10220 // Now that we have our default arguments, check the constructor
10221 // again. It could produce additional diagnostics or affect whether
10222 // the class has implicitly-declared destructors, among other
10223 // things.
10224 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10225 CheckConstructor(Constructor);
10226
10227 // Check the default arguments, which we may have added.
10228 if (!Method->isInvalidDecl())
10229 CheckCXXDefaultArguments(Method);
10230}
10231
10232// Emit the given diagnostic for each non-address-space qualifier.
10233// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10234static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10235 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10236 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10237 bool DiagOccured = false;
10238 FTI.MethodQualifiers->forEachQualifier(
10239 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10240 SourceLocation SL) {
10241 // This diagnostic should be emitted on any qualifier except an addr
10242 // space qualifier. However, forEachQualifier currently doesn't visit
10243 // addr space qualifiers, so there's no way to write this condition
10244 // right now; we just diagnose on everything.
10245 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10246 DiagOccured = true;
10247 });
10248 if (DiagOccured)
10249 D.setInvalidType();
10250 }
10251}
10252
10253/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10254/// the well-formedness of the constructor declarator @p D with type @p
10255/// R. If there are any errors in the declarator, this routine will
10256/// emit diagnostics and set the invalid bit to true. In any case, the type
10257/// will be updated to reflect a well-formed type for the constructor and
10258/// returned.
10259QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10260 StorageClass &SC) {
10261 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10262
10263 // C++ [class.ctor]p3:
10264 // A constructor shall not be virtual (10.3) or static (9.4). A
10265 // constructor can be invoked for a const, volatile or const
10266 // volatile object. A constructor shall not be declared const,
10267 // volatile, or const volatile (9.3.2).
10268 if (isVirtual) {
10269 if (!D.isInvalidType())
10270 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10271 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10272 << SourceRange(D.getIdentifierLoc());
10273 D.setInvalidType();
10274 }
10275 if (SC == SC_Static) {
10276 if (!D.isInvalidType())
10277 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10278 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10279 << SourceRange(D.getIdentifierLoc());
10280 D.setInvalidType();
10281 SC = SC_None;
10282 }
10283
10284 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10285 diagnoseIgnoredQualifiers(
10286 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10287 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10288 D.getDeclSpec().getRestrictSpecLoc(),
10289 D.getDeclSpec().getAtomicSpecLoc());
10290 D.setInvalidType();
10291 }
10292
10293 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10294
10295 // C++0x [class.ctor]p4:
10296 // A constructor shall not be declared with a ref-qualifier.
10297 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10298 if (FTI.hasRefQualifier()) {
10299 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10300 << FTI.RefQualifierIsLValueRef
10301 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10302 D.setInvalidType();
10303 }
10304
10305 // Rebuild the function type "R" without any type qualifiers (in
10306 // case any of the errors above fired) and with "void" as the
10307 // return type, since constructors don't have return types.
10308 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10309 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10310 return R;
10311
10312 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10313 EPI.TypeQuals = Qualifiers();
10314 EPI.RefQualifier = RQ_None;
10315
10316 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10317}
10318
10319/// CheckConstructor - Checks a fully-formed constructor for
10320/// well-formedness, issuing any diagnostics required. Returns true if
10321/// the constructor declarator is invalid.
10322void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10323 CXXRecordDecl *ClassDecl
10324 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10325 if (!ClassDecl)
10326 return Constructor->setInvalidDecl();
10327
10328 // C++ [class.copy]p3:
10329 // A declaration of a constructor for a class X is ill-formed if
10330 // its first parameter is of type (optionally cv-qualified) X and
10331 // either there are no other parameters or else all other
10332 // parameters have default arguments.
10333 if (!Constructor->isInvalidDecl() &&
10334 Constructor->hasOneParamOrDefaultArgs() &&
10335 Constructor->getTemplateSpecializationKind() !=
10336 TSK_ImplicitInstantiation) {
10337 QualType ParamType = Constructor->getParamDecl(0)->getType();
10338 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10339 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10340 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10341 const char *ConstRef
10342 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10343 : " const &";
10344 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10345 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10346
10347 // FIXME: Rather that making the constructor invalid, we should endeavor
10348 // to fix the type.
10349 Constructor->setInvalidDecl();
10350 }
10351 }
10352}
10353
10354/// CheckDestructor - Checks a fully-formed destructor definition for
10355/// well-formedness, issuing any diagnostics required. Returns true
10356/// on error.
10357bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10358 CXXRecordDecl *RD = Destructor->getParent();
10359
10360 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10361 SourceLocation Loc;
10362
10363 if (!Destructor->isImplicit())
10364 Loc = Destructor->getLocation();
10365 else
10366 Loc = RD->getLocation();
10367
10368 // If we have a virtual destructor, look up the deallocation function
10369 if (FunctionDecl *OperatorDelete =
10370 FindDeallocationFunctionForDestructor(Loc, RD)) {
10371 Expr *ThisArg = nullptr;
10372
10373 // If the notional 'delete this' expression requires a non-trivial
10374 // conversion from 'this' to the type of a destroying operator delete's
10375 // first parameter, perform that conversion now.
10376 if (OperatorDelete->isDestroyingOperatorDelete()) {
10377 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10378 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10379 // C++ [class.dtor]p13:
10380 // ... as if for the expression 'delete this' appearing in a
10381 // non-virtual destructor of the destructor's class.
10382 ContextRAII SwitchContext(*this, Destructor);
10383 ExprResult This =
10384 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10385 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?")(static_cast <bool> (!This.isInvalid() && "couldn't form 'this' expr in dtor?"
) ? void (0) : __assert_fail ("!This.isInvalid() && \"couldn't form 'this' expr in dtor?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 10385, __extension__ __PRETTY_FUNCTION__))
;
10386 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10387 if (This.isInvalid()) {
10388 // FIXME: Register this as a context note so that it comes out
10389 // in the right order.
10390 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10391 return true;
10392 }
10393 ThisArg = This.get();
10394 }
10395 }
10396
10397 DiagnoseUseOfDecl(OperatorDelete, Loc);
10398 MarkFunctionReferenced(Loc, OperatorDelete);
10399 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10400 }
10401 }
10402
10403 return false;
10404}
10405
10406/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10407/// the well-formednes of the destructor declarator @p D with type @p
10408/// R. If there are any errors in the declarator, this routine will
10409/// emit diagnostics and set the declarator to invalid. Even if this happens,
10410/// will be updated to reflect a well-formed type for the destructor and
10411/// returned.
10412QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10413 StorageClass& SC) {
10414 // C++ [class.dtor]p1:
10415 // [...] A typedef-name that names a class is a class-name
10416 // (7.1.3); however, a typedef-name that names a class shall not
10417 // be used as the identifier in the declarator for a destructor
10418 // declaration.
10419 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10420 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10421 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10422 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10423 else if (const TemplateSpecializationType *TST =
10424 DeclaratorType->getAs<TemplateSpecializationType>())
10425 if (TST->isTypeAlias())
10426 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10427 << DeclaratorType << 1;
10428
10429 // C++ [class.dtor]p2:
10430 // A destructor is used to destroy objects of its class type. A
10431 // destructor takes no parameters, and no return type can be
10432 // specified for it (not even void). The address of a destructor
10433 // shall not be taken. A destructor shall not be static. A
10434 // destructor can be invoked for a const, volatile or const
10435 // volatile object. A destructor shall not be declared const,
10436 // volatile or const volatile (9.3.2).
10437 if (SC == SC_Static) {
10438 if (!D.isInvalidType())
10439 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10440 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10441 << SourceRange(D.getIdentifierLoc())
10442 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10443
10444 SC = SC_None;
10445 }
10446 if (!D.isInvalidType()) {
10447 // Destructors don't have return types, but the parser will
10448 // happily parse something like:
10449 //
10450 // class X {
10451 // float ~X();
10452 // };
10453 //
10454 // The return type will be eliminated later.
10455 if (D.getDeclSpec().hasTypeSpecifier())
10456 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10457 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10458 << SourceRange(D.getIdentifierLoc());
10459 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10460 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10461 SourceLocation(),
10462 D.getDeclSpec().getConstSpecLoc(),
10463 D.getDeclSpec().getVolatileSpecLoc(),
10464 D.getDeclSpec().getRestrictSpecLoc(),
10465 D.getDeclSpec().getAtomicSpecLoc());
10466 D.setInvalidType();
10467 }
10468 }
10469
10470 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10471
10472 // C++0x [class.dtor]p2:
10473 // A destructor shall not be declared with a ref-qualifier.
10474 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10475 if (FTI.hasRefQualifier()) {
10476 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10477 << FTI.RefQualifierIsLValueRef
10478 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10479 D.setInvalidType();
10480 }
10481
10482 // Make sure we don't have any parameters.
10483 if (FTIHasNonVoidParameters(FTI)) {
10484 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10485
10486 // Delete the parameters.
10487 FTI.freeParams();
10488 D.setInvalidType();
10489 }
10490
10491 // Make sure the destructor isn't variadic.
10492 if (FTI.isVariadic) {
10493 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10494 D.setInvalidType();
10495 }
10496
10497 // Rebuild the function type "R" without any type qualifiers or
10498 // parameters (in case any of the errors above fired) and with
10499 // "void" as the return type, since destructors don't have return
10500 // types.
10501 if (!D.isInvalidType())
10502 return R;
10503
10504 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10505 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10506 EPI.Variadic = false;
10507 EPI.TypeQuals = Qualifiers();
10508 EPI.RefQualifier = RQ_None;
10509 return Context.getFunctionType(Context.VoidTy, None, EPI);
10510}
10511
10512static void extendLeft(SourceRange &R, SourceRange Before) {
10513 if (Before.isInvalid())
10514 return;
10515 R.setBegin(Before.getBegin());
10516 if (R.getEnd().isInvalid())
10517 R.setEnd(Before.getEnd());
10518}
10519
10520static void extendRight(SourceRange &R, SourceRange After) {
10521 if (After.isInvalid())
10522 return;
10523 if (R.getBegin().isInvalid())
10524 R.setBegin(After.getBegin());
10525 R.setEnd(After.getEnd());
10526}
10527
10528/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10529/// well-formednes of the conversion function declarator @p D with
10530/// type @p R. If there are any errors in the declarator, this routine
10531/// will emit diagnostics and return true. Otherwise, it will return
10532/// false. Either way, the type @p R will be updated to reflect a
10533/// well-formed type for the conversion operator.
10534void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10535 StorageClass& SC) {
10536 // C++ [class.conv.fct]p1:
10537 // Neither parameter types nor return type can be specified. The
10538 // type of a conversion function (8.3.5) is "function taking no
10539 // parameter returning conversion-type-id."
10540 if (SC == SC_Static) {
10541 if (!D.isInvalidType())
10542 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10543 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10544 << D.getName().getSourceRange();
10545 D.setInvalidType();
10546 SC = SC_None;
10547 }
10548
10549 TypeSourceInfo *ConvTSI = nullptr;
10550 QualType ConvType =
10551 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10552
10553 const DeclSpec &DS = D.getDeclSpec();
10554 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10555 // Conversion functions don't have return types, but the parser will
10556 // happily parse something like:
10557 //
10558 // class X {
10559 // float operator bool();
10560 // };
10561 //
10562 // The return type will be changed later anyway.
10563 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10564 << SourceRange(DS.getTypeSpecTypeLoc())
10565 << SourceRange(D.getIdentifierLoc());
10566 D.setInvalidType();
10567 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10568 // It's also plausible that the user writes type qualifiers in the wrong
10569 // place, such as:
10570 // struct S { const operator int(); };
10571 // FIXME: we could provide a fixit to move the qualifiers onto the
10572 // conversion type.
10573 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10574 << SourceRange(D.getIdentifierLoc()) << 0;
10575 D.setInvalidType();
10576 }
10577
10578 const auto *Proto = R->castAs<FunctionProtoType>();
10579
10580 // Make sure we don't have any parameters.
10581 if (Proto->getNumParams() > 0) {
10582 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10583
10584 // Delete the parameters.
10585 D.getFunctionTypeInfo().freeParams();
10586 D.setInvalidType();
10587 } else if (Proto->isVariadic()) {
10588 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10589 D.setInvalidType();
10590 }
10591
10592 // Diagnose "&operator bool()" and other such nonsense. This
10593 // is actually a gcc extension which we don't support.
10594 if (Proto->getReturnType() != ConvType) {
10595 bool NeedsTypedef = false;
10596 SourceRange Before, After;
10597
10598 // Walk the chunks and extract information on them for our diagnostic.
10599 bool PastFunctionChunk = false;
10600 for (auto &Chunk : D.type_objects()) {
10601 switch (Chunk.Kind) {
10602 case DeclaratorChunk::Function:
10603 if (!PastFunctionChunk) {
10604 if (Chunk.Fun.HasTrailingReturnType) {
10605 TypeSourceInfo *TRT = nullptr;
10606 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10607 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10608 }
10609 PastFunctionChunk = true;
10610 break;
10611 }
10612 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10613 case DeclaratorChunk::Array:
10614 NeedsTypedef = true;
10615 extendRight(After, Chunk.getSourceRange());
10616 break;
10617
10618 case DeclaratorChunk::Pointer:
10619 case DeclaratorChunk::BlockPointer:
10620 case DeclaratorChunk::Reference:
10621 case DeclaratorChunk::MemberPointer:
10622 case DeclaratorChunk::Pipe:
10623 extendLeft(Before, Chunk.getSourceRange());
10624 break;
10625
10626 case DeclaratorChunk::Paren:
10627 extendLeft(Before, Chunk.Loc);
10628 extendRight(After, Chunk.EndLoc);
10629 break;
10630 }
10631 }
10632
10633 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10634 After.isValid() ? After.getBegin() :
10635 D.getIdentifierLoc();
10636 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10637 DB << Before << After;
10638
10639 if (!NeedsTypedef) {
10640 DB << /*don't need a typedef*/0;
10641
10642 // If we can provide a correct fix-it hint, do so.
10643 if (After.isInvalid() && ConvTSI) {
10644 SourceLocation InsertLoc =
10645 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10646 DB << FixItHint::CreateInsertion(InsertLoc, " ")
10647 << FixItHint::CreateInsertionFromRange(
10648 InsertLoc, CharSourceRange::getTokenRange(Before))
10649 << FixItHint::CreateRemoval(Before);
10650 }
10651 } else if (!Proto->getReturnType()->isDependentType()) {
10652 DB << /*typedef*/1 << Proto->getReturnType();
10653 } else if (getLangOpts().CPlusPlus11) {
10654 DB << /*alias template*/2 << Proto->getReturnType();
10655 } else {
10656 DB << /*might not be fixable*/3;
10657 }
10658
10659 // Recover by incorporating the other type chunks into the result type.
10660 // Note, this does *not* change the name of the function. This is compatible
10661 // with the GCC extension:
10662 // struct S { &operator int(); } s;
10663 // int &r = s.operator int(); // ok in GCC
10664 // S::operator int&() {} // error in GCC, function name is 'operator int'.
10665 ConvType = Proto->getReturnType();
10666 }
10667
10668 // C++ [class.conv.fct]p4:
10669 // The conversion-type-id shall not represent a function type nor
10670 // an array type.
10671 if (ConvType->isArrayType()) {
10672 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10673 ConvType = Context.getPointerType(ConvType);
10674 D.setInvalidType();
10675 } else if (ConvType->isFunctionType()) {
10676 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10677 ConvType = Context.getPointerType(ConvType);
10678 D.setInvalidType();
10679 }
10680
10681 // Rebuild the function type "R" without any parameters (in case any
10682 // of the errors above fired) and with the conversion type as the
10683 // return type.
10684 if (D.isInvalidType())
10685 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10686
10687 // C++0x explicit conversion operators.
10688 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10689 Diag(DS.getExplicitSpecLoc(),
10690 getLangOpts().CPlusPlus11
10691 ? diag::warn_cxx98_compat_explicit_conversion_functions
10692 : diag::ext_explicit_conversion_functions)
10693 << SourceRange(DS.getExplicitSpecRange());
10694}
10695
10696/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10697/// the declaration of the given C++ conversion function. This routine
10698/// is responsible for recording the conversion function in the C++
10699/// class, if possible.
10700Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10701 assert(Conversion && "Expected to receive a conversion function declaration")(static_cast <bool> (Conversion && "Expected to receive a conversion function declaration"
) ? void (0) : __assert_fail ("Conversion && \"Expected to receive a conversion function declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 10701, __extension__ __PRETTY_FUNCTION__))
;
10702
10703 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10704
10705 // Make sure we aren't redeclaring the conversion function.
10706 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10707 // C++ [class.conv.fct]p1:
10708 // [...] A conversion function is never used to convert a
10709 // (possibly cv-qualified) object to the (possibly cv-qualified)
10710 // same object type (or a reference to it), to a (possibly
10711 // cv-qualified) base class of that type (or a reference to it),
10712 // or to (possibly cv-qualified) void.
10713 QualType ClassType
10714 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10715 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10716 ConvType = ConvTypeRef->getPointeeType();
10717 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10718 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10719 /* Suppress diagnostics for instantiations. */;
10720 else if (Conversion->size_overridden_methods() != 0)
10721 /* Suppress diagnostics for overriding virtual function in a base class. */;
10722 else if (ConvType->isRecordType()) {
10723 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10724 if (ConvType == ClassType)
10725 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10726 << ClassType;
10727 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10728 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10729 << ClassType << ConvType;
10730 } else if (ConvType->isVoidType()) {
10731 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10732 << ClassType << ConvType;
10733 }
10734
10735 if (FunctionTemplateDecl *ConversionTemplate
10736 = Conversion->getDescribedFunctionTemplate())
10737 return ConversionTemplate;
10738
10739 return Conversion;
10740}
10741
10742namespace {
10743/// Utility class to accumulate and print a diagnostic listing the invalid
10744/// specifier(s) on a declaration.
10745struct BadSpecifierDiagnoser {
10746 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10747 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10748 ~BadSpecifierDiagnoser() {
10749 Diagnostic << Specifiers;
10750 }
10751
10752 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10753 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10754 }
10755 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10756 return check(SpecLoc,
10757 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10758 }
10759 void check(SourceLocation SpecLoc, const char *Spec) {
10760 if (SpecLoc.isInvalid()) return;
10761 Diagnostic << SourceRange(SpecLoc, SpecLoc);
10762 if (!Specifiers.empty()) Specifiers += " ";
10763 Specifiers += Spec;
10764 }
10765
10766 Sema &S;
10767 Sema::SemaDiagnosticBuilder Diagnostic;
10768 std::string Specifiers;
10769};
10770}
10771
10772/// Check the validity of a declarator that we parsed for a deduction-guide.
10773/// These aren't actually declarators in the grammar, so we need to check that
10774/// the user didn't specify any pieces that are not part of the deduction-guide
10775/// grammar.
10776void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10777 StorageClass &SC) {
10778 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10779 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10780 assert(GuidedTemplateDecl && "missing template decl for deduction guide")(static_cast <bool> (GuidedTemplateDecl && "missing template decl for deduction guide"
) ? void (0) : __assert_fail ("GuidedTemplateDecl && \"missing template decl for deduction guide\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 10780, __extension__ __PRETTY_FUNCTION__))
;
10781
10782 // C++ [temp.deduct.guide]p3:
10783 // A deduction-gide shall be declared in the same scope as the
10784 // corresponding class template.
10785 if (!CurContext->getRedeclContext()->Equals(
10786 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10787 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10788 << GuidedTemplateDecl;
10789 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10790 }
10791
10792 auto &DS = D.getMutableDeclSpec();
10793 // We leave 'friend' and 'virtual' to be rejected in the normal way.
10794 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10795 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10796 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10797 BadSpecifierDiagnoser Diagnoser(
10798 *this, D.getIdentifierLoc(),
10799 diag::err_deduction_guide_invalid_specifier);
10800
10801 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10802 DS.ClearStorageClassSpecs();
10803 SC = SC_None;
10804
10805 // 'explicit' is permitted.
10806 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10807 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10808 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10809 DS.ClearConstexprSpec();
10810
10811 Diagnoser.check(DS.getConstSpecLoc(), "const");
10812 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10813 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10814 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10815 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10816 DS.ClearTypeQualifiers();
10817
10818 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10819 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10820 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10821 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10822 DS.ClearTypeSpecType();
10823 }
10824
10825 if (D.isInvalidType())
10826 return;
10827
10828 // Check the declarator is simple enough.
10829 bool FoundFunction = false;
10830 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10831 if (Chunk.Kind == DeclaratorChunk::Paren)
10832 continue;
10833 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10834 Diag(D.getDeclSpec().getBeginLoc(),
10835 diag::err_deduction_guide_with_complex_decl)
10836 << D.getSourceRange();
10837 break;
10838 }
10839 if (!Chunk.Fun.hasTrailingReturnType()) {
10840 Diag(D.getName().getBeginLoc(),
10841 diag::err_deduction_guide_no_trailing_return_type);
10842 break;
10843 }
10844
10845 // Check that the return type is written as a specialization of
10846 // the template specified as the deduction-guide's name.
10847 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10848 TypeSourceInfo *TSI = nullptr;
10849 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10850 assert(TSI && "deduction guide has valid type but invalid return type?")(static_cast <bool> (TSI && "deduction guide has valid type but invalid return type?"
) ? void (0) : __assert_fail ("TSI && \"deduction guide has valid type but invalid return type?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 10850, __extension__ __PRETTY_FUNCTION__))
;
10851 bool AcceptableReturnType = false;
10852 bool MightInstantiateToSpecialization = false;
10853 if (auto RetTST =
10854 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10855 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10856 bool TemplateMatches =
10857 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10858 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10859 AcceptableReturnType = true;
10860 else {
10861 // This could still instantiate to the right type, unless we know it
10862 // names the wrong class template.
10863 auto *TD = SpecifiedName.getAsTemplateDecl();
10864 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10865 !TemplateMatches);
10866 }
10867 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10868 MightInstantiateToSpecialization = true;
10869 }
10870
10871 if (!AcceptableReturnType) {
10872 Diag(TSI->getTypeLoc().getBeginLoc(),
10873 diag::err_deduction_guide_bad_trailing_return_type)
10874 << GuidedTemplate << TSI->getType()
10875 << MightInstantiateToSpecialization
10876 << TSI->getTypeLoc().getSourceRange();
10877 }
10878
10879 // Keep going to check that we don't have any inner declarator pieces (we
10880 // could still have a function returning a pointer to a function).
10881 FoundFunction = true;
10882 }
10883
10884 if (D.isFunctionDefinition())
10885 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10886}
10887
10888//===----------------------------------------------------------------------===//
10889// Namespace Handling
10890//===----------------------------------------------------------------------===//
10891
10892/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10893/// reopened.
10894static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10895 SourceLocation Loc,
10896 IdentifierInfo *II, bool *IsInline,
10897 NamespaceDecl *PrevNS) {
10898 assert(*IsInline != PrevNS->isInline())(static_cast <bool> (*IsInline != PrevNS->isInline()
) ? void (0) : __assert_fail ("*IsInline != PrevNS->isInline()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 10898, __extension__ __PRETTY_FUNCTION__))
;
10899
10900 if (PrevNS->isInline())
10901 // The user probably just forgot the 'inline', so suggest that it
10902 // be added back.
10903 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10904 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10905 else
10906 S.Diag(Loc, diag::err_inline_namespace_mismatch);
10907
10908 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10909 *IsInline = PrevNS->isInline();
10910}
10911
10912/// ActOnStartNamespaceDef - This is called at the start of a namespace
10913/// definition.
10914Decl *Sema::ActOnStartNamespaceDef(
10915 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10916 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10917 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10918 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10919 // For anonymous namespace, take the location of the left brace.
10920 SourceLocation Loc = II ? IdentLoc : LBrace;
10921 bool IsInline = InlineLoc.isValid();
10922 bool IsInvalid = false;
10923 bool IsStd = false;
10924 bool AddToKnown = false;
10925 Scope *DeclRegionScope = NamespcScope->getParent();
10926
10927 NamespaceDecl *PrevNS = nullptr;
10928 if (II) {
10929 // C++ [namespace.def]p2:
10930 // The identifier in an original-namespace-definition shall not
10931 // have been previously defined in the declarative region in
10932 // which the original-namespace-definition appears. The
10933 // identifier in an original-namespace-definition is the name of
10934 // the namespace. Subsequently in that declarative region, it is
10935 // treated as an original-namespace-name.
10936 //
10937 // Since namespace names are unique in their scope, and we don't
10938 // look through using directives, just look for any ordinary names
10939 // as if by qualified name lookup.
10940 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10941 ForExternalRedeclaration);
10942 LookupQualifiedName(R, CurContext->getRedeclContext());
10943 NamedDecl *PrevDecl =
10944 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10945 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10946
10947 if (PrevNS) {
10948 // This is an extended namespace definition.
10949 if (IsInline != PrevNS->isInline())
10950 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10951 &IsInline, PrevNS);
10952 } else if (PrevDecl) {
10953 // This is an invalid name redefinition.
10954 Diag(Loc, diag::err_redefinition_different_kind)
10955 << II;
10956 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10957 IsInvalid = true;
10958 // Continue on to push Namespc as current DeclContext and return it.
10959 } else if (II->isStr("std") &&
10960 CurContext->getRedeclContext()->isTranslationUnit()) {
10961 // This is the first "real" definition of the namespace "std", so update
10962 // our cache of the "std" namespace to point at this definition.
10963 PrevNS = getStdNamespace();
10964 IsStd = true;
10965 AddToKnown = !IsInline;
10966 } else {
10967 // We've seen this namespace for the first time.
10968 AddToKnown = !IsInline;
10969 }
10970 } else {
10971 // Anonymous namespaces.
10972
10973 // Determine whether the parent already has an anonymous namespace.
10974 DeclContext *Parent = CurContext->getRedeclContext();
10975 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10976 PrevNS = TU->getAnonymousNamespace();
10977 } else {
10978 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10979 PrevNS = ND->getAnonymousNamespace();
10980 }
10981
10982 if (PrevNS && IsInline != PrevNS->isInline())
10983 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10984 &IsInline, PrevNS);
10985 }
10986
10987 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10988 StartLoc, Loc, II, PrevNS);
10989 if (IsInvalid)
10990 Namespc->setInvalidDecl();
10991
10992 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10993 AddPragmaAttributes(DeclRegionScope, Namespc);
10994
10995 // FIXME: Should we be merging attributes?
10996 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10997 PushNamespaceVisibilityAttr(Attr, Loc);
10998
10999 if (IsStd)
11000 StdNamespace = Namespc;
11001 if (AddToKnown)
11002 KnownNamespaces[Namespc] = false;
11003
11004 if (II) {
11005 PushOnScopeChains(Namespc, DeclRegionScope);
11006 } else {
11007 // Link the anonymous namespace into its parent.
11008 DeclContext *Parent = CurContext->getRedeclContext();
11009 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11010 TU->setAnonymousNamespace(Namespc);
11011 } else {
11012 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11013 }
11014
11015 CurContext->addDecl(Namespc);
11016
11017 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11018 // behaves as if it were replaced by
11019 // namespace unique { /* empty body */ }
11020 // using namespace unique;
11021 // namespace unique { namespace-body }
11022 // where all occurrences of 'unique' in a translation unit are
11023 // replaced by the same identifier and this identifier differs
11024 // from all other identifiers in the entire program.
11025
11026 // We just create the namespace with an empty name and then add an
11027 // implicit using declaration, just like the standard suggests.
11028 //
11029 // CodeGen enforces the "universally unique" aspect by giving all
11030 // declarations semantically contained within an anonymous
11031 // namespace internal linkage.
11032
11033 if (!PrevNS) {
11034 UD = UsingDirectiveDecl::Create(Context, Parent,
11035 /* 'using' */ LBrace,
11036 /* 'namespace' */ SourceLocation(),
11037 /* qualifier */ NestedNameSpecifierLoc(),
11038 /* identifier */ SourceLocation(),
11039 Namespc,
11040 /* Ancestor */ Parent);
11041 UD->setImplicit();
11042 Parent->addDecl(UD);
11043 }
11044 }
11045
11046 ActOnDocumentableDecl(Namespc);
11047
11048 // Although we could have an invalid decl (i.e. the namespace name is a
11049 // redefinition), push it as current DeclContext and try to continue parsing.
11050 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11051 // for the namespace has the declarations that showed up in that particular
11052 // namespace definition.
11053 PushDeclContext(NamespcScope, Namespc);
11054 return Namespc;
11055}
11056
11057/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11058/// is a namespace alias, returns the namespace it points to.
11059static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11060 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11061 return AD->getNamespace();
11062 return dyn_cast_or_null<NamespaceDecl>(D);
11063}
11064
11065/// ActOnFinishNamespaceDef - This callback is called after a namespace is
11066/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11067void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11068 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11069 assert(Namespc && "Invalid parameter, expected NamespaceDecl")(static_cast <bool> (Namespc && "Invalid parameter, expected NamespaceDecl"
) ? void (0) : __assert_fail ("Namespc && \"Invalid parameter, expected NamespaceDecl\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11069, __extension__ __PRETTY_FUNCTION__))
;
11070 Namespc->setRBraceLoc(RBrace);
11071 PopDeclContext();
11072 if (Namespc->hasAttr<VisibilityAttr>())
11073 PopPragmaVisibility(true, RBrace);
11074 // If this namespace contains an export-declaration, export it now.
11075 if (DeferredExportedNamespaces.erase(Namespc))
11076 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11077}
11078
11079CXXRecordDecl *Sema::getStdBadAlloc() const {
11080 return cast_or_null<CXXRecordDecl>(
11081 StdBadAlloc.get(Context.getExternalSource()));
11082}
11083
11084EnumDecl *Sema::getStdAlignValT() const {
11085 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11086}
11087
11088NamespaceDecl *Sema::getStdNamespace() const {
11089 return cast_or_null<NamespaceDecl>(
11090 StdNamespace.get(Context.getExternalSource()));
11091}
11092
11093NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11094 if (!StdExperimentalNamespaceCache) {
11095 if (auto Std = getStdNamespace()) {
11096 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11097 SourceLocation(), LookupNamespaceName);
11098 if (!LookupQualifiedName(Result, Std) ||
11099 !(StdExperimentalNamespaceCache =
11100 Result.getAsSingle<NamespaceDecl>()))
11101 Result.suppressDiagnostics();
11102 }
11103 }
11104 return StdExperimentalNamespaceCache;
11105}
11106
11107namespace {
11108
11109enum UnsupportedSTLSelect {
11110 USS_InvalidMember,
11111 USS_MissingMember,
11112 USS_NonTrivial,
11113 USS_Other
11114};
11115
11116struct InvalidSTLDiagnoser {
11117 Sema &S;
11118 SourceLocation Loc;
11119 QualType TyForDiags;
11120
11121 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11122 const VarDecl *VD = nullptr) {
11123 {
11124 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11125 << TyForDiags << ((int)Sel);
11126 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11127 assert(!Name.empty())(static_cast <bool> (!Name.empty()) ? void (0) : __assert_fail
("!Name.empty()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11127, __extension__ __PRETTY_FUNCTION__))
;
11128 D << Name;
11129 }
11130 }
11131 if (Sel == USS_InvalidMember) {
11132 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11133 << VD << VD->getSourceRange();
11134 }
11135 return QualType();
11136 }
11137};
11138} // namespace
11139
11140QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11141 SourceLocation Loc,
11142 ComparisonCategoryUsage Usage) {
11143 assert(getLangOpts().CPlusPlus &&(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for comparison category type outside of C++.") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11144, __extension__ __PRETTY_FUNCTION__))
11144 "Looking for comparison category type outside of C++.")(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for comparison category type outside of C++.") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11144, __extension__ __PRETTY_FUNCTION__))
;
11145
11146 // Use an elaborated type for diagnostics which has a name containing the
11147 // prepended 'std' namespace but not any inline namespace names.
11148 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11149 auto *NNS =
11150 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11151 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11152 };
11153
11154 // Check if we've already successfully checked the comparison category type
11155 // before. If so, skip checking it again.
11156 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11157 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11158 // The only thing we need to check is that the type has a reachable
11159 // definition in the current context.
11160 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11161 return QualType();
11162
11163 return Info->getType();
11164 }
11165
11166 // If lookup failed
11167 if (!Info) {
11168 std::string NameForDiags = "std::";
11169 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11170 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11171 << NameForDiags << (int)Usage;
11172 return QualType();
11173 }
11174
11175 assert(Info->Kind == Kind)(static_cast <bool> (Info->Kind == Kind) ? void (0) :
__assert_fail ("Info->Kind == Kind", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11175, __extension__ __PRETTY_FUNCTION__))
;
11176 assert(Info->Record)(static_cast <bool> (Info->Record) ? void (0) : __assert_fail
("Info->Record", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11176, __extension__ __PRETTY_FUNCTION__))
;
11177
11178 // Update the Record decl in case we encountered a forward declaration on our
11179 // first pass. FIXME: This is a bit of a hack.
11180 if (Info->Record->hasDefinition())
11181 Info->Record = Info->Record->getDefinition();
11182
11183 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11184 return QualType();
11185
11186 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11187
11188 if (!Info->Record->isTriviallyCopyable())
11189 return UnsupportedSTLError(USS_NonTrivial);
11190
11191 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11192 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11193 // Tolerate empty base classes.
11194 if (Base->isEmpty())
11195 continue;
11196 // Reject STL implementations which have at least one non-empty base.
11197 return UnsupportedSTLError();
11198 }
11199
11200 // Check that the STL has implemented the types using a single integer field.
11201 // This expectation allows better codegen for builtin operators. We require:
11202 // (1) The class has exactly one field.
11203 // (2) The field is an integral or enumeration type.
11204 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11205 if (std::distance(FIt, FEnd) != 1 ||
11206 !FIt->getType()->isIntegralOrEnumerationType()) {
11207 return UnsupportedSTLError();
11208 }
11209
11210 // Build each of the require values and store them in Info.
11211 for (ComparisonCategoryResult CCR :
11212 ComparisonCategories::getPossibleResultsForType(Kind)) {
11213 StringRef MemName = ComparisonCategories::getResultString(CCR);
11214 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11215
11216 if (!ValInfo)
11217 return UnsupportedSTLError(USS_MissingMember, MemName);
11218
11219 VarDecl *VD = ValInfo->VD;
11220 assert(VD && "should not be null!")(static_cast <bool> (VD && "should not be null!"
) ? void (0) : __assert_fail ("VD && \"should not be null!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11220, __extension__ __PRETTY_FUNCTION__))
;
11221
11222 // Attempt to diagnose reasons why the STL definition of this type
11223 // might be foobar, including it failing to be a constant expression.
11224 // TODO Handle more ways the lookup or result can be invalid.
11225 if (!VD->isStaticDataMember() ||
11226 !VD->isUsableInConstantExpressions(Context))
11227 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11228
11229 // Attempt to evaluate the var decl as a constant expression and extract
11230 // the value of its first field as a ICE. If this fails, the STL
11231 // implementation is not supported.
11232 if (!ValInfo->hasValidIntValue())
11233 return UnsupportedSTLError();
11234
11235 MarkVariableReferenced(Loc, VD);
11236 }
11237
11238 // We've successfully built the required types and expressions. Update
11239 // the cache and return the newly cached value.
11240 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11241 return Info->getType();
11242}
11243
11244/// Retrieve the special "std" namespace, which may require us to
11245/// implicitly define the namespace.
11246NamespaceDecl *Sema::getOrCreateStdNamespace() {
11247 if (!StdNamespace) {
11248 // The "std" namespace has not yet been defined, so build one implicitly.
11249 StdNamespace = NamespaceDecl::Create(Context,
11250 Context.getTranslationUnitDecl(),
11251 /*Inline=*/false,
11252 SourceLocation(), SourceLocation(),
11253 &PP.getIdentifierTable().get("std"),
11254 /*PrevDecl=*/nullptr);
11255 getStdNamespace()->setImplicit(true);
11256 }
11257
11258 return getStdNamespace();
11259}
11260
11261bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11262 assert(getLangOpts().CPlusPlus &&(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for std::initializer_list outside of C++.") ? void (
0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11263, __extension__ __PRETTY_FUNCTION__))
11263 "Looking for std::initializer_list outside of C++.")(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for std::initializer_list outside of C++.") ? void (
0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11263, __extension__ __PRETTY_FUNCTION__))
;
11264
11265 // We're looking for implicit instantiations of
11266 // template <typename E> class std::initializer_list.
11267
11268 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11269 return false;
11270
11271 ClassTemplateDecl *Template = nullptr;
11272 const TemplateArgument *Arguments = nullptr;
11273
11274 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11275
11276 ClassTemplateSpecializationDecl *Specialization =
11277 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11278 if (!Specialization)
11279 return false;
11280
11281 Template = Specialization->getSpecializedTemplate();
11282 Arguments = Specialization->getTemplateArgs().data();
11283 } else if (const TemplateSpecializationType *TST =
11284 Ty->getAs<TemplateSpecializationType>()) {
11285 Template = dyn_cast_or_null<ClassTemplateDecl>(
11286 TST->getTemplateName().getAsTemplateDecl());
11287 Arguments = TST->getArgs();
11288 }
11289 if (!Template)
11290 return false;
11291
11292 if (!StdInitializerList) {
11293 // Haven't recognized std::initializer_list yet, maybe this is it.
11294 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11295 if (TemplateClass->getIdentifier() !=
11296 &PP.getIdentifierTable().get("initializer_list") ||
11297 !getStdNamespace()->InEnclosingNamespaceSetOf(
11298 TemplateClass->getDeclContext()))
11299 return false;
11300 // This is a template called std::initializer_list, but is it the right
11301 // template?
11302 TemplateParameterList *Params = Template->getTemplateParameters();
11303 if (Params->getMinRequiredArguments() != 1)
11304 return false;
11305 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11306 return false;
11307
11308 // It's the right template.
11309 StdInitializerList = Template;
11310 }
11311
11312 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11313 return false;
11314
11315 // This is an instance of std::initializer_list. Find the argument type.
11316 if (Element)
11317 *Element = Arguments[0].getAsType();
11318 return true;
11319}
11320
11321static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11322 NamespaceDecl *Std = S.getStdNamespace();
11323 if (!Std) {
11324 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11325 return nullptr;
11326 }
11327
11328 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11329 Loc, Sema::LookupOrdinaryName);
11330 if (!S.LookupQualifiedName(Result, Std)) {
11331 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11332 return nullptr;
11333 }
11334 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11335 if (!Template) {
11336 Result.suppressDiagnostics();
11337 // We found something weird. Complain about the first thing we found.
11338 NamedDecl *Found = *Result.begin();
11339 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11340 return nullptr;
11341 }
11342
11343 // We found some template called std::initializer_list. Now verify that it's
11344 // correct.
11345 TemplateParameterList *Params = Template->getTemplateParameters();
11346 if (Params->getMinRequiredArguments() != 1 ||
11347 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11348 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11349 return nullptr;
11350 }
11351
11352 return Template;
11353}
11354
11355QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11356 if (!StdInitializerList) {
11357 StdInitializerList = LookupStdInitializerList(*this, Loc);
11358 if (!StdInitializerList)
11359 return QualType();
11360 }
11361
11362 TemplateArgumentListInfo Args(Loc, Loc);
11363 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11364 Context.getTrivialTypeSourceInfo(Element,
11365 Loc)));
11366 return Context.getCanonicalType(
11367 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11368}
11369
11370bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11371 // C++ [dcl.init.list]p2:
11372 // A constructor is an initializer-list constructor if its first parameter
11373 // is of type std::initializer_list<E> or reference to possibly cv-qualified
11374 // std::initializer_list<E> for some type E, and either there are no other
11375 // parameters or else all other parameters have default arguments.
11376 if (!Ctor->hasOneParamOrDefaultArgs())
11377 return false;
11378
11379 QualType ArgType = Ctor->getParamDecl(0)->getType();
11380 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11381 ArgType = RT->getPointeeType().getUnqualifiedType();
11382
11383 return isStdInitializerList(ArgType, nullptr);
11384}
11385
11386/// Determine whether a using statement is in a context where it will be
11387/// apply in all contexts.
11388static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11389 switch (CurContext->getDeclKind()) {
11390 case Decl::TranslationUnit:
11391 return true;
11392 case Decl::LinkageSpec:
11393 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11394 default:
11395 return false;
11396 }
11397}
11398
11399namespace {
11400
11401// Callback to only accept typo corrections that are namespaces.
11402class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11403public:
11404 bool ValidateCandidate(const TypoCorrection &candidate) override {
11405 if (NamedDecl *ND = candidate.getCorrectionDecl())
11406 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11407 return false;
11408 }
11409
11410 std::unique_ptr<CorrectionCandidateCallback> clone() override {
11411 return std::make_unique<NamespaceValidatorCCC>(*this);
11412 }
11413};
11414
11415}
11416
11417static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11418 CXXScopeSpec &SS,
11419 SourceLocation IdentLoc,
11420 IdentifierInfo *Ident) {
11421 R.clear();
11422 NamespaceValidatorCCC CCC{};
11423 if (TypoCorrection Corrected =
11424 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11425 Sema::CTK_ErrorRecovery)) {
11426 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11427 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11428 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11429 Ident->getName().equals(CorrectedStr);
11430 S.diagnoseTypo(Corrected,
11431 S.PDiag(diag::err_using_directive_member_suggest)
11432 << Ident << DC << DroppedSpecifier << SS.getRange(),
11433 S.PDiag(diag::note_namespace_defined_here));
11434 } else {
11435 S.diagnoseTypo(Corrected,
11436 S.PDiag(diag::err_using_directive_suggest) << Ident,
11437 S.PDiag(diag::note_namespace_defined_here));
11438 }
11439 R.addDecl(Corrected.getFoundDecl());
11440 return true;
11441 }
11442 return false;
11443}
11444
11445Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11446 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11447 SourceLocation IdentLoc,
11448 IdentifierInfo *NamespcName,
11449 const ParsedAttributesView &AttrList) {
11450 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")(static_cast <bool> (!SS.isInvalid() && "Invalid CXXScopeSpec."
) ? void (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11450, __extension__ __PRETTY_FUNCTION__))
;
11451 assert(NamespcName && "Invalid NamespcName.")(static_cast <bool> (NamespcName && "Invalid NamespcName."
) ? void (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11451, __extension__ __PRETTY_FUNCTION__))
;
11452 assert(IdentLoc.isValid() && "Invalid NamespceName location.")(static_cast <bool> (IdentLoc.isValid() && "Invalid NamespceName location."
) ? void (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid NamespceName location.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11452, __extension__ __PRETTY_FUNCTION__))
;
11453
11454 // This can only happen along a recovery path.
11455 while (S->isTemplateParamScope())
11456 S = S->getParent();
11457 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")(static_cast <bool> (S->getFlags() & Scope::DeclScope
&& "Invalid Scope.") ? void (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11457, __extension__ __PRETTY_FUNCTION__))
;
11458
11459 UsingDirectiveDecl *UDir = nullptr;
11460 NestedNameSpecifier *Qualifier = nullptr;
11461 if (SS.isSet())
11462 Qualifier = SS.getScopeRep();
11463
11464 // Lookup namespace name.
11465 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11466 LookupParsedName(R, S, &SS);
11467 if (R.isAmbiguous())
11468 return nullptr;
11469
11470 if (R.empty()) {
11471 R.clear();
11472 // Allow "using namespace std;" or "using namespace ::std;" even if
11473 // "std" hasn't been defined yet, for GCC compatibility.
11474 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11475 NamespcName->isStr("std")) {
11476 Diag(IdentLoc, diag::ext_using_undefined_std);
11477 R.addDecl(getOrCreateStdNamespace());
11478 R.resolveKind();
11479 }
11480 // Otherwise, attempt typo correction.
11481 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11482 }
11483
11484 if (!R.empty()) {
11485 NamedDecl *Named = R.getRepresentativeDecl();
11486 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11487 assert(NS && "expected namespace decl")(static_cast <bool> (NS && "expected namespace decl"
) ? void (0) : __assert_fail ("NS && \"expected namespace decl\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11487, __extension__ __PRETTY_FUNCTION__))
;
11488
11489 // The use of a nested name specifier may trigger deprecation warnings.
11490 DiagnoseUseOfDecl(Named, IdentLoc);
11491
11492 // C++ [namespace.udir]p1:
11493 // A using-directive specifies that the names in the nominated
11494 // namespace can be used in the scope in which the
11495 // using-directive appears after the using-directive. During
11496 // unqualified name lookup (3.4.1), the names appear as if they
11497 // were declared in the nearest enclosing namespace which
11498 // contains both the using-directive and the nominated
11499 // namespace. [Note: in this context, "contains" means "contains
11500 // directly or indirectly". ]
11501
11502 // Find enclosing context containing both using-directive and
11503 // nominated namespace.
11504 DeclContext *CommonAncestor = NS;
11505 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11506 CommonAncestor = CommonAncestor->getParent();
11507
11508 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11509 SS.getWithLocInContext(Context),
11510 IdentLoc, Named, CommonAncestor);
11511
11512 if (IsUsingDirectiveInToplevelContext(CurContext) &&
11513 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11514 Diag(IdentLoc, diag::warn_using_directive_in_header);
11515 }
11516
11517 PushUsingDirective(S, UDir);
11518 } else {
11519 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11520 }
11521
11522 if (UDir)
11523 ProcessDeclAttributeList(S, UDir, AttrList);
11524
11525 return UDir;
11526}
11527
11528void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11529 // If the scope has an associated entity and the using directive is at
11530 // namespace or translation unit scope, add the UsingDirectiveDecl into
11531 // its lookup structure so qualified name lookup can find it.
11532 DeclContext *Ctx = S->getEntity();
11533 if (Ctx && !Ctx->isFunctionOrMethod())
11534 Ctx->addDecl(UDir);
11535 else
11536 // Otherwise, it is at block scope. The using-directives will affect lookup
11537 // only to the end of the scope.
11538 S->PushUsingDirective(UDir);
11539}
11540
11541Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11542 SourceLocation UsingLoc,
11543 SourceLocation TypenameLoc, CXXScopeSpec &SS,
11544 UnqualifiedId &Name,
11545 SourceLocation EllipsisLoc,
11546 const ParsedAttributesView &AttrList) {
11547 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")(static_cast <bool> (S->getFlags() & Scope::DeclScope
&& "Invalid Scope.") ? void (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11547, __extension__ __PRETTY_FUNCTION__))
;
11548
11549 if (SS.isEmpty()) {
11550 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11551 return nullptr;
11552 }
11553
11554 switch (Name.getKind()) {
11555 case UnqualifiedIdKind::IK_ImplicitSelfParam:
11556 case UnqualifiedIdKind::IK_Identifier:
11557 case UnqualifiedIdKind::IK_OperatorFunctionId:
11558 case UnqualifiedIdKind::IK_LiteralOperatorId:
11559 case UnqualifiedIdKind::IK_ConversionFunctionId:
11560 break;
11561
11562 case UnqualifiedIdKind::IK_ConstructorName:
11563 case UnqualifiedIdKind::IK_ConstructorTemplateId:
11564 // C++11 inheriting constructors.
11565 Diag(Name.getBeginLoc(),
11566 getLangOpts().CPlusPlus11
11567 ? diag::warn_cxx98_compat_using_decl_constructor
11568 : diag::err_using_decl_constructor)
11569 << SS.getRange();
11570
11571 if (getLangOpts().CPlusPlus11) break;
11572
11573 return nullptr;
11574
11575 case UnqualifiedIdKind::IK_DestructorName:
11576 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11577 return nullptr;
11578
11579 case UnqualifiedIdKind::IK_TemplateId:
11580 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11581 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11582 return nullptr;
11583
11584 case UnqualifiedIdKind::IK_DeductionGuideName:
11585 llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11585)
;
11586 }
11587
11588 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11589 DeclarationName TargetName = TargetNameInfo.getName();
11590 if (!TargetName)
11591 return nullptr;
11592
11593 // Warn about access declarations.
11594 if (UsingLoc.isInvalid()) {
11595 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11596 ? diag::err_access_decl
11597 : diag::warn_access_decl_deprecated)
11598 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11599 }
11600
11601 if (EllipsisLoc.isInvalid()) {
11602 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11603 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11604 return nullptr;
11605 } else {
11606 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11607 !TargetNameInfo.containsUnexpandedParameterPack()) {
11608 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11609 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11610 EllipsisLoc = SourceLocation();
11611 }
11612 }
11613
11614 NamedDecl *UD =
11615 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11616 SS, TargetNameInfo, EllipsisLoc, AttrList,
11617 /*IsInstantiation*/ false,
11618 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11619 if (UD)
11620 PushOnScopeChains(UD, S, /*AddToContext*/ false);
11621
11622 return UD;
11623}
11624
11625Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11626 SourceLocation UsingLoc,
11627 SourceLocation EnumLoc,
11628 const DeclSpec &DS) {
11629 switch (DS.getTypeSpecType()) {
11630 case DeclSpec::TST_error:
11631 // This will already have been diagnosed
11632 return nullptr;
11633
11634 case DeclSpec::TST_enum:
11635 break;
11636
11637 case DeclSpec::TST_typename:
11638 Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11639 return nullptr;
11640
11641 default:
11642 llvm_unreachable("unexpected DeclSpec type")::llvm::llvm_unreachable_internal("unexpected DeclSpec type",
"/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11642)
;
11643 }
11644
11645 // As with enum-decls, we ignore attributes for now.
11646 auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11647 if (auto *Def = Enum->getDefinition())
11648 Enum = Def;
11649
11650 auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11651 DS.getTypeSpecTypeNameLoc(), Enum);
11652 if (UD)
11653 PushOnScopeChains(UD, S, /*AddToContext*/ false);
11654
11655 return UD;
11656}
11657
11658/// Determine whether a using declaration considers the given
11659/// declarations as "equivalent", e.g., if they are redeclarations of
11660/// the same entity or are both typedefs of the same type.
11661static bool
11662IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11663 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11664 return true;
11665
11666 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11667 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11668 return Context.hasSameType(TD1->getUnderlyingType(),
11669 TD2->getUnderlyingType());
11670
11671 // Two using_if_exists using-declarations are equivalent if both are
11672 // unresolved.
11673 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11674 isa<UnresolvedUsingIfExistsDecl>(D2))
11675 return true;
11676
11677 return false;
11678}
11679
11680
11681/// Determines whether to create a using shadow decl for a particular
11682/// decl, given the set of decls existing prior to this using lookup.
11683bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11684 const LookupResult &Previous,
11685 UsingShadowDecl *&PrevShadow) {
11686 // Diagnose finding a decl which is not from a base class of the
11687 // current class. We do this now because there are cases where this
11688 // function will silently decide not to build a shadow decl, which
11689 // will pre-empt further diagnostics.
11690 //
11691 // We don't need to do this in C++11 because we do the check once on
11692 // the qualifier.
11693 //
11694 // FIXME: diagnose the following if we care enough:
11695 // struct A { int foo; };
11696 // struct B : A { using A::foo; };
11697 // template <class T> struct C : A {};
11698 // template <class T> struct D : C<T> { using B::foo; } // <---
11699 // This is invalid (during instantiation) in C++03 because B::foo
11700 // resolves to the using decl in B, which is not a base class of D<T>.
11701 // We can't diagnose it immediately because C<T> is an unknown
11702 // specialization. The UsingShadowDecl in D<T> then points directly
11703 // to A::foo, which will look well-formed when we instantiate.
11704 // The right solution is to not collapse the shadow-decl chain.
11705 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11706 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11707 DeclContext *OrigDC = Orig->getDeclContext();
11708
11709 // Handle enums and anonymous structs.
11710 if (isa<EnumDecl>(OrigDC))
11711 OrigDC = OrigDC->getParent();
11712 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11713 while (OrigRec->isAnonymousStructOrUnion())
11714 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11715
11716 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11717 if (OrigDC == CurContext) {
11718 Diag(Using->getLocation(),
11719 diag::err_using_decl_nested_name_specifier_is_current_class)
11720 << Using->getQualifierLoc().getSourceRange();
11721 Diag(Orig->getLocation(), diag::note_using_decl_target);
11722 Using->setInvalidDecl();
11723 return true;
11724 }
11725
11726 Diag(Using->getQualifierLoc().getBeginLoc(),
11727 diag::err_using_decl_nested_name_specifier_is_not_base_class)
11728 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11729 << Using->getQualifierLoc().getSourceRange();
11730 Diag(Orig->getLocation(), diag::note_using_decl_target);
11731 Using->setInvalidDecl();
11732 return true;
11733 }
11734 }
11735
11736 if (Previous.empty()) return false;
11737
11738 NamedDecl *Target = Orig;
11739 if (isa<UsingShadowDecl>(Target))
11740 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11741
11742 // If the target happens to be one of the previous declarations, we
11743 // don't have a conflict.
11744 //
11745 // FIXME: but we might be increasing its access, in which case we
11746 // should redeclare it.
11747 NamedDecl *NonTag = nullptr, *Tag = nullptr;
11748 bool FoundEquivalentDecl = false;
11749 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11750 I != E; ++I) {
11751 NamedDecl *D = (*I)->getUnderlyingDecl();
11752 // We can have UsingDecls in our Previous results because we use the same
11753 // LookupResult for checking whether the UsingDecl itself is a valid
11754 // redeclaration.
11755 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11756 continue;
11757
11758 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11759 // C++ [class.mem]p19:
11760 // If T is the name of a class, then [every named member other than
11761 // a non-static data member] shall have a name different from T
11762 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11763 !isa<IndirectFieldDecl>(Target) &&
11764 !isa<UnresolvedUsingValueDecl>(Target) &&
11765 DiagnoseClassNameShadow(
11766 CurContext,
11767 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11768 return true;
11769 }
11770
11771 if (IsEquivalentForUsingDecl(Context, D, Target)) {
11772 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11773 PrevShadow = Shadow;
11774 FoundEquivalentDecl = true;
11775 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11776 // We don't conflict with an existing using shadow decl of an equivalent
11777 // declaration, but we're not a redeclaration of it.
11778 FoundEquivalentDecl = true;
11779 }
11780
11781 if (isVisible(D))
11782 (isa<TagDecl>(D) ? Tag : NonTag) = D;
11783 }
11784
11785 if (FoundEquivalentDecl)
11786 return false;
11787
11788 // Always emit a diagnostic for a mismatch between an unresolved
11789 // using_if_exists and a resolved using declaration in either direction.
11790 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11791 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11792 if (!NonTag && !Tag)
11793 return false;
11794 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11795 Diag(Target->getLocation(), diag::note_using_decl_target);
11796 Diag((NonTag ? NonTag : Tag)->getLocation(),
11797 diag::note_using_decl_conflict);
11798 BUD->setInvalidDecl();
11799 return true;
11800 }
11801
11802 if (FunctionDecl *FD = Target->getAsFunction()) {
11803 NamedDecl *OldDecl = nullptr;
11804 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11805 /*IsForUsingDecl*/ true)) {
11806 case Ovl_Overload:
11807 return false;
11808
11809 case Ovl_NonFunction:
11810 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11811 break;
11812
11813 // We found a decl with the exact signature.
11814 case Ovl_Match:
11815 // If we're in a record, we want to hide the target, so we
11816 // return true (without a diagnostic) to tell the caller not to
11817 // build a shadow decl.
11818 if (CurContext->isRecord())
11819 return true;
11820
11821 // If we're not in a record, this is an error.
11822 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11823 break;
11824 }
11825
11826 Diag(Target->getLocation(), diag::note_using_decl_target);
11827 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11828 BUD->setInvalidDecl();
11829 return true;
11830 }
11831
11832 // Target is not a function.
11833
11834 if (isa<TagDecl>(Target)) {
11835 // No conflict between a tag and a non-tag.
11836 if (!Tag) return false;
11837
11838 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11839 Diag(Target->getLocation(), diag::note_using_decl_target);
11840 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11841 BUD->setInvalidDecl();
11842 return true;
11843 }
11844
11845 // No conflict between a tag and a non-tag.
11846 if (!NonTag) return false;
11847
11848 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11849 Diag(Target->getLocation(), diag::note_using_decl_target);
11850 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11851 BUD->setInvalidDecl();
11852 return true;
11853}
11854
11855/// Determine whether a direct base class is a virtual base class.
11856static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11857 if (!Derived->getNumVBases())
11858 return false;
11859 for (auto &B : Derived->bases())
11860 if (B.getType()->getAsCXXRecordDecl() == Base)
11861 return B.isVirtual();
11862 llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11862)
;
11863}
11864
11865/// Builds a shadow declaration corresponding to a 'using' declaration.
11866UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
11867 NamedDecl *Orig,
11868 UsingShadowDecl *PrevDecl) {
11869 // If we resolved to another shadow declaration, just coalesce them.
11870 NamedDecl *Target = Orig;
11871 if (isa<UsingShadowDecl>(Target)) {
11872 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11873 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration")(static_cast <bool> (!isa<UsingShadowDecl>(Target
) && "nested shadow declaration") ? void (0) : __assert_fail
("!isa<UsingShadowDecl>(Target) && \"nested shadow declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 11873, __extension__ __PRETTY_FUNCTION__))
;
11874 }
11875
11876 NamedDecl *NonTemplateTarget = Target;
11877 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11878 NonTemplateTarget = TargetTD->getTemplatedDecl();
11879
11880 UsingShadowDecl *Shadow;
11881 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11882 UsingDecl *Using = cast<UsingDecl>(BUD);
11883 bool IsVirtualBase =
11884 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11885 Using->getQualifier()->getAsRecordDecl());
11886 Shadow = ConstructorUsingShadowDecl::Create(
11887 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
11888 } else {
11889 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
11890 Target->getDeclName(), BUD, Target);
11891 }
11892 BUD->addShadowDecl(Shadow);
11893
11894 Shadow->setAccess(BUD->getAccess());
11895 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
11896 Shadow->setInvalidDecl();
11897
11898 Shadow->setPreviousDecl(PrevDecl);
11899
11900 if (S)
11901 PushOnScopeChains(Shadow, S);
11902 else
11903 CurContext->addDecl(Shadow);
11904
11905
11906 return Shadow;
11907}
11908
11909/// Hides a using shadow declaration. This is required by the current
11910/// using-decl implementation when a resolvable using declaration in a
11911/// class is followed by a declaration which would hide or override
11912/// one or more of the using decl's targets; for example:
11913///
11914/// struct Base { void foo(int); };
11915/// struct Derived : Base {
11916/// using Base::foo;
11917/// void foo(int);
11918/// };
11919///
11920/// The governing language is C++03 [namespace.udecl]p12:
11921///
11922/// When a using-declaration brings names from a base class into a
11923/// derived class scope, member functions in the derived class
11924/// override and/or hide member functions with the same name and
11925/// parameter types in a base class (rather than conflicting).
11926///
11927/// There are two ways to implement this:
11928/// (1) optimistically create shadow decls when they're not hidden
11929/// by existing declarations, or
11930/// (2) don't create any shadow decls (or at least don't make them
11931/// visible) until we've fully parsed/instantiated the class.
11932/// The problem with (1) is that we might have to retroactively remove
11933/// a shadow decl, which requires several O(n) operations because the
11934/// decl structures are (very reasonably) not designed for removal.
11935/// (2) avoids this but is very fiddly and phase-dependent.
11936void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11937 if (Shadow->getDeclName().getNameKind() ==
11938 DeclarationName::CXXConversionFunctionName)
11939 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11940
11941 // Remove it from the DeclContext...
11942 Shadow->getDeclContext()->removeDecl(Shadow);
11943
11944 // ...and the scope, if applicable...
11945 if (S) {
11946 S->RemoveDecl(Shadow);
11947 IdResolver.RemoveDecl(Shadow);
11948 }
11949
11950 // ...and the using decl.
11951 Shadow->getIntroducer()->removeShadowDecl(Shadow);
11952
11953 // TODO: complain somehow if Shadow was used. It shouldn't
11954 // be possible for this to happen, because...?
11955}
11956
11957/// Find the base specifier for a base class with the given type.
11958static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11959 QualType DesiredBase,
11960 bool &AnyDependentBases) {
11961 // Check whether the named type is a direct base class.
11962 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11963 .getUnqualifiedType();
11964 for (auto &Base : Derived->bases()) {
11965 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11966 if (CanonicalDesiredBase == BaseType)
11967 return &Base;
11968 if (BaseType->isDependentType())
11969 AnyDependentBases = true;
11970 }
11971 return nullptr;
11972}
11973
11974namespace {
11975class UsingValidatorCCC final : public CorrectionCandidateCallback {
11976public:
11977 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11978 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11979 : HasTypenameKeyword(HasTypenameKeyword),
11980 IsInstantiation(IsInstantiation), OldNNS(NNS),
11981 RequireMemberOf(RequireMemberOf) {}
11982
11983 bool ValidateCandidate(const TypoCorrection &Candidate) override {
11984 NamedDecl *ND = Candidate.getCorrectionDecl();
11985
11986 // Keywords are not valid here.
11987 if (!ND || isa<NamespaceDecl>(ND))
11988 return false;
11989
11990 // Completely unqualified names are invalid for a 'using' declaration.
11991 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11992 return false;
11993
11994 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11995 // reject.
11996
11997 if (RequireMemberOf) {
11998 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11999 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12000 // No-one ever wants a using-declaration to name an injected-class-name
12001 // of a base class, unless they're declaring an inheriting constructor.
12002 ASTContext &Ctx = ND->getASTContext();
12003 if (!Ctx.getLangOpts().CPlusPlus11)
12004 return false;
12005 QualType FoundType = Ctx.getRecordType(FoundRecord);
12006
12007 // Check that the injected-class-name is named as a member of its own
12008 // type; we don't want to suggest 'using Derived::Base;', since that
12009 // means something else.
12010 NestedNameSpecifier *Specifier =
12011 Candidate.WillReplaceSpecifier()
12012 ? Candidate.getCorrectionSpecifier()
12013 : OldNNS;
12014 if (!Specifier->getAsType() ||
12015 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12016 return false;
12017
12018 // Check that this inheriting constructor declaration actually names a
12019 // direct base class of the current class.
12020 bool AnyDependentBases = false;
12021 if (!findDirectBaseWithType(RequireMemberOf,
12022 Ctx.getRecordType(FoundRecord),
12023 AnyDependentBases) &&
12024 !AnyDependentBases)
12025 return false;
12026 } else {
12027 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12028 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12029 return false;
12030
12031 // FIXME: Check that the base class member is accessible?
12032 }
12033 } else {
12034 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12035 if (FoundRecord && FoundRecord->isInjectedClassName())
12036 return false;
12037 }
12038
12039 if (isa<TypeDecl>(ND))
12040 return HasTypenameKeyword || !IsInstantiation;
12041
12042 return !HasTypenameKeyword;
12043 }
12044
12045 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12046 return std::make_unique<UsingValidatorCCC>(*this);
12047 }
12048
12049private:
12050 bool HasTypenameKeyword;
12051 bool IsInstantiation;
12052 NestedNameSpecifier *OldNNS;
12053 CXXRecordDecl *RequireMemberOf;
12054};
12055} // end anonymous namespace
12056
12057/// Remove decls we can't actually see from a lookup being used to declare
12058/// shadow using decls.
12059///
12060/// \param S - The scope of the potential shadow decl
12061/// \param Previous - The lookup of a potential shadow decl's name.
12062void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12063 // It is really dumb that we have to do this.
12064 LookupResult::Filter F = Previous.makeFilter();
12065 while (F.hasNext()) {
12066 NamedDecl *D = F.next();
12067 if (!isDeclInScope(D, CurContext, S))
12068 F.erase();
12069 // If we found a local extern declaration that's not ordinarily visible,
12070 // and this declaration is being added to a non-block scope, ignore it.
12071 // We're only checking for scope conflicts here, not also for violations
12072 // of the linkage rules.
12073 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12074 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12075 F.erase();
12076 }
12077 F.done();
12078}
12079
12080/// Builds a using declaration.
12081///
12082/// \param IsInstantiation - Whether this call arises from an
12083/// instantiation of an unresolved using declaration. We treat
12084/// the lookup differently for these declarations.
12085NamedDecl *Sema::BuildUsingDeclaration(
12086 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12087 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12088 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12089 const ParsedAttributesView &AttrList, bool IsInstantiation,
12090 bool IsUsingIfExists) {
12091 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")(static_cast <bool> (!SS.isInvalid() && "Invalid CXXScopeSpec."
) ? void (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12091, __extension__ __PRETTY_FUNCTION__))
;
12092 SourceLocation IdentLoc = NameInfo.getLoc();
12093 assert(IdentLoc.isValid() && "Invalid TargetName location.")(static_cast <bool> (IdentLoc.isValid() && "Invalid TargetName location."
) ? void (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid TargetName location.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12093, __extension__ __PRETTY_FUNCTION__))
;
12094
12095 // FIXME: We ignore attributes for now.
12096
12097 // For an inheriting constructor declaration, the name of the using
12098 // declaration is the name of a constructor in this class, not in the
12099 // base class.
12100 DeclarationNameInfo UsingName = NameInfo;
12101 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12102 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12103 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12104 Context.getCanonicalType(Context.getRecordType(RD))));
12105
12106 // Do the redeclaration lookup in the current scope.
12107 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12108 ForVisibleRedeclaration);
12109 Previous.setHideTags(false);
12110 if (S) {
12111 LookupName(Previous, S);
12112
12113 FilterUsingLookup(S, Previous);
12114 } else {
12115 assert(IsInstantiation && "no scope in non-instantiation")(static_cast <bool> (IsInstantiation && "no scope in non-instantiation"
) ? void (0) : __assert_fail ("IsInstantiation && \"no scope in non-instantiation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12115, __extension__ __PRETTY_FUNCTION__))
;
12116 if (CurContext->isRecord())
12117 LookupQualifiedName(Previous, CurContext);
12118 else {
12119 // No redeclaration check is needed here; in non-member contexts we
12120 // diagnosed all possible conflicts with other using-declarations when
12121 // building the template:
12122 //
12123 // For a dependent non-type using declaration, the only valid case is
12124 // if we instantiate to a single enumerator. We check for conflicts
12125 // between shadow declarations we introduce, and we check in the template
12126 // definition for conflicts between a non-type using declaration and any
12127 // other declaration, which together covers all cases.
12128 //
12129 // A dependent typename using declaration will never successfully
12130 // instantiate, since it will always name a class member, so we reject
12131 // that in the template definition.
12132 }
12133 }
12134
12135 // Check for invalid redeclarations.
12136 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12137 SS, IdentLoc, Previous))
12138 return nullptr;
12139
12140 // 'using_if_exists' doesn't make sense on an inherited constructor.
12141 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12142 DeclarationName::CXXConstructorName) {
12143 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12144 return nullptr;
12145 }
12146
12147 DeclContext *LookupContext = computeDeclContext(SS);
12148 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12149 if (!LookupContext || EllipsisLoc.isValid()) {
12150 NamedDecl *D;
12151 // Dependent scope, or an unexpanded pack
12152 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12153 SS, NameInfo, IdentLoc))
12154 return nullptr;
12155
12156 if (HasTypenameKeyword) {
12157 // FIXME: not all declaration name kinds are legal here
12158 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12159 UsingLoc, TypenameLoc,
12160 QualifierLoc,
12161 IdentLoc, NameInfo.getName(),
12162 EllipsisLoc);
12163 } else {
12164 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12165 QualifierLoc, NameInfo, EllipsisLoc);
12166 }
12167 D->setAccess(AS);
12168 CurContext->addDecl(D);
12169 ProcessDeclAttributeList(S, D, AttrList);
12170 return D;
12171 }
12172
12173 auto Build = [&](bool Invalid) {
12174 UsingDecl *UD =
12175 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12176 UsingName, HasTypenameKeyword);
12177 UD->setAccess(AS);
12178 CurContext->addDecl(UD);
12179 ProcessDeclAttributeList(S, UD, AttrList);
12180 UD->setInvalidDecl(Invalid);
12181 return UD;
12182 };
12183 auto BuildInvalid = [&]{ return Build(true); };
12184 auto BuildValid = [&]{ return Build(false); };
12185
12186 if (RequireCompleteDeclContext(SS, LookupContext))
12187 return BuildInvalid();
12188
12189 // Look up the target name.
12190 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12191
12192 // Unlike most lookups, we don't always want to hide tag
12193 // declarations: tag names are visible through the using declaration
12194 // even if hidden by ordinary names, *except* in a dependent context
12195 // where it's important for the sanity of two-phase lookup.
12196 if (!IsInstantiation)
12197 R.setHideTags(false);
12198
12199 // For the purposes of this lookup, we have a base object type
12200 // equal to that of the current context.
12201 if (CurContext->isRecord()) {
12202 R.setBaseObjectType(
12203 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12204 }
12205
12206 LookupQualifiedName(R, LookupContext);
12207
12208 // Validate the context, now we have a lookup
12209 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12210 IdentLoc, &R))
12211 return nullptr;
12212
12213 if (R.empty() && IsUsingIfExists)
12214 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12215 UsingName.getName()),
12216 AS_public);
12217
12218 // Try to correct typos if possible. If constructor name lookup finds no
12219 // results, that means the named class has no explicit constructors, and we
12220 // suppressed declaring implicit ones (probably because it's dependent or
12221 // invalid).
12222 if (R.empty() &&
12223 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12224 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12225 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12226 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12227 auto *II = NameInfo.getName().getAsIdentifierInfo();
12228 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12229 CurContext->isStdNamespace() &&
12230 isa<TranslationUnitDecl>(LookupContext) &&
12231 getSourceManager().isInSystemHeader(UsingLoc))
12232 return nullptr;
12233 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12234 dyn_cast<CXXRecordDecl>(CurContext));
12235 if (TypoCorrection Corrected =
12236 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12237 CTK_ErrorRecovery)) {
12238 // We reject candidates where DroppedSpecifier == true, hence the
12239 // literal '0' below.
12240 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12241 << NameInfo.getName() << LookupContext << 0
12242 << SS.getRange());
12243
12244 // If we picked a correction with no attached Decl we can't do anything
12245 // useful with it, bail out.
12246 NamedDecl *ND = Corrected.getCorrectionDecl();
12247 if (!ND)
12248 return BuildInvalid();
12249
12250 // If we corrected to an inheriting constructor, handle it as one.
12251 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12252 if (RD && RD->isInjectedClassName()) {
12253 // The parent of the injected class name is the class itself.
12254 RD = cast<CXXRecordDecl>(RD->getParent());
12255
12256 // Fix up the information we'll use to build the using declaration.
12257 if (Corrected.WillReplaceSpecifier()) {
12258 NestedNameSpecifierLocBuilder Builder;
12259 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12260 QualifierLoc.getSourceRange());
12261 QualifierLoc = Builder.getWithLocInContext(Context);
12262 }
12263
12264 // In this case, the name we introduce is the name of a derived class
12265 // constructor.
12266 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12267 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12268 Context.getCanonicalType(Context.getRecordType(CurClass))));
12269 UsingName.setNamedTypeInfo(nullptr);
12270 for (auto *Ctor : LookupConstructors(RD))
12271 R.addDecl(Ctor);
12272 R.resolveKind();
12273 } else {
12274 // FIXME: Pick up all the declarations if we found an overloaded
12275 // function.
12276 UsingName.setName(ND->getDeclName());
12277 R.addDecl(ND);
12278 }
12279 } else {
12280 Diag(IdentLoc, diag::err_no_member)
12281 << NameInfo.getName() << LookupContext << SS.getRange();
12282 return BuildInvalid();
12283 }
12284 }
12285
12286 if (R.isAmbiguous())
12287 return BuildInvalid();
12288
12289 if (HasTypenameKeyword) {
12290 // If we asked for a typename and got a non-type decl, error out.
12291 if (!R.getAsSingle<TypeDecl>() &&
12292 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12293 Diag(IdentLoc, diag::err_using_typename_non_type);
12294 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12295 Diag((*I)->getUnderlyingDecl()->getLocation(),
12296 diag::note_using_decl_target);
12297 return BuildInvalid();
12298 }
12299 } else {
12300 // If we asked for a non-typename and we got a type, error out,
12301 // but only if this is an instantiation of an unresolved using
12302 // decl. Otherwise just silently find the type name.
12303 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12304 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12305 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12306 return BuildInvalid();
12307 }
12308 }
12309
12310 // C++14 [namespace.udecl]p6:
12311 // A using-declaration shall not name a namespace.
12312 if (R.getAsSingle<NamespaceDecl>()) {
12313 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12314 << SS.getRange();
12315 return BuildInvalid();
12316 }
12317
12318 UsingDecl *UD = BuildValid();
12319
12320 // Some additional rules apply to inheriting constructors.
12321 if (UsingName.getName().getNameKind() ==
12322 DeclarationName::CXXConstructorName) {
12323 // Suppress access diagnostics; the access check is instead performed at the
12324 // point of use for an inheriting constructor.
12325 R.suppressDiagnostics();
12326 if (CheckInheritingConstructorUsingDecl(UD))
12327 return UD;
12328 }
12329
12330 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12331 UsingShadowDecl *PrevDecl = nullptr;
12332 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12333 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12334 }
12335
12336 return UD;
12337}
12338
12339NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12340 SourceLocation UsingLoc,
12341 SourceLocation EnumLoc,
12342 SourceLocation NameLoc,
12343 EnumDecl *ED) {
12344 bool Invalid = false;
12345
12346 if (CurContext->getRedeclContext()->isRecord()) {
12347 /// In class scope, check if this is a duplicate, for better a diagnostic.
12348 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12349 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12350 ForVisibleRedeclaration);
12351
12352 LookupName(Previous, S);
12353
12354 for (NamedDecl *D : Previous)
12355 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12356 if (UED->getEnumDecl() == ED) {
12357 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12358 << SourceRange(EnumLoc, NameLoc);
12359 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12360 Invalid = true;
12361 break;
12362 }
12363 }
12364
12365 if (RequireCompleteEnumDecl(ED, NameLoc))
12366 Invalid = true;
12367
12368 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12369 EnumLoc, NameLoc, ED);
12370 UD->setAccess(AS);
12371 CurContext->addDecl(UD);
12372
12373 if (Invalid) {
12374 UD->setInvalidDecl();
12375 return UD;
12376 }
12377
12378 // Create the shadow decls for each enumerator
12379 for (EnumConstantDecl *EC : ED->enumerators()) {
12380 UsingShadowDecl *PrevDecl = nullptr;
12381 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12382 LookupResult Previous(*this, DNI, LookupOrdinaryName,
12383 ForVisibleRedeclaration);
12384 LookupName(Previous, S);
12385 FilterUsingLookup(S, Previous);
12386
12387 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12388 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12389 }
12390
12391 return UD;
12392}
12393
12394NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12395 ArrayRef<NamedDecl *> Expansions) {
12396 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||(static_cast <bool> (isa<UnresolvedUsingValueDecl>
(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(
InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom
)) ? void (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12398, __extension__ __PRETTY_FUNCTION__))
12397 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||(static_cast <bool> (isa<UnresolvedUsingValueDecl>
(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(
InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom
)) ? void (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12398, __extension__ __PRETTY_FUNCTION__))
12398 isa<UsingPackDecl>(InstantiatedFrom))(static_cast <bool> (isa<UnresolvedUsingValueDecl>
(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(
InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom
)) ? void (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12398, __extension__ __PRETTY_FUNCTION__))
;
12399
12400 auto *UPD =
12401 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12402 UPD->setAccess(InstantiatedFrom->getAccess());
12403 CurContext->addDecl(UPD);
12404 return UPD;
12405}
12406
12407/// Additional checks for a using declaration referring to a constructor name.
12408bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12409 assert(!UD->hasTypename() && "expecting a constructor name")(static_cast <bool> (!UD->hasTypename() && "expecting a constructor name"
) ? void (0) : __assert_fail ("!UD->hasTypename() && \"expecting a constructor name\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12409, __extension__ __PRETTY_FUNCTION__))
;
12410
12411 const Type *SourceType = UD->getQualifier()->getAsType();
12412 assert(SourceType &&(static_cast <bool> (SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? void (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12413, __extension__ __PRETTY_FUNCTION__))
12413 "Using decl naming constructor doesn't have type in scope spec.")(static_cast <bool> (SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? void (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12413, __extension__ __PRETTY_FUNCTION__))
;
12414 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12415
12416 // Check whether the named type is a direct base class.
12417 bool AnyDependentBases = false;
12418 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12419 AnyDependentBases);
12420 if (!Base && !AnyDependentBases) {
12421 Diag(UD->getUsingLoc(),
12422 diag::err_using_decl_constructor_not_in_direct_base)
12423 << UD->getNameInfo().getSourceRange()
12424 << QualType(SourceType, 0) << TargetClass;
12425 UD->setInvalidDecl();
12426 return true;
12427 }
12428
12429 if (Base)
12430 Base->setInheritConstructors();
12431
12432 return false;
12433}
12434
12435/// Checks that the given using declaration is not an invalid
12436/// redeclaration. Note that this is checking only for the using decl
12437/// itself, not for any ill-formedness among the UsingShadowDecls.
12438bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12439 bool HasTypenameKeyword,
12440 const CXXScopeSpec &SS,
12441 SourceLocation NameLoc,
12442 const LookupResult &Prev) {
12443 NestedNameSpecifier *Qual = SS.getScopeRep();
12444
12445 // C++03 [namespace.udecl]p8:
12446 // C++0x [namespace.udecl]p10:
12447 // A using-declaration is a declaration and can therefore be used
12448 // repeatedly where (and only where) multiple declarations are
12449 // allowed.
12450 //
12451 // That's in non-member contexts.
12452 if (!CurContext->getRedeclContext()->isRecord()) {
12453 // A dependent qualifier outside a class can only ever resolve to an
12454 // enumeration type. Therefore it conflicts with any other non-type
12455 // declaration in the same scope.
12456 // FIXME: How should we check for dependent type-type conflicts at block
12457 // scope?
12458 if (Qual->isDependent() && !HasTypenameKeyword) {
12459 for (auto *D : Prev) {
12460 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12461 bool OldCouldBeEnumerator =
12462 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12463 Diag(NameLoc,
12464 OldCouldBeEnumerator ? diag::err_redefinition
12465 : diag::err_redefinition_different_kind)
12466 << Prev.getLookupName();
12467 Diag(D->getLocation(), diag::note_previous_definition);
12468 return true;
12469 }
12470 }
12471 }
12472 return false;
12473 }
12474
12475 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12476 NamedDecl *D = *I;
12477
12478 bool DTypename;
12479 NestedNameSpecifier *DQual;
12480 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12481 DTypename = UD->hasTypename();
12482 DQual = UD->getQualifier();
12483 } else if (UnresolvedUsingValueDecl *UD
12484 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12485 DTypename = false;
12486 DQual = UD->getQualifier();
12487 } else if (UnresolvedUsingTypenameDecl *UD
12488 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12489 DTypename = true;
12490 DQual = UD->getQualifier();
12491 } else continue;
12492
12493 // using decls differ if one says 'typename' and the other doesn't.
12494 // FIXME: non-dependent using decls?
12495 if (HasTypenameKeyword != DTypename) continue;
12496
12497 // using decls differ if they name different scopes (but note that
12498 // template instantiation can cause this check to trigger when it
12499 // didn't before instantiation).
12500 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12501 Context.getCanonicalNestedNameSpecifier(DQual))
12502 continue;
12503
12504 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12505 Diag(D->getLocation(), diag::note_using_decl) << 1;
12506 return true;
12507 }
12508
12509 return false;
12510}
12511
12512/// Checks that the given nested-name qualifier used in a using decl
12513/// in the current context is appropriately related to the current
12514/// scope. If an error is found, diagnoses it and returns true.
12515/// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12516/// result of that lookup. UD is likewise nullptr, except when we have an
12517/// already-populated UsingDecl whose shadow decls contain the same information
12518/// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12519bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12520 const CXXScopeSpec &SS,
12521 const DeclarationNameInfo &NameInfo,
12522 SourceLocation NameLoc,
12523 const LookupResult *R, const UsingDecl *UD) {
12524 DeclContext *NamedContext = computeDeclContext(SS);
12525 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&(static_cast <bool> (bool(NamedContext) == (R || UD) &&
!(R && UD) && "resolvable context must have exactly one set of decls"
) ? void (0) : __assert_fail ("bool(NamedContext) == (R || UD) && !(R && UD) && \"resolvable context must have exactly one set of decls\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12526, __extension__ __PRETTY_FUNCTION__))
12526 "resolvable context must have exactly one set of decls")(static_cast <bool> (bool(NamedContext) == (R || UD) &&
!(R && UD) && "resolvable context must have exactly one set of decls"
) ? void (0) : __assert_fail ("bool(NamedContext) == (R || UD) && !(R && UD) && \"resolvable context must have exactly one set of decls\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12526, __extension__ __PRETTY_FUNCTION__))
;
12527
12528 // C++ 20 permits using an enumerator that does not have a class-hierarchy
12529 // relationship.
12530 bool Cxx20Enumerator = false;
12531 if (NamedContext) {
12532 EnumConstantDecl *EC = nullptr;
12533 if (R)
12534 EC = R->getAsSingle<EnumConstantDecl>();
12535 else if (UD && UD->shadow_size() == 1)
12536 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12537 if (EC)
12538 Cxx20Enumerator = getLangOpts().CPlusPlus20;
12539
12540 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12541 // C++14 [namespace.udecl]p7:
12542 // A using-declaration shall not name a scoped enumerator.
12543 // C++20 p1099 permits enumerators.
12544 if (EC && R && ED->isScoped())
12545 Diag(SS.getBeginLoc(),
12546 getLangOpts().CPlusPlus20
12547 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12548 : diag::ext_using_decl_scoped_enumerator)
12549 << SS.getRange();
12550
12551 // We want to consider the scope of the enumerator
12552 NamedContext = ED->getDeclContext();
12553 }
12554 }
12555
12556 if (!CurContext->isRecord()) {
12557 // C++03 [namespace.udecl]p3:
12558 // C++0x [namespace.udecl]p8:
12559 // A using-declaration for a class member shall be a member-declaration.
12560 // C++20 [namespace.udecl]p7
12561 // ... other than an enumerator ...
12562
12563 // If we weren't able to compute a valid scope, it might validly be a
12564 // dependent class or enumeration scope. If we have a 'typename' keyword,
12565 // the scope must resolve to a class type.
12566 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12567 : !HasTypename)
12568 return false; // OK
12569
12570 Diag(NameLoc,
12571 Cxx20Enumerator
12572 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12573 : diag::err_using_decl_can_not_refer_to_class_member)
12574 << SS.getRange();
12575
12576 if (Cxx20Enumerator)
12577 return false; // OK
12578
12579 auto *RD = NamedContext
12580 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12581 : nullptr;
12582 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12583 // See if there's a helpful fixit
12584
12585 if (!R) {
12586 // We will have already diagnosed the problem on the template
12587 // definition, Maybe we should do so again?
12588 } else if (R->getAsSingle<TypeDecl>()) {
12589 if (getLangOpts().CPlusPlus11) {
12590 // Convert 'using X::Y;' to 'using Y = X::Y;'.
12591 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12592 << 0 // alias declaration
12593 << FixItHint::CreateInsertion(SS.getBeginLoc(),
12594 NameInfo.getName().getAsString() +
12595 " = ");
12596 } else {
12597 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12598 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12599 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12600 << 1 // typedef declaration
12601 << FixItHint::CreateReplacement(UsingLoc, "typedef")
12602 << FixItHint::CreateInsertion(
12603 InsertLoc, " " + NameInfo.getName().getAsString());
12604 }
12605 } else if (R->getAsSingle<VarDecl>()) {
12606 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12607 // repeating the type of the static data member here.
12608 FixItHint FixIt;
12609 if (getLangOpts().CPlusPlus11) {
12610 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12611 FixIt = FixItHint::CreateReplacement(
12612 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12613 }
12614
12615 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12616 << 2 // reference declaration
12617 << FixIt;
12618 } else if (R->getAsSingle<EnumConstantDecl>()) {
12619 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12620 // repeating the type of the enumeration here, and we can't do so if
12621 // the type is anonymous.
12622 FixItHint FixIt;
12623 if (getLangOpts().CPlusPlus11) {
12624 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12625 FixIt = FixItHint::CreateReplacement(
12626 UsingLoc,
12627 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12628 }
12629
12630 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12631 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12632 << FixIt;
12633 }
12634 }
12635
12636 return true; // Fail
12637 }
12638
12639 // If the named context is dependent, we can't decide much.
12640 if (!NamedContext) {
12641 // FIXME: in C++0x, we can diagnose if we can prove that the
12642 // nested-name-specifier does not refer to a base class, which is
12643 // still possible in some cases.
12644
12645 // Otherwise we have to conservatively report that things might be
12646 // okay.
12647 return false;
12648 }
12649
12650 // The current scope is a record.
12651 if (!NamedContext->isRecord()) {
12652 // Ideally this would point at the last name in the specifier,
12653 // but we don't have that level of source info.
12654 Diag(SS.getBeginLoc(),
12655 Cxx20Enumerator
12656 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12657 : diag::err_using_decl_nested_name_specifier_is_not_class)
12658 << SS.getScopeRep() << SS.getRange();
12659
12660 if (Cxx20Enumerator)
12661 return false; // OK
12662
12663 return true;
12664 }
12665
12666 if (!NamedContext->isDependentContext() &&
12667 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12668 return true;
12669
12670 if (getLangOpts().CPlusPlus11) {
12671 // C++11 [namespace.udecl]p3:
12672 // In a using-declaration used as a member-declaration, the
12673 // nested-name-specifier shall name a base class of the class
12674 // being defined.
12675
12676 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12677 cast<CXXRecordDecl>(NamedContext))) {
12678
12679 if (Cxx20Enumerator) {
12680 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12681 << SS.getRange();
12682 return false;
12683 }
12684
12685 if (CurContext == NamedContext) {
12686 Diag(SS.getBeginLoc(),
12687 diag::err_using_decl_nested_name_specifier_is_current_class)
12688 << SS.getRange();
12689 return !getLangOpts().CPlusPlus20;
12690 }
12691
12692 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12693 Diag(SS.getBeginLoc(),
12694 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12695 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12696 << SS.getRange();
12697 }
12698 return true;
12699 }
12700
12701 return false;
12702 }
12703
12704 // C++03 [namespace.udecl]p4:
12705 // A using-declaration used as a member-declaration shall refer
12706 // to a member of a base class of the class being defined [etc.].
12707
12708 // Salient point: SS doesn't have to name a base class as long as
12709 // lookup only finds members from base classes. Therefore we can
12710 // diagnose here only if we can prove that that can't happen,
12711 // i.e. if the class hierarchies provably don't intersect.
12712
12713 // TODO: it would be nice if "definitely valid" results were cached
12714 // in the UsingDecl and UsingShadowDecl so that these checks didn't
12715 // need to be repeated.
12716
12717 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12718 auto Collect = [&Bases](const CXXRecordDecl *Base) {
12719 Bases.insert(Base);
12720 return true;
12721 };
12722
12723 // Collect all bases. Return false if we find a dependent base.
12724 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12725 return false;
12726
12727 // Returns true if the base is dependent or is one of the accumulated base
12728 // classes.
12729 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12730 return !Bases.count(Base);
12731 };
12732
12733 // Return false if the class has a dependent base or if it or one
12734 // of its bases is present in the base set of the current context.
12735 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12736 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12737 return false;
12738
12739 Diag(SS.getRange().getBegin(),
12740 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12741 << SS.getScopeRep()
12742 << cast<CXXRecordDecl>(CurContext)
12743 << SS.getRange();
12744
12745 return true;
12746}
12747
12748Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12749 MultiTemplateParamsArg TemplateParamLists,
12750 SourceLocation UsingLoc, UnqualifiedId &Name,
12751 const ParsedAttributesView &AttrList,
12752 TypeResult Type, Decl *DeclFromDeclSpec) {
12753 // Skip up to the relevant declaration scope.
12754 while (S->isTemplateParamScope())
12755 S = S->getParent();
12756 assert((S->getFlags() & Scope::DeclScope) &&(static_cast <bool> ((S->getFlags() & Scope::DeclScope
) && "got alias-declaration outside of declaration scope"
) ? void (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12757, __extension__ __PRETTY_FUNCTION__))
12757 "got alias-declaration outside of declaration scope")(static_cast <bool> ((S->getFlags() & Scope::DeclScope
) && "got alias-declaration outside of declaration scope"
) ? void (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12757, __extension__ __PRETTY_FUNCTION__))
;
12758
12759 if (Type.isInvalid())
12760 return nullptr;
12761
12762 bool Invalid = false;
12763 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12764 TypeSourceInfo *TInfo = nullptr;
12765 GetTypeFromParser(Type.get(), &TInfo);
12766
12767 if (DiagnoseClassNameShadow(CurContext, NameInfo))
12768 return nullptr;
12769
12770 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12771 UPPC_DeclarationType)) {
12772 Invalid = true;
12773 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12774 TInfo->getTypeLoc().getBeginLoc());
12775 }
12776
12777 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12778 TemplateParamLists.size()
12779 ? forRedeclarationInCurContext()
12780 : ForVisibleRedeclaration);
12781 LookupName(Previous, S);
12782
12783 // Warn about shadowing the name of a template parameter.
12784 if (Previous.isSingleResult() &&
12785 Previous.getFoundDecl()->isTemplateParameter()) {
12786 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12787 Previous.clear();
12788 }
12789
12790 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&(static_cast <bool> (Name.Kind == UnqualifiedIdKind::IK_Identifier
&& "name in alias declaration must be an identifier"
) ? void (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12791, __extension__ __PRETTY_FUNCTION__))
12791 "name in alias declaration must be an identifier")(static_cast <bool> (Name.Kind == UnqualifiedIdKind::IK_Identifier
&& "name in alias declaration must be an identifier"
) ? void (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12791, __extension__ __PRETTY_FUNCTION__))
;
12792 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12793 Name.StartLocation,
12794 Name.Identifier, TInfo);
12795
12796 NewTD->setAccess(AS);
12797
12798 if (Invalid)
12799 NewTD->setInvalidDecl();
12800
12801 ProcessDeclAttributeList(S, NewTD, AttrList);
12802 AddPragmaAttributes(S, NewTD);
12803
12804 CheckTypedefForVariablyModifiedType(S, NewTD);
12805 Invalid |= NewTD->isInvalidDecl();
12806
12807 bool Redeclaration = false;
12808
12809 NamedDecl *NewND;
12810 if (TemplateParamLists.size()) {
12811 TypeAliasTemplateDecl *OldDecl = nullptr;
12812 TemplateParameterList *OldTemplateParams = nullptr;
12813
12814 if (TemplateParamLists.size() != 1) {
12815 Diag(UsingLoc, diag::err_alias_template_extra_headers)
12816 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12817 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12818 }
12819 TemplateParameterList *TemplateParams = TemplateParamLists[0];
12820
12821 // Check that we can declare a template here.
12822 if (CheckTemplateDeclScope(S, TemplateParams))
12823 return nullptr;
12824
12825 // Only consider previous declarations in the same scope.
12826 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12827 /*ExplicitInstantiationOrSpecialization*/false);
12828 if (!Previous.empty()) {
12829 Redeclaration = true;
12830
12831 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12832 if (!OldDecl && !Invalid) {
12833 Diag(UsingLoc, diag::err_redefinition_different_kind)
12834 << Name.Identifier;
12835
12836 NamedDecl *OldD = Previous.getRepresentativeDecl();
12837 if (OldD->getLocation().isValid())
12838 Diag(OldD->getLocation(), diag::note_previous_definition);
12839
12840 Invalid = true;
12841 }
12842
12843 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12844 if (TemplateParameterListsAreEqual(TemplateParams,
12845 OldDecl->getTemplateParameters(),
12846 /*Complain=*/true,
12847 TPL_TemplateMatch))
12848 OldTemplateParams =
12849 OldDecl->getMostRecentDecl()->getTemplateParameters();
12850 else
12851 Invalid = true;
12852
12853 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12854 if (!Invalid &&
12855 !Context.hasSameType(OldTD->getUnderlyingType(),
12856 NewTD->getUnderlyingType())) {
12857 // FIXME: The C++0x standard does not clearly say this is ill-formed,
12858 // but we can't reasonably accept it.
12859 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12860 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12861 if (OldTD->getLocation().isValid())
12862 Diag(OldTD->getLocation(), diag::note_previous_definition);
12863 Invalid = true;
12864 }
12865 }
12866 }
12867
12868 // Merge any previous default template arguments into our parameters,
12869 // and check the parameter list.
12870 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12871 TPC_TypeAliasTemplate))
12872 return nullptr;
12873
12874 TypeAliasTemplateDecl *NewDecl =
12875 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12876 Name.Identifier, TemplateParams,
12877 NewTD);
12878 NewTD->setDescribedAliasTemplate(NewDecl);
12879
12880 NewDecl->setAccess(AS);
12881
12882 if (Invalid)
12883 NewDecl->setInvalidDecl();
12884 else if (OldDecl) {
12885 NewDecl->setPreviousDecl(OldDecl);
12886 CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12887 }
12888
12889 NewND = NewDecl;
12890 } else {
12891 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12892 setTagNameForLinkagePurposes(TD, NewTD);
12893 handleTagNumbering(TD, S);
12894 }
12895 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12896 NewND = NewTD;
12897 }
12898
12899 PushOnScopeChains(NewND, S);
12900 ActOnDocumentableDecl(NewND);
12901 return NewND;
12902}
12903
12904Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12905 SourceLocation AliasLoc,
12906 IdentifierInfo *Alias, CXXScopeSpec &SS,
12907 SourceLocation IdentLoc,
12908 IdentifierInfo *Ident) {
12909
12910 // Lookup the namespace name.
12911 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12912 LookupParsedName(R, S, &SS);
12913
12914 if (R.isAmbiguous())
12915 return nullptr;
12916
12917 if (R.empty()) {
12918 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12919 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12920 return nullptr;
12921 }
12922 }
12923 assert(!R.isAmbiguous() && !R.empty())(static_cast <bool> (!R.isAmbiguous() && !R.empty
()) ? void (0) : __assert_fail ("!R.isAmbiguous() && !R.empty()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 12923, __extension__ __PRETTY_FUNCTION__))
;
12924 NamedDecl *ND = R.getRepresentativeDecl();
12925
12926 // Check if we have a previous declaration with the same name.
12927 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12928 ForVisibleRedeclaration);
12929 LookupName(PrevR, S);
12930
12931 // Check we're not shadowing a template parameter.
12932 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12933 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12934 PrevR.clear();
12935 }
12936
12937 // Filter out any other lookup result from an enclosing scope.
12938 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12939 /*AllowInlineNamespace*/false);
12940
12941 // Find the previous declaration and check that we can redeclare it.
12942 NamespaceAliasDecl *Prev = nullptr;
12943 if (PrevR.isSingleResult()) {
12944 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12945 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12946 // We already have an alias with the same name that points to the same
12947 // namespace; check that it matches.
12948 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12949 Prev = AD;
12950 } else if (isVisible(PrevDecl)) {
12951 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12952 << Alias;
12953 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12954 << AD->getNamespace();
12955 return nullptr;
12956 }
12957 } else if (isVisible(PrevDecl)) {
12958 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12959 ? diag::err_redefinition
12960 : diag::err_redefinition_different_kind;
12961 Diag(AliasLoc, DiagID) << Alias;
12962 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12963 return nullptr;
12964 }
12965 }
12966
12967 // The use of a nested name specifier may trigger deprecation warnings.
12968 DiagnoseUseOfDecl(ND, IdentLoc);
12969
12970 NamespaceAliasDecl *AliasDecl =
12971 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12972 Alias, SS.getWithLocInContext(Context),
12973 IdentLoc, ND);
12974 if (Prev)
12975 AliasDecl->setPreviousDecl(Prev);
12976
12977 PushOnScopeChains(AliasDecl, S);
12978 return AliasDecl;
12979}
12980
12981namespace {
12982struct SpecialMemberExceptionSpecInfo
12983 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12984 SourceLocation Loc;
12985 Sema::ImplicitExceptionSpecification ExceptSpec;
12986
12987 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12988 Sema::CXXSpecialMember CSM,
12989 Sema::InheritedConstructorInfo *ICI,
12990 SourceLocation Loc)
12991 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12992
12993 bool visitBase(CXXBaseSpecifier *Base);
12994 bool visitField(FieldDecl *FD);
12995
12996 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12997 unsigned Quals);
12998
12999 void visitSubobjectCall(Subobject Subobj,
13000 Sema::SpecialMemberOverloadResult SMOR);
13001};
13002}
13003
13004bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13005 auto *RT = Base->getType()->getAs<RecordType>();
13006 if (!RT)
13007 return false;
13008
13009 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13010 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13011 if (auto *BaseCtor = SMOR.getMethod()) {
13012 visitSubobjectCall(Base, BaseCtor);
13013 return false;
13014 }
13015
13016 visitClassSubobject(BaseClass, Base, 0);
13017 return false;
13018}
13019
13020bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13021 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13022 Expr *E = FD->getInClassInitializer();
13023 if (!E)
13024 // FIXME: It's a little wasteful to build and throw away a
13025 // CXXDefaultInitExpr here.
13026 // FIXME: We should have a single context note pointing at Loc, and
13027 // this location should be MD->getLocation() instead, since that's
13028 // the location where we actually use the default init expression.
13029 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13030 if (E)
13031 ExceptSpec.CalledExpr(E);
13032 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13033 ->getAs<RecordType>()) {
13034 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13035 FD->getType().getCVRQualifiers());
13036 }
13037 return false;
13038}
13039
13040void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13041 Subobject Subobj,
13042 unsigned Quals) {
13043 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13044 bool IsMutable = Field && Field->isMutable();
13045 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13046}
13047
13048void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13049 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13050 // Note, if lookup fails, it doesn't matter what exception specification we
13051 // choose because the special member will be deleted.
13052 if (CXXMethodDecl *MD = SMOR.getMethod())
13053 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13054}
13055
13056bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13057 llvm::APSInt Result;
13058 ExprResult Converted = CheckConvertedConstantExpression(
13059 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13060 ExplicitSpec.setExpr(Converted.get());
13061 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13062 ExplicitSpec.setKind(Result.getBoolValue()
13063 ? ExplicitSpecKind::ResolvedTrue
13064 : ExplicitSpecKind::ResolvedFalse);
13065 return true;
13066 }
13067 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13068 return false;
13069}
13070
13071ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13072 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13073 if (!ExplicitExpr->isTypeDependent())
13074 tryResolveExplicitSpecifier(ES);
13075 return ES;
13076}
13077
13078static Sema::ImplicitExceptionSpecification
13079ComputeDefaultedSpecialMemberExceptionSpec(
13080 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13081 Sema::InheritedConstructorInfo *ICI) {
13082 ComputingExceptionSpec CES(S, MD, Loc);
13083
13084 CXXRecordDecl *ClassDecl = MD->getParent();
13085
13086 // C++ [except.spec]p14:
13087 // An implicitly declared special member function (Clause 12) shall have an
13088 // exception-specification. [...]
13089 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13090 if (ClassDecl->isInvalidDecl())
13091 return Info.ExceptSpec;
13092
13093 // FIXME: If this diagnostic fires, we're probably missing a check for
13094 // attempting to resolve an exception specification before it's known
13095 // at a higher level.
13096 if (S.RequireCompleteType(MD->getLocation(),
13097 S.Context.getRecordType(ClassDecl),
13098 diag::err_exception_spec_incomplete_type))
13099 return Info.ExceptSpec;
13100
13101 // C++1z [except.spec]p7:
13102 // [Look for exceptions thrown by] a constructor selected [...] to
13103 // initialize a potentially constructed subobject,
13104 // C++1z [except.spec]p8:
13105 // The exception specification for an implicitly-declared destructor, or a
13106 // destructor without a noexcept-specifier, is potentially-throwing if and
13107 // only if any of the destructors for any of its potentially constructed
13108 // subojects is potentially throwing.
13109 // FIXME: We respect the first rule but ignore the "potentially constructed"
13110 // in the second rule to resolve a core issue (no number yet) that would have
13111 // us reject:
13112 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13113 // struct B : A {};
13114 // struct C : B { void f(); };
13115 // ... due to giving B::~B() a non-throwing exception specification.
13116 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13117 : Info.VisitAllBases);
13118
13119 return Info.ExceptSpec;
13120}
13121
13122namespace {
13123/// RAII object to register a special member as being currently declared.
13124struct DeclaringSpecialMember {
13125 Sema &S;
13126 Sema::SpecialMemberDecl D;
13127 Sema::ContextRAII SavedContext;
13128 bool WasAlreadyBeingDeclared;
13129
13130 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13131 : S(S), D(RD, CSM), SavedContext(S, RD) {
13132 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13133 if (WasAlreadyBeingDeclared)
13134 // This almost never happens, but if it does, ensure that our cache
13135 // doesn't contain a stale result.
13136 S.SpecialMemberCache.clear();
13137 else {
13138 // Register a note to be produced if we encounter an error while
13139 // declaring the special member.
13140 Sema::CodeSynthesisContext Ctx;
13141 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13142 // FIXME: We don't have a location to use here. Using the class's
13143 // location maintains the fiction that we declare all special members
13144 // with the class, but (1) it's not clear that lying about that helps our
13145 // users understand what's going on, and (2) there may be outer contexts
13146 // on the stack (some of which are relevant) and printing them exposes
13147 // our lies.
13148 Ctx.PointOfInstantiation = RD->getLocation();
13149 Ctx.Entity = RD;
13150 Ctx.SpecialMember = CSM;
13151 S.pushCodeSynthesisContext(Ctx);
13152 }
13153 }
13154 ~DeclaringSpecialMember() {
13155 if (!WasAlreadyBeingDeclared) {
13156 S.SpecialMembersBeingDeclared.erase(D);
13157 S.popCodeSynthesisContext();
13158 }
13159 }
13160
13161 /// Are we already trying to declare this special member?
13162 bool isAlreadyBeingDeclared() const {
13163 return WasAlreadyBeingDeclared;
13164 }
13165};
13166}
13167
13168void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13169 // Look up any existing declarations, but don't trigger declaration of all
13170 // implicit special members with this name.
13171 DeclarationName Name = FD->getDeclName();
13172 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13173 ForExternalRedeclaration);
13174 for (auto *D : FD->getParent()->lookup(Name))
13175 if (auto *Acceptable = R.getAcceptableDecl(D))
13176 R.addDecl(Acceptable);
13177 R.resolveKind();
13178 R.suppressDiagnostics();
13179
13180 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
13181}
13182
13183void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13184 QualType ResultTy,
13185 ArrayRef<QualType> Args) {
13186 // Build an exception specification pointing back at this constructor.
13187 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13188
13189 LangAS AS = getDefaultCXXMethodAddrSpace();
13190 if (AS != LangAS::Default) {
13191 EPI.TypeQuals.addAddressSpace(AS);
13192 }
13193
13194 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13195 SpecialMem->setType(QT);
13196
13197 // During template instantiation of implicit special member functions we need
13198 // a reliable TypeSourceInfo for the function prototype in order to allow
13199 // functions to be substituted.
13200 if (inTemplateInstantiation() &&
13201 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13202 TypeSourceInfo *TSI =
13203 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13204 SpecialMem->setTypeSourceInfo(TSI);
13205 }
13206}
13207
13208CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13209 CXXRecordDecl *ClassDecl) {
13210 // C++ [class.ctor]p5:
13211 // A default constructor for a class X is a constructor of class X
13212 // that can be called without an argument. If there is no
13213 // user-declared constructor for class X, a default constructor is
13214 // implicitly declared. An implicitly-declared default constructor
13215 // is an inline public member of its class.
13216 assert(ClassDecl->needsImplicitDefaultConstructor() &&(static_cast <bool> (ClassDecl->needsImplicitDefaultConstructor
() && "Should not build implicit default constructor!"
) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13217, __extension__ __PRETTY_FUNCTION__))
13217 "Should not build implicit default constructor!")(static_cast <bool> (ClassDecl->needsImplicitDefaultConstructor
() && "Should not build implicit default constructor!"
) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13217, __extension__ __PRETTY_FUNCTION__))
;
13218
13219 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13220 if (DSM.isAlreadyBeingDeclared())
13221 return nullptr;
13222
13223 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13224 CXXDefaultConstructor,
13225 false);
13226
13227 // Create the actual constructor declaration.
13228 CanQualType ClassType
13229 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13230 SourceLocation ClassLoc = ClassDecl->getLocation();
13231 DeclarationName Name
13232 = Context.DeclarationNames.getCXXConstructorName(ClassType);
13233 DeclarationNameInfo NameInfo(Name, ClassLoc);
13234 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13235 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13236 /*TInfo=*/nullptr, ExplicitSpecifier(),
13237 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13238 Constexpr ? ConstexprSpecKind::Constexpr
13239 : ConstexprSpecKind::Unspecified);
13240 DefaultCon->setAccess(AS_public);
13241 DefaultCon->setDefaulted();
13242
13243 if (getLangOpts().CUDA) {
13244 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13245 DefaultCon,
13246 /* ConstRHS */ false,
13247 /* Diagnose */ false);
13248 }
13249
13250 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13251
13252 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13253 // constructors is easy to compute.
13254 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13255
13256 // Note that we have declared this constructor.
13257 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13258
13259 Scope *S = getScopeForContext(ClassDecl);
13260 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13261
13262 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13263 SetDeclDeleted(DefaultCon, ClassLoc);
13264
13265 if (S)
13266 PushOnScopeChains(DefaultCon, S, false);
13267 ClassDecl->addDecl(DefaultCon);
13268
13269 return DefaultCon;
13270}
13271
13272void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13273 CXXConstructorDecl *Constructor) {
13274 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13277, __extension__ __PRETTY_FUNCTION__))
13275 !Constructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13277, __extension__ __PRETTY_FUNCTION__))
13276 !Constructor->isDeleted()) &&(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13277, __extension__ __PRETTY_FUNCTION__))
13277 "DefineImplicitDefaultConstructor - call it for implicit default ctor")(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13277, __extension__ __PRETTY_FUNCTION__))
;
13278 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13279 return;
13280
13281 CXXRecordDecl *ClassDecl = Constructor->getParent();
13282 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor")(static_cast <bool> (ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitDefaultConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13282, __extension__ __PRETTY_FUNCTION__))
;
13283
13284 SynthesizedFunctionScope Scope(*this, Constructor);
13285
13286 // The exception specification is needed because we are defining the
13287 // function.
13288 ResolveExceptionSpec(CurrentLocation,
13289 Constructor->getType()->castAs<FunctionProtoType>());
13290 MarkVTableUsed(CurrentLocation, ClassDecl);
13291
13292 // Add a context note for diagnostics produced after this point.
13293 Scope.addContextNote(CurrentLocation);
13294
13295 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13296 Constructor->setInvalidDecl();
13297 return;
13298 }
13299
13300 SourceLocation Loc = Constructor->getEndLoc().isValid()
13301 ? Constructor->getEndLoc()
13302 : Constructor->getLocation();
13303 Constructor->setBody(new (Context) CompoundStmt(Loc));
13304 Constructor->markUsed(Context);
13305
13306 if (ASTMutationListener *L = getASTMutationListener()) {
13307 L->CompletedImplicitDefinition(Constructor);
13308 }
13309
13310 DiagnoseUninitializedFields(*this, Constructor);
13311}
13312
13313void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13314 // Perform any delayed checks on exception specifications.
13315 CheckDelayedMemberExceptionSpecs();
13316}
13317
13318/// Find or create the fake constructor we synthesize to model constructing an
13319/// object of a derived class via a constructor of a base class.
13320CXXConstructorDecl *
13321Sema::findInheritingConstructor(SourceLocation Loc,
13322 CXXConstructorDecl *BaseCtor,
13323 ConstructorUsingShadowDecl *Shadow) {
13324 CXXRecordDecl *Derived = Shadow->getParent();
13325 SourceLocation UsingLoc = Shadow->getLocation();
13326
13327 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13328 // For now we use the name of the base class constructor as a member of the
13329 // derived class to indicate a (fake) inherited constructor name.
13330 DeclarationName Name = BaseCtor->getDeclName();
13331
13332 // Check to see if we already have a fake constructor for this inherited
13333 // constructor call.
13334 for (NamedDecl *Ctor : Derived->lookup(Name))
13335 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13336 ->getInheritedConstructor()
13337 .getConstructor(),
13338 BaseCtor))
13339 return cast<CXXConstructorDecl>(Ctor);
13340
13341 DeclarationNameInfo NameInfo(Name, UsingLoc);
13342 TypeSourceInfo *TInfo =
13343 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13344 FunctionProtoTypeLoc ProtoLoc =
13345 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13346
13347 // Check the inherited constructor is valid and find the list of base classes
13348 // from which it was inherited.
13349 InheritedConstructorInfo ICI(*this, Loc, Shadow);
13350
13351 bool Constexpr =
13352 BaseCtor->isConstexpr() &&
13353 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13354 false, BaseCtor, &ICI);
13355
13356 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13357 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13358 BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13359 /*isImplicitlyDeclared=*/true,
13360 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13361 InheritedConstructor(Shadow, BaseCtor),
13362 BaseCtor->getTrailingRequiresClause());
13363 if (Shadow->isInvalidDecl())
13364 DerivedCtor->setInvalidDecl();
13365
13366 // Build an unevaluated exception specification for this fake constructor.
13367 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13368 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13369 EPI.ExceptionSpec.Type = EST_Unevaluated;
13370 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13371 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13372 FPT->getParamTypes(), EPI));
13373
13374 // Build the parameter declarations.
13375 SmallVector<ParmVarDecl *, 16> ParamDecls;
13376 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13377 TypeSourceInfo *TInfo =
13378 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13379 ParmVarDecl *PD = ParmVarDecl::Create(
13380 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13381 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13382 PD->setScopeInfo(0, I);
13383 PD->setImplicit();
13384 // Ensure attributes are propagated onto parameters (this matters for
13385 // format, pass_object_size, ...).
13386 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13387 ParamDecls.push_back(PD);
13388 ProtoLoc.setParam(I, PD);
13389 }
13390
13391 // Set up the new constructor.
13392 assert(!BaseCtor->isDeleted() && "should not use deleted constructor")(static_cast <bool> (!BaseCtor->isDeleted() &&
"should not use deleted constructor") ? void (0) : __assert_fail
("!BaseCtor->isDeleted() && \"should not use deleted constructor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13392, __extension__ __PRETTY_FUNCTION__))
;
13393 DerivedCtor->setAccess(BaseCtor->getAccess());
13394 DerivedCtor->setParams(ParamDecls);
13395 Derived->addDecl(DerivedCtor);
13396
13397 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13398 SetDeclDeleted(DerivedCtor, UsingLoc);
13399
13400 return DerivedCtor;
13401}
13402
13403void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13404 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13405 Ctor->getInheritedConstructor().getShadowDecl());
13406 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13407 /*Diagnose*/true);
13408}
13409
13410void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13411 CXXConstructorDecl *Constructor) {
13412 CXXRecordDecl *ClassDecl = Constructor->getParent();
13413 assert(Constructor->getInheritedConstructor() &&(static_cast <bool> (Constructor->getInheritedConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) ? void (0) : __assert_fail
("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13415, __extension__ __PRETTY_FUNCTION__))
13414 !Constructor->doesThisDeclarationHaveABody() &&(static_cast <bool> (Constructor->getInheritedConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) ? void (0) : __assert_fail
("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13415, __extension__ __PRETTY_FUNCTION__))
13415 !Constructor->isDeleted())(static_cast <bool> (Constructor->getInheritedConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) ? void (0) : __assert_fail
("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13415, __extension__ __PRETTY_FUNCTION__))
;
13416 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13417 return;
13418
13419 // Initializations are performed "as if by a defaulted default constructor",
13420 // so enter the appropriate scope.
13421 SynthesizedFunctionScope Scope(*this, Constructor);
13422
13423 // The exception specification is needed because we are defining the
13424 // function.
13425 ResolveExceptionSpec(CurrentLocation,
13426 Constructor->getType()->castAs<FunctionProtoType>());
13427 MarkVTableUsed(CurrentLocation, ClassDecl);
13428
13429 // Add a context note for diagnostics produced after this point.
13430 Scope.addContextNote(CurrentLocation);
13431
13432 ConstructorUsingShadowDecl *Shadow =
13433 Constructor->getInheritedConstructor().getShadowDecl();
13434 CXXConstructorDecl *InheritedCtor =
13435 Constructor->getInheritedConstructor().getConstructor();
13436
13437 // [class.inhctor.init]p1:
13438 // initialization proceeds as if a defaulted default constructor is used to
13439 // initialize the D object and each base class subobject from which the
13440 // constructor was inherited
13441
13442 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13443 CXXRecordDecl *RD = Shadow->getParent();
13444 SourceLocation InitLoc = Shadow->getLocation();
13445
13446 // Build explicit initializers for all base classes from which the
13447 // constructor was inherited.
13448 SmallVector<CXXCtorInitializer*, 8> Inits;
13449 for (bool VBase : {false, true}) {
13450 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13451 if (B.isVirtual() != VBase)
13452 continue;
13453
13454 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13455 if (!BaseRD)
13456 continue;
13457
13458 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13459 if (!BaseCtor.first)
13460 continue;
13461
13462 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13463 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13464 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13465
13466 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13467 Inits.push_back(new (Context) CXXCtorInitializer(
13468 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13469 SourceLocation()));
13470 }
13471 }
13472
13473 // We now proceed as if for a defaulted default constructor, with the relevant
13474 // initializers replaced.
13475
13476 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13477 Constructor->setInvalidDecl();
13478 return;
13479 }
13480
13481 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13482 Constructor->markUsed(Context);
13483
13484 if (ASTMutationListener *L = getASTMutationListener()) {
13485 L->CompletedImplicitDefinition(Constructor);
13486 }
13487
13488 DiagnoseUninitializedFields(*this, Constructor);
13489}
13490
13491CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13492 // C++ [class.dtor]p2:
13493 // If a class has no user-declared destructor, a destructor is
13494 // declared implicitly. An implicitly-declared destructor is an
13495 // inline public member of its class.
13496 assert(ClassDecl->needsImplicitDestructor())(static_cast <bool> (ClassDecl->needsImplicitDestructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13496, __extension__ __PRETTY_FUNCTION__))
;
13497
13498 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13499 if (DSM.isAlreadyBeingDeclared())
13500 return nullptr;
13501
13502 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13503 CXXDestructor,
13504 false);
13505
13506 // Create the actual destructor declaration.
13507 CanQualType ClassType
13508 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13509 SourceLocation ClassLoc = ClassDecl->getLocation();
13510 DeclarationName Name
13511 = Context.DeclarationNames.getCXXDestructorName(ClassType);
13512 DeclarationNameInfo NameInfo(Name, ClassLoc);
13513 CXXDestructorDecl *Destructor =
13514 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13515 QualType(), nullptr, /*isInline=*/true,
13516 /*isImplicitlyDeclared=*/true,
13517 Constexpr ? ConstexprSpecKind::Constexpr
13518 : ConstexprSpecKind::Unspecified);
13519 Destructor->setAccess(AS_public);
13520 Destructor->setDefaulted();
13521
13522 if (getLangOpts().CUDA) {
13523 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13524 Destructor,
13525 /* ConstRHS */ false,
13526 /* Diagnose */ false);
13527 }
13528
13529 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13530
13531 // We don't need to use SpecialMemberIsTrivial here; triviality for
13532 // destructors is easy to compute.
13533 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13534 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13535 ClassDecl->hasTrivialDestructorForCall());
13536
13537 // Note that we have declared this destructor.
13538 ++getASTContext().NumImplicitDestructorsDeclared;
13539
13540 Scope *S = getScopeForContext(ClassDecl);
13541 CheckImplicitSpecialMemberDeclaration(S, Destructor);
13542
13543 // We can't check whether an implicit destructor is deleted before we complete
13544 // the definition of the class, because its validity depends on the alignment
13545 // of the class. We'll check this from ActOnFields once the class is complete.
13546 if (ClassDecl->isCompleteDefinition() &&
13547 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13548 SetDeclDeleted(Destructor, ClassLoc);
13549
13550 // Introduce this destructor into its scope.
13551 if (S)
13552 PushOnScopeChains(Destructor, S, false);
13553 ClassDecl->addDecl(Destructor);
13554
13555 return Destructor;
13556}
13557
13558void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13559 CXXDestructorDecl *Destructor) {
13560 assert((Destructor->isDefaulted() &&(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13563, __extension__ __PRETTY_FUNCTION__))
13561 !Destructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13563, __extension__ __PRETTY_FUNCTION__))
13562 !Destructor->isDeleted()) &&(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13563, __extension__ __PRETTY_FUNCTION__))
13563 "DefineImplicitDestructor - call it for implicit default dtor")(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13563, __extension__ __PRETTY_FUNCTION__))
;
13564 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13565 return;
13566
13567 CXXRecordDecl *ClassDecl = Destructor->getParent();
13568 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor")(static_cast <bool> (ClassDecl && "DefineImplicitDestructor - invalid destructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitDestructor - invalid destructor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13568, __extension__ __PRETTY_FUNCTION__))
;
13569
13570 SynthesizedFunctionScope Scope(*this, Destructor);
13571
13572 // The exception specification is needed because we are defining the
13573 // function.
13574 ResolveExceptionSpec(CurrentLocation,
13575 Destructor->getType()->castAs<FunctionProtoType>());
13576 MarkVTableUsed(CurrentLocation, ClassDecl);
13577
13578 // Add a context note for diagnostics produced after this point.
13579 Scope.addContextNote(CurrentLocation);
13580
13581 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13582 Destructor->getParent());
13583
13584 if (CheckDestructor(Destructor)) {
13585 Destructor->setInvalidDecl();
13586 return;
13587 }
13588
13589 SourceLocation Loc = Destructor->getEndLoc().isValid()
13590 ? Destructor->getEndLoc()
13591 : Destructor->getLocation();
13592 Destructor->setBody(new (Context) CompoundStmt(Loc));
13593 Destructor->markUsed(Context);
13594
13595 if (ASTMutationListener *L = getASTMutationListener()) {
13596 L->CompletedImplicitDefinition(Destructor);
13597 }
13598}
13599
13600void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13601 CXXDestructorDecl *Destructor) {
13602 if (Destructor->isInvalidDecl())
13603 return;
13604
13605 CXXRecordDecl *ClassDecl = Destructor->getParent();
13606 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&(static_cast <bool> (Context.getTargetInfo().getCXXABI(
).isMicrosoft() && "implicit complete dtors unneeded outside MS ABI"
) ? void (0) : __assert_fail ("Context.getTargetInfo().getCXXABI().isMicrosoft() && \"implicit complete dtors unneeded outside MS ABI\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13607, __extension__ __PRETTY_FUNCTION__))
13607 "implicit complete dtors unneeded outside MS ABI")(static_cast <bool> (Context.getTargetInfo().getCXXABI(
).isMicrosoft() && "implicit complete dtors unneeded outside MS ABI"
) ? void (0) : __assert_fail ("Context.getTargetInfo().getCXXABI().isMicrosoft() && \"implicit complete dtors unneeded outside MS ABI\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13607, __extension__ __PRETTY_FUNCTION__))
;
13608 assert(ClassDecl->getNumVBases() > 0 &&(static_cast <bool> (ClassDecl->getNumVBases() > 0
&& "complete dtor only exists for classes with vbases"
) ? void (0) : __assert_fail ("ClassDecl->getNumVBases() > 0 && \"complete dtor only exists for classes with vbases\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13609, __extension__ __PRETTY_FUNCTION__))
13609 "complete dtor only exists for classes with vbases")(static_cast <bool> (ClassDecl->getNumVBases() > 0
&& "complete dtor only exists for classes with vbases"
) ? void (0) : __assert_fail ("ClassDecl->getNumVBases() > 0 && \"complete dtor only exists for classes with vbases\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13609, __extension__ __PRETTY_FUNCTION__))
;
13610
13611 SynthesizedFunctionScope Scope(*this, Destructor);
13612
13613 // Add a context note for diagnostics produced after this point.
13614 Scope.addContextNote(CurrentLocation);
13615
13616 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13617}
13618
13619/// Perform any semantic analysis which needs to be delayed until all
13620/// pending class member declarations have been parsed.
13621void Sema::ActOnFinishCXXMemberDecls() {
13622 // If the context is an invalid C++ class, just suppress these checks.
13623 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13624 if (Record->isInvalidDecl()) {
13625 DelayedOverridingExceptionSpecChecks.clear();
13626 DelayedEquivalentExceptionSpecChecks.clear();
13627 return;
13628 }
13629 checkForMultipleExportedDefaultConstructors(*this, Record);
13630 }
13631}
13632
13633void Sema::ActOnFinishCXXNonNestedClass() {
13634 referenceDLLExportedClassMethods();
13635
13636 if (!DelayedDllExportMemberFunctions.empty()) {
13637 SmallVector<CXXMethodDecl*, 4> WorkList;
13638 std::swap(DelayedDllExportMemberFunctions, WorkList);
13639 for (CXXMethodDecl *M : WorkList) {
13640 DefineDefaultedFunction(*this, M, M->getLocation());
13641
13642 // Pass the method to the consumer to get emitted. This is not necessary
13643 // for explicit instantiation definitions, as they will get emitted
13644 // anyway.
13645 if (M->getParent()->getTemplateSpecializationKind() !=
13646 TSK_ExplicitInstantiationDefinition)
13647 ActOnFinishInlineFunctionDef(M);
13648 }
13649 }
13650}
13651
13652void Sema::referenceDLLExportedClassMethods() {
13653 if (!DelayedDllExportClasses.empty()) {
13654 // Calling ReferenceDllExportedMembers might cause the current function to
13655 // be called again, so use a local copy of DelayedDllExportClasses.
13656 SmallVector<CXXRecordDecl *, 4> WorkList;
13657 std::swap(DelayedDllExportClasses, WorkList);
13658 for (CXXRecordDecl *Class : WorkList)
13659 ReferenceDllExportedMembers(*this, Class);
13660 }
13661}
13662
13663void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13664 assert(getLangOpts().CPlusPlus11 &&(static_cast <bool> (getLangOpts().CPlusPlus11 &&
"adjusting dtor exception specs was introduced in c++11") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13665, __extension__ __PRETTY_FUNCTION__))
13665 "adjusting dtor exception specs was introduced in c++11")(static_cast <bool> (getLangOpts().CPlusPlus11 &&
"adjusting dtor exception specs was introduced in c++11") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13665, __extension__ __PRETTY_FUNCTION__))
;
13666
13667 if (Destructor->isDependentContext())
13668 return;
13669
13670 // C++11 [class.dtor]p3:
13671 // A declaration of a destructor that does not have an exception-
13672 // specification is implicitly considered to have the same exception-
13673 // specification as an implicit declaration.
13674 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13675 if (DtorType->hasExceptionSpec())
13676 return;
13677
13678 // Replace the destructor's type, building off the existing one. Fortunately,
13679 // the only thing of interest in the destructor type is its extended info.
13680 // The return and arguments are fixed.
13681 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13682 EPI.ExceptionSpec.Type = EST_Unevaluated;
13683 EPI.ExceptionSpec.SourceDecl = Destructor;
13684 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13685
13686 // FIXME: If the destructor has a body that could throw, and the newly created
13687 // spec doesn't allow exceptions, we should emit a warning, because this
13688 // change in behavior can break conforming C++03 programs at runtime.
13689 // However, we don't have a body or an exception specification yet, so it
13690 // needs to be done somewhere else.
13691}
13692
13693namespace {
13694/// An abstract base class for all helper classes used in building the
13695// copy/move operators. These classes serve as factory functions and help us
13696// avoid using the same Expr* in the AST twice.
13697class ExprBuilder {
13698 ExprBuilder(const ExprBuilder&) = delete;
13699 ExprBuilder &operator=(const ExprBuilder&) = delete;
13700
13701protected:
13702 static Expr *assertNotNull(Expr *E) {
13703 assert(E && "Expression construction must not fail.")(static_cast <bool> (E && "Expression construction must not fail."
) ? void (0) : __assert_fail ("E && \"Expression construction must not fail.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13703, __extension__ __PRETTY_FUNCTION__))
;
13704 return E;
13705 }
13706
13707public:
13708 ExprBuilder() {}
13709 virtual ~ExprBuilder() {}
13710
13711 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13712};
13713
13714class RefBuilder: public ExprBuilder {
13715 VarDecl *Var;
13716 QualType VarType;
13717
13718public:
13719 Expr *build(Sema &S, SourceLocation Loc) const override {
13720 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13721 }
13722
13723 RefBuilder(VarDecl *Var, QualType VarType)
13724 : Var(Var), VarType(VarType) {}
13725};
13726
13727class ThisBuilder: public ExprBuilder {
13728public:
13729 Expr *build(Sema &S, SourceLocation Loc) const override {
13730 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13731 }
13732};
13733
13734class CastBuilder: public ExprBuilder {
13735 const ExprBuilder &Builder;
13736 QualType Type;
13737 ExprValueKind Kind;
13738 const CXXCastPath &Path;
13739
13740public:
13741 Expr *build(Sema &S, SourceLocation Loc) const override {
13742 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13743 CK_UncheckedDerivedToBase, Kind,
13744 &Path).get());
13745 }
13746
13747 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13748 const CXXCastPath &Path)
13749 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13750};
13751
13752class DerefBuilder: public ExprBuilder {
13753 const ExprBuilder &Builder;
13754
13755public:
13756 Expr *build(Sema &S, SourceLocation Loc) const override {
13757 return assertNotNull(
13758 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13759 }
13760
13761 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13762};
13763
13764class MemberBuilder: public ExprBuilder {
13765 const ExprBuilder &Builder;
13766 QualType Type;
13767 CXXScopeSpec SS;
13768 bool IsArrow;
13769 LookupResult &MemberLookup;
13770
13771public:
13772 Expr *build(Sema &S, SourceLocation Loc) const override {
13773 return assertNotNull(S.BuildMemberReferenceExpr(
13774 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13775 nullptr, MemberLookup, nullptr, nullptr).get());
13776 }
13777
13778 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13779 LookupResult &MemberLookup)
13780 : Builder(Builder), Type(Type), IsArrow(IsArrow),
13781 MemberLookup(MemberLookup) {}
13782};
13783
13784class MoveCastBuilder: public ExprBuilder {
13785 const ExprBuilder &Builder;
13786
13787public:
13788 Expr *build(Sema &S, SourceLocation Loc) const override {
13789 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13790 }
13791
13792 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13793};
13794
13795class LvalueConvBuilder: public ExprBuilder {
13796 const ExprBuilder &Builder;
13797
13798public:
13799 Expr *build(Sema &S, SourceLocation Loc) const override {
13800 return assertNotNull(
13801 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13802 }
13803
13804 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13805};
13806
13807class SubscriptBuilder: public ExprBuilder {
13808 const ExprBuilder &Base;
13809 const ExprBuilder &Index;
13810
13811public:
13812 Expr *build(Sema &S, SourceLocation Loc) const override {
13813 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13814 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13815 }
13816
13817 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13818 : Base(Base), Index(Index) {}
13819};
13820
13821} // end anonymous namespace
13822
13823/// When generating a defaulted copy or move assignment operator, if a field
13824/// should be copied with __builtin_memcpy rather than via explicit assignments,
13825/// do so. This optimization only applies for arrays of scalars, and for arrays
13826/// of class type where the selected copy/move-assignment operator is trivial.
13827static StmtResult
13828buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13829 const ExprBuilder &ToB, const ExprBuilder &FromB) {
13830 // Compute the size of the memory buffer to be copied.
13831 QualType SizeType = S.Context.getSizeType();
13832 llvm::APInt Size(S.Context.getTypeSize(SizeType),
13833 S.Context.getTypeSizeInChars(T).getQuantity());
13834
13835 // Take the address of the field references for "from" and "to". We
13836 // directly construct UnaryOperators here because semantic analysis
13837 // does not permit us to take the address of an xvalue.
13838 Expr *From = FromB.build(S, Loc);
13839 From = UnaryOperator::Create(
13840 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13841 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13842 Expr *To = ToB.build(S, Loc);
13843 To = UnaryOperator::Create(
13844 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13845 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13846
13847 const Type *E = T->getBaseElementTypeUnsafe();
13848 bool NeedsCollectableMemCpy =
13849 E->isRecordType() &&
13850 E->castAs<RecordType>()->getDecl()->hasObjectMember();
13851
13852 // Create a reference to the __builtin_objc_memmove_collectable function
13853 StringRef MemCpyName = NeedsCollectableMemCpy ?
13854 "__builtin_objc_memmove_collectable" :
13855 "__builtin_memcpy";
13856 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13857 Sema::LookupOrdinaryName);
13858 S.LookupName(R, S.TUScope, true);
13859
13860 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13861 if (!MemCpy)
13862 // Something went horribly wrong earlier, and we will have complained
13863 // about it.
13864 return StmtError();
13865
13866 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13867 VK_PRValue, Loc, nullptr);
13868 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail")(static_cast <bool> (MemCpyRef.isUsable() && "Builtin reference cannot fail"
) ? void (0) : __assert_fail ("MemCpyRef.isUsable() && \"Builtin reference cannot fail\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13868, __extension__ __PRETTY_FUNCTION__))
;
13869
13870 Expr *CallArgs[] = {
13871 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13872 };
13873 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13874 Loc, CallArgs, Loc);
13875
13876 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!")(static_cast <bool> (!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"
) ? void (0) : __assert_fail ("!Call.isInvalid() && \"Call to __builtin_memcpy cannot fail!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 13876, __extension__ __PRETTY_FUNCTION__))
;
13877 return Call.getAs<Stmt>();
13878}
13879
13880/// Builds a statement that copies/moves the given entity from \p From to
13881/// \c To.
13882///
13883/// This routine is used to copy/move the members of a class with an
13884/// implicitly-declared copy/move assignment operator. When the entities being
13885/// copied are arrays, this routine builds for loops to copy them.
13886///
13887/// \param S The Sema object used for type-checking.
13888///
13889/// \param Loc The location where the implicit copy/move is being generated.
13890///
13891/// \param T The type of the expressions being copied/moved. Both expressions
13892/// must have this type.
13893///
13894/// \param To The expression we are copying/moving to.
13895///
13896/// \param From The expression we are copying/moving from.
13897///
13898/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13899/// Otherwise, it's a non-static member subobject.
13900///
13901/// \param Copying Whether we're copying or moving.
13902///
13903/// \param Depth Internal parameter recording the depth of the recursion.
13904///
13905/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13906/// if a memcpy should be used instead.
13907static StmtResult
13908buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13909 const ExprBuilder &To, const ExprBuilder &From,
13910 bool CopyingBaseSubobject, bool Copying,
13911 unsigned Depth = 0) {
13912 // C++11 [class.copy]p28:
13913 // Each subobject is assigned in the manner appropriate to its type:
13914 //
13915 // - if the subobject is of class type, as if by a call to operator= with
13916 // the subobject as the object expression and the corresponding
13917 // subobject of x as a single function argument (as if by explicit
13918 // qualification; that is, ignoring any possible virtual overriding
13919 // functions in more derived classes);
13920 //
13921 // C++03 [class.copy]p13:
13922 // - if the subobject is of class type, the copy assignment operator for
13923 // the class is used (as if by explicit qualification; that is,
13924 // ignoring any possible virtual overriding functions in more derived
13925 // classes);
13926 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13927 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13928
13929 // Look for operator=.
13930 DeclarationName Name
13931 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13932 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13933 S.LookupQualifiedName(OpLookup, ClassDecl, false);
13934
13935 // Prior to C++11, filter out any result that isn't a copy/move-assignment
13936 // operator.
13937 if (!S.getLangOpts().CPlusPlus11) {
13938 LookupResult::Filter F = OpLookup.makeFilter();
13939 while (F.hasNext()) {
13940 NamedDecl *D = F.next();
13941 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13942 if (Method->isCopyAssignmentOperator() ||
13943 (!Copying && Method->isMoveAssignmentOperator()))
13944 continue;
13945
13946 F.erase();
13947 }
13948 F.done();
13949 }
13950
13951 // Suppress the protected check (C++ [class.protected]) for each of the
13952 // assignment operators we found. This strange dance is required when
13953 // we're assigning via a base classes's copy-assignment operator. To
13954 // ensure that we're getting the right base class subobject (without
13955 // ambiguities), we need to cast "this" to that subobject type; to
13956 // ensure that we don't go through the virtual call mechanism, we need
13957 // to qualify the operator= name with the base class (see below). However,
13958 // this means that if the base class has a protected copy assignment
13959 // operator, the protected member access check will fail. So, we
13960 // rewrite "protected" access to "public" access in this case, since we
13961 // know by construction that we're calling from a derived class.
13962 if (CopyingBaseSubobject) {
13963 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13964 L != LEnd; ++L) {
13965 if (L.getAccess() == AS_protected)
13966 L.setAccess(AS_public);
13967 }
13968 }
13969
13970 // Create the nested-name-specifier that will be used to qualify the
13971 // reference to operator=; this is required to suppress the virtual
13972 // call mechanism.
13973 CXXScopeSpec SS;
13974 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13975 SS.MakeTrivial(S.Context,
13976 NestedNameSpecifier::Create(S.Context, nullptr, false,
13977 CanonicalT),
13978 Loc);
13979
13980 // Create the reference to operator=.
13981 ExprResult OpEqualRef
13982 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13983 SS, /*TemplateKWLoc=*/SourceLocation(),
13984 /*FirstQualifierInScope=*/nullptr,
13985 OpLookup,
13986 /*TemplateArgs=*/nullptr, /*S*/nullptr,
13987 /*SuppressQualifierCheck=*/true);
13988 if (OpEqualRef.isInvalid())
13989 return StmtError();
13990
13991 // Build the call to the assignment operator.
13992
13993 Expr *FromInst = From.build(S, Loc);
13994 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13995 OpEqualRef.getAs<Expr>(),
13996 Loc, FromInst, Loc);
13997 if (Call.isInvalid())
13998 return StmtError();
13999
14000 // If we built a call to a trivial 'operator=' while copying an array,
14001 // bail out. We'll replace the whole shebang with a memcpy.
14002 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14003 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14004 return StmtResult((Stmt*)nullptr);
14005
14006 // Convert to an expression-statement, and clean up any produced
14007 // temporaries.
14008 return S.ActOnExprStmt(Call);
14009 }
14010
14011 // - if the subobject is of scalar type, the built-in assignment
14012 // operator is used.
14013 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14014 if (!ArrayTy) {
14015 ExprResult Assignment = S.CreateBuiltinBinOp(
14016 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14017 if (Assignment.isInvalid())
14018 return StmtError();
14019 return S.ActOnExprStmt(Assignment);
14020 }
14021
14022 // - if the subobject is an array, each element is assigned, in the
14023 // manner appropriate to the element type;
14024
14025 // Construct a loop over the array bounds, e.g.,
14026 //
14027 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14028 //
14029 // that will copy each of the array elements.
14030 QualType SizeType = S.Context.getSizeType();
14031
14032 // Create the iteration variable.
14033 IdentifierInfo *IterationVarName = nullptr;
14034 {
14035 SmallString<8> Str;
14036 llvm::raw_svector_ostream OS(Str);
14037 OS << "__i" << Depth;
14038 IterationVarName = &S.Context.Idents.get(OS.str());
14039 }
14040 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14041 IterationVarName, SizeType,
14042 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14043 SC_None);
14044
14045 // Initialize the iteration variable to zero.
14046 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14047 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14048
14049 // Creates a reference to the iteration variable.
14050 RefBuilder IterationVarRef(IterationVar, SizeType);
14051 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14052
14053 // Create the DeclStmt that holds the iteration variable.
14054 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14055
14056 // Subscript the "from" and "to" expressions with the iteration variable.
14057 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14058 MoveCastBuilder FromIndexMove(FromIndexCopy);
14059 const ExprBuilder *FromIndex;
14060 if (Copying)
14061 FromIndex = &FromIndexCopy;
14062 else
14063 FromIndex = &FromIndexMove;
14064
14065 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14066
14067 // Build the copy/move for an individual element of the array.
14068 StmtResult Copy =
14069 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14070 ToIndex, *FromIndex, CopyingBaseSubobject,
14071 Copying, Depth + 1);
14072 // Bail out if copying fails or if we determined that we should use memcpy.
14073 if (Copy.isInvalid() || !Copy.get())
14074 return Copy;
14075
14076 // Create the comparison against the array bound.
14077 llvm::APInt Upper
14078 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14079 Expr *Comparison = BinaryOperator::Create(
14080 S.Context, IterationVarRefRVal.build(S, Loc),
14081 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14082 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14083 S.CurFPFeatureOverrides());
14084
14085 // Create the pre-increment of the iteration variable. We can determine
14086 // whether the increment will overflow based on the value of the array
14087 // bound.
14088 Expr *Increment = UnaryOperator::Create(
14089 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14090 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14091
14092 // Construct the loop that copies all elements of this array.
14093 return S.ActOnForStmt(
14094 Loc, Loc, InitStmt,
14095 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14096 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14097}
14098
14099static StmtResult
14100buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14101 const ExprBuilder &To, const ExprBuilder &From,
14102 bool CopyingBaseSubobject, bool Copying) {
14103 // Maybe we should use a memcpy?
14104 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14105 T.isTriviallyCopyableType(S.Context))
14106 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14107
14108 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14109 CopyingBaseSubobject,
14110 Copying, 0));
14111
14112 // If we ended up picking a trivial assignment operator for an array of a
14113 // non-trivially-copyable class type, just emit a memcpy.
14114 if (!Result.isInvalid() && !Result.get())
14115 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14116
14117 return Result;
14118}
14119
14120CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14121 // Note: The following rules are largely analoguous to the copy
14122 // constructor rules. Note that virtual bases are not taken into account
14123 // for determining the argument type of the operator. Note also that
14124 // operators taking an object instead of a reference are allowed.
14125 assert(ClassDecl->needsImplicitCopyAssignment())(static_cast <bool> (ClassDecl->needsImplicitCopyAssignment
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14125, __extension__ __PRETTY_FUNCTION__))
;
14126
14127 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14128 if (DSM.isAlreadyBeingDeclared())
14129 return nullptr;
14130
14131 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14132 LangAS AS = getDefaultCXXMethodAddrSpace();
14133 if (AS != LangAS::Default)
14134 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14135 QualType RetType = Context.getLValueReferenceType(ArgType);
14136 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14137 if (Const)
14138 ArgType = ArgType.withConst();
14139
14140 ArgType = Context.getLValueReferenceType(ArgType);
14141
14142 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14143 CXXCopyAssignment,
14144 Const);
14145
14146 // An implicitly-declared copy assignment operator is an inline public
14147 // member of its class.
14148 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14149 SourceLocation ClassLoc = ClassDecl->getLocation();
14150 DeclarationNameInfo NameInfo(Name, ClassLoc);
14151 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14152 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14153 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14154 /*isInline=*/true,
14155 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14156 SourceLocation());
14157 CopyAssignment->setAccess(AS_public);
14158 CopyAssignment->setDefaulted();
14159 CopyAssignment->setImplicit();
14160
14161 if (getLangOpts().CUDA) {
14162 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14163 CopyAssignment,
14164 /* ConstRHS */ Const,
14165 /* Diagnose */ false);
14166 }
14167
14168 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14169
14170 // Add the parameter to the operator.
14171 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14172 ClassLoc, ClassLoc,
14173 /*Id=*/nullptr, ArgType,
14174 /*TInfo=*/nullptr, SC_None,
14175 nullptr);
14176 CopyAssignment->setParams(FromParam);
14177
14178 CopyAssignment->setTrivial(
14179 ClassDecl->needsOverloadResolutionForCopyAssignment()
14180 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14181 : ClassDecl->hasTrivialCopyAssignment());
14182
14183 // Note that we have added this copy-assignment operator.
14184 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14185
14186 Scope *S = getScopeForContext(ClassDecl);
14187 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14188
14189 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14190 ClassDecl->setImplicitCopyAssignmentIsDeleted();
14191 SetDeclDeleted(CopyAssignment, ClassLoc);
14192 }
14193
14194 if (S)
14195 PushOnScopeChains(CopyAssignment, S, false);
14196 ClassDecl->addDecl(CopyAssignment);
14197
14198 return CopyAssignment;
14199}
14200
14201/// Diagnose an implicit copy operation for a class which is odr-used, but
14202/// which is deprecated because the class has a user-declared copy constructor,
14203/// copy assignment operator, or destructor.
14204static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14205 assert(CopyOp->isImplicit())(static_cast <bool> (CopyOp->isImplicit()) ? void (0
) : __assert_fail ("CopyOp->isImplicit()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14205, __extension__ __PRETTY_FUNCTION__))
;
14206
14207 CXXRecordDecl *RD = CopyOp->getParent();
14208 CXXMethodDecl *UserDeclaredOperation = nullptr;
14209
14210 // In Microsoft mode, assignment operations don't affect constructors and
14211 // vice versa.
14212 if (RD->hasUserDeclaredDestructor()) {
14213 UserDeclaredOperation = RD->getDestructor();
14214 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14215 RD->hasUserDeclaredCopyConstructor() &&
14216 !S.getLangOpts().MSVCCompat) {
14217 // Find any user-declared copy constructor.
14218 for (auto *I : RD->ctors()) {
14219 if (I->isCopyConstructor()) {
14220 UserDeclaredOperation = I;
14221 break;
14222 }
14223 }
14224 assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) :
__assert_fail ("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14224, __extension__ __PRETTY_FUNCTION__))
;
14225 } else if (isa<CXXConstructorDecl>(CopyOp) &&
14226 RD->hasUserDeclaredCopyAssignment() &&
14227 !S.getLangOpts().MSVCCompat) {
14228 // Find any user-declared move assignment operator.
14229 for (auto *I : RD->methods()) {
14230 if (I->isCopyAssignmentOperator()) {
14231 UserDeclaredOperation = I;
14232 break;
14233 }
14234 }
14235 assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) :
__assert_fail ("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14235, __extension__ __PRETTY_FUNCTION__))
;
14236 }
14237
14238 if (UserDeclaredOperation) {
14239 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14240 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14241 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14242 unsigned DiagID =
14243 (UDOIsUserProvided && UDOIsDestructor)
14244 ? diag::warn_deprecated_copy_with_user_provided_dtor
14245 : (UDOIsUserProvided && !UDOIsDestructor)
14246 ? diag::warn_deprecated_copy_with_user_provided_copy
14247 : (!UDOIsUserProvided && UDOIsDestructor)
14248 ? diag::warn_deprecated_copy_with_dtor
14249 : diag::warn_deprecated_copy;
14250 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14251 << RD << IsCopyAssignment;
14252 }
14253}
14254
14255void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14256 CXXMethodDecl *CopyAssignOperator) {
14257 assert((CopyAssignOperator->isDefaulted() &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? 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-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14262, __extension__ __PRETTY_FUNCTION__))
14258 CopyAssignOperator->isOverloadedOperator() &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? 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-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14262, __extension__ __PRETTY_FUNCTION__))
14259 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? 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-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14262, __extension__ __PRETTY_FUNCTION__))
14260 !CopyAssignOperator->doesThisDeclarationHaveABody() &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? 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-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14262, __extension__ __PRETTY_FUNCTION__))
14261 !CopyAssignOperator->isDeleted()) &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? 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-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14262, __extension__ __PRETTY_FUNCTION__))
14262 "DefineImplicitCopyAssignment called for wrong function")(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? 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-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14262, __extension__ __PRETTY_FUNCTION__))
;
14263 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14264 return;
14265
14266 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14267 if (ClassDecl->isInvalidDecl()) {
14268 CopyAssignOperator->setInvalidDecl();
14269 return;
14270 }
14271
14272 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14273
14274 // The exception specification is needed because we are defining the
14275 // function.
14276 ResolveExceptionSpec(CurrentLocation,
14277 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14278
14279 // Add a context note for diagnostics produced after this point.
14280 Scope.addContextNote(CurrentLocation);
14281
14282 // C++11 [class.copy]p18:
14283 // The [definition of an implicitly declared copy assignment operator] is
14284 // deprecated if the class has a user-declared copy constructor or a
14285 // user-declared destructor.
14286 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14287 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14288
14289 // C++0x [class.copy]p30:
14290 // The implicitly-defined or explicitly-defaulted copy assignment operator
14291 // for a non-union class X performs memberwise copy assignment of its
14292 // subobjects. The direct base classes of X are assigned first, in the
14293 // order of their declaration in the base-specifier-list, and then the
14294 // immediate non-static data members of X are assigned, in the order in
14295 // which they were declared in the class definition.
14296
14297 // The statements that form the synthesized function body.
14298 SmallVector<Stmt*, 8> Statements;
14299
14300 // The parameter for the "other" object, which we are copying from.
14301 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14302 Qualifiers OtherQuals = Other->getType().getQualifiers();
14303 QualType OtherRefType = Other->getType();
14304 if (const LValueReferenceType *OtherRef
14305 = OtherRefType->getAs<LValueReferenceType>()) {
14306 OtherRefType = OtherRef->getPointeeType();
14307 OtherQuals = OtherRefType.getQualifiers();
14308 }
14309
14310 // Our location for everything implicitly-generated.
14311 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14312 ? CopyAssignOperator->getEndLoc()
14313 : CopyAssignOperator->getLocation();
14314
14315 // Builds a DeclRefExpr for the "other" object.
14316 RefBuilder OtherRef(Other, OtherRefType);
14317
14318 // Builds the "this" pointer.
14319 ThisBuilder This;
14320
14321 // Assign base classes.
14322 bool Invalid = false;
14323 for (auto &Base : ClassDecl->bases()) {
14324 // Form the assignment:
14325 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14326 QualType BaseType = Base.getType().getUnqualifiedType();
14327 if (!BaseType->isRecordType()) {
14328 Invalid = true;
14329 continue;
14330 }
14331
14332 CXXCastPath BasePath;
14333 BasePath.push_back(&Base);
14334
14335 // Construct the "from" expression, which is an implicit cast to the
14336 // appropriately-qualified base type.
14337 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14338 VK_LValue, BasePath);
14339
14340 // Dereference "this".
14341 DerefBuilder DerefThis(This);
14342 CastBuilder To(DerefThis,
14343 Context.getQualifiedType(
14344 BaseType, CopyAssignOperator->getMethodQualifiers()),
14345 VK_LValue, BasePath);
14346
14347 // Build the copy.
14348 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14349 To, From,
14350 /*CopyingBaseSubobject=*/true,
14351 /*Copying=*/true);
14352 if (Copy.isInvalid()) {
14353 CopyAssignOperator->setInvalidDecl();
14354 return;
14355 }
14356
14357 // Success! Record the copy.
14358 Statements.push_back(Copy.getAs<Expr>());
14359 }
14360
14361 // Assign non-static members.
14362 for (auto *Field : ClassDecl->fields()) {
14363 // FIXME: We should form some kind of AST representation for the implied
14364 // memcpy in a union copy operation.
14365 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14366 continue;
14367
14368 if (Field->isInvalidDecl()) {
14369 Invalid = true;
14370 continue;
14371 }
14372
14373 // Check for members of reference type; we can't copy those.
14374 if (Field->getType()->isReferenceType()) {
14375 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14376 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14377 Diag(Field->getLocation(), diag::note_declared_at);
14378 Invalid = true;
14379 continue;
14380 }
14381
14382 // Check for members of const-qualified, non-class type.
14383 QualType BaseType = Context.getBaseElementType(Field->getType());
14384 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14385 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14386 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14387 Diag(Field->getLocation(), diag::note_declared_at);
14388 Invalid = true;
14389 continue;
14390 }
14391
14392 // Suppress assigning zero-width bitfields.
14393 if (Field->isZeroLengthBitField(Context))
14394 continue;
14395
14396 QualType FieldType = Field->getType().getNonReferenceType();
14397 if (FieldType->isIncompleteArrayType()) {
14398 assert(ClassDecl->hasFlexibleArrayMember() &&(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14399, __extension__ __PRETTY_FUNCTION__))
14399 "Incomplete array type is not valid")(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14399, __extension__ __PRETTY_FUNCTION__))
;
14400 continue;
14401 }
14402
14403 // Build references to the field in the object we're copying from and to.
14404 CXXScopeSpec SS; // Intentionally empty
14405 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14406 LookupMemberName);
14407 MemberLookup.addDecl(Field);
14408 MemberLookup.resolveKind();
14409
14410 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14411
14412 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14413
14414 // Build the copy of this field.
14415 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14416 To, From,
14417 /*CopyingBaseSubobject=*/false,
14418 /*Copying=*/true);
14419 if (Copy.isInvalid()) {
14420 CopyAssignOperator->setInvalidDecl();
14421 return;
14422 }
14423
14424 // Success! Record the copy.
14425 Statements.push_back(Copy.getAs<Stmt>());
14426 }
14427
14428 if (!Invalid) {
14429 // Add a "return *this;"
14430 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14431
14432 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14433 if (Return.isInvalid())
14434 Invalid = true;
14435 else
14436 Statements.push_back(Return.getAs<Stmt>());
14437 }
14438
14439 if (Invalid) {
14440 CopyAssignOperator->setInvalidDecl();
14441 return;
14442 }
14443
14444 StmtResult Body;
14445 {
14446 CompoundScopeRAII CompoundScope(*this);
14447 Body = ActOnCompoundStmt(Loc, Loc, Statements,
14448 /*isStmtExpr=*/false);
14449 assert(!Body.isInvalid() && "Compound statement creation cannot fail")(static_cast <bool> (!Body.isInvalid() && "Compound statement creation cannot fail"
) ? void (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14449, __extension__ __PRETTY_FUNCTION__))
;
14450 }
14451 CopyAssignOperator->setBody(Body.getAs<Stmt>());
14452 CopyAssignOperator->markUsed(Context);
14453
14454 if (ASTMutationListener *L = getASTMutationListener()) {
14455 L->CompletedImplicitDefinition(CopyAssignOperator);
14456 }
14457}
14458
14459CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14460 assert(ClassDecl->needsImplicitMoveAssignment())(static_cast <bool> (ClassDecl->needsImplicitMoveAssignment
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveAssignment()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14460, __extension__ __PRETTY_FUNCTION__))
;
14461
14462 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14463 if (DSM.isAlreadyBeingDeclared())
14464 return nullptr;
14465
14466 // Note: The following rules are largely analoguous to the move
14467 // constructor rules.
14468
14469 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14470 LangAS AS = getDefaultCXXMethodAddrSpace();
14471 if (AS != LangAS::Default)
14472 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14473 QualType RetType = Context.getLValueReferenceType(ArgType);
14474 ArgType = Context.getRValueReferenceType(ArgType);
14475
14476 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14477 CXXMoveAssignment,
14478 false);
14479
14480 // An implicitly-declared move assignment operator is an inline public
14481 // member of its class.
14482 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14483 SourceLocation ClassLoc = ClassDecl->getLocation();
14484 DeclarationNameInfo NameInfo(Name, ClassLoc);
14485 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14486 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14487 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14488 /*isInline=*/true,
14489 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14490 SourceLocation());
14491 MoveAssignment->setAccess(AS_public);
14492 MoveAssignment->setDefaulted();
14493 MoveAssignment->setImplicit();
14494
14495 if (getLangOpts().CUDA) {
14496 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14497 MoveAssignment,
14498 /* ConstRHS */ false,
14499 /* Diagnose */ false);
14500 }
14501
14502 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14503
14504 // Add the parameter to the operator.
14505 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14506 ClassLoc, ClassLoc,
14507 /*Id=*/nullptr, ArgType,
14508 /*TInfo=*/nullptr, SC_None,
14509 nullptr);
14510 MoveAssignment->setParams(FromParam);
14511
14512 MoveAssignment->setTrivial(
14513 ClassDecl->needsOverloadResolutionForMoveAssignment()
14514 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14515 : ClassDecl->hasTrivialMoveAssignment());
14516
14517 // Note that we have added this copy-assignment operator.
14518 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14519
14520 Scope *S = getScopeForContext(ClassDecl);
14521 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14522
14523 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14524 ClassDecl->setImplicitMoveAssignmentIsDeleted();
14525 SetDeclDeleted(MoveAssignment, ClassLoc);
14526 }
14527
14528 if (S)
14529 PushOnScopeChains(MoveAssignment, S, false);
14530 ClassDecl->addDecl(MoveAssignment);
14531
14532 return MoveAssignment;
14533}
14534
14535/// Check if we're implicitly defining a move assignment operator for a class
14536/// with virtual bases. Such a move assignment might move-assign the virtual
14537/// base multiple times.
14538static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14539 SourceLocation CurrentLocation) {
14540 assert(!Class->isDependentContext() && "should not define dependent move")(static_cast <bool> (!Class->isDependentContext() &&
"should not define dependent move") ? void (0) : __assert_fail
("!Class->isDependentContext() && \"should not define dependent move\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14540, __extension__ __PRETTY_FUNCTION__))
;
14541
14542 // Only a virtual base could get implicitly move-assigned multiple times.
14543 // Only a non-trivial move assignment can observe this. We only want to
14544 // diagnose if we implicitly define an assignment operator that assigns
14545 // two base classes, both of which move-assign the same virtual base.
14546 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14547 Class->getNumBases() < 2)
14548 return;
14549
14550 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14551 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14552 VBaseMap VBases;
14553
14554 for (auto &BI : Class->bases()) {
14555 Worklist.push_back(&BI);
14556 while (!Worklist.empty()) {
14557 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14558 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14559
14560 // If the base has no non-trivial move assignment operators,
14561 // we don't care about moves from it.
14562 if (!Base->hasNonTrivialMoveAssignment())
14563 continue;
14564
14565 // If there's nothing virtual here, skip it.
14566 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14567 continue;
14568
14569 // If we're not actually going to call a move assignment for this base,
14570 // or the selected move assignment is trivial, skip it.
14571 Sema::SpecialMemberOverloadResult SMOR =
14572 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14573 /*ConstArg*/false, /*VolatileArg*/false,
14574 /*RValueThis*/true, /*ConstThis*/false,
14575 /*VolatileThis*/false);
14576 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14577 !SMOR.getMethod()->isMoveAssignmentOperator())
14578 continue;
14579
14580 if (BaseSpec->isVirtual()) {
14581 // We're going to move-assign this virtual base, and its move
14582 // assignment operator is not trivial. If this can happen for
14583 // multiple distinct direct bases of Class, diagnose it. (If it
14584 // only happens in one base, we'll diagnose it when synthesizing
14585 // that base class's move assignment operator.)
14586 CXXBaseSpecifier *&Existing =
14587 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14588 .first->second;
14589 if (Existing && Existing != &BI) {
14590 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14591 << Class << Base;
14592 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14593 << (Base->getCanonicalDecl() ==
14594 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14595 << Base << Existing->getType() << Existing->getSourceRange();
14596 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14597 << (Base->getCanonicalDecl() ==
14598 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14599 << Base << BI.getType() << BaseSpec->getSourceRange();
14600
14601 // Only diagnose each vbase once.
14602 Existing = nullptr;
14603 }
14604 } else {
14605 // Only walk over bases that have defaulted move assignment operators.
14606 // We assume that any user-provided move assignment operator handles
14607 // the multiple-moves-of-vbase case itself somehow.
14608 if (!SMOR.getMethod()->isDefaulted())
14609 continue;
14610
14611 // We're going to move the base classes of Base. Add them to the list.
14612 for (auto &BI : Base->bases())
14613 Worklist.push_back(&BI);
14614 }
14615 }
14616 }
14617}
14618
14619void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14620 CXXMethodDecl *MoveAssignOperator) {
14621 assert((MoveAssignOperator->isDefaulted() &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14626, __extension__ __PRETTY_FUNCTION__))
14622 MoveAssignOperator->isOverloadedOperator() &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14626, __extension__ __PRETTY_FUNCTION__))
14623 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14626, __extension__ __PRETTY_FUNCTION__))
14624 !MoveAssignOperator->doesThisDeclarationHaveABody() &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14626, __extension__ __PRETTY_FUNCTION__))
14625 !MoveAssignOperator->isDeleted()) &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14626, __extension__ __PRETTY_FUNCTION__))
14626 "DefineImplicitMoveAssignment called for wrong function")(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14626, __extension__ __PRETTY_FUNCTION__))
;
14627 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14628 return;
14629
14630 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14631 if (ClassDecl->isInvalidDecl()) {
14632 MoveAssignOperator->setInvalidDecl();
14633 return;
14634 }
14635
14636 // C++0x [class.copy]p28:
14637 // The implicitly-defined or move assignment operator for a non-union class
14638 // X performs memberwise move assignment of its subobjects. The direct base
14639 // classes of X are assigned first, in the order of their declaration in the
14640 // base-specifier-list, and then the immediate non-static data members of X
14641 // are assigned, in the order in which they were declared in the class
14642 // definition.
14643
14644 // Issue a warning if our implicit move assignment operator will move
14645 // from a virtual base more than once.
14646 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14647
14648 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14649
14650 // The exception specification is needed because we are defining the
14651 // function.
14652 ResolveExceptionSpec(CurrentLocation,
14653 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14654
14655 // Add a context note for diagnostics produced after this point.
14656 Scope.addContextNote(CurrentLocation);
14657
14658 // The statements that form the synthesized function body.
14659 SmallVector<Stmt*, 8> Statements;
14660
14661 // The parameter for the "other" object, which we are move from.
14662 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14663 QualType OtherRefType =
14664 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14665
14666 // Our location for everything implicitly-generated.
14667 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14668 ? MoveAssignOperator->getEndLoc()
14669 : MoveAssignOperator->getLocation();
14670
14671 // Builds a reference to the "other" object.
14672 RefBuilder OtherRef(Other, OtherRefType);
14673 // Cast to rvalue.
14674 MoveCastBuilder MoveOther(OtherRef);
14675
14676 // Builds the "this" pointer.
14677 ThisBuilder This;
14678
14679 // Assign base classes.
14680 bool Invalid = false;
14681 for (auto &Base : ClassDecl->bases()) {
14682 // C++11 [class.copy]p28:
14683 // It is unspecified whether subobjects representing virtual base classes
14684 // are assigned more than once by the implicitly-defined copy assignment
14685 // operator.
14686 // FIXME: Do not assign to a vbase that will be assigned by some other base
14687 // class. For a move-assignment, this can result in the vbase being moved
14688 // multiple times.
14689
14690 // Form the assignment:
14691 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14692 QualType BaseType = Base.getType().getUnqualifiedType();
14693 if (!BaseType->isRecordType()) {
14694 Invalid = true;
14695 continue;
14696 }
14697
14698 CXXCastPath BasePath;
14699 BasePath.push_back(&Base);
14700
14701 // Construct the "from" expression, which is an implicit cast to the
14702 // appropriately-qualified base type.
14703 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14704
14705 // Dereference "this".
14706 DerefBuilder DerefThis(This);
14707
14708 // Implicitly cast "this" to the appropriately-qualified base type.
14709 CastBuilder To(DerefThis,
14710 Context.getQualifiedType(
14711 BaseType, MoveAssignOperator->getMethodQualifiers()),
14712 VK_LValue, BasePath);
14713
14714 // Build the move.
14715 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14716 To, From,
14717 /*CopyingBaseSubobject=*/true,
14718 /*Copying=*/false);
14719 if (Move.isInvalid()) {
14720 MoveAssignOperator->setInvalidDecl();
14721 return;
14722 }
14723
14724 // Success! Record the move.
14725 Statements.push_back(Move.getAs<Expr>());
14726 }
14727
14728 // Assign non-static members.
14729 for (auto *Field : ClassDecl->fields()) {
14730 // FIXME: We should form some kind of AST representation for the implied
14731 // memcpy in a union copy operation.
14732 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14733 continue;
14734
14735 if (Field->isInvalidDecl()) {
14736 Invalid = true;
14737 continue;
14738 }
14739
14740 // Check for members of reference type; we can't move those.
14741 if (Field->getType()->isReferenceType()) {
14742 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14743 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14744 Diag(Field->getLocation(), diag::note_declared_at);
14745 Invalid = true;
14746 continue;
14747 }
14748
14749 // Check for members of const-qualified, non-class type.
14750 QualType BaseType = Context.getBaseElementType(Field->getType());
14751 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14752 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14753 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14754 Diag(Field->getLocation(), diag::note_declared_at);
14755 Invalid = true;
14756 continue;
14757 }
14758
14759 // Suppress assigning zero-width bitfields.
14760 if (Field->isZeroLengthBitField(Context))
14761 continue;
14762
14763 QualType FieldType = Field->getType().getNonReferenceType();
14764 if (FieldType->isIncompleteArrayType()) {
14765 assert(ClassDecl->hasFlexibleArrayMember() &&(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14766, __extension__ __PRETTY_FUNCTION__))
14766 "Incomplete array type is not valid")(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14766, __extension__ __PRETTY_FUNCTION__))
;
14767 continue;
14768 }
14769
14770 // Build references to the field in the object we're copying from and to.
14771 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14772 LookupMemberName);
14773 MemberLookup.addDecl(Field);
14774 MemberLookup.resolveKind();
14775 MemberBuilder From(MoveOther, OtherRefType,
14776 /*IsArrow=*/false, MemberLookup);
14777 MemberBuilder To(This, getCurrentThisType(),
14778 /*IsArrow=*/true, MemberLookup);
14779
14780 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue(static_cast <bool> (!From.build(*this, Loc)->isLValue
() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? void
(0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14782, __extension__ __PRETTY_FUNCTION__))
14781 "Member reference with rvalue base must be rvalue except for reference "(static_cast <bool> (!From.build(*this, Loc)->isLValue
() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? void
(0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14782, __extension__ __PRETTY_FUNCTION__))
14782 "members, which aren't allowed for move assignment.")(static_cast <bool> (!From.build(*this, Loc)->isLValue
() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? void
(0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14782, __extension__ __PRETTY_FUNCTION__))
;
14783
14784 // Build the move of this field.
14785 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14786 To, From,
14787 /*CopyingBaseSubobject=*/false,
14788 /*Copying=*/false);
14789 if (Move.isInvalid()) {
14790 MoveAssignOperator->setInvalidDecl();
14791 return;
14792 }
14793
14794 // Success! Record the copy.
14795 Statements.push_back(Move.getAs<Stmt>());
14796 }
14797
14798 if (!Invalid) {
14799 // Add a "return *this;"
14800 ExprResult ThisObj =
14801 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14802
14803 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14804 if (Return.isInvalid())
14805 Invalid = true;
14806 else
14807 Statements.push_back(Return.getAs<Stmt>());
14808 }
14809
14810 if (Invalid) {
14811 MoveAssignOperator->setInvalidDecl();
14812 return;
14813 }
14814
14815 StmtResult Body;
14816 {
14817 CompoundScopeRAII CompoundScope(*this);
14818 Body = ActOnCompoundStmt(Loc, Loc, Statements,
14819 /*isStmtExpr=*/false);
14820 assert(!Body.isInvalid() && "Compound statement creation cannot fail")(static_cast <bool> (!Body.isInvalid() && "Compound statement creation cannot fail"
) ? void (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14820, __extension__ __PRETTY_FUNCTION__))
;
14821 }
14822 MoveAssignOperator->setBody(Body.getAs<Stmt>());
14823 MoveAssignOperator->markUsed(Context);
14824
14825 if (ASTMutationListener *L = getASTMutationListener()) {
14826 L->CompletedImplicitDefinition(MoveAssignOperator);
14827 }
14828}
14829
14830CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14831 CXXRecordDecl *ClassDecl) {
14832 // C++ [class.copy]p4:
14833 // If the class definition does not explicitly declare a copy
14834 // constructor, one is declared implicitly.
14835 assert(ClassDecl->needsImplicitCopyConstructor())(static_cast <bool> (ClassDecl->needsImplicitCopyConstructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyConstructor()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14835, __extension__ __PRETTY_FUNCTION__))
;
14836
14837 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14838 if (DSM.isAlreadyBeingDeclared())
14839 return nullptr;
14840
14841 QualType ClassType = Context.getTypeDeclType(ClassDecl);
14842 QualType ArgType = ClassType;
14843 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14844 if (Const)
14845 ArgType = ArgType.withConst();
14846
14847 LangAS AS = getDefaultCXXMethodAddrSpace();
14848 if (AS != LangAS::Default)
14849 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14850
14851 ArgType = Context.getLValueReferenceType(ArgType);
14852
14853 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14854 CXXCopyConstructor,
14855 Const);
14856
14857 DeclarationName Name
14858 = Context.DeclarationNames.getCXXConstructorName(
14859 Context.getCanonicalType(ClassType));
14860 SourceLocation ClassLoc = ClassDecl->getLocation();
14861 DeclarationNameInfo NameInfo(Name, ClassLoc);
14862
14863 // An implicitly-declared copy constructor is an inline public
14864 // member of its class.
14865 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14866 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14867 ExplicitSpecifier(),
14868 /*isInline=*/true,
14869 /*isImplicitlyDeclared=*/true,
14870 Constexpr ? ConstexprSpecKind::Constexpr
14871 : ConstexprSpecKind::Unspecified);
14872 CopyConstructor->setAccess(AS_public);
14873 CopyConstructor->setDefaulted();
14874
14875 if (getLangOpts().CUDA) {
14876 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14877 CopyConstructor,
14878 /* ConstRHS */ Const,
14879 /* Diagnose */ false);
14880 }
14881
14882 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14883
14884 // During template instantiation of special member functions we need a
14885 // reliable TypeSourceInfo for the parameter types in order to allow functions
14886 // to be substituted.
14887 TypeSourceInfo *TSI = nullptr;
14888 if (inTemplateInstantiation() && ClassDecl->isLambda())
14889 TSI = Context.getTrivialTypeSourceInfo(ArgType);
14890
14891 // Add the parameter to the constructor.
14892 ParmVarDecl *FromParam =
14893 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
14894 /*IdentifierInfo=*/nullptr, ArgType,
14895 /*TInfo=*/TSI, SC_None, nullptr);
14896 CopyConstructor->setParams(FromParam);
14897
14898 CopyConstructor->setTrivial(
14899 ClassDecl->needsOverloadResolutionForCopyConstructor()
14900 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14901 : ClassDecl->hasTrivialCopyConstructor());
14902
14903 CopyConstructor->setTrivialForCall(
14904 ClassDecl->hasAttr<TrivialABIAttr>() ||
14905 (ClassDecl->needsOverloadResolutionForCopyConstructor()
14906 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14907 TAH_ConsiderTrivialABI)
14908 : ClassDecl->hasTrivialCopyConstructorForCall()));
14909
14910 // Note that we have declared this constructor.
14911 ++getASTContext().NumImplicitCopyConstructorsDeclared;
14912
14913 Scope *S = getScopeForContext(ClassDecl);
14914 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14915
14916 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14917 ClassDecl->setImplicitCopyConstructorIsDeleted();
14918 SetDeclDeleted(CopyConstructor, ClassLoc);
14919 }
14920
14921 if (S)
14922 PushOnScopeChains(CopyConstructor, S, false);
14923 ClassDecl->addDecl(CopyConstructor);
14924
14925 return CopyConstructor;
14926}
14927
14928void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14929 CXXConstructorDecl *CopyConstructor) {
14930 assert((CopyConstructor->isDefaulted() &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14934, __extension__ __PRETTY_FUNCTION__))
14931 CopyConstructor->isCopyConstructor() &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14934, __extension__ __PRETTY_FUNCTION__))
14932 !CopyConstructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14934, __extension__ __PRETTY_FUNCTION__))
14933 !CopyConstructor->isDeleted()) &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14934, __extension__ __PRETTY_FUNCTION__))
14934 "DefineImplicitCopyConstructor - call it for implicit copy ctor")(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14934, __extension__ __PRETTY_FUNCTION__))
;
14935 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14936 return;
14937
14938 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14939 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor")(static_cast <bool> (ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitCopyConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14939, __extension__ __PRETTY_FUNCTION__))
;
14940
14941 SynthesizedFunctionScope Scope(*this, CopyConstructor);
14942
14943 // The exception specification is needed because we are defining the
14944 // function.
14945 ResolveExceptionSpec(CurrentLocation,
14946 CopyConstructor->getType()->castAs<FunctionProtoType>());
14947 MarkVTableUsed(CurrentLocation, ClassDecl);
14948
14949 // Add a context note for diagnostics produced after this point.
14950 Scope.addContextNote(CurrentLocation);
14951
14952 // C++11 [class.copy]p7:
14953 // The [definition of an implicitly declared copy constructor] is
14954 // deprecated if the class has a user-declared copy assignment operator
14955 // or a user-declared destructor.
14956 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14957 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14958
14959 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14960 CopyConstructor->setInvalidDecl();
14961 } else {
14962 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14963 ? CopyConstructor->getEndLoc()
14964 : CopyConstructor->getLocation();
14965 Sema::CompoundScopeRAII CompoundScope(*this);
14966 CopyConstructor->setBody(
14967 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14968 CopyConstructor->markUsed(Context);
14969 }
14970
14971 if (ASTMutationListener *L = getASTMutationListener()) {
14972 L->CompletedImplicitDefinition(CopyConstructor);
14973 }
14974}
14975
14976CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14977 CXXRecordDecl *ClassDecl) {
14978 assert(ClassDecl->needsImplicitMoveConstructor())(static_cast <bool> (ClassDecl->needsImplicitMoveConstructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveConstructor()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 14978, __extension__ __PRETTY_FUNCTION__))
;
14979
14980 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14981 if (DSM.isAlreadyBeingDeclared())
14982 return nullptr;
14983
14984 QualType ClassType = Context.getTypeDeclType(ClassDecl);
14985
14986 QualType ArgType = ClassType;
14987 LangAS AS = getDefaultCXXMethodAddrSpace();
14988 if (AS != LangAS::Default)
14989 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14990 ArgType = Context.getRValueReferenceType(ArgType);
14991
14992 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14993 CXXMoveConstructor,
14994 false);
14995
14996 DeclarationName Name
14997 = Context.DeclarationNames.getCXXConstructorName(
14998 Context.getCanonicalType(ClassType));
14999 SourceLocation ClassLoc = ClassDecl->getLocation();
15000 DeclarationNameInfo NameInfo(Name, ClassLoc);
15001
15002 // C++11 [class.copy]p11:
15003 // An implicitly-declared copy/move constructor is an inline public
15004 // member of its class.
15005 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15006 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15007 ExplicitSpecifier(),
15008 /*isInline=*/true,
15009 /*isImplicitlyDeclared=*/true,
15010 Constexpr ? ConstexprSpecKind::Constexpr
15011 : ConstexprSpecKind::Unspecified);
15012 MoveConstructor->setAccess(AS_public);
15013 MoveConstructor->setDefaulted();
15014
15015 if (getLangOpts().CUDA) {
15016 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15017 MoveConstructor,
15018 /* ConstRHS */ false,
15019 /* Diagnose */ false);
15020 }
15021
15022 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15023
15024 // Add the parameter to the constructor.
15025 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15026 ClassLoc, ClassLoc,
15027 /*IdentifierInfo=*/nullptr,
15028 ArgType, /*TInfo=*/nullptr,
15029 SC_None, nullptr);
15030 MoveConstructor->setParams(FromParam);
15031
15032 MoveConstructor->setTrivial(
15033 ClassDecl->needsOverloadResolutionForMoveConstructor()
15034 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15035 : ClassDecl->hasTrivialMoveConstructor());
15036
15037 MoveConstructor->setTrivialForCall(
15038 ClassDecl->hasAttr<TrivialABIAttr>() ||
15039 (ClassDecl->needsOverloadResolutionForMoveConstructor()
15040 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15041 TAH_ConsiderTrivialABI)
15042 : ClassDecl->hasTrivialMoveConstructorForCall()));
15043
15044 // Note that we have declared this constructor.
15045 ++getASTContext().NumImplicitMoveConstructorsDeclared;
15046
15047 Scope *S = getScopeForContext(ClassDecl);
15048 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15049
15050 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15051 ClassDecl->setImplicitMoveConstructorIsDeleted();
15052 SetDeclDeleted(MoveConstructor, ClassLoc);
15053 }
15054
15055 if (S)
15056 PushOnScopeChains(MoveConstructor, S, false);
15057 ClassDecl->addDecl(MoveConstructor);
15058
15059 return MoveConstructor;
15060}
15061
15062void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15063 CXXConstructorDecl *MoveConstructor) {
15064 assert((MoveConstructor->isDefaulted() &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15068, __extension__ __PRETTY_FUNCTION__))
15065 MoveConstructor->isMoveConstructor() &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15068, __extension__ __PRETTY_FUNCTION__))
15066 !MoveConstructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15068, __extension__ __PRETTY_FUNCTION__))
15067 !MoveConstructor->isDeleted()) &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15068, __extension__ __PRETTY_FUNCTION__))
15068 "DefineImplicitMoveConstructor - call it for implicit move ctor")(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15068, __extension__ __PRETTY_FUNCTION__))
;
15069 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15070 return;
15071
15072 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15073 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor")(static_cast <bool> (ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitMoveConstructor - invalid constructor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15073, __extension__ __PRETTY_FUNCTION__))
;
15074
15075 SynthesizedFunctionScope Scope(*this, MoveConstructor);
15076
15077 // The exception specification is needed because we are defining the
15078 // function.
15079 ResolveExceptionSpec(CurrentLocation,
15080 MoveConstructor->getType()->castAs<FunctionProtoType>());
15081 MarkVTableUsed(CurrentLocation, ClassDecl);
15082
15083 // Add a context note for diagnostics produced after this point.
15084 Scope.addContextNote(CurrentLocation);
15085
15086 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15087 MoveConstructor->setInvalidDecl();
15088 } else {
15089 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15090 ? MoveConstructor->getEndLoc()
15091 : MoveConstructor->getLocation();
15092 Sema::CompoundScopeRAII CompoundScope(*this);
15093 MoveConstructor->setBody(ActOnCompoundStmt(
15094 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15095 MoveConstructor->markUsed(Context);
15096 }
15097
15098 if (ASTMutationListener *L = getASTMutationListener()) {
15099 L->CompletedImplicitDefinition(MoveConstructor);
15100 }
15101}
15102
15103bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15104 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15105}
15106
15107void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15108 SourceLocation CurrentLocation,
15109 CXXConversionDecl *Conv) {
15110 SynthesizedFunctionScope Scope(*this, Conv);
15111 assert(!Conv->getReturnType()->isUndeducedType())(static_cast <bool> (!Conv->getReturnType()->isUndeducedType
()) ? void (0) : __assert_fail ("!Conv->getReturnType()->isUndeducedType()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15111, __extension__ __PRETTY_FUNCTION__))
;
15112
15113 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15114 CallingConv CC =
15115 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15116
15117 CXXRecordDecl *Lambda = Conv->getParent();
15118 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15119 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15120
15121 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15122 CallOp = InstantiateFunctionDeclaration(
15123 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15124 if (!CallOp)
15125 return;
15126
15127 Invoker = InstantiateFunctionDeclaration(
15128 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15129 if (!Invoker)
15130 return;
15131 }
15132
15133 if (CallOp->isInvalidDecl())
15134 return;
15135
15136 // Mark the call operator referenced (and add to pending instantiations
15137 // if necessary).
15138 // For both the conversion and static-invoker template specializations
15139 // we construct their body's in this function, so no need to add them
15140 // to the PendingInstantiations.
15141 MarkFunctionReferenced(CurrentLocation, CallOp);
15142
15143 // Fill in the __invoke function with a dummy implementation. IR generation
15144 // will fill in the actual details. Update its type in case it contained
15145 // an 'auto'.
15146 Invoker->markUsed(Context);
15147 Invoker->setReferenced();
15148 Invoker->setType(Conv->getReturnType()->getPointeeType());
15149 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15150
15151 // Construct the body of the conversion function { return __invoke; }.
15152 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15153 VK_LValue, Conv->getLocation());
15154 assert(FunctionRef && "Can't refer to __invoke function?")(static_cast <bool> (FunctionRef && "Can't refer to __invoke function?"
) ? void (0) : __assert_fail ("FunctionRef && \"Can't refer to __invoke function?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15154, __extension__ __PRETTY_FUNCTION__))
;
15155 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15156 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
15157 Conv->getLocation()));
15158 Conv->markUsed(Context);
15159 Conv->setReferenced();
15160
15161 if (ASTMutationListener *L = getASTMutationListener()) {
15162 L->CompletedImplicitDefinition(Conv);
15163 L->CompletedImplicitDefinition(Invoker);
15164 }
15165}
15166
15167
15168
15169void Sema::DefineImplicitLambdaToBlockPointerConversion(
15170 SourceLocation CurrentLocation,
15171 CXXConversionDecl *Conv)
15172{
15173 assert(!Conv->getParent()->isGenericLambda())(static_cast <bool> (!Conv->getParent()->isGenericLambda
()) ? void (0) : __assert_fail ("!Conv->getParent()->isGenericLambda()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15173, __extension__ __PRETTY_FUNCTION__))
;
15174
15175 SynthesizedFunctionScope Scope(*this, Conv);
15176
15177 // Copy-initialize the lambda object as needed to capture it.
15178 Expr *This = ActOnCXXThis(CurrentLocation).get();
15179 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15180
15181 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15182 Conv->getLocation(),
15183 Conv, DerefThis);
15184
15185 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15186 // behavior. Note that only the general conversion function does this
15187 // (since it's unusable otherwise); in the case where we inline the
15188 // block literal, it has block literal lifetime semantics.
15189 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15190 BuildBlock = ImplicitCastExpr::Create(
15191 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15192 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15193
15194 if (BuildBlock.isInvalid()) {
15195 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15196 Conv->setInvalidDecl();
15197 return;
15198 }
15199
15200 // Create the return statement that returns the block from the conversion
15201 // function.
15202 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15203 if (Return.isInvalid()) {
15204 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15205 Conv->setInvalidDecl();
15206 return;
15207 }
15208
15209 // Set the body of the conversion function.
15210 Stmt *ReturnS = Return.get();
15211 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15212 Conv->getLocation()));
15213 Conv->markUsed(Context);
15214
15215 // We're done; notify the mutation listener, if any.
15216 if (ASTMutationListener *L = getASTMutationListener()) {
15217 L->CompletedImplicitDefinition(Conv);
15218 }
15219}
15220
15221/// Determine whether the given list arguments contains exactly one
15222/// "real" (non-default) argument.
15223static bool hasOneRealArgument(MultiExprArg Args) {
15224 switch (Args.size()) {
15225 case 0:
15226 return false;
15227
15228 default:
15229 if (!Args[1]->isDefaultArgument())
15230 return false;
15231
15232 LLVM_FALLTHROUGH[[gnu::fallthrough]];
15233 case 1:
15234 return !Args[0]->isDefaultArgument();
15235 }
15236
15237 return false;
15238}
15239
15240ExprResult
15241Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15242 NamedDecl *FoundDecl,
15243 CXXConstructorDecl *Constructor,
15244 MultiExprArg ExprArgs,
15245 bool HadMultipleCandidates,
15246 bool IsListInitialization,
15247 bool IsStdInitListInitialization,
15248 bool RequiresZeroInit,
15249 unsigned ConstructKind,
15250 SourceRange ParenRange) {
15251 bool Elidable = false;
15252
15253 // C++0x [class.copy]p34:
15254 // When certain criteria are met, an implementation is allowed to
15255 // omit the copy/move construction of a class object, even if the
15256 // copy/move constructor and/or destructor for the object have
15257 // side effects. [...]
15258 // - when a temporary class object that has not been bound to a
15259 // reference (12.2) would be copied/moved to a class object
15260 // with the same cv-unqualified type, the copy/move operation
15261 // can be omitted by constructing the temporary object
15262 // directly into the target of the omitted copy/move
15263 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15264 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15265 Expr *SubExpr = ExprArgs[0];
15266 Elidable = SubExpr->isTemporaryObject(
15267 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15268 }
15269
15270 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15271 FoundDecl, Constructor,
15272 Elidable, ExprArgs, HadMultipleCandidates,
15273 IsListInitialization,
15274 IsStdInitListInitialization, RequiresZeroInit,
15275 ConstructKind, ParenRange);
15276}
15277
15278ExprResult
15279Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15280 NamedDecl *FoundDecl,
15281 CXXConstructorDecl *Constructor,
15282 bool Elidable,
15283 MultiExprArg ExprArgs,
15284 bool HadMultipleCandidates,
15285 bool IsListInitialization,
15286 bool IsStdInitListInitialization,
15287 bool RequiresZeroInit,
15288 unsigned ConstructKind,
15289 SourceRange ParenRange) {
15290 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15291 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15292 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15293 return ExprError();
15294 }
15295
15296 return BuildCXXConstructExpr(
15297 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15298 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15299 RequiresZeroInit, ConstructKind, ParenRange);
15300}
15301
15302/// BuildCXXConstructExpr - Creates a complete call to a constructor,
15303/// including handling of its default argument expressions.
15304ExprResult
15305Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15306 CXXConstructorDecl *Constructor,
15307 bool Elidable,
15308 MultiExprArg ExprArgs,
15309 bool HadMultipleCandidates,
15310 bool IsListInitialization,
15311 bool IsStdInitListInitialization,
15312 bool RequiresZeroInit,
15313 unsigned ConstructKind,
15314 SourceRange ParenRange) {
15315 assert(declaresSameEntity((static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15318, __extension__ __PRETTY_FUNCTION__))
15316 Constructor->getParent(),(static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15318, __extension__ __PRETTY_FUNCTION__))
15317 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&(static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15318, __extension__ __PRETTY_FUNCTION__))
15318 "given constructor for wrong type")(static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15318, __extension__ __PRETTY_FUNCTION__))
;
15319 MarkFunctionReferenced(ConstructLoc, Constructor);
15320 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15321 return ExprError();
15322 if (getLangOpts().SYCLIsDevice &&
15323 !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15324 return ExprError();
15325
15326 return CheckForImmediateInvocation(
15327 CXXConstructExpr::Create(
15328 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15329 HadMultipleCandidates, IsListInitialization,
15330 IsStdInitListInitialization, RequiresZeroInit,
15331 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15332 ParenRange),
15333 Constructor);
15334}
15335
15336ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15337 assert(Field->hasInClassInitializer())(static_cast <bool> (Field->hasInClassInitializer())
? void (0) : __assert_fail ("Field->hasInClassInitializer()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15337, __extension__ __PRETTY_FUNCTION__))
;
15338
15339 // If we already have the in-class initializer nothing needs to be done.
15340 if (Field->getInClassInitializer())
15341 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15342
15343 // If we might have already tried and failed to instantiate, don't try again.
15344 if (Field->isInvalidDecl())
15345 return ExprError();
15346
15347 // Maybe we haven't instantiated the in-class initializer. Go check the
15348 // pattern FieldDecl to see if it has one.
15349 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15350
15351 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15352 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15353 DeclContext::lookup_result Lookup =
15354 ClassPattern->lookup(Field->getDeclName());
15355
15356 FieldDecl *Pattern = nullptr;
15357 for (auto L : Lookup) {
15358 if (isa<FieldDecl>(L)) {
15359 Pattern = cast<FieldDecl>(L);
15360 break;
15361 }
15362 }
15363 assert(Pattern && "We must have set the Pattern!")(static_cast <bool> (Pattern && "We must have set the Pattern!"
) ? void (0) : __assert_fail ("Pattern && \"We must have set the Pattern!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15363, __extension__ __PRETTY_FUNCTION__))
;
15364
15365 if (!Pattern->hasInClassInitializer() ||
15366 InstantiateInClassInitializer(Loc, Field, Pattern,
15367 getTemplateInstantiationArgs(Field))) {
15368 // Don't diagnose this again.
15369 Field->setInvalidDecl();
15370 return ExprError();
15371 }
15372 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15373 }
15374
15375 // DR1351:
15376 // If the brace-or-equal-initializer of a non-static data member
15377 // invokes a defaulted default constructor of its class or of an
15378 // enclosing class in a potentially evaluated subexpression, the
15379 // program is ill-formed.
15380 //
15381 // This resolution is unworkable: the exception specification of the
15382 // default constructor can be needed in an unevaluated context, in
15383 // particular, in the operand of a noexcept-expression, and we can be
15384 // unable to compute an exception specification for an enclosed class.
15385 //
15386 // Any attempt to resolve the exception specification of a defaulted default
15387 // constructor before the initializer is lexically complete will ultimately
15388 // come here at which point we can diagnose it.
15389 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15390 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15391 << OutermostClass << Field;
15392 Diag(Field->getEndLoc(),
15393 diag::note_default_member_initializer_not_yet_parsed);
15394 // Recover by marking the field invalid, unless we're in a SFINAE context.
15395 if (!isSFINAEContext())
15396 Field->setInvalidDecl();
15397 return ExprError();
15398}
15399
15400void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15401 if (VD->isInvalidDecl()) return;
15402 // If initializing the variable failed, don't also diagnose problems with
15403 // the desctructor, they're likely related.
15404 if (VD->getInit() && VD->getInit()->containsErrors())
15405 return;
15406
15407 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15408 if (ClassDecl->isInvalidDecl()) return;
15409 if (ClassDecl->hasIrrelevantDestructor()) return;
15410 if (ClassDecl->isDependentContext()) return;
15411
15412 if (VD->isNoDestroy(getASTContext()))
15413 return;
15414
15415 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15416
15417 // If this is an array, we'll require the destructor during initialization, so
15418 // we can skip over this. We still want to emit exit-time destructor warnings
15419 // though.
15420 if (!VD->getType()->isArrayType()) {
15421 MarkFunctionReferenced(VD->getLocation(), Destructor);
15422 CheckDestructorAccess(VD->getLocation(), Destructor,
15423 PDiag(diag::err_access_dtor_var)
15424 << VD->getDeclName() << VD->getType());
15425 DiagnoseUseOfDecl(Destructor, VD->getLocation());
15426 }
15427
15428 if (Destructor->isTrivial()) return;
15429
15430 // If the destructor is constexpr, check whether the variable has constant
15431 // destruction now.
15432 if (Destructor->isConstexpr()) {
15433 bool HasConstantInit = false;
15434 if (VD->getInit() && !VD->getInit()->isValueDependent())
15435 HasConstantInit = VD->evaluateValue();
15436 SmallVector<PartialDiagnosticAt, 8> Notes;
15437 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15438 HasConstantInit) {
15439 Diag(VD->getLocation(),
15440 diag::err_constexpr_var_requires_const_destruction) << VD;
15441 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15442 Diag(Notes[I].first, Notes[I].second);
15443 }
15444 }
15445
15446 if (!VD->hasGlobalStorage()) return;
15447
15448 // Emit warning for non-trivial dtor in global scope (a real global,
15449 // class-static, function-static).
15450 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15451
15452 // TODO: this should be re-enabled for static locals by !CXAAtExit
15453 if (!VD->isStaticLocal())
15454 Diag(VD->getLocation(), diag::warn_global_destructor);
15455}
15456
15457/// Given a constructor and the set of arguments provided for the
15458/// constructor, convert the arguments and add any required default arguments
15459/// to form a proper call to this constructor.
15460///
15461/// \returns true if an error occurred, false otherwise.
15462bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15463 QualType DeclInitType, MultiExprArg ArgsPtr,
15464 SourceLocation Loc,
15465 SmallVectorImpl<Expr *> &ConvertedArgs,
15466 bool AllowExplicit,
15467 bool IsListInitialization) {
15468 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15469 unsigned NumArgs = ArgsPtr.size();
15470 Expr **Args = ArgsPtr.data();
15471
15472 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15473 unsigned NumParams = Proto->getNumParams();
15474
15475 // If too few arguments are available, we'll fill in the rest with defaults.
15476 if (NumArgs < NumParams)
15477 ConvertedArgs.reserve(NumParams);
15478 else
15479 ConvertedArgs.reserve(NumArgs);
15480
15481 VariadicCallType CallType =
15482 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15483 SmallVector<Expr *, 8> AllArgs;
15484 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15485 Proto, 0,
15486 llvm::makeArrayRef(Args, NumArgs),
15487 AllArgs,
15488 CallType, AllowExplicit,
15489 IsListInitialization);
15490 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15491
15492 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15493
15494 CheckConstructorCall(Constructor, DeclInitType,
15495 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15496 Proto, Loc);
15497
15498 return Invalid;
15499}
15500
15501static inline bool
15502CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15503 const FunctionDecl *FnDecl) {
15504 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15505 if (isa<NamespaceDecl>(DC)) {
15506 return SemaRef.Diag(FnDecl->getLocation(),
15507 diag::err_operator_new_delete_declared_in_namespace)
15508 << FnDecl->getDeclName();
15509 }
15510
15511 if (isa<TranslationUnitDecl>(DC) &&
15512 FnDecl->getStorageClass() == SC_Static) {
15513 return SemaRef.Diag(FnDecl->getLocation(),
15514 diag::err_operator_new_delete_declared_static)
15515 << FnDecl->getDeclName();
15516 }
15517
15518 return false;
15519}
15520
15521static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15522 const PointerType *PtrTy) {
15523 auto &Ctx = SemaRef.Context;
15524 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15525 PtrQuals.removeAddressSpace();
15526 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15527 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15528}
15529
15530static inline bool
15531CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15532 CanQualType ExpectedResultType,
15533 CanQualType ExpectedFirstParamType,
15534 unsigned DependentParamTypeDiag,
15535 unsigned InvalidParamTypeDiag) {
15536 QualType ResultType =
15537 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15538
15539 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15540 // The operator is valid on any address space for OpenCL.
15541 // Drop address space from actual and expected result types.
15542 if (const auto *PtrTy = ResultType->getAs<PointerType>())
15543 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15544
15545 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15546 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15547 }
15548
15549 // Check that the result type is what we expect.
15550 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15551 // Reject even if the type is dependent; an operator delete function is
15552 // required to have a non-dependent result type.
15553 return SemaRef.Diag(
15554 FnDecl->getLocation(),
15555 ResultType->isDependentType()
15556 ? diag::err_operator_new_delete_dependent_result_type
15557 : diag::err_operator_new_delete_invalid_result_type)
15558 << FnDecl->getDeclName() << ExpectedResultType;
15559 }
15560
15561 // A function template must have at least 2 parameters.
15562 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15563 return SemaRef.Diag(FnDecl->getLocation(),
15564 diag::err_operator_new_delete_template_too_few_parameters)
15565 << FnDecl->getDeclName();
15566
15567 // The function decl must have at least 1 parameter.
15568 if (FnDecl->getNumParams() == 0)
15569 return SemaRef.Diag(FnDecl->getLocation(),
15570 diag::err_operator_new_delete_too_few_parameters)
15571 << FnDecl->getDeclName();
15572
15573 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15574 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15575 // The operator is valid on any address space for OpenCL.
15576 // Drop address space from actual and expected first parameter types.
15577 if (const auto *PtrTy =
15578 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15579 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15580
15581 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15582 ExpectedFirstParamType =
15583 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15584 }
15585
15586 // Check that the first parameter type is what we expect.
15587 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15588 ExpectedFirstParamType) {
15589 // The first parameter type is not allowed to be dependent. As a tentative
15590 // DR resolution, we allow a dependent parameter type if it is the right
15591 // type anyway, to allow destroying operator delete in class templates.
15592 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15593 ? DependentParamTypeDiag
15594 : InvalidParamTypeDiag)
15595 << FnDecl->getDeclName() << ExpectedFirstParamType;
15596 }
15597
15598 return false;
15599}
15600
15601static bool
15602CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15603 // C++ [basic.stc.dynamic.allocation]p1:
15604 // A program is ill-formed if an allocation function is declared in a
15605 // namespace scope other than global scope or declared static in global
15606 // scope.
15607 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15608 return true;
15609
15610 CanQualType SizeTy =
15611 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15612
15613 // C++ [basic.stc.dynamic.allocation]p1:
15614 // The return type shall be void*. The first parameter shall have type
15615 // std::size_t.
15616 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15617 SizeTy,
15618 diag::err_operator_new_dependent_param_type,
15619 diag::err_operator_new_param_type))
15620 return true;
15621
15622 // C++ [basic.stc.dynamic.allocation]p1:
15623 // The first parameter shall not have an associated default argument.
15624 if (FnDecl->getParamDecl(0)->hasDefaultArg())
15625 return SemaRef.Diag(FnDecl->getLocation(),
15626 diag::err_operator_new_default_arg)
15627 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15628
15629 return false;
15630}
15631
15632static bool
15633CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15634 // C++ [basic.stc.dynamic.deallocation]p1:
15635 // A program is ill-formed if deallocation functions are declared in a
15636 // namespace scope other than global scope or declared static in global
15637 // scope.
15638 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15639 return true;
15640
15641 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15642
15643 // C++ P0722:
15644 // Within a class C, the first parameter of a destroying operator delete
15645 // shall be of type C *. The first parameter of any other deallocation
15646 // function shall be of type void *.
15647 CanQualType ExpectedFirstParamType =
15648 MD && MD->isDestroyingOperatorDelete()
15649 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15650 SemaRef.Context.getRecordType(MD->getParent())))
15651 : SemaRef.Context.VoidPtrTy;
15652
15653 // C++ [basic.stc.dynamic.deallocation]p2:
15654 // Each deallocation function shall return void
15655 if (CheckOperatorNewDeleteTypes(
15656 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15657 diag::err_operator_delete_dependent_param_type,
15658 diag::err_operator_delete_param_type))
15659 return true;
15660
15661 // C++ P0722:
15662 // A destroying operator delete shall be a usual deallocation function.
15663 if (MD && !MD->getParent()->isDependentContext() &&
15664 MD->isDestroyingOperatorDelete() &&
15665 !SemaRef.isUsualDeallocationFunction(MD)) {
15666 SemaRef.Diag(MD->getLocation(),
15667 diag::err_destroying_operator_delete_not_usual);
15668 return true;
15669 }
15670
15671 return false;
15672}
15673
15674/// CheckOverloadedOperatorDeclaration - Check whether the declaration
15675/// of this overloaded operator is well-formed. If so, returns false;
15676/// otherwise, emits appropriate diagnostics and returns true.
15677bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15678 assert(FnDecl && FnDecl->isOverloadedOperator() &&(static_cast <bool> (FnDecl && FnDecl->isOverloadedOperator
() && "Expected an overloaded operator declaration") ?
void (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15679, __extension__ __PRETTY_FUNCTION__))
15679 "Expected an overloaded operator declaration")(static_cast <bool> (FnDecl && FnDecl->isOverloadedOperator
() && "Expected an overloaded operator declaration") ?
void (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15679, __extension__ __PRETTY_FUNCTION__))
;
15680
15681 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15682
15683 // C++ [over.oper]p5:
15684 // The allocation and deallocation functions, operator new,
15685 // operator new[], operator delete and operator delete[], are
15686 // described completely in 3.7.3. The attributes and restrictions
15687 // found in the rest of this subclause do not apply to them unless
15688 // explicitly stated in 3.7.3.
15689 if (Op == OO_Delete || Op == OO_Array_Delete)
15690 return CheckOperatorDeleteDeclaration(*this, FnDecl);
15691
15692 if (Op == OO_New || Op == OO_Array_New)
15693 return CheckOperatorNewDeclaration(*this, FnDecl);
15694
15695 // C++ [over.oper]p6:
15696 // An operator function shall either be a non-static member
15697 // function or be a non-member function and have at least one
15698 // parameter whose type is a class, a reference to a class, an
15699 // enumeration, or a reference to an enumeration.
15700 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15701 if (MethodDecl->isStatic())
15702 return Diag(FnDecl->getLocation(),
15703 diag::err_operator_overload_static) << FnDecl->getDeclName();
15704 } else {
15705 bool ClassOrEnumParam = false;
15706 for (auto Param : FnDecl->parameters()) {
15707 QualType ParamType = Param->getType().getNonReferenceType();
15708 if (ParamType->isDependentType() || ParamType->isRecordType() ||
15709 ParamType->isEnumeralType()) {
15710 ClassOrEnumParam = true;
15711 break;
15712 }
15713 }
15714
15715 if (!ClassOrEnumParam)
15716 return Diag(FnDecl->getLocation(),
15717 diag::err_operator_overload_needs_class_or_enum)
15718 << FnDecl->getDeclName();
15719 }
15720
15721 // C++ [over.oper]p8:
15722 // An operator function cannot have default arguments (8.3.6),
15723 // except where explicitly stated below.
15724 //
15725 // Only the function-call operator allows default arguments
15726 // (C++ [over.call]p1).
15727 if (Op != OO_Call) {
15728 for (auto Param : FnDecl->parameters()) {
15729 if (Param->hasDefaultArg())
15730 return Diag(Param->getLocation(),
15731 diag::err_operator_overload_default_arg)
15732 << FnDecl->getDeclName() << Param->getDefaultArgRange();
15733 }
15734 }
15735
15736 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15737 { false, false, false }
15738#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15739 , { Unary, Binary, MemberOnly }
15740#include "clang/Basic/OperatorKinds.def"
15741 };
15742
15743 bool CanBeUnaryOperator = OperatorUses[Op][0];
15744 bool CanBeBinaryOperator = OperatorUses[Op][1];
15745 bool MustBeMemberOperator = OperatorUses[Op][2];
15746
15747 // C++ [over.oper]p8:
15748 // [...] Operator functions cannot have more or fewer parameters
15749 // than the number required for the corresponding operator, as
15750 // described in the rest of this subclause.
15751 unsigned NumParams = FnDecl->getNumParams()
15752 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15753 if (Op != OO_Call &&
15754 ((NumParams == 1 && !CanBeUnaryOperator) ||
15755 (NumParams == 2 && !CanBeBinaryOperator) ||
15756 (NumParams < 1) || (NumParams > 2))) {
15757 // We have the wrong number of parameters.
15758 unsigned ErrorKind;
15759 if (CanBeUnaryOperator && CanBeBinaryOperator) {
15760 ErrorKind = 2; // 2 -> unary or binary.
15761 } else if (CanBeUnaryOperator) {
15762 ErrorKind = 0; // 0 -> unary
15763 } else {
15764 assert(CanBeBinaryOperator &&(static_cast <bool> (CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? void (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15765, __extension__ __PRETTY_FUNCTION__))
15765 "All non-call overloaded operators are unary or binary!")(static_cast <bool> (CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? void (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 15765, __extension__ __PRETTY_FUNCTION__))
;
15766 ErrorKind = 1; // 1 -> binary
15767 }
15768
15769 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15770 << FnDecl->getDeclName() << NumParams << ErrorKind;
15771 }
15772
15773 // Overloaded operators other than operator() cannot be variadic.
15774 if (Op != OO_Call &&
15775 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15776 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15777 << FnDecl->getDeclName();
15778 }
15779
15780 // Some operators must be non-static member functions.
15781 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15782 return Diag(FnDecl->getLocation(),
15783 diag::err_operator_overload_must_be_member)
15784 << FnDecl->getDeclName();
15785 }
15786
15787 // C++ [over.inc]p1:
15788 // The user-defined function called operator++ implements the
15789 // prefix and postfix ++ operator. If this function is a member
15790 // function with no parameters, or a non-member function with one
15791 // parameter of class or enumeration type, it defines the prefix
15792 // increment operator ++ for objects of that type. If the function
15793 // is a member function with one parameter (which shall be of type
15794 // int) or a non-member function with two parameters (the second
15795 // of which shall be of type int), it defines the postfix
15796 // increment operator ++ for objects of that type.
15797 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15798 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15799 QualType ParamType = LastParam->getType();
15800
15801 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15802 !ParamType->isDependentType())
15803 return Diag(LastParam->getLocation(),
15804 diag::err_operator_overload_post_incdec_must_be_int)
15805 << LastParam->getType() << (Op == OO_MinusMinus);
15806 }
15807
15808 return false;
15809}
15810
15811static bool
15812checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15813 FunctionTemplateDecl *TpDecl) {
15814 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15815
15816 // Must have one or two template parameters.
15817 if (TemplateParams->size() == 1) {
15818 NonTypeTemplateParmDecl *PmDecl =
15819 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15820
15821 // The template parameter must be a char parameter pack.
15822 if (PmDecl && PmDecl->isTemplateParameterPack() &&
15823 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15824 return false;
15825
15826 // C++20 [over.literal]p5:
15827 // A string literal operator template is a literal operator template
15828 // whose template-parameter-list comprises a single non-type
15829 // template-parameter of class type.
15830 //
15831 // As a DR resolution, we also allow placeholders for deduced class
15832 // template specializations.
15833 if (SemaRef.getLangOpts().CPlusPlus20 &&
15834 !PmDecl->isTemplateParameterPack() &&
15835 (PmDecl->getType()->isRecordType() ||
15836 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15837 return false;
15838 } else if (TemplateParams->size() == 2) {
15839 TemplateTypeParmDecl *PmType =
15840 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15841 NonTypeTemplateParmDecl *PmArgs =
15842 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15843
15844 // The second template parameter must be a parameter pack with the
15845 // first template parameter as its type.
15846 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15847 PmArgs->isTemplateParameterPack()) {
15848 const TemplateTypeParmType *TArgs =
15849 PmArgs->getType()->getAs<TemplateTypeParmType>();
15850 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15851 TArgs->getIndex() == PmType->getIndex()) {
15852 if (!SemaRef.inTemplateInstantiation())
15853 SemaRef.Diag(TpDecl->getLocation(),
15854 diag::ext_string_literal_operator_template);
15855 return false;
15856 }
15857 }
15858 }
15859
15860 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15861 diag::err_literal_operator_template)
15862 << TpDecl->getTemplateParameters()->getSourceRange();
15863 return true;
15864}
15865
15866/// CheckLiteralOperatorDeclaration - Check whether the declaration
15867/// of this literal operator function is well-formed. If so, returns
15868/// false; otherwise, emits appropriate diagnostics and returns true.
15869bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15870 if (isa<CXXMethodDecl>(FnDecl)) {
15871 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15872 << FnDecl->getDeclName();
15873 return true;
15874 }
15875
15876 if (FnDecl->isExternC()) {
15877 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15878 if (const LinkageSpecDecl *LSD =
15879 FnDecl->getDeclContext()->getExternCContext())
15880 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15881 return true;
15882 }
15883
15884 // This might be the definition of a literal operator template.
15885 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15886
15887 // This might be a specialization of a literal operator template.
15888 if (!TpDecl)
15889 TpDecl = FnDecl->getPrimaryTemplate();
15890
15891 // template <char...> type operator "" name() and
15892 // template <class T, T...> type operator "" name() are the only valid
15893 // template signatures, and the only valid signatures with no parameters.
15894 //
15895 // C++20 also allows template <SomeClass T> type operator "" name().
15896 if (TpDecl) {
15897 if (FnDecl->param_size() != 0) {
15898 Diag(FnDecl->getLocation(),
15899 diag::err_literal_operator_template_with_params);
15900 return true;
15901 }
15902
15903 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15904 return true;
15905
15906 } else if (FnDecl->param_size() == 1) {
15907 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15908
15909 QualType ParamType = Param->getType().getUnqualifiedType();
15910
15911 // Only unsigned long long int, long double, any character type, and const
15912 // char * are allowed as the only parameters.
15913 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15914 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15915 Context.hasSameType(ParamType, Context.CharTy) ||
15916 Context.hasSameType(ParamType, Context.WideCharTy) ||
15917 Context.hasSameType(ParamType, Context.Char8Ty) ||
15918 Context.hasSameType(ParamType, Context.Char16Ty) ||
15919 Context.hasSameType(ParamType, Context.Char32Ty)) {
15920 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15921 QualType InnerType = Ptr->getPointeeType();
15922
15923 // Pointer parameter must be a const char *.
15924 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15925 Context.CharTy) &&
15926 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15927 Diag(Param->getSourceRange().getBegin(),
15928 diag::err_literal_operator_param)
15929 << ParamType << "'const char *'" << Param->getSourceRange();
15930 return true;
15931 }
15932
15933 } else if (ParamType->isRealFloatingType()) {
15934 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15935 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15936 return true;
15937
15938 } else if (ParamType->isIntegerType()) {
15939 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15940 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15941 return true;
15942
15943 } else {
15944 Diag(Param->getSourceRange().getBegin(),
15945 diag::err_literal_operator_invalid_param)
15946 << ParamType << Param->getSourceRange();
15947 return true;
15948 }
15949
15950 } else if (FnDecl->param_size() == 2) {
15951 FunctionDecl::param_iterator Param = FnDecl->param_begin();
15952
15953 // First, verify that the first parameter is correct.
15954
15955 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15956
15957 // Two parameter function must have a pointer to const as a
15958 // first parameter; let's strip those qualifiers.
15959 const PointerType *PT = FirstParamType->getAs<PointerType>();
15960
15961 if (!PT) {
15962 Diag((*Param)->getSourceRange().getBegin(),
15963 diag::err_literal_operator_param)
15964 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15965 return true;
15966 }
15967
15968 QualType PointeeType = PT->getPointeeType();
15969 // First parameter must be const
15970 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15971 Diag((*Param)->getSourceRange().getBegin(),
15972 diag::err_literal_operator_param)
15973 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15974 return true;
15975 }
15976
15977 QualType InnerType = PointeeType.getUnqualifiedType();
15978 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15979 // const char32_t* are allowed as the first parameter to a two-parameter
15980 // function
15981 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15982 Context.hasSameType(InnerType, Context.WideCharTy) ||
15983 Context.hasSameType(InnerType, Context.Char8Ty) ||
15984 Context.hasSameType(InnerType, Context.Char16Ty) ||
15985 Context.hasSameType(InnerType, Context.Char32Ty))) {
15986 Diag((*Param)->getSourceRange().getBegin(),
15987 diag::err_literal_operator_param)
15988 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15989 return true;
15990 }
15991
15992 // Move on to the second and final parameter.
15993 ++Param;
15994
15995 // The second parameter must be a std::size_t.
15996 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15997 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15998 Diag((*Param)->getSourceRange().getBegin(),
15999 diag::err_literal_operator_param)
16000 << SecondParamType << Context.getSizeType()
16001 << (*Param)->getSourceRange();
16002 return true;
16003 }
16004 } else {
16005 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16006 return true;
16007 }
16008
16009 // Parameters are good.
16010
16011 // A parameter-declaration-clause containing a default argument is not
16012 // equivalent to any of the permitted forms.
16013 for (auto Param : FnDecl->parameters()) {
16014 if (Param->hasDefaultArg()) {
16015 Diag(Param->getDefaultArgRange().getBegin(),
16016 diag::err_literal_operator_default_argument)
16017 << Param->getDefaultArgRange();
16018 break;
16019 }
16020 }
16021
16022 StringRef LiteralName
16023 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16024 if (LiteralName[0] != '_' &&
16025 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16026 // C++11 [usrlit.suffix]p1:
16027 // Literal suffix identifiers that do not start with an underscore
16028 // are reserved for future standardization.
16029 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16030 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16031 }
16032
16033 return false;
16034}
16035
16036/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16037/// linkage specification, including the language and (if present)
16038/// the '{'. ExternLoc is the location of the 'extern', Lang is the
16039/// language string literal. LBraceLoc, if valid, provides the location of
16040/// the '{' brace. Otherwise, this linkage specification does not
16041/// have any braces.
16042Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16043 Expr *LangStr,
16044 SourceLocation LBraceLoc) {
16045 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16046 if (!Lit->isAscii()) {
16047 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16048 << LangStr->getSourceRange();
16049 return nullptr;
16050 }
16051
16052 StringRef Lang = Lit->getString();
16053 LinkageSpecDecl::LanguageIDs Language;
16054 if (Lang == "C")
16055 Language = LinkageSpecDecl::lang_c;
16056 else if (Lang == "C++")
16057 Language = LinkageSpecDecl::lang_cxx;
16058 else {
16059 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16060 << LangStr->getSourceRange();
16061 return nullptr;
16062 }
16063
16064 // FIXME: Add all the various semantics of linkage specifications
16065
16066 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16067 LangStr->getExprLoc(), Language,
16068 LBraceLoc.isValid());
16069 CurContext->addDecl(D);
16070 PushDeclContext(S, D);
16071 return D;
16072}
16073
16074/// ActOnFinishLinkageSpecification - Complete the definition of
16075/// the C++ linkage specification LinkageSpec. If RBraceLoc is
16076/// valid, it's the position of the closing '}' brace in a linkage
16077/// specification that uses braces.
16078Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16079 Decl *LinkageSpec,
16080 SourceLocation RBraceLoc) {
16081 if (RBraceLoc.isValid()) {
16082 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16083 LSDecl->setRBraceLoc(RBraceLoc);
16084 }
16085 PopDeclContext();
16086 return LinkageSpec;
16087}
16088
16089Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16090 const ParsedAttributesView &AttrList,
16091 SourceLocation SemiLoc) {
16092 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16093 // Attribute declarations appertain to empty declaration so we handle
16094 // them here.
16095 ProcessDeclAttributeList(S, ED, AttrList);
16096
16097 CurContext->addDecl(ED);
16098 return ED;
16099}
16100
16101/// Perform semantic analysis for the variable declaration that
16102/// occurs within a C++ catch clause, returning the newly-created
16103/// variable.
16104VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16105 TypeSourceInfo *TInfo,
16106 SourceLocation StartLoc,
16107 SourceLocation Loc,
16108 IdentifierInfo *Name) {
16109 bool Invalid = false;
16110 QualType ExDeclType = TInfo->getType();
16111
16112 // Arrays and functions decay.
16113 if (ExDeclType->isArrayType())
16114 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16115 else if (ExDeclType->isFunctionType())
16116 ExDeclType = Context.getPointerType(ExDeclType);
16117
16118 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16119 // The exception-declaration shall not denote a pointer or reference to an
16120 // incomplete type, other than [cv] void*.
16121 // N2844 forbids rvalue references.
16122 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16123 Diag(Loc, diag::err_catch_rvalue_ref);
16124 Invalid = true;
16125 }
16126
16127 if (ExDeclType->isVariablyModifiedType()) {
16128 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16129 Invalid = true;
16130 }
16131
16132 QualType BaseType = ExDeclType;
16133 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16134 unsigned DK = diag::err_catch_incomplete;
16135 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16136 BaseType = Ptr->getPointeeType();
16137 Mode = 1;
16138 DK = diag::err_catch_incomplete_ptr;
16139 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16140 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16141 BaseType = Ref->getPointeeType();
16142 Mode = 2;
16143 DK = diag::err_catch_incomplete_ref;
16144 }
16145 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16146 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16147 Invalid = true;
16148
16149 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16150 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16151 Invalid = true;
16152 }
16153
16154 if (!Invalid && !ExDeclType->isDependentType() &&
16155 RequireNonAbstractType(Loc, ExDeclType,
16156 diag::err_abstract_type_in_decl,
16157 AbstractVariableType))
16158 Invalid = true;
16159
16160 // Only the non-fragile NeXT runtime currently supports C++ catches
16161 // of ObjC types, and no runtime supports catching ObjC types by value.
16162 if (!Invalid && getLangOpts().ObjC) {
16163 QualType T = ExDeclType;
16164 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16165 T = RT->getPointeeType();
16166
16167 if (T->isObjCObjectType()) {
16168 Diag(Loc, diag::err_objc_object_catch);
16169 Invalid = true;
16170 } else if (T->isObjCObjectPointerType()) {
16171 // FIXME: should this be a test for macosx-fragile specifically?
16172 if (getLangOpts().ObjCRuntime.isFragile())
16173 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16174 }
16175 }
16176
16177 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16178 ExDeclType, TInfo, SC_None);
16179 ExDecl->setExceptionVariable(true);
16180
16181 // In ARC, infer 'retaining' for variables of retainable type.
16182 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16183 Invalid = true;
16184
16185 if (!Invalid && !ExDeclType->isDependentType()) {
16186 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16187 // Insulate this from anything else we might currently be parsing.
16188 EnterExpressionEvaluationContext scope(
16189 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16190
16191 // C++ [except.handle]p16:
16192 // The object declared in an exception-declaration or, if the
16193 // exception-declaration does not specify a name, a temporary (12.2) is
16194 // copy-initialized (8.5) from the exception object. [...]
16195 // The object is destroyed when the handler exits, after the destruction
16196 // of any automatic objects initialized within the handler.
16197 //
16198 // We just pretend to initialize the object with itself, then make sure
16199 // it can be destroyed later.
16200 QualType initType = Context.getExceptionObjectType(ExDeclType);
16201
16202 InitializedEntity entity =
16203 InitializedEntity::InitializeVariable(ExDecl);
16204 InitializationKind initKind =
16205 InitializationKind::CreateCopy(Loc, SourceLocation());
16206
16207 Expr *opaqueValue =
16208 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16209 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16210 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16211 if (result.isInvalid())
16212 Invalid = true;
16213 else {
16214 // If the constructor used was non-trivial, set this as the
16215 // "initializer".
16216 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16217 if (!construct->getConstructor()->isTrivial()) {
16218 Expr *init = MaybeCreateExprWithCleanups(construct);
16219 ExDecl->setInit(init);
16220 }
16221
16222 // And make sure it's destructable.
16223 FinalizeVarWithDestructor(ExDecl, recordType);
16224 }
16225 }
16226 }
16227
16228 if (Invalid)
16229 ExDecl->setInvalidDecl();
16230
16231 return ExDecl;
16232}
16233
16234/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16235/// handler.
16236Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16237 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16238 bool Invalid = D.isInvalidType();
16239
16240 // Check for unexpanded parameter packs.
16241 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16242 UPPC_ExceptionType)) {
16243 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16244 D.getIdentifierLoc());
16245 Invalid = true;
16246 }
16247
16248 IdentifierInfo *II = D.getIdentifier();
16249 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16250 LookupOrdinaryName,
16251 ForVisibleRedeclaration)) {
16252 // The scope should be freshly made just for us. There is just no way
16253 // it contains any previous declaration, except for function parameters in
16254 // a function-try-block's catch statement.
16255 assert(!S->isDeclScope(PrevDecl))(static_cast <bool> (!S->isDeclScope(PrevDecl)) ? void
(0) : __assert_fail ("!S->isDeclScope(PrevDecl)", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 16255, __extension__ __PRETTY_FUNCTION__))
;
16256 if (isDeclInScope(PrevDecl, CurContext, S)) {
16257 Diag(D.getIdentifierLoc(), diag::err_redefinition)
16258 << D.getIdentifier();
16259 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16260 Invalid = true;
16261 } else if (PrevDecl->isTemplateParameter())
16262 // Maybe we will complain about the shadowed template parameter.
16263 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16264 }
16265
16266 if (D.getCXXScopeSpec().isSet() && !Invalid) {
16267 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16268 << D.getCXXScopeSpec().getRange();
16269 Invalid = true;
16270 }
16271
16272 VarDecl *ExDecl = BuildExceptionDeclaration(
16273 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16274 if (Invalid)
16275 ExDecl->setInvalidDecl();
16276
16277 // Add the exception declaration into this scope.
16278 if (II)
16279 PushOnScopeChains(ExDecl, S);
16280 else
16281 CurContext->addDecl(ExDecl);
16282
16283 ProcessDeclAttributes(S, ExDecl, D);
16284 return ExDecl;
16285}
16286
16287Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16288 Expr *AssertExpr,
16289 Expr *AssertMessageExpr,
16290 SourceLocation RParenLoc) {
16291 StringLiteral *AssertMessage =
16292 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16293
16294 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16295 return nullptr;
16296
16297 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16298 AssertMessage, RParenLoc, false);
16299}
16300
16301Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16302 Expr *AssertExpr,
16303 StringLiteral *AssertMessage,
16304 SourceLocation RParenLoc,
16305 bool Failed) {
16306 assert(AssertExpr != nullptr && "Expected non-null condition")(static_cast <bool> (AssertExpr != nullptr && "Expected non-null condition"
) ? void (0) : __assert_fail ("AssertExpr != nullptr && \"Expected non-null condition\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 16306, __extension__ __PRETTY_FUNCTION__))
;
16307 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16308 !Failed) {
16309 // In a static_assert-declaration, the constant-expression shall be a
16310 // constant expression that can be contextually converted to bool.
16311 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16312 if (Converted.isInvalid())
16313 Failed = true;
16314
16315 ExprResult FullAssertExpr =
16316 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16317 /*DiscardedValue*/ false,
16318 /*IsConstexpr*/ true);
16319 if (FullAssertExpr.isInvalid())
16320 Failed = true;
16321 else
16322 AssertExpr = FullAssertExpr.get();
16323
16324 llvm::APSInt Cond;
16325 if (!Failed && VerifyIntegerConstantExpression(
16326 AssertExpr, &Cond,
16327 diag::err_static_assert_expression_is_not_constant)
16328 .isInvalid())
16329 Failed = true;
16330
16331 if (!Failed && !Cond) {
16332 SmallString<256> MsgBuffer;
16333 llvm::raw_svector_ostream Msg(MsgBuffer);
16334 if (AssertMessage)
16335 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16336
16337 Expr *InnerCond = nullptr;
16338 std::string InnerCondDescription;
16339 std::tie(InnerCond, InnerCondDescription) =
16340 findFailedBooleanCondition(Converted.get());
16341 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16342 // Drill down into concept specialization expressions to see why they
16343 // weren't satisfied.
16344 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16345 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16346 ConstraintSatisfaction Satisfaction;
16347 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16348 DiagnoseUnsatisfiedConstraint(Satisfaction);
16349 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16350 && !isa<IntegerLiteral>(InnerCond)) {
16351 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16352 << InnerCondDescription << !AssertMessage
16353 << Msg.str() << InnerCond->getSourceRange();
16354 } else {
16355 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16356 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16357 }
16358 Failed = true;
16359 }
16360 } else {
16361 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16362 /*DiscardedValue*/false,
16363 /*IsConstexpr*/true);
16364 if (FullAssertExpr.isInvalid())
16365 Failed = true;
16366 else
16367 AssertExpr = FullAssertExpr.get();
16368 }
16369
16370 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16371 AssertExpr, AssertMessage, RParenLoc,
16372 Failed);
16373
16374 CurContext->addDecl(Decl);
16375 return Decl;
16376}
16377
16378/// Perform semantic analysis of the given friend type declaration.
16379///
16380/// \returns A friend declaration that.
16381FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16382 SourceLocation FriendLoc,
16383 TypeSourceInfo *TSInfo) {
16384 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration")(static_cast <bool> (TSInfo && "NULL TypeSourceInfo for friend type declaration"
) ? void (0) : __assert_fail ("TSInfo && \"NULL TypeSourceInfo for friend type declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 16384, __extension__ __PRETTY_FUNCTION__))
;
16385
16386 QualType T = TSInfo->getType();
16387 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16388
16389 // C++03 [class.friend]p2:
16390 // An elaborated-type-specifier shall be used in a friend declaration
16391 // for a class.*
16392 //
16393 // * The class-key of the elaborated-type-specifier is required.
16394 if (!CodeSynthesisContexts.empty()) {
16395 // Do not complain about the form of friend template types during any kind
16396 // of code synthesis. For template instantiation, we will have complained
16397 // when the template was defined.
16398 } else {
16399 if (!T->isElaboratedTypeSpecifier()) {
16400 // If we evaluated the type to a record type, suggest putting
16401 // a tag in front.
16402 if (const RecordType *RT = T->getAs<RecordType>()) {
16403 RecordDecl *RD = RT->getDecl();
16404
16405 SmallString<16> InsertionText(" ");
16406 InsertionText += RD->getKindName();
16407
16408 Diag(TypeRange.getBegin(),
16409 getLangOpts().CPlusPlus11 ?
16410 diag::warn_cxx98_compat_unelaborated_friend_type :
16411 diag::ext_unelaborated_friend_type)
16412 << (unsigned) RD->getTagKind()
16413 << T
16414 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16415 InsertionText);
16416 } else {
16417 Diag(FriendLoc,
16418 getLangOpts().CPlusPlus11 ?
16419 diag::warn_cxx98_compat_nonclass_type_friend :
16420 diag::ext_nonclass_type_friend)
16421 << T
16422 << TypeRange;
16423 }
16424 } else if (T->getAs<EnumType>()) {
16425 Diag(FriendLoc,
16426 getLangOpts().CPlusPlus11 ?
16427 diag::warn_cxx98_compat_enum_friend :
16428 diag::ext_enum_friend)
16429 << T
16430 << TypeRange;
16431 }
16432
16433 // C++11 [class.friend]p3:
16434 // A friend declaration that does not declare a function shall have one
16435 // of the following forms:
16436 // friend elaborated-type-specifier ;
16437 // friend simple-type-specifier ;
16438 // friend typename-specifier ;
16439 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16440 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16441 }
16442
16443 // If the type specifier in a friend declaration designates a (possibly
16444 // cv-qualified) class type, that class is declared as a friend; otherwise,
16445 // the friend declaration is ignored.
16446 return FriendDecl::Create(Context, CurContext,
16447 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16448 FriendLoc);
16449}
16450
16451/// Handle a friend tag declaration where the scope specifier was
16452/// templated.
16453Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16454 unsigned TagSpec, SourceLocation TagLoc,
16455 CXXScopeSpec &SS, IdentifierInfo *Name,
16456 SourceLocation NameLoc,
16457 const ParsedAttributesView &Attr,
16458 MultiTemplateParamsArg TempParamLists) {
16459 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16460
16461 bool IsMemberSpecialization = false;
16462 bool Invalid = false;
16463
16464 if (TemplateParameterList *TemplateParams =
16465 MatchTemplateParametersToScopeSpecifier(
16466 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16467 IsMemberSpecialization, Invalid)) {
16468 if (TemplateParams->size() > 0) {
16469 // This is a declaration of a class template.
16470 if (Invalid)
16471 return nullptr;
16472
16473 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16474 NameLoc, Attr, TemplateParams, AS_public,
16475 /*ModulePrivateLoc=*/SourceLocation(),
16476 FriendLoc, TempParamLists.size() - 1,
16477 TempParamLists.data()).get();
16478 } else {
16479 // The "template<>" header is extraneous.
16480 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16481 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16482 IsMemberSpecialization = true;
16483 }
16484 }
16485
16486 if (Invalid) return nullptr;
16487
16488 bool isAllExplicitSpecializations = true;
16489 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16490 if (TempParamLists[I]->size()) {
16491 isAllExplicitSpecializations = false;
16492 break;
16493 }
16494 }
16495
16496 // FIXME: don't ignore attributes.
16497
16498 // If it's explicit specializations all the way down, just forget
16499 // about the template header and build an appropriate non-templated
16500 // friend. TODO: for source fidelity, remember the headers.
16501 if (isAllExplicitSpecializations) {
16502 if (SS.isEmpty()) {
16503 bool Owned = false;
16504 bool IsDependent = false;
16505 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16506 Attr, AS_public,
16507 /*ModulePrivateLoc=*/SourceLocation(),
16508 MultiTemplateParamsArg(), Owned, IsDependent,
16509 /*ScopedEnumKWLoc=*/SourceLocation(),
16510 /*ScopedEnumUsesClassTag=*/false,
16511 /*UnderlyingType=*/TypeResult(),
16512 /*IsTypeSpecifier=*/false,
16513 /*IsTemplateParamOrArg=*/false);
16514 }
16515
16516 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16517 ElaboratedTypeKeyword Keyword
16518 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16519 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16520 *Name, NameLoc);
16521 if (T.isNull())
16522 return nullptr;
16523
16524 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16525 if (isa<DependentNameType>(T)) {
16526 DependentNameTypeLoc TL =
16527 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16528 TL.setElaboratedKeywordLoc(TagLoc);
16529 TL.setQualifierLoc(QualifierLoc);
16530 TL.setNameLoc(NameLoc);
16531 } else {
16532 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16533 TL.setElaboratedKeywordLoc(TagLoc);
16534 TL.setQualifierLoc(QualifierLoc);
16535 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16536 }
16537
16538 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16539 TSI, FriendLoc, TempParamLists);
16540 Friend->setAccess(AS_public);
16541 CurContext->addDecl(Friend);
16542 return Friend;
16543 }
16544
16545 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?")(static_cast <bool> (SS.isNotEmpty() && "valid templated tag with no SS and no direct?"
) ? void (0) : __assert_fail ("SS.isNotEmpty() && \"valid templated tag with no SS and no direct?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 16545, __extension__ __PRETTY_FUNCTION__))
;
16546
16547
16548
16549 // Handle the case of a templated-scope friend class. e.g.
16550 // template <class T> class A<T>::B;
16551 // FIXME: we don't support these right now.
16552 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16553 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16554 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16555 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16556 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16557 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16558 TL.setElaboratedKeywordLoc(TagLoc);
16559 TL.setQualifierLoc(SS.getWithLocInContext(Context));
16560 TL.setNameLoc(NameLoc);
16561
16562 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16563 TSI, FriendLoc, TempParamLists);
16564 Friend->setAccess(AS_public);
16565 Friend->setUnsupportedFriend(true);
16566 CurContext->addDecl(Friend);
16567 return Friend;
16568}
16569
16570/// Handle a friend type declaration. This works in tandem with
16571/// ActOnTag.
16572///
16573/// Notes on friend class templates:
16574///
16575/// We generally treat friend class declarations as if they were
16576/// declaring a class. So, for example, the elaborated type specifier
16577/// in a friend declaration is required to obey the restrictions of a
16578/// class-head (i.e. no typedefs in the scope chain), template
16579/// parameters are required to match up with simple template-ids, &c.
16580/// However, unlike when declaring a template specialization, it's
16581/// okay to refer to a template specialization without an empty
16582/// template parameter declaration, e.g.
16583/// friend class A<T>::B<unsigned>;
16584/// We permit this as a special case; if there are any template
16585/// parameters present at all, require proper matching, i.e.
16586/// template <> template \<class T> friend class A<int>::B;
16587Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16588 MultiTemplateParamsArg TempParams) {
16589 SourceLocation Loc = DS.getBeginLoc();
16590
16591 assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0)
: __assert_fail ("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 16591, __extension__ __PRETTY_FUNCTION__))
;
16592 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_unspecified) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 16592, __extension__ __PRETTY_FUNCTION__))
;
16593
16594 // C++ [class.friend]p3:
16595 // A friend declaration that does not declare a function shall have one of
16596 // the following forms:
16597 // friend elaborated-type-specifier ;
16598 // friend simple-type-specifier ;
16599 // friend typename-specifier ;
16600 //
16601 // Any declaration with a type qualifier does not have that form. (It's
16602 // legal to specify a qualified type as a friend, you just can't write the
16603 // keywords.)
16604 if (DS.getTypeQualifiers()) {
16605 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16606 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16607 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16608 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16609 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16610 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16611 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16612 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16613 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16614 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16615 }
16616
16617 // Try to convert the decl specifier to a type. This works for
16618 // friend templates because ActOnTag never produces a ClassTemplateDecl
16619 // for a TUK_Friend.
16620 Declarator TheDeclarator(DS, DeclaratorContext::Member);
16621 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16622 QualType T = TSI->getType();
16623 if (TheDeclarator.isInvalidType())
16624 return nullptr;
16625
16626 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16627 return nullptr;
16628
16629 // This is definitely an error in C++98. It's probably meant to
16630 // be forbidden in C++0x, too, but the specification is just
16631 // poorly written.
16632 //
16633 // The problem is with declarations like the following:
16634 // template <T> friend A<T>::foo;
16635 // where deciding whether a class C is a friend or not now hinges
16636 // on whether there exists an instantiation of A that causes
16637 // 'foo' to equal C. There are restrictions on class-heads
16638 // (which we declare (by fiat) elaborated friend declarations to
16639 // be) that makes this tractable.
16640 //
16641 // FIXME: handle "template <> friend class A<T>;", which
16642 // is possibly well-formed? Who even knows?
16643 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16644 Diag(Loc, diag::err_tagless_friend_type_template)
16645 << DS.getSourceRange();
16646 return nullptr;
16647 }
16648
16649 // C++98 [class.friend]p1: A friend of a class is a function
16650 // or class that is not a member of the class . . .
16651 // This is fixed in DR77, which just barely didn't make the C++03
16652 // deadline. It's also a very silly restriction that seriously
16653 // affects inner classes and which nobody else seems to implement;
16654 // thus we never diagnose it, not even in -pedantic.
16655 //
16656 // But note that we could warn about it: it's always useless to
16657 // friend one of your own members (it's not, however, worthless to
16658 // friend a member of an arbitrary specialization of your template).
16659
16660 Decl *D;
16661 if (!TempParams.empty())
16662 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16663 TempParams,
16664 TSI,
16665 DS.getFriendSpecLoc());
16666 else
16667 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16668
16669 if (!D)
16670 return nullptr;
16671
16672 D->setAccess(AS_public);
16673 CurContext->addDecl(D);
16674
16675 return D;
16676}
16677
16678NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16679 MultiTemplateParamsArg TemplateParams) {
16680 const DeclSpec &DS = D.getDeclSpec();
16681
16682 assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0)
: __assert_fail ("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 16682, __extension__ __PRETTY_FUNCTION__))
;
16683 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_unspecified) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 16683, __extension__ __PRETTY_FUNCTION__))
;
16684
16685 SourceLocation Loc = D.getIdentifierLoc();
16686 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16687
16688 // C++ [class.friend]p1
16689 // A friend of a class is a function or class....
16690 // Note that this sees through typedefs, which is intended.
16691 // It *doesn't* see through dependent types, which is correct
16692 // according to [temp.arg.type]p3:
16693 // If a declaration acquires a function type through a
16694 // type dependent on a template-parameter and this causes
16695 // a declaration that does not use the syntactic form of a
16696 // function declarator to have a function type, the program
16697 // is ill-formed.
16698 if (!TInfo->getType()->isFunctionType()) {
16699 Diag(Loc, diag::err_unexpected_friend);
16700
16701 // It might be worthwhile to try to recover by creating an
16702 // appropriate declaration.
16703 return nullptr;
16704 }
16705
16706 // C++ [namespace.memdef]p3
16707 // - If a friend declaration in a non-local class first declares a
16708 // class or function, the friend class or function is a member
16709 // of the innermost enclosing namespace.
16710 // - The name of the friend is not found by simple name lookup
16711 // until a matching declaration is provided in that namespace
16712 // scope (either before or after the class declaration granting
16713 // friendship).
16714 // - If a friend function is called, its name may be found by the
16715 // name lookup that considers functions from namespaces and
16716 // classes associated with the types of the function arguments.
16717 // - When looking for a prior declaration of a class or a function
16718 // declared as a friend, scopes outside the innermost enclosing
16719 // namespace scope are not considered.
16720
16721 CXXScopeSpec &SS = D.getCXXScopeSpec();
16722 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16723 assert(NameInfo.getName())(static_cast <bool> (NameInfo.getName()) ? void (0) : __assert_fail
("NameInfo.getName()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 16723, __extension__ __PRETTY_FUNCTION__))
;
16724
16725 // Check for unexpanded parameter packs.
16726 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16727 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16728 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16729 return nullptr;
16730
16731 // The context we found the declaration in, or in which we should
16732 // create the declaration.
16733 DeclContext *DC;
16734 Scope *DCScope = S;
16735 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16736 ForExternalRedeclaration);
16737
16738 // There are five cases here.
16739 // - There's no scope specifier and we're in a local class. Only look
16740 // for functions declared in the immediately-enclosing block scope.
16741 // We recover from invalid scope qualifiers as if they just weren't there.
16742 FunctionDecl *FunctionContainingLocalClass = nullptr;
16743 if ((SS.isInvalid() || !SS.isSet()) &&
16744 (FunctionContainingLocalClass =
16745 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16746 // C++11 [class.friend]p11:
16747 // If a friend declaration appears in a local class and the name
16748 // specified is an unqualified name, a prior declaration is
16749 // looked up without considering scopes that are outside the
16750 // innermost enclosing non-class scope. For a friend function
16751 // declaration, if there is no prior declaration, the program is
16752 // ill-formed.
16753
16754 // Find the innermost enclosing non-class scope. This is the block
16755 // scope containing the local class definition (or for a nested class,
16756 // the outer local class).
16757 DCScope = S->getFnParent();
16758
16759 // Look up the function name in the scope.
16760 Previous.clear(LookupLocalFriendName);
16761 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16762
16763 if (!Previous.empty()) {
16764 // All possible previous declarations must have the same context:
16765 // either they were declared at block scope or they are members of
16766 // one of the enclosing local classes.
16767 DC = Previous.getRepresentativeDecl()->getDeclContext();
16768 } else {
16769 // This is ill-formed, but provide the context that we would have
16770 // declared the function in, if we were permitted to, for error recovery.
16771 DC = FunctionContainingLocalClass;
16772 }
16773 adjustContextForLocalExternDecl(DC);
16774
16775 // C++ [class.friend]p6:
16776 // A function can be defined in a friend declaration of a class if and
16777 // only if the class is a non-local class (9.8), the function name is
16778 // unqualified, and the function has namespace scope.
16779 if (D.isFunctionDefinition()) {
16780 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16781 }
16782
16783 // - There's no scope specifier, in which case we just go to the
16784 // appropriate scope and look for a function or function template
16785 // there as appropriate.
16786 } else if (SS.isInvalid() || !SS.isSet()) {
16787 // C++11 [namespace.memdef]p3:
16788 // If the name in a friend declaration is neither qualified nor
16789 // a template-id and the declaration is a function or an
16790 // elaborated-type-specifier, the lookup to determine whether
16791 // the entity has been previously declared shall not consider
16792 // any scopes outside the innermost enclosing namespace.
16793 bool isTemplateId =
16794 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16795
16796 // Find the appropriate context according to the above.
16797 DC = CurContext;
16798
16799 // Skip class contexts. If someone can cite chapter and verse
16800 // for this behavior, that would be nice --- it's what GCC and
16801 // EDG do, and it seems like a reasonable intent, but the spec
16802 // really only says that checks for unqualified existing
16803 // declarations should stop at the nearest enclosing namespace,
16804 // not that they should only consider the nearest enclosing
16805 // namespace.
16806 while (DC->isRecord())
16807 DC = DC->getParent();
16808
16809 DeclContext *LookupDC = DC;
16810 while (LookupDC->isTransparentContext())
16811 LookupDC = LookupDC->getParent();
16812
16813 while (true) {
16814 LookupQualifiedName(Previous, LookupDC);
16815
16816 if (!Previous.empty()) {
16817 DC = LookupDC;
16818 break;
16819 }
16820
16821 if (isTemplateId) {
16822 if (isa<TranslationUnitDecl>(LookupDC)) break;
16823 } else {
16824 if (LookupDC->isFileContext()) break;
16825 }
16826 LookupDC = LookupDC->getParent();
16827 }
16828
16829 DCScope = getScopeForDeclContext(S, DC);
16830
16831 // - There's a non-dependent scope specifier, in which case we
16832 // compute it and do a previous lookup there for a function
16833 // or function template.
16834 } else if (!SS.getScopeRep()->isDependent()) {
16835 DC = computeDeclContext(SS);
16836 if (!DC) return nullptr;
16837
16838 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16839
16840 LookupQualifiedName(Previous, DC);
16841
16842 // C++ [class.friend]p1: A friend of a class is a function or
16843 // class that is not a member of the class . . .
16844 if (DC->Equals(CurContext))
16845 Diag(DS.getFriendSpecLoc(),
16846 getLangOpts().CPlusPlus11 ?
16847 diag::warn_cxx98_compat_friend_is_member :
16848 diag::err_friend_is_member);
16849
16850 if (D.isFunctionDefinition()) {
16851 // C++ [class.friend]p6:
16852 // A function can be defined in a friend declaration of a class if and
16853 // only if the class is a non-local class (9.8), the function name is
16854 // unqualified, and the function has namespace scope.
16855 //
16856 // FIXME: We should only do this if the scope specifier names the
16857 // innermost enclosing namespace; otherwise the fixit changes the
16858 // meaning of the code.
16859 SemaDiagnosticBuilder DB
16860 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16861
16862 DB << SS.getScopeRep();
16863 if (DC->isFileContext())
16864 DB << FixItHint::CreateRemoval(SS.getRange());
16865 SS.clear();
16866 }
16867
16868 // - There's a scope specifier that does not match any template
16869 // parameter lists, in which case we use some arbitrary context,
16870 // create a method or method template, and wait for instantiation.
16871 // - There's a scope specifier that does match some template
16872 // parameter lists, which we don't handle right now.
16873 } else {
16874 if (D.isFunctionDefinition()) {
16875 // C++ [class.friend]p6:
16876 // A function can be defined in a friend declaration of a class if and
16877 // only if the class is a non-local class (9.8), the function name is
16878 // unqualified, and the function has namespace scope.
16879 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16880 << SS.getScopeRep();
16881 }
16882
16883 DC = CurContext;
16884 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?")(static_cast <bool> (isa<CXXRecordDecl>(DC) &&
"friend declaration not in class?") ? void (0) : __assert_fail
("isa<CXXRecordDecl>(DC) && \"friend declaration not in class?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 16884, __extension__ __PRETTY_FUNCTION__))
;
16885 }
16886
16887 if (!DC->isRecord()) {
16888 int DiagArg = -1;
16889 switch (D.getName().getKind()) {
16890 case UnqualifiedIdKind::IK_ConstructorTemplateId:
16891 case UnqualifiedIdKind::IK_ConstructorName:
16892 DiagArg = 0;
16893 break;
16894 case UnqualifiedIdKind::IK_DestructorName:
16895 DiagArg = 1;
16896 break;
16897 case UnqualifiedIdKind::IK_ConversionFunctionId:
16898 DiagArg = 2;
16899 break;
16900 case UnqualifiedIdKind::IK_DeductionGuideName:
16901 DiagArg = 3;
16902 break;
16903 case UnqualifiedIdKind::IK_Identifier:
16904 case UnqualifiedIdKind::IK_ImplicitSelfParam:
16905 case UnqualifiedIdKind::IK_LiteralOperatorId:
16906 case UnqualifiedIdKind::IK_OperatorFunctionId:
16907 case UnqualifiedIdKind::IK_TemplateId:
16908 break;
16909 }
16910 // This implies that it has to be an operator or function.
16911 if (DiagArg >= 0) {
16912 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16913 return nullptr;
16914 }
16915 }
16916
16917 // FIXME: This is an egregious hack to cope with cases where the scope stack
16918 // does not contain the declaration context, i.e., in an out-of-line
16919 // definition of a class.
16920 Scope FakeDCScope(S, Scope::DeclScope, Diags);
16921 if (!DCScope) {
16922 FakeDCScope.setEntity(DC);
16923 DCScope = &FakeDCScope;
16924 }
16925
16926 bool AddToScope = true;
16927 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16928 TemplateParams, AddToScope);
16929 if (!ND) return nullptr;
16930
16931 assert(ND->getLexicalDeclContext() == CurContext)(static_cast <bool> (ND->getLexicalDeclContext() == CurContext
) ? void (0) : __assert_fail ("ND->getLexicalDeclContext() == CurContext"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 16931, __extension__ __PRETTY_FUNCTION__))
;
16932
16933 // If we performed typo correction, we might have added a scope specifier
16934 // and changed the decl context.
16935 DC = ND->getDeclContext();
16936
16937 // Add the function declaration to the appropriate lookup tables,
16938 // adjusting the redeclarations list as necessary. We don't
16939 // want to do this yet if the friending class is dependent.
16940 //
16941 // Also update the scope-based lookup if the target context's
16942 // lookup context is in lexical scope.
16943 if (!CurContext->isDependentContext()) {
16944 DC = DC->getRedeclContext();
16945 DC->makeDeclVisibleInContext(ND);
16946 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16947 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16948 }
16949
16950 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16951 D.getIdentifierLoc(), ND,
16952 DS.getFriendSpecLoc());
16953 FrD->setAccess(AS_public);
16954 CurContext->addDecl(FrD);
16955
16956 if (ND->isInvalidDecl()) {
16957 FrD->setInvalidDecl();
16958 } else {
16959 if (DC->isRecord()) CheckFriendAccess(ND);
16960
16961 FunctionDecl *FD;
16962 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16963 FD = FTD->getTemplatedDecl();
16964 else
16965 FD = cast<FunctionDecl>(ND);
16966
16967 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16968 // default argument expression, that declaration shall be a definition
16969 // and shall be the only declaration of the function or function
16970 // template in the translation unit.
16971 if (functionDeclHasDefaultArgument(FD)) {
16972 // We can't look at FD->getPreviousDecl() because it may not have been set
16973 // if we're in a dependent context. If the function is known to be a
16974 // redeclaration, we will have narrowed Previous down to the right decl.
16975 if (D.isRedeclaration()) {
16976 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16977 Diag(Previous.getRepresentativeDecl()->getLocation(),
16978 diag::note_previous_declaration);
16979 } else if (!D.isFunctionDefinition())
16980 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16981 }
16982
16983 // Mark templated-scope function declarations as unsupported.
16984 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16985 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16986 << SS.getScopeRep() << SS.getRange()
16987 << cast<CXXRecordDecl>(CurContext);
16988 FrD->setUnsupportedFriend(true);
16989 }
16990 }
16991
16992 warnOnReservedIdentifier(ND);
16993
16994 return ND;
16995}
16996
16997void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16998 AdjustDeclIfTemplate(Dcl);
16999
17000 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17001 if (!Fn) {
17002 Diag(DelLoc, diag::err_deleted_non_function);
17003 return;
17004 }
17005
17006 // Deleted function does not have a body.
17007 Fn->setWillHaveBody(false);
17008
17009 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17010 // Don't consider the implicit declaration we generate for explicit
17011 // specializations. FIXME: Do not generate these implicit declarations.
17012 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17013 Prev->getPreviousDecl()) &&
17014 !Prev->isDefined()) {
17015 Diag(DelLoc, diag::err_deleted_decl_not_first);
17016 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17017 Prev->isImplicit() ? diag::note_previous_implicit_declaration
17018 : diag::note_previous_declaration);
17019 // We can't recover from this; the declaration might have already
17020 // been used.
17021 Fn->setInvalidDecl();
17022 return;
17023 }
17024
17025 // To maintain the invariant that functions are only deleted on their first
17026 // declaration, mark the implicitly-instantiated declaration of the
17027 // explicitly-specialized function as deleted instead of marking the
17028 // instantiated redeclaration.
17029 Fn = Fn->getCanonicalDecl();
17030 }
17031
17032 // dllimport/dllexport cannot be deleted.
17033 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17034 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17035 Fn->setInvalidDecl();
17036 }
17037
17038 // C++11 [basic.start.main]p3:
17039 // A program that defines main as deleted [...] is ill-formed.
17040 if (Fn->isMain())
17041 Diag(DelLoc, diag::err_deleted_main);
17042
17043 // C++11 [dcl.fct.def.delete]p4:
17044 // A deleted function is implicitly inline.
17045 Fn->setImplicitlyInline();
17046 Fn->setDeletedAsWritten();
17047}
17048
17049void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17050 if (!Dcl || Dcl->isInvalidDecl())
17051 return;
17052
17053 auto *FD = dyn_cast<FunctionDecl>(Dcl);
17054 if (!FD) {
17055 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17056 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17057 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17058 return;
17059 }
17060 }
17061
17062 Diag(DefaultLoc, diag::err_default_special_members)
17063 << getLangOpts().CPlusPlus20;
17064 return;
17065 }
17066
17067 // Reject if this can't possibly be a defaultable function.
17068 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17069 if (!DefKind &&
17070 // A dependent function that doesn't locally look defaultable can
17071 // still instantiate to a defaultable function if it's a constructor
17072 // or assignment operator.
17073 (!FD->isDependentContext() ||
17074 (!isa<CXXConstructorDecl>(FD) &&
17075 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17076 Diag(DefaultLoc, diag::err_default_special_members)
17077 << getLangOpts().CPlusPlus20;
17078 return;
17079 }
17080
17081 if (DefKind.isComparison() &&
17082 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
17083 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
17084 << (int)DefKind.asComparison();
17085 return;
17086 }
17087
17088 // Issue compatibility warning. We already warned if the operator is
17089 // 'operator<=>' when parsing the '<=>' token.
17090 if (DefKind.isComparison() &&
17091 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17092 Diag(DefaultLoc, getLangOpts().CPlusPlus20
17093 ? diag::warn_cxx17_compat_defaulted_comparison
17094 : diag::ext_defaulted_comparison);
17095 }
17096
17097 FD->setDefaulted();
17098 FD->setExplicitlyDefaulted();
17099
17100 // Defer checking functions that are defaulted in a dependent context.
17101 if (FD->isDependentContext())
17102 return;
17103
17104 // Unset that we will have a body for this function. We might not,
17105 // if it turns out to be trivial, and we don't need this marking now
17106 // that we've marked it as defaulted.
17107 FD->setWillHaveBody(false);
17108
17109 // If this definition appears within the record, do the checking when
17110 // the record is complete. This is always the case for a defaulted
17111 // comparison.
17112 if (DefKind.isComparison())
17113 return;
17114 auto *MD = cast<CXXMethodDecl>(FD);
17115
17116 const FunctionDecl *Primary = FD;
17117 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17118 // Ask the template instantiation pattern that actually had the
17119 // '= default' on it.
17120 Primary = Pattern;
17121
17122 // If the method was defaulted on its first declaration, we will have
17123 // already performed the checking in CheckCompletedCXXClass. Such a
17124 // declaration doesn't trigger an implicit definition.
17125 if (Primary->getCanonicalDecl()->isDefaulted())
17126 return;
17127
17128 // FIXME: Once we support defining comparisons out of class, check for a
17129 // defaulted comparison here.
17130 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17131 MD->setInvalidDecl();
17132 else
17133 DefineDefaultedFunction(*this, MD, DefaultLoc);
17134}
17135
17136static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17137 for (Stmt *SubStmt : S->children()) {
17138 if (!SubStmt)
17139 continue;
17140 if (isa<ReturnStmt>(SubStmt))
17141 Self.Diag(SubStmt->getBeginLoc(),
17142 diag::err_return_in_constructor_handler);
17143 if (!isa<Expr>(SubStmt))
17144 SearchForReturnInStmt(Self, SubStmt);
17145 }
17146}
17147
17148void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17149 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17150 CXXCatchStmt *Handler = TryBlock->getHandler(I);
17151 SearchForReturnInStmt(*this, Handler);
17152 }
17153}
17154
17155bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17156 const CXXMethodDecl *Old) {
17157 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17158 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17159
17160 if (OldFT->hasExtParameterInfos()) {
17161 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17162 // A parameter of the overriding method should be annotated with noescape
17163 // if the corresponding parameter of the overridden method is annotated.
17164 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17165 !NewFT->getExtParameterInfo(I).isNoEscape()) {
17166 Diag(New->getParamDecl(I)->getLocation(),
17167 diag::warn_overriding_method_missing_noescape);
17168 Diag(Old->getParamDecl(I)->getLocation(),
17169 diag::note_overridden_marked_noescape);
17170 }
17171 }
17172
17173 // Virtual overrides must have the same code_seg.
17174 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17175 const auto *NewCSA = New->getAttr<CodeSegAttr>();
17176 if ((NewCSA || OldCSA) &&
17177 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17178 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17179 Diag(Old->getLocation(), diag::note_previous_declaration);
17180 return true;
17181 }
17182
17183 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17184
17185 // If the calling conventions match, everything is fine
17186 if (NewCC == OldCC)
17187 return false;
17188
17189 // If the calling conventions mismatch because the new function is static,
17190 // suppress the calling convention mismatch error; the error about static
17191 // function override (err_static_overrides_virtual from
17192 // Sema::CheckFunctionDeclaration) is more clear.
17193 if (New->getStorageClass() == SC_Static)
17194 return false;
17195
17196 Diag(New->getLocation(),
17197 diag::err_conflicting_overriding_cc_attributes)
17198 << New->getDeclName() << New->getType() << Old->getType();
17199 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17200 return true;
17201}
17202
17203bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17204 const CXXMethodDecl *Old) {
17205 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17206 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17207
17208 if (Context.hasSameType(NewTy, OldTy) ||
17209 NewTy->isDependentType() || OldTy->isDependentType())
17210 return false;
17211
17212 // Check if the return types are covariant
17213 QualType NewClassTy, OldClassTy;
17214
17215 /// Both types must be pointers or references to classes.
17216 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17217 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17218 NewClassTy = NewPT->getPointeeType();
17219 OldClassTy = OldPT->getPointeeType();
17220 }
17221 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17222 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17223 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17224 NewClassTy = NewRT->getPointeeType();
17225 OldClassTy = OldRT->getPointeeType();
17226 }
17227 }
17228 }
17229
17230 // The return types aren't either both pointers or references to a class type.
17231 if (NewClassTy.isNull()) {
17232 Diag(New->getLocation(),
17233 diag::err_different_return_type_for_overriding_virtual_function)
17234 << New->getDeclName() << NewTy << OldTy
17235 << New->getReturnTypeSourceRange();
17236 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17237 << Old->getReturnTypeSourceRange();
17238
17239 return true;
17240 }
17241
17242 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17243 // C++14 [class.virtual]p8:
17244 // If the class type in the covariant return type of D::f differs from
17245 // that of B::f, the class type in the return type of D::f shall be
17246 // complete at the point of declaration of D::f or shall be the class
17247 // type D.
17248 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17249 if (!RT->isBeingDefined() &&
17250 RequireCompleteType(New->getLocation(), NewClassTy,
17251 diag::err_covariant_return_incomplete,
17252 New->getDeclName()))
17253 return true;
17254 }
17255
17256 // Check if the new class derives from the old class.
17257 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17258 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17259 << New->getDeclName() << NewTy << OldTy
17260 << New->getReturnTypeSourceRange();
17261 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17262 << Old->getReturnTypeSourceRange();
17263 return true;
17264 }
17265
17266 // Check if we the conversion from derived to base is valid.
17267 if (CheckDerivedToBaseConversion(
17268 NewClassTy, OldClassTy,
17269 diag::err_covariant_return_inaccessible_base,
17270 diag::err_covariant_return_ambiguous_derived_to_base_conv,
17271 New->getLocation(), New->getReturnTypeSourceRange(),
17272 New->getDeclName(), nullptr)) {
17273 // FIXME: this note won't trigger for delayed access control
17274 // diagnostics, and it's impossible to get an undelayed error
17275 // here from access control during the original parse because
17276 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17277 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17278 << Old->getReturnTypeSourceRange();
17279 return true;
17280 }
17281 }
17282
17283 // The qualifiers of the return types must be the same.
17284 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17285 Diag(New->getLocation(),
17286 diag::err_covariant_return_type_different_qualifications)
17287 << New->getDeclName() << NewTy << OldTy
17288 << New->getReturnTypeSourceRange();
17289 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17290 << Old->getReturnTypeSourceRange();
17291 return true;
17292 }
17293
17294
17295 // The new class type must have the same or less qualifiers as the old type.
17296 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17297 Diag(New->getLocation(),
17298 diag::err_covariant_return_type_class_type_more_qualified)
17299 << New->getDeclName() << NewTy << OldTy
17300 << New->getReturnTypeSourceRange();
17301 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17302 << Old->getReturnTypeSourceRange();
17303 return true;
17304 }
17305
17306 return false;
17307}
17308
17309/// Mark the given method pure.
17310///
17311/// \param Method the method to be marked pure.
17312///
17313/// \param InitRange the source range that covers the "0" initializer.
17314bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17315 SourceLocation EndLoc = InitRange.getEnd();
17316 if (EndLoc.isValid())
17317 Method->setRangeEnd(EndLoc);
17318
17319 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17320 Method->setPure();
17321 return false;
17322 }
17323
17324 if (!Method->isInvalidDecl())
17325 Diag(Method->getLocation(), diag::err_non_virtual_pure)
17326 << Method->getDeclName() << InitRange;
17327 return true;
17328}
17329
17330void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17331 if (D->getFriendObjectKind())
17332 Diag(D->getLocation(), diag::err_pure_friend);
17333 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17334 CheckPureMethod(M, ZeroLoc);
17335 else
17336 Diag(D->getLocation(), diag::err_illegal_initializer);
17337}
17338
17339/// Determine whether the given declaration is a global variable or
17340/// static data member.
17341static bool isNonlocalVariable(const Decl *D) {
17342 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17343 return Var->hasGlobalStorage();
17344
17345 return false;
17346}
17347
17348/// Invoked when we are about to parse an initializer for the declaration
17349/// 'Dcl'.
17350///
17351/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17352/// static data member of class X, names should be looked up in the scope of
17353/// class X. If the declaration had a scope specifier, a scope will have
17354/// been created and passed in for this purpose. Otherwise, S will be null.
17355void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17356 // If there is no declaration, there was an error parsing it.
17357 if (!D || D->isInvalidDecl())
17358 return;
17359
17360 // We will always have a nested name specifier here, but this declaration
17361 // might not be out of line if the specifier names the current namespace:
17362 // extern int n;
17363 // int ::n = 0;
17364 if (S && D->isOutOfLine())
17365 EnterDeclaratorContext(S, D->getDeclContext());
17366
17367 // If we are parsing the initializer for a static data member, push a
17368 // new expression evaluation context that is associated with this static
17369 // data member.
17370 if (isNonlocalVariable(D))
17371 PushExpressionEvaluationContext(
17372 ExpressionEvaluationContext::PotentiallyEvaluated, D);
17373}
17374
17375/// Invoked after we are finished parsing an initializer for the declaration D.
17376void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17377 // If there is no declaration, there was an error parsing it.
17378 if (!D || D->isInvalidDecl())
17379 return;
17380
17381 if (isNonlocalVariable(D))
17382 PopExpressionEvaluationContext();
17383
17384 if (S && D->isOutOfLine())
17385 ExitDeclaratorContext(S);
17386}
17387
17388/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17389/// C++ if/switch/while/for statement.
17390/// e.g: "if (int x = f()) {...}"
17391DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17392 // C++ 6.4p2:
17393 // The declarator shall not specify a function or an array.
17394 // The type-specifier-seq shall not contain typedef and shall not declare a
17395 // new class or enumeration.
17396 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&(static_cast <bool> (D.getDeclSpec().getStorageClassSpec
() != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class of condition decl."
) ? void (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 17397, __extension__ __PRETTY_FUNCTION__))
17397 "Parser allowed 'typedef' as storage class of condition decl.")(static_cast <bool> (D.getDeclSpec().getStorageClassSpec
() != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class of condition decl."
) ? void (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 17397, __extension__ __PRETTY_FUNCTION__))
;
17398
17399 Decl *Dcl = ActOnDeclarator(S, D);
17400 if (!Dcl)
17401 return true;
17402
17403 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17404 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17405 << D.getSourceRange();
17406 return true;
17407 }
17408
17409 return Dcl;
17410}
17411
17412void Sema::LoadExternalVTableUses() {
17413 if (!ExternalSource)
17414 return;
17415
17416 SmallVector<ExternalVTableUse, 4> VTables;
17417 ExternalSource->ReadUsedVTables(VTables);
17418 SmallVector<VTableUse, 4> NewUses;
17419 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17420 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17421 = VTablesUsed.find(VTables[I].Record);
17422 // Even if a definition wasn't required before, it may be required now.
17423 if (Pos != VTablesUsed.end()) {
17424 if (!Pos->second && VTables[I].DefinitionRequired)
17425 Pos->second = true;
17426 continue;
17427 }
17428
17429 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17430 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17431 }
17432
17433 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17434}
17435
17436void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17437 bool DefinitionRequired) {
17438 // Ignore any vtable uses in unevaluated operands or for classes that do
17439 // not have a vtable.
17440 if (!Class->isDynamicClass() || Class->isDependentContext() ||
17441 CurContext->isDependentContext() || isUnevaluatedContext())
17442 return;
17443 // Do not mark as used if compiling for the device outside of the target
17444 // region.
17445 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17446 !isInOpenMPDeclareTargetContext() &&
17447 !isInOpenMPTargetExecutionDirective()) {
17448 if (!DefinitionRequired)
17449 MarkVirtualMembersReferenced(Loc, Class);
17450 return;
17451 }
17452
17453 // Try to insert this class into the map.
17454 LoadExternalVTableUses();
17455 Class = Class->getCanonicalDecl();
17456 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17457 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17458 if (!Pos.second) {
17459 // If we already had an entry, check to see if we are promoting this vtable
17460 // to require a definition. If so, we need to reappend to the VTableUses
17461 // list, since we may have already processed the first entry.
17462 if (DefinitionRequired && !Pos.first->second) {
17463 Pos.first->second = true;
17464 } else {
17465 // Otherwise, we can early exit.
17466 return;
17467 }
17468 } else {
17469 // The Microsoft ABI requires that we perform the destructor body
17470 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17471 // the deleting destructor is emitted with the vtable, not with the
17472 // destructor definition as in the Itanium ABI.
17473 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17474 CXXDestructorDecl *DD = Class->getDestructor();
17475 if (DD && DD->isVirtual() && !DD->isDeleted()) {
17476 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17477 // If this is an out-of-line declaration, marking it referenced will
17478 // not do anything. Manually call CheckDestructor to look up operator
17479 // delete().
17480 ContextRAII SavedContext(*this, DD);
17481 CheckDestructor(DD);
17482 } else {
17483 MarkFunctionReferenced(Loc, Class->getDestructor());
17484 }
17485 }
17486 }
17487 }
17488
17489 // Local classes need to have their virtual members marked
17490 // immediately. For all other classes, we mark their virtual members
17491 // at the end of the translation unit.
17492 if (Class->isLocalClass())
17493 MarkVirtualMembersReferenced(Loc, Class);
17494 else
17495 VTableUses.push_back(std::make_pair(Class, Loc));
17496}
17497
17498bool Sema::DefineUsedVTables() {
17499 LoadExternalVTableUses();
17500 if (VTableUses.empty())
17501 return false;
17502
17503 // Note: The VTableUses vector could grow as a result of marking
17504 // the members of a class as "used", so we check the size each
17505 // time through the loop and prefer indices (which are stable) to
17506 // iterators (which are not).
17507 bool DefinedAnything = false;
17508 for (unsigned I = 0; I != VTableUses.size(); ++I) {
17509 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17510 if (!Class)
17511 continue;
17512 TemplateSpecializationKind ClassTSK =
17513 Class->getTemplateSpecializationKind();
17514
17515 SourceLocation Loc = VTableUses[I].second;
17516
17517 bool DefineVTable = true;
17518
17519 // If this class has a key function, but that key function is
17520 // defined in another translation unit, we don't need to emit the
17521 // vtable even though we're using it.
17522 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17523 if (KeyFunction && !KeyFunction->hasBody()) {
17524 // The key function is in another translation unit.
17525 DefineVTable = false;
17526 TemplateSpecializationKind TSK =
17527 KeyFunction->getTemplateSpecializationKind();
17528 assert(TSK != TSK_ExplicitInstantiationDefinition &&(static_cast <bool> (TSK != TSK_ExplicitInstantiationDefinition
&& TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? void (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 17530, __extension__ __PRETTY_FUNCTION__))
17529 TSK != TSK_ImplicitInstantiation &&(static_cast <bool> (TSK != TSK_ExplicitInstantiationDefinition
&& TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? void (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 17530, __extension__ __PRETTY_FUNCTION__))
17530 "Instantiations don't have key functions")(static_cast <bool> (TSK != TSK_ExplicitInstantiationDefinition
&& TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? void (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 17530, __extension__ __PRETTY_FUNCTION__))
;
17531 (void)TSK;
17532 } else if (!KeyFunction) {
17533 // If we have a class with no key function that is the subject
17534 // of an explicit instantiation declaration, suppress the
17535 // vtable; it will live with the explicit instantiation
17536 // definition.
17537 bool IsExplicitInstantiationDeclaration =
17538 ClassTSK == TSK_ExplicitInstantiationDeclaration;
17539 for (auto R : Class->redecls()) {
17540 TemplateSpecializationKind TSK
17541 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17542 if (TSK == TSK_ExplicitInstantiationDeclaration)
17543 IsExplicitInstantiationDeclaration = true;
17544 else if (TSK == TSK_ExplicitInstantiationDefinition) {
17545 IsExplicitInstantiationDeclaration = false;
17546 break;
17547 }
17548 }
17549
17550 if (IsExplicitInstantiationDeclaration)
17551 DefineVTable = false;
17552 }
17553
17554 // The exception specifications for all virtual members may be needed even
17555 // if we are not providing an authoritative form of the vtable in this TU.
17556 // We may choose to emit it available_externally anyway.
17557 if (!DefineVTable) {
17558 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17559 continue;
17560 }
17561
17562 // Mark all of the virtual members of this class as referenced, so
17563 // that we can build a vtable. Then, tell the AST consumer that a
17564 // vtable for this class is required.
17565 DefinedAnything = true;
17566 MarkVirtualMembersReferenced(Loc, Class);
17567 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17568 if (VTablesUsed[Canonical])
17569 Consumer.HandleVTable(Class);
17570
17571 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17572 // no key function or the key function is inlined. Don't warn in C++ ABIs
17573 // that lack key functions, since the user won't be able to make one.
17574 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17575 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17576 const FunctionDecl *KeyFunctionDef = nullptr;
17577 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17578 KeyFunctionDef->isInlined())) {
17579 Diag(Class->getLocation(),
17580 ClassTSK == TSK_ExplicitInstantiationDefinition
17581 ? diag::warn_weak_template_vtable
17582 : diag::warn_weak_vtable)
17583 << Class;
17584 }
17585 }
17586 }
17587 VTableUses.clear();
17588
17589 return DefinedAnything;
17590}
17591
17592void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17593 const CXXRecordDecl *RD) {
17594 for (const auto *I : RD->methods())
17595 if (I->isVirtual() && !I->isPure())
17596 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17597}
17598
17599void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17600 const CXXRecordDecl *RD,
17601 bool ConstexprOnly) {
17602 // Mark all functions which will appear in RD's vtable as used.
17603 CXXFinalOverriderMap FinalOverriders;
17604 RD->getFinalOverriders(FinalOverriders);
17605 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17606 E = FinalOverriders.end();
17607 I != E; ++I) {
17608 for (OverridingMethods::const_iterator OI = I->second.begin(),
17609 OE = I->second.end();
17610 OI != OE; ++OI) {
17611 assert(OI->second.size() > 0 && "no final overrider")(static_cast <bool> (OI->second.size() > 0 &&
"no final overrider") ? void (0) : __assert_fail ("OI->second.size() > 0 && \"no final overrider\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 17611, __extension__ __PRETTY_FUNCTION__))
;
17612 CXXMethodDecl *Overrider = OI->second.front().Method;
17613
17614 // C++ [basic.def.odr]p2:
17615 // [...] A virtual member function is used if it is not pure. [...]
17616 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17617 MarkFunctionReferenced(Loc, Overrider);
17618 }
17619 }
17620
17621 // Only classes that have virtual bases need a VTT.
17622 if (RD->getNumVBases() == 0)
17623 return;
17624
17625 for (const auto &I : RD->bases()) {
17626 const auto *Base =
17627 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17628 if (Base->getNumVBases() == 0)
17629 continue;
17630 MarkVirtualMembersReferenced(Loc, Base);
17631 }
17632}
17633
17634/// SetIvarInitializers - This routine builds initialization ASTs for the
17635/// Objective-C implementation whose ivars need be initialized.
17636void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17637 if (!getLangOpts().CPlusPlus)
17638 return;
17639 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17640 SmallVector<ObjCIvarDecl*, 8> ivars;
17641 CollectIvarsToConstructOrDestruct(OID, ivars);
17642 if (ivars.empty())
17643 return;
17644 SmallVector<CXXCtorInitializer*, 32> AllToInit;
17645 for (unsigned i = 0; i < ivars.size(); i++) {
17646 FieldDecl *Field = ivars[i];
17647 if (Field->isInvalidDecl())
17648 continue;
17649
17650 CXXCtorInitializer *Member;
17651 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17652 InitializationKind InitKind =
17653 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17654
17655 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17656 ExprResult MemberInit =
17657 InitSeq.Perform(*this, InitEntity, InitKind, None);
17658 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17659 // Note, MemberInit could actually come back empty if no initialization
17660 // is required (e.g., because it would call a trivial default constructor)
17661 if (!MemberInit.get() || MemberInit.isInvalid())
17662 continue;
17663
17664 Member =
17665 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17666 SourceLocation(),
17667 MemberInit.getAs<Expr>(),
17668 SourceLocation());
17669 AllToInit.push_back(Member);
17670
17671 // Be sure that the destructor is accessible and is marked as referenced.
17672 if (const RecordType *RecordTy =
17673 Context.getBaseElementType(Field->getType())
17674 ->getAs<RecordType>()) {
17675 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17676 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17677 MarkFunctionReferenced(Field->getLocation(), Destructor);
17678 CheckDestructorAccess(Field->getLocation(), Destructor,
17679 PDiag(diag::err_access_dtor_ivar)
17680 << Context.getBaseElementType(Field->getType()));
17681 }
17682 }
17683 }
17684 ObjCImplementation->setIvarInitializers(Context,
17685 AllToInit.data(), AllToInit.size());
17686 }
17687}
17688
17689static
17690void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17691 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17692 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17693 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17694 Sema &S) {
17695 if (Ctor->isInvalidDecl())
17696 return;
17697
17698 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17699
17700 // Target may not be determinable yet, for instance if this is a dependent
17701 // call in an uninstantiated template.
17702 if (Target) {
17703 const FunctionDecl *FNTarget = nullptr;
17704 (void)Target->hasBody(FNTarget);
17705 Target = const_cast<CXXConstructorDecl*>(
17706 cast_or_null<CXXConstructorDecl>(FNTarget));
17707 }
17708
17709 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17710 // Avoid dereferencing a null pointer here.
17711 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17712
17713 if (!Current.insert(Canonical).second)
17714 return;
17715
17716 // We know that beyond here, we aren't chaining into a cycle.
17717 if (!Target || !Target->isDelegatingConstructor() ||
17718 Target->isInvalidDecl() || Valid.count(TCanonical)) {
17719 Valid.insert(Current.begin(), Current.end());
17720 Current.clear();
17721 // We've hit a cycle.
17722 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17723 Current.count(TCanonical)) {
17724 // If we haven't diagnosed this cycle yet, do so now.
17725 if (!Invalid.count(TCanonical)) {
17726 S.Diag((*Ctor->init_begin())->getSourceLocation(),
17727 diag::warn_delegating_ctor_cycle)
17728 << Ctor;
17729
17730 // Don't add a note for a function delegating directly to itself.
17731 if (TCanonical != Canonical)
17732 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17733
17734 CXXConstructorDecl *C = Target;
17735 while (C->getCanonicalDecl() != Canonical) {
17736 const FunctionDecl *FNTarget = nullptr;
17737 (void)C->getTargetConstructor()->hasBody(FNTarget);
17738 assert(FNTarget && "Ctor cycle through bodiless function")(static_cast <bool> (FNTarget && "Ctor cycle through bodiless function"
) ? void (0) : __assert_fail ("FNTarget && \"Ctor cycle through bodiless function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 17738, __extension__ __PRETTY_FUNCTION__))
;
17739
17740 C = const_cast<CXXConstructorDecl*>(
17741 cast<CXXConstructorDecl>(FNTarget));
17742 S.Diag(C->getLocation(), diag::note_which_delegates_to);
17743 }
17744 }
17745
17746 Invalid.insert(Current.begin(), Current.end());
17747 Current.clear();
17748 } else {
17749 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17750 }
17751}
17752
17753
17754void Sema::CheckDelegatingCtorCycles() {
17755 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17756
17757 for (DelegatingCtorDeclsType::iterator
17758 I = DelegatingCtorDecls.begin(ExternalSource),
17759 E = DelegatingCtorDecls.end();
17760 I != E; ++I)
17761 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17762
17763 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17764 (*CI)->setInvalidDecl();
17765}
17766
17767namespace {
17768 /// AST visitor that finds references to the 'this' expression.
17769 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17770 Sema &S;
17771
17772 public:
17773 explicit FindCXXThisExpr(Sema &S) : S(S) { }
17774
17775 bool VisitCXXThisExpr(CXXThisExpr *E) {
17776 S.Diag(E->getLocation(), diag::err_this_static_member_func)
17777 << E->isImplicit();
17778 return false;
17779 }
17780 };
17781}
17782
17783bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17784 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17785 if (!TSInfo)
17786 return false;
17787
17788 TypeLoc TL = TSInfo->getTypeLoc();
17789 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17790 if (!ProtoTL)
17791 return false;
17792
17793 // C++11 [expr.prim.general]p3:
17794 // [The expression this] shall not appear before the optional
17795 // cv-qualifier-seq and it shall not appear within the declaration of a
17796 // static member function (although its type and value category are defined
17797 // within a static member function as they are within a non-static member
17798 // function). [ Note: this is because declaration matching does not occur
17799 // until the complete declarator is known. - end note ]
17800 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17801 FindCXXThisExpr Finder(*this);
17802
17803 // If the return type came after the cv-qualifier-seq, check it now.
17804 if (Proto->hasTrailingReturn() &&
17805 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17806 return true;
17807
17808 // Check the exception specification.
17809 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17810 return true;
17811
17812 // Check the trailing requires clause
17813 if (Expr *E = Method->getTrailingRequiresClause())
17814 if (!Finder.TraverseStmt(E))
17815 return true;
17816
17817 return checkThisInStaticMemberFunctionAttributes(Method);
17818}
17819
17820bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17821 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17822 if (!TSInfo)
17823 return false;
17824
17825 TypeLoc TL = TSInfo->getTypeLoc();
17826 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17827 if (!ProtoTL)
17828 return false;
17829
17830 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17831 FindCXXThisExpr Finder(*this);
17832
17833 switch (Proto->getExceptionSpecType()) {
17834 case EST_Unparsed:
17835 case EST_Uninstantiated:
17836 case EST_Unevaluated:
17837 case EST_BasicNoexcept:
17838 case EST_NoThrow:
17839 case EST_DynamicNone:
17840 case EST_MSAny:
17841 case EST_None:
17842 break;
17843
17844 case EST_DependentNoexcept:
17845 case EST_NoexceptFalse:
17846 case EST_NoexceptTrue:
17847 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17848 return true;
17849 LLVM_FALLTHROUGH[[gnu::fallthrough]];
17850
17851 case EST_Dynamic:
17852 for (const auto &E : Proto->exceptions()) {
17853 if (!Finder.TraverseType(E))
17854 return true;
17855 }
17856 break;
17857 }
17858
17859 return false;
17860}
17861
17862bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17863 FindCXXThisExpr Finder(*this);
17864
17865 // Check attributes.
17866 for (const auto *A : Method->attrs()) {
17867 // FIXME: This should be emitted by tblgen.
17868 Expr *Arg = nullptr;
17869 ArrayRef<Expr *> Args;
17870 if (const auto *G = dyn_cast<GuardedByAttr>(A))
17871 Arg = G->getArg();
17872 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17873 Arg = G->getArg();
17874 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17875 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17876 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17877 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17878 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17879 Arg = ETLF->getSuccessValue();
17880 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17881 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17882 Arg = STLF->getSuccessValue();
17883 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17884 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17885 Arg = LR->getArg();
17886 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17887 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17888 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17889 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17890 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17891 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17892 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17893 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17894 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17895 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17896
17897 if (Arg && !Finder.TraverseStmt(Arg))
17898 return true;
17899
17900 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17901 if (!Finder.TraverseStmt(Args[I]))
17902 return true;
17903 }
17904 }
17905
17906 return false;
17907}
17908
17909void Sema::checkExceptionSpecification(
17910 bool IsTopLevel, ExceptionSpecificationType EST,
17911 ArrayRef<ParsedType> DynamicExceptions,
17912 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17913 SmallVectorImpl<QualType> &Exceptions,
17914 FunctionProtoType::ExceptionSpecInfo &ESI) {
17915 Exceptions.clear();
17916 ESI.Type = EST;
17917 if (EST == EST_Dynamic) {
17918 Exceptions.reserve(DynamicExceptions.size());
17919 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17920 // FIXME: Preserve type source info.
17921 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17922
17923 if (IsTopLevel) {
17924 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17925 collectUnexpandedParameterPacks(ET, Unexpanded);
17926 if (!Unexpanded.empty()) {
17927 DiagnoseUnexpandedParameterPacks(
17928 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17929 Unexpanded);
17930 continue;
17931 }
17932 }
17933
17934 // Check that the type is valid for an exception spec, and
17935 // drop it if not.
17936 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17937 Exceptions.push_back(ET);
17938 }
17939 ESI.Exceptions = Exceptions;
17940 return;
17941 }
17942
17943 if (isComputedNoexcept(EST)) {
17944 assert((NoexceptExpr->isTypeDependent() ||(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 17947, __extension__ __PRETTY_FUNCTION__))
17945 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 17947, __extension__ __PRETTY_FUNCTION__))
17946 Context.BoolTy) &&(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 17947, __extension__ __PRETTY_FUNCTION__))
17947 "Parser should have made sure that the expression is boolean")(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaDeclCXX.cpp"
, 17947, __extension__ __PRETTY_FUNCTION__))
;
17948 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17949 ESI.Type = EST_BasicNoexcept;
17950 return;
17951 }
17952
17953 ESI.NoexceptExpr = NoexceptExpr;
17954 return;
17955 }
17956}
17957
17958void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17959 ExceptionSpecificationType EST,
17960 SourceRange SpecificationRange,
17961 ArrayRef<ParsedType> DynamicExceptions,
17962 ArrayRef<SourceRange> DynamicExceptionRanges,
17963 Expr *NoexceptExpr) {
17964 if (!MethodD)
17965 return;
17966
17967 // Dig out the method we're referring to.
17968 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17969 MethodD = FunTmpl->getTemplatedDecl();
17970
17971 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17972 if (!Method)
17973 return;
17974
17975 // Check the exception specification.
17976 llvm::SmallVector<QualType, 4> Exceptions;
17977 FunctionProtoType::ExceptionSpecInfo ESI;
17978 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17979 DynamicExceptionRanges, NoexceptExpr, Exceptions,
17980 ESI);
17981
17982 // Update the exception specification on the function type.
17983 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17984
17985 if (Method->isStatic())
17986 checkThisInStaticMemberFunctionExceptionSpec(Method);
17987
17988 if (Method->isVirtual()) {
17989 // Check overrides, which we previously had to delay.
17990 for (const CXXMethodDecl *O : Method->overridden_methods())
17991 CheckOverridingFunctionExceptionSpec(Method, O);
17992 }
17993}
17994
17995/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17996///
17997MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17998 SourceLocation DeclStart, Declarator &D,
17999 Expr *BitWidth,
18000 InClassInitStyle InitStyle,
18001 AccessSpecifier AS,
18002 const ParsedAttr &MSPropertyAttr) {
18003 IdentifierInfo *II = D.getIdentifier();
18004 if (!II) {
18005 Diag(DeclStart, diag::err_anonymous_property);
18006 return nullptr;
18007 }
18008 SourceLocation Loc = D.getIdentifierLoc();
18009
18010 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18011 QualType T = TInfo->getType();
18012 if (getLangOpts().CPlusPlus) {
18013 CheckExtraCXXDefaultArguments(D);
18014
18015 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18016 UPPC_DataMemberType)) {
18017 D.setInvalidType();
18018 T = Context.IntTy;
18019 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18020 }
18021 }
18022
18023 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18024
18025 if (D.getDeclSpec().isInlineSpecified())
18026 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18027 << getLangOpts().CPlusPlus17;
18028 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18029 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18030 diag::err_invalid_thread)
18031 << DeclSpec::getSpecifierName(TSCS);
18032
18033 // Check to see if this name was declared as a member previously
18034 NamedDecl *PrevDecl = nullptr;
18035 LookupResult Previous(*this, II, Loc, LookupMemberName,
18036 ForVisibleRedeclaration);
18037 LookupName(Previous, S);
18038 switch (Previous.getResultKind()) {
18039 case LookupResult::Found:
18040 case LookupResult::FoundUnresolvedValue:
18041 PrevDecl = Previous.getAsSingle<NamedDecl>();
18042 break;
18043
18044 case LookupResult::FoundOverloaded:
18045 PrevDecl = Previous.getRepresentativeDecl();
18046 break;
18047
18048 case LookupResult::NotFound:
18049 case LookupResult::NotFoundInCurrentInstantiation:
18050 case LookupResult::Ambiguous:
18051 break;
18052 }
18053
18054 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18055 // Maybe we will complain about the shadowed template parameter.
18056 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18057 // Just pretend that we didn't see the previous declaration.
18058 PrevDecl = nullptr;
18059 }
18060
18061 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18062 PrevDecl = nullptr;
18063
18064 SourceLocation TSSL = D.getBeginLoc();
18065 MSPropertyDecl *NewPD =
18066 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18067 MSPropertyAttr.getPropertyDataGetter(),
18068 MSPropertyAttr.getPropertyDataSetter());
18069 ProcessDeclAttributes(TUScope, NewPD, D);
18070 NewPD->setAccess(AS);
18071
18072 if (NewPD->isInvalidDecl())
18073 Record->setInvalidDecl();
18074
18075 if (D.getDeclSpec().isModulePrivateSpecified())
18076 NewPD->setModulePrivate();
18077
18078 if (NewPD->isInvalidDecl() && PrevDecl) {
18079 // Don't introduce NewFD into scope; there's already something
18080 // with the same name in the same scope.
18081 } else if (II) {
18082 PushOnScopeChains(NewPD, S);
18083 } else
18084 Record->addDecl(NewPD);
18085
18086 return NewPD;
18087}
18088
18089void Sema::ActOnStartFunctionDeclarationDeclarator(
18090 Declarator &Declarator, unsigned TemplateParameterDepth) {
18091 auto &Info = InventedParameterInfos.emplace_back();
18092 TemplateParameterList *ExplicitParams = nullptr;
18093 ArrayRef<TemplateParameterList *> ExplicitLists =
18094 Declarator.getTemplateParameterLists();
18095 if (!ExplicitLists.empty()) {
18096 bool IsMemberSpecialization, IsInvalid;
18097 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18098 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18099 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18100 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18101 /*SuppressDiagnostic=*/true);
18102 }
18103 if (ExplicitParams) {
18104 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18105 for (NamedDecl *Param : *ExplicitParams)
18106 Info.TemplateParams.push_back(Param);
18107 Info.NumExplicitTemplateParams = ExplicitParams->size();
18108 } else {
18109 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18110 Info.NumExplicitTemplateParams = 0;
18111 }
18112}
18113
18114void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18115 auto &FSI = InventedParameterInfos.back();
18116 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18117 if (FSI.NumExplicitTemplateParams != 0) {
18118 TemplateParameterList *ExplicitParams =
18119 Declarator.getTemplateParameterLists().back();
18120 Declarator.setInventedTemplateParameterList(
18121 TemplateParameterList::Create(
18122 Context, ExplicitParams->getTemplateLoc(),
18123 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18124 ExplicitParams->getRAngleLoc(),
18125 ExplicitParams->getRequiresClause()));
18126 } else {
18127 Declarator.setInventedTemplateParameterList(
18128 TemplateParameterList::Create(
18129 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18130 SourceLocation(), /*RequiresClause=*/nullptr));
18131 }
18132 }
18133 InventedParameterInfos.pop_back();
18134}

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/Ownership.h

1//===- Ownership.h - Parser ownership helpers -------------------*- 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// This file contains classes for managing ownership of Stmt and Expr nodes.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_SEMA_OWNERSHIP_H
14#define LLVM_CLANG_SEMA_OWNERSHIP_H
15
16#include "clang/AST/Expr.h"
17#include "clang/Basic/LLVM.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/Support/PointerLikeTypeTraits.h"
20#include "llvm/Support/type_traits.h"
21#include <cassert>
22#include <cstddef>
23#include <cstdint>
24
25//===----------------------------------------------------------------------===//
26// OpaquePtr
27//===----------------------------------------------------------------------===//
28
29namespace clang {
30
31class CXXBaseSpecifier;
32class CXXCtorInitializer;
33class Decl;
34class Expr;
35class ParsedTemplateArgument;
36class QualType;
37class Stmt;
38class TemplateName;
39class TemplateParameterList;
40
41 /// Wrapper for void* pointer.
42 /// \tparam PtrTy Either a pointer type like 'T*' or a type that behaves like
43 /// a pointer.
44 ///
45 /// This is a very simple POD type that wraps a pointer that the Parser
46 /// doesn't know about but that Sema or another client does. The PtrTy
47 /// template argument is used to make sure that "Decl" pointers are not
48 /// compatible with "Type" pointers for example.
49 template <class PtrTy>
50 class OpaquePtr {
51 void *Ptr = nullptr;
52
53 explicit OpaquePtr(void *Ptr) : Ptr(Ptr) {}
54
55 using Traits = llvm::PointerLikeTypeTraits<PtrTy>;
56
57 public:
58 OpaquePtr(std::nullptr_t = nullptr) {}
59
60 static OpaquePtr make(PtrTy P) { OpaquePtr OP; OP.set(P); return OP; }
61
62 /// Returns plain pointer to the entity pointed by this wrapper.
63 /// \tparam PointeeT Type of pointed entity.
64 ///
65 /// It is identical to getPtrAs<PointeeT*>.
66 template <typename PointeeT> PointeeT* getPtrTo() const {
67 return get();
68 }
69
70 /// Returns pointer converted to the specified type.
71 /// \tparam PtrT Result pointer type. There must be implicit conversion
72 /// from PtrTy to PtrT.
73 ///
74 /// In contrast to getPtrTo, this method allows the return type to be
75 /// a smart pointer.
76 template <typename PtrT> PtrT getPtrAs() const {
77 return get();
78 }
79
80 PtrTy get() const {
81 return Traits::getFromVoidPointer(Ptr);
82 }
83
84 void set(PtrTy P) {
85 Ptr = Traits::getAsVoidPointer(P);
86 }
87
88 explicit operator bool() const { return Ptr != nullptr; }
14
Assuming the condition is false
15
Returning zero, which participates in a condition later
89
90 void *getAsOpaquePtr() const { return Ptr; }
91 static OpaquePtr getFromOpaquePtr(void *P) { return OpaquePtr(P); }
92 };
93
94 /// UnionOpaquePtr - A version of OpaquePtr suitable for membership
95 /// in a union.
96 template <class T> struct UnionOpaquePtr {
97 void *Ptr;
98
99 static UnionOpaquePtr make(OpaquePtr<T> P) {
100 UnionOpaquePtr OP = { P.getAsOpaquePtr() };
101 return OP;
102 }
103
104 OpaquePtr<T> get() const { return OpaquePtr<T>::getFromOpaquePtr(Ptr); }
105 operator OpaquePtr<T>() const { return get(); }
106
107 UnionOpaquePtr &operator=(OpaquePtr<T> P) {
108 Ptr = P.getAsOpaquePtr();
109 return *this;
110 }
111 };
112
113} // namespace clang
114
115namespace llvm {
116
117 template <class T>
118 struct PointerLikeTypeTraits<clang::OpaquePtr<T>> {
119 static constexpr int NumLowBitsAvailable = 0;
120
121 static inline void *getAsVoidPointer(clang::OpaquePtr<T> P) {
122 // FIXME: Doesn't work? return P.getAs< void >();
123 return P.getAsOpaquePtr();
124 }
125
126 static inline clang::OpaquePtr<T> getFromVoidPointer(void *P) {
127 return clang::OpaquePtr<T>::getFromOpaquePtr(P);
128 }
129 };
130
131} // namespace llvm
132
133namespace clang {
134
135 // Basic
136class StreamingDiagnostic;
137
138// Determines whether the low bit of the result pointer for the
139// given UID is always zero. If so, ActionResult will use that bit
140// for it's "invalid" flag.
141template <class Ptr> struct IsResultPtrLowBitFree {
142 static const bool value = false;
143 };
144
145 /// ActionResult - This structure is used while parsing/acting on
146 /// expressions, stmts, etc. It encapsulates both the object returned by
147 /// the action, plus a sense of whether or not it is valid.
148 /// When CompressInvalid is true, the "invalid" flag will be
149 /// stored in the low bit of the Val pointer.
150 template<class PtrTy,
151 bool CompressInvalid = IsResultPtrLowBitFree<PtrTy>::value>
152 class ActionResult {
153 PtrTy Val;
154 bool Invalid;
155
156 public:
157 ActionResult(bool Invalid = false) : Val(PtrTy()), Invalid(Invalid) {}
158 ActionResult(PtrTy val) : Val(val), Invalid(false) {}
159 ActionResult(const DiagnosticBuilder &) : Val(PtrTy()), Invalid(true) {}
160
161 // These two overloads prevent void* -> bool conversions.
162 ActionResult(const void *) = delete;
163 ActionResult(volatile void *) = delete;
164
165 bool isInvalid() const { return Invalid; }
166 bool isUsable() const { return !Invalid && Val; }
167 bool isUnset() const { return !Invalid && !Val; }
168
169 PtrTy get() const { return Val; }
170 template <typename T> T *getAs() { return static_cast<T*>(get()); }
171
172 void set(PtrTy V) { Val = V; }
173
174 const ActionResult &operator=(PtrTy RHS) {
175 Val = RHS;
176 Invalid = false;
177 return *this;
178 }
179 };
180
181 // This ActionResult partial specialization places the "invalid"
182 // flag into the low bit of the pointer.
183 template<typename PtrTy>
184 class ActionResult<PtrTy, true> {
185 // A pointer whose low bit is 1 if this result is invalid, 0
186 // otherwise.
187 uintptr_t PtrWithInvalid;
188
189 using PtrTraits = llvm::PointerLikeTypeTraits<PtrTy>;
190
191 public:
192 ActionResult(bool Invalid = false)
193 : PtrWithInvalid(static_cast<uintptr_t>(Invalid)) {}
194
195 ActionResult(PtrTy V) {
196 void *VP = PtrTraits::getAsVoidPointer(V);
197 PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
198 assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer")(static_cast <bool> ((PtrWithInvalid & 0x01) == 0 &&
"Badly aligned pointer") ? void (0) : __assert_fail ("(PtrWithInvalid & 0x01) == 0 && \"Badly aligned pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/Ownership.h"
, 198, __extension__ __PRETTY_FUNCTION__))
;
199 }
200
201 ActionResult(const DiagnosticBuilder &) : PtrWithInvalid(0x01) {}
202
203 // These two overloads prevent void* -> bool conversions.
204 ActionResult(const void *) = delete;
205 ActionResult(volatile void *) = delete;
206
207 bool isInvalid() const { return PtrWithInvalid & 0x01; }
208 bool isUsable() const { return PtrWithInvalid > 0x01; }
3
Assuming field 'PtrWithInvalid' is > 1
4
Returning the value 1, which participates in a condition later
209 bool isUnset() const { return PtrWithInvalid == 0; }
210
211 PtrTy get() const {
212 void *VP = reinterpret_cast<void *>(PtrWithInvalid & ~0x01);
213 return PtrTraits::getFromVoidPointer(VP);
214 }
215
216 template <typename T> T *getAs() { return static_cast<T*>(get()); }
217
218 void set(PtrTy V) {
219 void *VP = PtrTraits::getAsVoidPointer(V);
220 PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
221 assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer")(static_cast <bool> ((PtrWithInvalid & 0x01) == 0 &&
"Badly aligned pointer") ? void (0) : __assert_fail ("(PtrWithInvalid & 0x01) == 0 && \"Badly aligned pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/Ownership.h"
, 221, __extension__ __PRETTY_FUNCTION__))
;
222 }
223
224 const ActionResult &operator=(PtrTy RHS) {
225 void *VP = PtrTraits::getAsVoidPointer(RHS);
226 PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
227 assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer")(static_cast <bool> ((PtrWithInvalid & 0x01) == 0 &&
"Badly aligned pointer") ? void (0) : __assert_fail ("(PtrWithInvalid & 0x01) == 0 && \"Badly aligned pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/Ownership.h"
, 227, __extension__ __PRETTY_FUNCTION__))
;
228 return *this;
229 }
230
231 // For types where we can fit a flag in with the pointer, provide
232 // conversions to/from pointer type.
233 static ActionResult getFromOpaquePointer(void *P) {
234 ActionResult Result;
235 Result.PtrWithInvalid = (uintptr_t)P;
236 return Result;
237 }
238 void *getAsOpaquePointer() const { return (void*)PtrWithInvalid; }
239 };
240
241 /// An opaque type for threading parsed type information through the
242 /// parser.
243 using ParsedType = OpaquePtr<QualType>;
244 using UnionParsedType = UnionOpaquePtr<QualType>;
245
246 // We can re-use the low bit of expression, statement, base, and
247 // member-initializer pointers for the "invalid" flag of
248 // ActionResult.
249 template<> struct IsResultPtrLowBitFree<Expr*> {
250 static const bool value = true;
251 };
252 template<> struct IsResultPtrLowBitFree<Stmt*> {
253 static const bool value = true;
254 };
255 template<> struct IsResultPtrLowBitFree<CXXBaseSpecifier*> {
256 static const bool value = true;
257 };
258 template<> struct IsResultPtrLowBitFree<CXXCtorInitializer*> {
259 static const bool value = true;
260 };
261
262 using ExprResult = ActionResult<Expr *>;
263 using StmtResult = ActionResult<Stmt *>;
264 using TypeResult = ActionResult<ParsedType>;
265 using BaseResult = ActionResult<CXXBaseSpecifier *>;
266 using MemInitResult = ActionResult<CXXCtorInitializer *>;
267
268 using DeclResult = ActionResult<Decl *>;
269 using ParsedTemplateTy = OpaquePtr<TemplateName>;
270 using UnionParsedTemplateTy = UnionOpaquePtr<TemplateName>;
271
272 using MultiExprArg = MutableArrayRef<Expr *>;
273 using MultiStmtArg = MutableArrayRef<Stmt *>;
274 using ASTTemplateArgsPtr = MutableArrayRef<ParsedTemplateArgument>;
275 using MultiTypeArg = MutableArrayRef<ParsedType>;
276 using MultiTemplateParamsArg = MutableArrayRef<TemplateParameterList *>;
277
278 inline ExprResult ExprError() { return ExprResult(true); }
279 inline StmtResult StmtError() { return StmtResult(true); }
280 inline TypeResult TypeError() { return TypeResult(true); }
281
282 inline ExprResult ExprError(const StreamingDiagnostic &) {
283 return ExprError();
284 }
285 inline StmtResult StmtError(const StreamingDiagnostic &) {
286 return StmtError();
287 }
288
289 inline ExprResult ExprEmpty() { return ExprResult(false); }
290 inline StmtResult StmtEmpty() { return StmtResult(false); }
291
292 inline Expr *AssertSuccess(ExprResult R) {
293 assert(!R.isInvalid() && "operation was asserted to never fail!")(static_cast <bool> (!R.isInvalid() && "operation was asserted to never fail!"
) ? void (0) : __assert_fail ("!R.isInvalid() && \"operation was asserted to never fail!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/Ownership.h"
, 293, __extension__ __PRETTY_FUNCTION__))
;
294 return R.get();
295 }
296
297 inline Stmt *AssertSuccess(StmtResult R) {
298 assert(!R.isInvalid() && "operation was asserted to never fail!")(static_cast <bool> (!R.isInvalid() && "operation was asserted to never fail!"
) ? void (0) : __assert_fail ("!R.isInvalid() && \"operation was asserted to never fail!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/Ownership.h"
, 298, __extension__ __PRETTY_FUNCTION__))
;
299 return R.get();
300 }
301
302} // namespace clang
303
304#endif // LLVM_CLANG_SEMA_OWNERSHIP_H

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h

1//===--- DeclSpec.h - Parsed declaration specifiers -------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file defines the classes used to store parsed information about
11/// declaration-specifiers and declarators.
12///
13/// \verbatim
14/// static const int volatile x, *y, *(*(*z)[10])(const void *x);
15/// ------------------------- - -- ---------------------------
16/// declaration-specifiers \ | /
17/// declarators
18/// \endverbatim
19///
20//===----------------------------------------------------------------------===//
21
22#ifndef LLVM_CLANG_SEMA_DECLSPEC_H
23#define LLVM_CLANG_SEMA_DECLSPEC_H
24
25#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclObjCCommon.h"
27#include "clang/AST/NestedNameSpecifier.h"
28#include "clang/Basic/ExceptionSpecificationType.h"
29#include "clang/Basic/Lambda.h"
30#include "clang/Basic/OperatorKinds.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Lex/Token.h"
33#include "clang/Sema/Ownership.h"
34#include "clang/Sema/ParsedAttr.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/ErrorHandling.h"
38
39namespace clang {
40 class ASTContext;
41 class CXXRecordDecl;
42 class TypeLoc;
43 class LangOptions;
44 class IdentifierInfo;
45 class NamespaceAliasDecl;
46 class NamespaceDecl;
47 class ObjCDeclSpec;
48 class Sema;
49 class Declarator;
50 struct TemplateIdAnnotation;
51
52/// Represents a C++ nested-name-specifier or a global scope specifier.
53///
54/// These can be in 3 states:
55/// 1) Not present, identified by isEmpty()
56/// 2) Present, identified by isNotEmpty()
57/// 2.a) Valid, identified by isValid()
58/// 2.b) Invalid, identified by isInvalid().
59///
60/// isSet() is deprecated because it mostly corresponded to "valid" but was
61/// often used as if it meant "present".
62///
63/// The actual scope is described by getScopeRep().
64class CXXScopeSpec {
65 SourceRange Range;
66 NestedNameSpecifierLocBuilder Builder;
67
68public:
69 SourceRange getRange() const { return Range; }
70 void setRange(SourceRange R) { Range = R; }
71 void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
72 void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
73 SourceLocation getBeginLoc() const { return Range.getBegin(); }
74 SourceLocation getEndLoc() const { return Range.getEnd(); }
75
76 /// Retrieve the representation of the nested-name-specifier.
77 NestedNameSpecifier *getScopeRep() const {
78 return Builder.getRepresentation();
79 }
80
81 /// Extend the current nested-name-specifier by another
82 /// nested-name-specifier component of the form 'type::'.
83 ///
84 /// \param Context The AST context in which this nested-name-specifier
85 /// resides.
86 ///
87 /// \param TemplateKWLoc The location of the 'template' keyword, if present.
88 ///
89 /// \param TL The TypeLoc that describes the type preceding the '::'.
90 ///
91 /// \param ColonColonLoc The location of the trailing '::'.
92 void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL,
93 SourceLocation ColonColonLoc);
94
95 /// Extend the current nested-name-specifier by another
96 /// nested-name-specifier component of the form 'identifier::'.
97 ///
98 /// \param Context The AST context in which this nested-name-specifier
99 /// resides.
100 ///
101 /// \param Identifier The identifier.
102 ///
103 /// \param IdentifierLoc The location of the identifier.
104 ///
105 /// \param ColonColonLoc The location of the trailing '::'.
106 void Extend(ASTContext &Context, IdentifierInfo *Identifier,
107 SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
108
109 /// Extend the current nested-name-specifier by another
110 /// nested-name-specifier component of the form 'namespace::'.
111 ///
112 /// \param Context The AST context in which this nested-name-specifier
113 /// resides.
114 ///
115 /// \param Namespace The namespace.
116 ///
117 /// \param NamespaceLoc The location of the namespace name.
118 ///
119 /// \param ColonColonLoc The location of the trailing '::'.
120 void Extend(ASTContext &Context, NamespaceDecl *Namespace,
121 SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
122
123 /// Extend the current nested-name-specifier by another
124 /// nested-name-specifier component of the form 'namespace-alias::'.
125 ///
126 /// \param Context The AST context in which this nested-name-specifier
127 /// resides.
128 ///
129 /// \param Alias The namespace alias.
130 ///
131 /// \param AliasLoc The location of the namespace alias
132 /// name.
133 ///
134 /// \param ColonColonLoc The location of the trailing '::'.
135 void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
136 SourceLocation AliasLoc, SourceLocation ColonColonLoc);
137
138 /// Turn this (empty) nested-name-specifier into the global
139 /// nested-name-specifier '::'.
140 void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
141
142 /// Turns this (empty) nested-name-specifier into '__super'
143 /// nested-name-specifier.
144 ///
145 /// \param Context The AST context in which this nested-name-specifier
146 /// resides.
147 ///
148 /// \param RD The declaration of the class in which nested-name-specifier
149 /// appeared.
150 ///
151 /// \param SuperLoc The location of the '__super' keyword.
152 /// name.
153 ///
154 /// \param ColonColonLoc The location of the trailing '::'.
155 void MakeSuper(ASTContext &Context, CXXRecordDecl *RD,
156 SourceLocation SuperLoc, SourceLocation ColonColonLoc);
157
158 /// Make a new nested-name-specifier from incomplete source-location
159 /// information.
160 ///
161 /// FIXME: This routine should be used very, very rarely, in cases where we
162 /// need to synthesize a nested-name-specifier. Most code should instead use
163 /// \c Adopt() with a proper \c NestedNameSpecifierLoc.
164 void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,
165 SourceRange R);
166
167 /// Adopt an existing nested-name-specifier (with source-range
168 /// information).
169 void Adopt(NestedNameSpecifierLoc Other);
170
171 /// Retrieve a nested-name-specifier with location information, copied
172 /// into the given AST context.
173 ///
174 /// \param Context The context into which this nested-name-specifier will be
175 /// copied.
176 NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
177
178 /// Retrieve the location of the name in the last qualifier
179 /// in this nested name specifier.
180 ///
181 /// For example, the location of \c bar
182 /// in
183 /// \verbatim
184 /// \::foo::bar<0>::
185 /// ^~~
186 /// \endverbatim
187 SourceLocation getLastQualifierNameLoc() const;
188
189 /// No scope specifier.
190 bool isEmpty() const { return Range.isInvalid() && getScopeRep() == nullptr; }
191 /// A scope specifier is present, but may be valid or invalid.
192 bool isNotEmpty() const { return !isEmpty(); }
193
194 /// An error occurred during parsing of the scope specifier.
195 bool isInvalid() const { return Range.isValid() && getScopeRep() == nullptr; }
196 /// A scope specifier is present, and it refers to a real scope.
197 bool isValid() const { return getScopeRep() != nullptr; }
198
199 /// Indicate that this nested-name-specifier is invalid.
200 void SetInvalid(SourceRange R) {
201 assert(R.isValid() && "Must have a valid source range")(static_cast <bool> (R.isValid() && "Must have a valid source range"
) ? void (0) : __assert_fail ("R.isValid() && \"Must have a valid source range\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 201, __extension__ __PRETTY_FUNCTION__))
;
202 if (Range.getBegin().isInvalid())
203 Range.setBegin(R.getBegin());
204 Range.setEnd(R.getEnd());
205 Builder.Clear();
206 }
207
208 /// Deprecated. Some call sites intend isNotEmpty() while others intend
209 /// isValid().
210 bool isSet() const { return getScopeRep() != nullptr; }
29
Assuming the condition is true
30
Returning the value 1, which participates in a condition later
211
212 void clear() {
213 Range = SourceRange();
214 Builder.Clear();
215 }
216
217 /// Retrieve the data associated with the source-location information.
218 char *location_data() const { return Builder.getBuffer().first; }
219
220 /// Retrieve the size of the data associated with source-location
221 /// information.
222 unsigned location_size() const { return Builder.getBuffer().second; }
223};
224
225/// Captures information about "declaration specifiers".
226///
227/// "Declaration specifiers" encompasses storage-class-specifiers,
228/// type-specifiers, type-qualifiers, and function-specifiers.
229class DeclSpec {
230public:
231 /// storage-class-specifier
232 /// \note The order of these enumerators is important for diagnostics.
233 enum SCS {
234 SCS_unspecified = 0,
235 SCS_typedef,
236 SCS_extern,
237 SCS_static,
238 SCS_auto,
239 SCS_register,
240 SCS_private_extern,
241 SCS_mutable
242 };
243
244 // Import thread storage class specifier enumeration and constants.
245 // These can be combined with SCS_extern and SCS_static.
246 typedef ThreadStorageClassSpecifier TSCS;
247 static const TSCS TSCS_unspecified = clang::TSCS_unspecified;
248 static const TSCS TSCS___thread = clang::TSCS___thread;
249 static const TSCS TSCS_thread_local = clang::TSCS_thread_local;
250 static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local;
251
252 enum TSC {
253 TSC_unspecified,
254 TSC_imaginary,
255 TSC_complex
256 };
257
258 // Import type specifier type enumeration and constants.
259 typedef TypeSpecifierType TST;
260 static const TST TST_unspecified = clang::TST_unspecified;
261 static const TST TST_void = clang::TST_void;
262 static const TST TST_char = clang::TST_char;
263 static const TST TST_wchar = clang::TST_wchar;
264 static const TST TST_char8 = clang::TST_char8;
265 static const TST TST_char16 = clang::TST_char16;
266 static const TST TST_char32 = clang::TST_char32;
267 static const TST TST_int = clang::TST_int;
268 static const TST TST_int128 = clang::TST_int128;
269 static const TST TST_extint = clang::TST_extint;
270 static const TST TST_half = clang::TST_half;
271 static const TST TST_BFloat16 = clang::TST_BFloat16;
272 static const TST TST_float = clang::TST_float;
273 static const TST TST_double = clang::TST_double;
274 static const TST TST_float16 = clang::TST_Float16;
275 static const TST TST_accum = clang::TST_Accum;
276 static const TST TST_fract = clang::TST_Fract;
277 static const TST TST_float128 = clang::TST_float128;
278 static const TST TST_bool = clang::TST_bool;
279 static const TST TST_decimal32 = clang::TST_decimal32;
280 static const TST TST_decimal64 = clang::TST_decimal64;
281 static const TST TST_decimal128 = clang::TST_decimal128;
282 static const TST TST_enum = clang::TST_enum;
283 static const TST TST_union = clang::TST_union;
284 static const TST TST_struct = clang::TST_struct;
285 static const TST TST_interface = clang::TST_interface;
286 static const TST TST_class = clang::TST_class;
287 static const TST TST_typename = clang::TST_typename;
288 static const TST TST_typeofType = clang::TST_typeofType;
289 static const TST TST_typeofExpr = clang::TST_typeofExpr;
290 static const TST TST_decltype = clang::TST_decltype;
291 static const TST TST_decltype_auto = clang::TST_decltype_auto;
292 static const TST TST_underlyingType = clang::TST_underlyingType;
293 static const TST TST_auto = clang::TST_auto;
294 static const TST TST_auto_type = clang::TST_auto_type;
295 static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
296 static const TST TST_atomic = clang::TST_atomic;
297#define GENERIC_IMAGE_TYPE(ImgType, Id) \
298 static const TST TST_##ImgType##_t = clang::TST_##ImgType##_t;
299#include "clang/Basic/OpenCLImageTypes.def"
300 static const TST TST_error = clang::TST_error;
301
302 // type-qualifiers
303 enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ.
304 TQ_unspecified = 0,
305 TQ_const = 1,
306 TQ_restrict = 2,
307 TQ_volatile = 4,
308 TQ_unaligned = 8,
309 // This has no corresponding Qualifiers::TQ value, because it's not treated
310 // as a qualifier in our type system.
311 TQ_atomic = 16
312 };
313
314 /// ParsedSpecifiers - Flags to query which specifiers were applied. This is
315 /// returned by getParsedSpecifiers.
316 enum ParsedSpecifiers {
317 PQ_None = 0,
318 PQ_StorageClassSpecifier = 1,
319 PQ_TypeSpecifier = 2,
320 PQ_TypeQualifier = 4,
321 PQ_FunctionSpecifier = 8
322 // FIXME: Attributes should be included here.
323 };
324
325private:
326 // storage-class-specifier
327 /*SCS*/unsigned StorageClassSpec : 3;
328 /*TSCS*/unsigned ThreadStorageClassSpec : 2;
329 unsigned SCS_extern_in_linkage_spec : 1;
330
331 // type-specifier
332 /*TypeSpecifierWidth*/ unsigned TypeSpecWidth : 2;
333 /*TSC*/unsigned TypeSpecComplex : 2;
334 /*TSS*/unsigned TypeSpecSign : 2;
335 /*TST*/unsigned TypeSpecType : 6;
336 unsigned TypeAltiVecVector : 1;
337 unsigned TypeAltiVecPixel : 1;
338 unsigned TypeAltiVecBool : 1;
339 unsigned TypeSpecOwned : 1;
340 unsigned TypeSpecPipe : 1;
341 unsigned TypeSpecSat : 1;
342 unsigned ConstrainedAuto : 1;
343
344 // type-qualifiers
345 unsigned TypeQualifiers : 5; // Bitwise OR of TQ.
346
347 // function-specifier
348 unsigned FS_inline_specified : 1;
349 unsigned FS_forceinline_specified: 1;
350 unsigned FS_virtual_specified : 1;
351 unsigned FS_noreturn_specified : 1;
352
353 // friend-specifier
354 unsigned Friend_specified : 1;
355
356 // constexpr-specifier
357 unsigned ConstexprSpecifier : 2;
358
359 union {
360 UnionParsedType TypeRep;
361 Decl *DeclRep;
362 Expr *ExprRep;
363 TemplateIdAnnotation *TemplateIdRep;
364 };
365
366 /// ExplicitSpecifier - Store information about explicit spicifer.
367 ExplicitSpecifier FS_explicit_specifier;
368
369 // attributes.
370 ParsedAttributes Attrs;
371
372 // Scope specifier for the type spec, if applicable.
373 CXXScopeSpec TypeScope;
374
375 // SourceLocation info. These are null if the item wasn't specified or if
376 // the setting was synthesized.
377 SourceRange Range;
378
379 SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
380 SourceRange TSWRange;
381 SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc, TSSatLoc;
382 /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
383 /// typename, then this is the location of the named type (if present);
384 /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
385 /// TSTNameLoc provides source range info for tag types.
386 SourceLocation TSTNameLoc;
387 SourceRange TypeofParensRange;
388 SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc,
389 TQ_unalignedLoc;
390 SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
391 SourceLocation FS_explicitCloseParenLoc;
392 SourceLocation FS_forceinlineLoc;
393 SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc;
394 SourceLocation TQ_pipeLoc;
395
396 WrittenBuiltinSpecs writtenBS;
397 void SaveWrittenBuiltinSpecs();
398
399 ObjCDeclSpec *ObjCQualifiers;
400
401 static bool isTypeRep(TST T) {
402 return (T == TST_typename || T == TST_typeofType ||
403 T == TST_underlyingType || T == TST_atomic);
404 }
405 static bool isExprRep(TST T) {
406 return (T == TST_typeofExpr || T == TST_decltype || T == TST_extint);
407 }
408 static bool isTemplateIdRep(TST T) {
409 return (T == TST_auto || T == TST_decltype_auto);
410 }
411
412 DeclSpec(const DeclSpec &) = delete;
413 void operator=(const DeclSpec &) = delete;
414public:
415 static bool isDeclRep(TST T) {
416 return (T == TST_enum || T == TST_struct ||
417 T == TST_interface || T == TST_union ||
418 T == TST_class);
419 }
420
421 DeclSpec(AttributeFactory &attrFactory)
422 : StorageClassSpec(SCS_unspecified),
423 ThreadStorageClassSpec(TSCS_unspecified),
424 SCS_extern_in_linkage_spec(false),
425 TypeSpecWidth(static_cast<unsigned>(TypeSpecifierWidth::Unspecified)),
426 TypeSpecComplex(TSC_unspecified),
427 TypeSpecSign(static_cast<unsigned>(TypeSpecifierSign::Unspecified)),
428 TypeSpecType(TST_unspecified), TypeAltiVecVector(false),
429 TypeAltiVecPixel(false), TypeAltiVecBool(false), TypeSpecOwned(false),
430 TypeSpecPipe(false), TypeSpecSat(false), ConstrainedAuto(false),
431 TypeQualifiers(TQ_unspecified), FS_inline_specified(false),
432 FS_forceinline_specified(false), FS_virtual_specified(false),
433 FS_noreturn_specified(false), Friend_specified(false),
434 ConstexprSpecifier(
435 static_cast<unsigned>(ConstexprSpecKind::Unspecified)),
436 FS_explicit_specifier(), Attrs(attrFactory), writtenBS(),
437 ObjCQualifiers(nullptr) {}
438
439 // storage-class-specifier
440 SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
441 TSCS getThreadStorageClassSpec() const {
442 return (TSCS)ThreadStorageClassSpec;
443 }
444 bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
445 void setExternInLinkageSpec(bool Value) {
446 SCS_extern_in_linkage_spec = Value;
447 }
448
449 SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
450 SourceLocation getThreadStorageClassSpecLoc() const {
451 return ThreadStorageClassSpecLoc;
452 }
453
454 void ClearStorageClassSpecs() {
455 StorageClassSpec = DeclSpec::SCS_unspecified;
456 ThreadStorageClassSpec = DeclSpec::TSCS_unspecified;
457 SCS_extern_in_linkage_spec = false;
458 StorageClassSpecLoc = SourceLocation();
459 ThreadStorageClassSpecLoc = SourceLocation();
460 }
461
462 void ClearTypeSpecType() {
463 TypeSpecType = DeclSpec::TST_unspecified;
464 TypeSpecOwned = false;
465 TSTLoc = SourceLocation();
466 }
467
468 // type-specifier
469 TypeSpecifierWidth getTypeSpecWidth() const {
470 return static_cast<TypeSpecifierWidth>(TypeSpecWidth);
471 }
472 TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
473 TypeSpecifierSign getTypeSpecSign() const {
474 return static_cast<TypeSpecifierSign>(TypeSpecSign);
475 }
476 TST getTypeSpecType() const { return (TST)TypeSpecType; }
477 bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
478 bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
479 bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
480 bool isTypeSpecOwned() const { return TypeSpecOwned; }
481 bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); }
482 bool isTypeSpecPipe() const { return TypeSpecPipe; }
483 bool isTypeSpecSat() const { return TypeSpecSat; }
484 bool isConstrainedAuto() const { return ConstrainedAuto; }
485
486 ParsedType getRepAsType() const {
487 assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type")(static_cast <bool> (isTypeRep((TST) TypeSpecType) &&
"DeclSpec does not store a type") ? void (0) : __assert_fail
("isTypeRep((TST) TypeSpecType) && \"DeclSpec does not store a type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 487, __extension__ __PRETTY_FUNCTION__))
;
488 return TypeRep;
489 }
490 Decl *getRepAsDecl() const {
491 assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl")(static_cast <bool> (isDeclRep((TST) TypeSpecType) &&
"DeclSpec does not store a decl") ? void (0) : __assert_fail
("isDeclRep((TST) TypeSpecType) && \"DeclSpec does not store a decl\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 491, __extension__ __PRETTY_FUNCTION__))
;
492 return DeclRep;
493 }
494 Expr *getRepAsExpr() const {
495 assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr")(static_cast <bool> (isExprRep((TST) TypeSpecType) &&
"DeclSpec does not store an expr") ? void (0) : __assert_fail
("isExprRep((TST) TypeSpecType) && \"DeclSpec does not store an expr\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 495, __extension__ __PRETTY_FUNCTION__))
;
496 return ExprRep;
497 }
498 TemplateIdAnnotation *getRepAsTemplateId() const {
499 assert(isTemplateIdRep((TST) TypeSpecType) &&(static_cast <bool> (isTemplateIdRep((TST) TypeSpecType
) && "DeclSpec does not store a template id") ? void (
0) : __assert_fail ("isTemplateIdRep((TST) TypeSpecType) && \"DeclSpec does not store a template id\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 500, __extension__ __PRETTY_FUNCTION__))
500 "DeclSpec does not store a template id")(static_cast <bool> (isTemplateIdRep((TST) TypeSpecType
) && "DeclSpec does not store a template id") ? void (
0) : __assert_fail ("isTemplateIdRep((TST) TypeSpecType) && \"DeclSpec does not store a template id\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 500, __extension__ __PRETTY_FUNCTION__))
;
501 return TemplateIdRep;
502 }
503 CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
504 const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
505
506 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
507 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
508 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
509
510 SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); }
511 SourceRange getTypeSpecWidthRange() const { return TSWRange; }
512 SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
513 SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
514 SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
515 SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
516 SourceLocation getTypeSpecSatLoc() const { return TSSatLoc; }
517
518 SourceLocation getTypeSpecTypeNameLoc() const {
519 assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename)(static_cast <bool> (isDeclRep((TST) TypeSpecType) || TypeSpecType
== TST_typename) ? void (0) : __assert_fail ("isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 519, __extension__ __PRETTY_FUNCTION__))
;
520 return TSTNameLoc;
521 }
522
523 SourceRange getTypeofParensRange() const { return TypeofParensRange; }
524 void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
525
526 bool hasAutoTypeSpec() const {
527 return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type ||
528 TypeSpecType == TST_decltype_auto);
529 }
530
531 bool hasTagDefinition() const;
532
533 /// Turn a type-specifier-type into a string like "_Bool" or "union".
534 static const char *getSpecifierName(DeclSpec::TST T,
535 const PrintingPolicy &Policy);
536 static const char *getSpecifierName(DeclSpec::TQ Q);
537 static const char *getSpecifierName(TypeSpecifierSign S);
538 static const char *getSpecifierName(DeclSpec::TSC C);
539 static const char *getSpecifierName(TypeSpecifierWidth W);
540 static const char *getSpecifierName(DeclSpec::SCS S);
541 static const char *getSpecifierName(DeclSpec::TSCS S);
542 static const char *getSpecifierName(ConstexprSpecKind C);
543
544 // type-qualifiers
545
546 /// getTypeQualifiers - Return a set of TQs.
547 unsigned getTypeQualifiers() const { return TypeQualifiers; }
548 SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
549 SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
550 SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
551 SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
552 SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; }
553 SourceLocation getPipeLoc() const { return TQ_pipeLoc; }
554
555 /// Clear out all of the type qualifiers.
556 void ClearTypeQualifiers() {
557 TypeQualifiers = 0;
558 TQ_constLoc = SourceLocation();
559 TQ_restrictLoc = SourceLocation();
560 TQ_volatileLoc = SourceLocation();
561 TQ_atomicLoc = SourceLocation();
562 TQ_unalignedLoc = SourceLocation();
563 TQ_pipeLoc = SourceLocation();
564 }
565
566 // function-specifier
567 bool isInlineSpecified() const {
568 return FS_inline_specified | FS_forceinline_specified;
569 }
570 SourceLocation getInlineSpecLoc() const {
571 return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
572 }
573
574 ExplicitSpecifier getExplicitSpecifier() const {
575 return FS_explicit_specifier;
576 }
577
578 bool isVirtualSpecified() const { return FS_virtual_specified; }
579 SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
580
581 bool hasExplicitSpecifier() const {
582 return FS_explicit_specifier.isSpecified();
583 }
584 SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
585 SourceRange getExplicitSpecRange() const {
586 return FS_explicit_specifier.getExpr()
587 ? SourceRange(FS_explicitLoc, FS_explicitCloseParenLoc)
588 : SourceRange(FS_explicitLoc);
589 }
590
591 bool isNoreturnSpecified() const { return FS_noreturn_specified; }
592 SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
593
594 void ClearFunctionSpecs() {
595 FS_inline_specified = false;
596 FS_inlineLoc = SourceLocation();
597 FS_forceinline_specified = false;
598 FS_forceinlineLoc = SourceLocation();
599 FS_virtual_specified = false;
600 FS_virtualLoc = SourceLocation();
601 FS_explicit_specifier = ExplicitSpecifier();
602 FS_explicitLoc = SourceLocation();
603 FS_explicitCloseParenLoc = SourceLocation();
604 FS_noreturn_specified = false;
605 FS_noreturnLoc = SourceLocation();
606 }
607
608 /// This method calls the passed in handler on each CVRU qual being
609 /// set.
610 /// Handle - a handler to be invoked.
611 void forEachCVRUQualifier(
612 llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
613
614 /// This method calls the passed in handler on each qual being
615 /// set.
616 /// Handle - a handler to be invoked.
617 void forEachQualifier(
618 llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle);
619
620 /// Return true if any type-specifier has been found.
621 bool hasTypeSpecifier() const {
622 return getTypeSpecType() != DeclSpec::TST_unspecified ||
623 getTypeSpecWidth() != TypeSpecifierWidth::Unspecified ||
624 getTypeSpecComplex() != DeclSpec::TSC_unspecified ||
625 getTypeSpecSign() != TypeSpecifierSign::Unspecified;
626 }
627
628 /// Return a bitmask of which flavors of specifiers this
629 /// DeclSpec includes.
630 unsigned getParsedSpecifiers() const;
631
632 /// isEmpty - Return true if this declaration specifier is completely empty:
633 /// no tokens were parsed in the production of it.
634 bool isEmpty() const {
635 return getParsedSpecifiers() == DeclSpec::PQ_None;
636 }
637
638 void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
639 void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
640
641 /// These methods set the specified attribute of the DeclSpec and
642 /// return false if there was no error. If an error occurs (for
643 /// example, if we tried to set "auto" on a spec with "extern"
644 /// already set), they return true and set PrevSpec and DiagID
645 /// such that
646 /// Diag(Loc, DiagID) << PrevSpec;
647 /// will yield a useful result.
648 ///
649 /// TODO: use a more general approach that still allows these
650 /// diagnostics to be ignored when desired.
651 bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
652 const char *&PrevSpec, unsigned &DiagID,
653 const PrintingPolicy &Policy);
654 bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
655 const char *&PrevSpec, unsigned &DiagID);
656 bool SetTypeSpecWidth(TypeSpecifierWidth W, SourceLocation Loc,
657 const char *&PrevSpec, unsigned &DiagID,
658 const PrintingPolicy &Policy);
659 bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
660 unsigned &DiagID);
661 bool SetTypeSpecSign(TypeSpecifierSign S, SourceLocation Loc,
662 const char *&PrevSpec, unsigned &DiagID);
663 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
664 unsigned &DiagID, const PrintingPolicy &Policy);
665 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
666 unsigned &DiagID, ParsedType Rep,
667 const PrintingPolicy &Policy);
668 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
669 unsigned &DiagID, TypeResult Rep,
670 const PrintingPolicy &Policy) {
671 if (Rep.isInvalid())
672 return SetTypeSpecError();
673 return SetTypeSpecType(T, Loc, PrevSpec, DiagID, Rep.get(), Policy);
674 }
675 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
676 unsigned &DiagID, Decl *Rep, bool Owned,
677 const PrintingPolicy &Policy);
678 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
679 SourceLocation TagNameLoc, const char *&PrevSpec,
680 unsigned &DiagID, ParsedType Rep,
681 const PrintingPolicy &Policy);
682 bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
683 SourceLocation TagNameLoc, const char *&PrevSpec,
684 unsigned &DiagID, Decl *Rep, bool Owned,
685 const PrintingPolicy &Policy);
686 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
687 unsigned &DiagID, TemplateIdAnnotation *Rep,
688 const PrintingPolicy &Policy);
689
690 bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
691 unsigned &DiagID, Expr *Rep,
692 const PrintingPolicy &policy);
693 bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
694 const char *&PrevSpec, unsigned &DiagID,
695 const PrintingPolicy &Policy);
696 bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
697 const char *&PrevSpec, unsigned &DiagID,
698 const PrintingPolicy &Policy);
699 bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
700 const char *&PrevSpec, unsigned &DiagID,
701 const PrintingPolicy &Policy);
702 bool SetTypePipe(bool isPipe, SourceLocation Loc,
703 const char *&PrevSpec, unsigned &DiagID,
704 const PrintingPolicy &Policy);
705 bool SetExtIntType(SourceLocation KWLoc, Expr *BitWidth,
706 const char *&PrevSpec, unsigned &DiagID,
707 const PrintingPolicy &Policy);
708 bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec,
709 unsigned &DiagID);
710 bool SetTypeSpecError();
711 void UpdateDeclRep(Decl *Rep) {
712 assert(isDeclRep((TST) TypeSpecType))(static_cast <bool> (isDeclRep((TST) TypeSpecType)) ? void
(0) : __assert_fail ("isDeclRep((TST) TypeSpecType)", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 712, __extension__ __PRETTY_FUNCTION__))
;
713 DeclRep = Rep;
714 }
715 void UpdateTypeRep(ParsedType Rep) {
716 assert(isTypeRep((TST) TypeSpecType))(static_cast <bool> (isTypeRep((TST) TypeSpecType)) ? void
(0) : __assert_fail ("isTypeRep((TST) TypeSpecType)", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 716, __extension__ __PRETTY_FUNCTION__))
;
717 TypeRep = Rep;
718 }
719 void UpdateExprRep(Expr *Rep) {
720 assert(isExprRep((TST) TypeSpecType))(static_cast <bool> (isExprRep((TST) TypeSpecType)) ? void
(0) : __assert_fail ("isExprRep((TST) TypeSpecType)", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 720, __extension__ __PRETTY_FUNCTION__))
;
721 ExprRep = Rep;
722 }
723
724 bool SetTypeQual(TQ T, SourceLocation Loc);
725
726 bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
727 unsigned &DiagID, const LangOptions &Lang);
728
729 bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
730 unsigned &DiagID);
731 bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
732 unsigned &DiagID);
733 bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
734 unsigned &DiagID);
735 bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
736 unsigned &DiagID, ExplicitSpecifier ExplicitSpec,
737 SourceLocation CloseParenLoc);
738 bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
739 unsigned &DiagID);
740
741 bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
742 unsigned &DiagID);
743 bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
744 unsigned &DiagID);
745 bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc,
746 const char *&PrevSpec, unsigned &DiagID);
747
748 bool isFriendSpecified() const { return Friend_specified; }
749 SourceLocation getFriendSpecLoc() const { return FriendLoc; }
750
751 bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
752 SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
753
754 ConstexprSpecKind getConstexprSpecifier() const {
755 return ConstexprSpecKind(ConstexprSpecifier);
756 }
757
758 SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
759 bool hasConstexprSpecifier() const {
760 return getConstexprSpecifier() != ConstexprSpecKind::Unspecified;
761 }
762
763 void ClearConstexprSpec() {
764 ConstexprSpecifier = static_cast<unsigned>(ConstexprSpecKind::Unspecified);
765 ConstexprLoc = SourceLocation();
766 }
767
768 AttributePool &getAttributePool() const {
769 return Attrs.getPool();
770 }
771
772 /// Concatenates two attribute lists.
773 ///
774 /// The GCC attribute syntax allows for the following:
775 ///
776 /// \code
777 /// short __attribute__(( unused, deprecated ))
778 /// int __attribute__(( may_alias, aligned(16) )) var;
779 /// \endcode
780 ///
781 /// This declares 4 attributes using 2 lists. The following syntax is
782 /// also allowed and equivalent to the previous declaration.
783 ///
784 /// \code
785 /// short __attribute__((unused)) __attribute__((deprecated))
786 /// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
787 /// \endcode
788 ///
789 void addAttributes(ParsedAttributesView &AL) {
790 Attrs.addAll(AL.begin(), AL.end());
791 }
792
793 bool hasAttributes() const { return !Attrs.empty(); }
794
795 ParsedAttributes &getAttributes() { return Attrs; }
796 const ParsedAttributes &getAttributes() const { return Attrs; }
797
798 void takeAttributesFrom(ParsedAttributes &attrs) {
799 Attrs.takeAllFrom(attrs);
800 }
801
802 /// Finish - This does final analysis of the declspec, issuing diagnostics for
803 /// things like "_Imaginary" (lacking an FP type). After calling this method,
804 /// DeclSpec is guaranteed self-consistent, even if an error occurred.
805 void Finish(Sema &S, const PrintingPolicy &Policy);
806
807 const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
808 return writtenBS;
809 }
810
811 ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
812 void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
813
814 /// Checks if this DeclSpec can stand alone, without a Declarator.
815 ///
816 /// Only tag declspecs can stand alone.
817 bool isMissingDeclaratorOk();
818};
819
820/// Captures information about "declaration specifiers" specific to
821/// Objective-C.
822class ObjCDeclSpec {
823public:
824 /// ObjCDeclQualifier - Qualifier used on types in method
825 /// declarations. Not all combinations are sensible. Parameters
826 /// can be one of { in, out, inout } with one of { bycopy, byref }.
827 /// Returns can either be { oneway } or not.
828 ///
829 /// This should be kept in sync with Decl::ObjCDeclQualifier.
830 enum ObjCDeclQualifier {
831 DQ_None = 0x0,
832 DQ_In = 0x1,
833 DQ_Inout = 0x2,
834 DQ_Out = 0x4,
835 DQ_Bycopy = 0x8,
836 DQ_Byref = 0x10,
837 DQ_Oneway = 0x20,
838 DQ_CSNullability = 0x40
839 };
840
841 ObjCDeclSpec()
842 : objcDeclQualifier(DQ_None),
843 PropertyAttributes(ObjCPropertyAttribute::kind_noattr), Nullability(0),
844 GetterName(nullptr), SetterName(nullptr) {}
845
846 ObjCDeclQualifier getObjCDeclQualifier() const {
847 return (ObjCDeclQualifier)objcDeclQualifier;
848 }
849 void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
850 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
851 }
852 void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
853 objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
854 }
855
856 ObjCPropertyAttribute::Kind getPropertyAttributes() const {
857 return ObjCPropertyAttribute::Kind(PropertyAttributes);
858 }
859 void setPropertyAttributes(ObjCPropertyAttribute::Kind PRVal) {
860 PropertyAttributes =
861 (ObjCPropertyAttribute::Kind)(PropertyAttributes | PRVal);
862 }
863
864 NullabilityKind getNullability() const {
865 assert((static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 868, __extension__ __PRETTY_FUNCTION__))
866 ((getObjCDeclQualifier() & DQ_CSNullability) ||(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 868, __extension__ __PRETTY_FUNCTION__))
867 (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 868, __extension__ __PRETTY_FUNCTION__))
868 "Objective-C declspec doesn't have nullability")(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 868, __extension__ __PRETTY_FUNCTION__))
;
869 return static_cast<NullabilityKind>(Nullability);
870 }
871
872 SourceLocation getNullabilityLoc() const {
873 assert((static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 876, __extension__ __PRETTY_FUNCTION__))
874 ((getObjCDeclQualifier() & DQ_CSNullability) ||(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 876, __extension__ __PRETTY_FUNCTION__))
875 (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 876, __extension__ __PRETTY_FUNCTION__))
876 "Objective-C declspec doesn't have nullability")(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Objective-C declspec doesn't have nullability"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 876, __extension__ __PRETTY_FUNCTION__))
;
877 return NullabilityLoc;
878 }
879
880 void setNullability(SourceLocation loc, NullabilityKind kind) {
881 assert((static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Set the nullability declspec or property attribute first"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 884, __extension__ __PRETTY_FUNCTION__))
882 ((getObjCDeclQualifier() & DQ_CSNullability) ||(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Set the nullability declspec or property attribute first"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 884, __extension__ __PRETTY_FUNCTION__))
883 (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Set the nullability declspec or property attribute first"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 884, __extension__ __PRETTY_FUNCTION__))
884 "Set the nullability declspec or property attribute first")(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability
) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability
)) && "Set the nullability declspec or property attribute first"
) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 884, __extension__ __PRETTY_FUNCTION__))
;
885 Nullability = static_cast<unsigned>(kind);
886 NullabilityLoc = loc;
887 }
888
889 const IdentifierInfo *getGetterName() const { return GetterName; }
890 IdentifierInfo *getGetterName() { return GetterName; }
891 SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
892 void setGetterName(IdentifierInfo *name, SourceLocation loc) {
893 GetterName = name;
894 GetterNameLoc = loc;
895 }
896
897 const IdentifierInfo *getSetterName() const { return SetterName; }
898 IdentifierInfo *getSetterName() { return SetterName; }
899 SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
900 void setSetterName(IdentifierInfo *name, SourceLocation loc) {
901 SetterName = name;
902 SetterNameLoc = loc;
903 }
904
905private:
906 // FIXME: These two are unrelated and mutually exclusive. So perhaps
907 // we can put them in a union to reflect their mutual exclusivity
908 // (space saving is negligible).
909 unsigned objcDeclQualifier : 7;
910
911 // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttribute::Kind
912 unsigned PropertyAttributes : NumObjCPropertyAttrsBits;
913
914 unsigned Nullability : 2;
915
916 SourceLocation NullabilityLoc;
917
918 IdentifierInfo *GetterName; // getter name or NULL if no getter
919 IdentifierInfo *SetterName; // setter name or NULL if no setter
920 SourceLocation GetterNameLoc; // location of the getter attribute's value
921 SourceLocation SetterNameLoc; // location of the setter attribute's value
922
923};
924
925/// Describes the kind of unqualified-id parsed.
926enum class UnqualifiedIdKind {
927 /// An identifier.
928 IK_Identifier,
929 /// An overloaded operator name, e.g., operator+.
930 IK_OperatorFunctionId,
931 /// A conversion function name, e.g., operator int.
932 IK_ConversionFunctionId,
933 /// A user-defined literal name, e.g., operator "" _i.
934 IK_LiteralOperatorId,
935 /// A constructor name.
936 IK_ConstructorName,
937 /// A constructor named via a template-id.
938 IK_ConstructorTemplateId,
939 /// A destructor name.
940 IK_DestructorName,
941 /// A template-id, e.g., f<int>.
942 IK_TemplateId,
943 /// An implicit 'self' parameter
944 IK_ImplicitSelfParam,
945 /// A deduction-guide name (a template-name)
946 IK_DeductionGuideName
947};
948
949/// Represents a C++ unqualified-id that has been parsed.
950class UnqualifiedId {
951private:
952 UnqualifiedId(const UnqualifiedId &Other) = delete;
953 const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
954
955public:
956 /// Describes the kind of unqualified-id parsed.
957 UnqualifiedIdKind Kind;
958
959 struct OFI {
960 /// The kind of overloaded operator.
961 OverloadedOperatorKind Operator;
962
963 /// The source locations of the individual tokens that name
964 /// the operator, e.g., the "new", "[", and "]" tokens in
965 /// operator new [].
966 ///
967 /// Different operators have different numbers of tokens in their name,
968 /// up to three. Any remaining source locations in this array will be
969 /// set to an invalid value for operators with fewer than three tokens.
970 SourceLocation SymbolLocations[3];
971 };
972
973 /// Anonymous union that holds extra data associated with the
974 /// parsed unqualified-id.
975 union {
976 /// When Kind == IK_Identifier, the parsed identifier, or when
977 /// Kind == IK_UserLiteralId, the identifier suffix.
978 IdentifierInfo *Identifier;
979
980 /// When Kind == IK_OperatorFunctionId, the overloaded operator
981 /// that we parsed.
982 struct OFI OperatorFunctionId;
983
984 /// When Kind == IK_ConversionFunctionId, the type that the
985 /// conversion function names.
986 UnionParsedType ConversionFunctionId;
987
988 /// When Kind == IK_ConstructorName, the class-name of the type
989 /// whose constructor is being referenced.
990 UnionParsedType ConstructorName;
991
992 /// When Kind == IK_DestructorName, the type referred to by the
993 /// class-name.
994 UnionParsedType DestructorName;
995
996 /// When Kind == IK_DeductionGuideName, the parsed template-name.
997 UnionParsedTemplateTy TemplateName;
998
999 /// When Kind == IK_TemplateId or IK_ConstructorTemplateId,
1000 /// the template-id annotation that contains the template name and
1001 /// template arguments.
1002 TemplateIdAnnotation *TemplateId;
1003 };
1004
1005 /// The location of the first token that describes this unqualified-id,
1006 /// which will be the location of the identifier, "operator" keyword,
1007 /// tilde (for a destructor), or the template name of a template-id.
1008 SourceLocation StartLocation;
1009
1010 /// The location of the last token that describes this unqualified-id.
1011 SourceLocation EndLocation;
1012
1013 UnqualifiedId()
1014 : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {}
1015
1016 /// Clear out this unqualified-id, setting it to default (invalid)
1017 /// state.
1018 void clear() {
1019 Kind = UnqualifiedIdKind::IK_Identifier;
1020 Identifier = nullptr;
1021 StartLocation = SourceLocation();
1022 EndLocation = SourceLocation();
1023 }
1024
1025 /// Determine whether this unqualified-id refers to a valid name.
1026 bool isValid() const { return StartLocation.isValid(); }
1027
1028 /// Determine whether this unqualified-id refers to an invalid name.
1029 bool isInvalid() const { return !isValid(); }
1030
1031 /// Determine what kind of name we have.
1032 UnqualifiedIdKind getKind() const { return Kind; }
1033
1034 /// Specify that this unqualified-id was parsed as an identifier.
1035 ///
1036 /// \param Id the parsed identifier.
1037 /// \param IdLoc the location of the parsed identifier.
1038 void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
1039 Kind = UnqualifiedIdKind::IK_Identifier;
1040 Identifier = const_cast<IdentifierInfo *>(Id);
1041 StartLocation = EndLocation = IdLoc;
1042 }
1043
1044 /// Specify that this unqualified-id was parsed as an
1045 /// operator-function-id.
1046 ///
1047 /// \param OperatorLoc the location of the 'operator' keyword.
1048 ///
1049 /// \param Op the overloaded operator.
1050 ///
1051 /// \param SymbolLocations the locations of the individual operator symbols
1052 /// in the operator.
1053 void setOperatorFunctionId(SourceLocation OperatorLoc,
1054 OverloadedOperatorKind Op,
1055 SourceLocation SymbolLocations[3]);
1056
1057 /// Specify that this unqualified-id was parsed as a
1058 /// conversion-function-id.
1059 ///
1060 /// \param OperatorLoc the location of the 'operator' keyword.
1061 ///
1062 /// \param Ty the type to which this conversion function is converting.
1063 ///
1064 /// \param EndLoc the location of the last token that makes up the type name.
1065 void setConversionFunctionId(SourceLocation OperatorLoc,
1066 ParsedType Ty,
1067 SourceLocation EndLoc) {
1068 Kind = UnqualifiedIdKind::IK_ConversionFunctionId;
1069 StartLocation = OperatorLoc;
1070 EndLocation = EndLoc;
1071 ConversionFunctionId = Ty;
1072 }
1073
1074 /// Specific that this unqualified-id was parsed as a
1075 /// literal-operator-id.
1076 ///
1077 /// \param Id the parsed identifier.
1078 ///
1079 /// \param OpLoc the location of the 'operator' keyword.
1080 ///
1081 /// \param IdLoc the location of the identifier.
1082 void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
1083 SourceLocation IdLoc) {
1084 Kind = UnqualifiedIdKind::IK_LiteralOperatorId;
1085 Identifier = const_cast<IdentifierInfo *>(Id);
1086 StartLocation = OpLoc;
1087 EndLocation = IdLoc;
1088 }
1089
1090 /// Specify that this unqualified-id was parsed as a constructor name.
1091 ///
1092 /// \param ClassType the class type referred to by the constructor name.
1093 ///
1094 /// \param ClassNameLoc the location of the class name.
1095 ///
1096 /// \param EndLoc the location of the last token that makes up the type name.
1097 void setConstructorName(ParsedType ClassType,
1098 SourceLocation ClassNameLoc,
1099 SourceLocation EndLoc) {
1100 Kind = UnqualifiedIdKind::IK_ConstructorName;
1101 StartLocation = ClassNameLoc;
1102 EndLocation = EndLoc;
1103 ConstructorName = ClassType;
1104 }
1105
1106 /// Specify that this unqualified-id was parsed as a
1107 /// template-id that names a constructor.
1108 ///
1109 /// \param TemplateId the template-id annotation that describes the parsed
1110 /// template-id. This UnqualifiedId instance will take ownership of the
1111 /// \p TemplateId and will free it on destruction.
1112 void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
1113
1114 /// Specify that this unqualified-id was parsed as a destructor name.
1115 ///
1116 /// \param TildeLoc the location of the '~' that introduces the destructor
1117 /// name.
1118 ///
1119 /// \param ClassType the name of the class referred to by the destructor name.
1120 void setDestructorName(SourceLocation TildeLoc,
1121 ParsedType ClassType,
1122 SourceLocation EndLoc) {
1123 Kind = UnqualifiedIdKind::IK_DestructorName;
1124 StartLocation = TildeLoc;
1125 EndLocation = EndLoc;
1126 DestructorName = ClassType;
1127 }
1128
1129 /// Specify that this unqualified-id was parsed as a template-id.
1130 ///
1131 /// \param TemplateId the template-id annotation that describes the parsed
1132 /// template-id. This UnqualifiedId instance will take ownership of the
1133 /// \p TemplateId and will free it on destruction.
1134 void setTemplateId(TemplateIdAnnotation *TemplateId);
1135
1136 /// Specify that this unqualified-id was parsed as a template-name for
1137 /// a deduction-guide.
1138 ///
1139 /// \param Template The parsed template-name.
1140 /// \param TemplateLoc The location of the parsed template-name.
1141 void setDeductionGuideName(ParsedTemplateTy Template,
1142 SourceLocation TemplateLoc) {
1143 Kind = UnqualifiedIdKind::IK_DeductionGuideName;
1144 TemplateName = Template;
1145 StartLocation = EndLocation = TemplateLoc;
1146 }
1147
1148 /// Specify that this unqualified-id is an implicit 'self'
1149 /// parameter.
1150 ///
1151 /// \param Id the identifier.
1152 void setImplicitSelfParam(const IdentifierInfo *Id) {
1153 Kind = UnqualifiedIdKind::IK_ImplicitSelfParam;
1154 Identifier = const_cast<IdentifierInfo *>(Id);
1155 StartLocation = EndLocation = SourceLocation();
1156 }
1157
1158 /// Return the source range that covers this unqualified-id.
1159 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
1160 return SourceRange(StartLocation, EndLocation);
1161 }
1162 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return StartLocation; }
1163 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return EndLocation; }
1164};
1165
1166/// A set of tokens that has been cached for later parsing.
1167typedef SmallVector<Token, 4> CachedTokens;
1168
1169/// One instance of this struct is used for each type in a
1170/// declarator that is parsed.
1171///
1172/// This is intended to be a small value object.
1173struct DeclaratorChunk {
1174 DeclaratorChunk() {};
1175
1176 enum {
1177 Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe
1178 } Kind;
1179
1180 /// Loc - The place where this type was defined.
1181 SourceLocation Loc;
1182 /// EndLoc - If valid, the place where this chunck ends.
1183 SourceLocation EndLoc;
1184
1185 SourceRange getSourceRange() const {
1186 if (EndLoc.isInvalid())
1187 return SourceRange(Loc, Loc);
1188 return SourceRange(Loc, EndLoc);
1189 }
1190
1191 ParsedAttributesView AttrList;
1192
1193 struct PointerTypeInfo {
1194 /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
1195 unsigned TypeQuals : 5;
1196
1197 /// The location of the const-qualifier, if any.
1198 SourceLocation ConstQualLoc;
1199
1200 /// The location of the volatile-qualifier, if any.
1201 SourceLocation VolatileQualLoc;
1202
1203 /// The location of the restrict-qualifier, if any.
1204 SourceLocation RestrictQualLoc;
1205
1206 /// The location of the _Atomic-qualifier, if any.
1207 SourceLocation AtomicQualLoc;
1208
1209 /// The location of the __unaligned-qualifier, if any.
1210 SourceLocation UnalignedQualLoc;
1211
1212 void destroy() {
1213 }
1214 };
1215
1216 struct ReferenceTypeInfo {
1217 /// The type qualifier: restrict. [GNU] C++ extension
1218 bool HasRestrict : 1;
1219 /// True if this is an lvalue reference, false if it's an rvalue reference.
1220 bool LValueRef : 1;
1221 void destroy() {
1222 }
1223 };
1224
1225 struct ArrayTypeInfo {
1226 /// The type qualifiers for the array:
1227 /// const/volatile/restrict/__unaligned/_Atomic.
1228 unsigned TypeQuals : 5;
1229
1230 /// True if this dimension included the 'static' keyword.
1231 unsigned hasStatic : 1;
1232
1233 /// True if this dimension was [*]. In this case, NumElts is null.
1234 unsigned isStar : 1;
1235
1236 /// This is the size of the array, or null if [] or [*] was specified.
1237 /// Since the parser is multi-purpose, and we don't want to impose a root
1238 /// expression class on all clients, NumElts is untyped.
1239 Expr *NumElts;
1240
1241 void destroy() {}
1242 };
1243
1244 /// ParamInfo - An array of paraminfo objects is allocated whenever a function
1245 /// declarator is parsed. There are two interesting styles of parameters
1246 /// here:
1247 /// K&R-style identifier lists and parameter type lists. K&R-style identifier
1248 /// lists will have information about the identifier, but no type information.
1249 /// Parameter type lists will have type info (if the actions module provides
1250 /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
1251 struct ParamInfo {
1252 IdentifierInfo *Ident;
1253 SourceLocation IdentLoc;
1254 Decl *Param;
1255
1256 /// DefaultArgTokens - When the parameter's default argument
1257 /// cannot be parsed immediately (because it occurs within the
1258 /// declaration of a member function), it will be stored here as a
1259 /// sequence of tokens to be parsed once the class definition is
1260 /// complete. Non-NULL indicates that there is a default argument.
1261 std::unique_ptr<CachedTokens> DefaultArgTokens;
1262
1263 ParamInfo() = default;
1264 ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
1265 Decl *param,
1266 std::unique_ptr<CachedTokens> DefArgTokens = nullptr)
1267 : Ident(ident), IdentLoc(iloc), Param(param),
1268 DefaultArgTokens(std::move(DefArgTokens)) {}
1269 };
1270
1271 struct TypeAndRange {
1272 ParsedType Ty;
1273 SourceRange Range;
1274 };
1275
1276 struct FunctionTypeInfo {
1277 /// hasPrototype - This is true if the function had at least one typed
1278 /// parameter. If the function is () or (a,b,c), then it has no prototype,
1279 /// and is treated as a K&R-style function.
1280 unsigned hasPrototype : 1;
1281
1282 /// isVariadic - If this function has a prototype, and if that
1283 /// proto ends with ',...)', this is true. When true, EllipsisLoc
1284 /// contains the location of the ellipsis.
1285 unsigned isVariadic : 1;
1286
1287 /// Can this declaration be a constructor-style initializer?
1288 unsigned isAmbiguous : 1;
1289
1290 /// Whether the ref-qualifier (if any) is an lvalue reference.
1291 /// Otherwise, it's an rvalue reference.
1292 unsigned RefQualifierIsLValueRef : 1;
1293
1294 /// ExceptionSpecType - An ExceptionSpecificationType value.
1295 unsigned ExceptionSpecType : 4;
1296
1297 /// DeleteParams - If this is true, we need to delete[] Params.
1298 unsigned DeleteParams : 1;
1299
1300 /// HasTrailingReturnType - If this is true, a trailing return type was
1301 /// specified.
1302 unsigned HasTrailingReturnType : 1;
1303
1304 /// The location of the left parenthesis in the source.
1305 SourceLocation LParenLoc;
1306
1307 /// When isVariadic is true, the location of the ellipsis in the source.
1308 SourceLocation EllipsisLoc;
1309
1310 /// The location of the right parenthesis in the source.
1311 SourceLocation RParenLoc;
1312
1313 /// NumParams - This is the number of formal parameters specified by the
1314 /// declarator.
1315 unsigned NumParams;
1316
1317 /// NumExceptionsOrDecls - This is the number of types in the
1318 /// dynamic-exception-decl, if the function has one. In C, this is the
1319 /// number of declarations in the function prototype.
1320 unsigned NumExceptionsOrDecls;
1321
1322 /// The location of the ref-qualifier, if any.
1323 ///
1324 /// If this is an invalid location, there is no ref-qualifier.
1325 SourceLocation RefQualifierLoc;
1326
1327 /// The location of the 'mutable' qualifer in a lambda-declarator, if
1328 /// any.
1329 SourceLocation MutableLoc;
1330
1331 /// The beginning location of the exception specification, if any.
1332 SourceLocation ExceptionSpecLocBeg;
1333
1334 /// The end location of the exception specification, if any.
1335 SourceLocation ExceptionSpecLocEnd;
1336
1337 /// Params - This is a pointer to a new[]'d array of ParamInfo objects that
1338 /// describe the parameters specified by this function declarator. null if
1339 /// there are no parameters specified.
1340 ParamInfo *Params;
1341
1342 /// DeclSpec for the function with the qualifier related info.
1343 DeclSpec *MethodQualifiers;
1344
1345 /// AtttibuteFactory for the MethodQualifiers.
1346 AttributeFactory *QualAttrFactory;
1347
1348 union {
1349 /// Pointer to a new[]'d array of TypeAndRange objects that
1350 /// contain the types in the function's dynamic exception specification
1351 /// and their locations, if there is one.
1352 TypeAndRange *Exceptions;
1353
1354 /// Pointer to the expression in the noexcept-specifier of this
1355 /// function, if it has one.
1356 Expr *NoexceptExpr;
1357
1358 /// Pointer to the cached tokens for an exception-specification
1359 /// that has not yet been parsed.
1360 CachedTokens *ExceptionSpecTokens;
1361
1362 /// Pointer to a new[]'d array of declarations that need to be available
1363 /// for lookup inside the function body, if one exists. Does not exist in
1364 /// C++.
1365 NamedDecl **DeclsInPrototype;
1366 };
1367
1368 /// If HasTrailingReturnType is true, this is the trailing return
1369 /// type specified.
1370 UnionParsedType TrailingReturnType;
1371
1372 /// If HasTrailingReturnType is true, this is the location of the trailing
1373 /// return type.
1374 SourceLocation TrailingReturnTypeLoc;
1375
1376 /// Reset the parameter list to having zero parameters.
1377 ///
1378 /// This is used in various places for error recovery.
1379 void freeParams() {
1380 for (unsigned I = 0; I < NumParams; ++I)
1381 Params[I].DefaultArgTokens.reset();
1382 if (DeleteParams) {
1383 delete[] Params;
1384 DeleteParams = false;
1385 }
1386 NumParams = 0;
1387 }
1388
1389 void destroy() {
1390 freeParams();
1391 delete QualAttrFactory;
1392 delete MethodQualifiers;
1393 switch (getExceptionSpecType()) {
1394 default:
1395 break;
1396 case EST_Dynamic:
1397 delete[] Exceptions;
1398 break;
1399 case EST_Unparsed:
1400 delete ExceptionSpecTokens;
1401 break;
1402 case EST_None:
1403 if (NumExceptionsOrDecls != 0)
1404 delete[] DeclsInPrototype;
1405 break;
1406 }
1407 }
1408
1409 DeclSpec &getOrCreateMethodQualifiers() {
1410 if (!MethodQualifiers) {
1411 QualAttrFactory = new AttributeFactory();
1412 MethodQualifiers = new DeclSpec(*QualAttrFactory);
1413 }
1414 return *MethodQualifiers;
1415 }
1416
1417 /// isKNRPrototype - Return true if this is a K&R style identifier list,
1418 /// like "void foo(a,b,c)". In a function definition, this will be followed
1419 /// by the parameter type definitions.
1420 bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
1421
1422 SourceLocation getLParenLoc() const { return LParenLoc; }
1423
1424 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
1425
1426 SourceLocation getRParenLoc() const { return RParenLoc; }
1427
1428 SourceLocation getExceptionSpecLocBeg() const {
1429 return ExceptionSpecLocBeg;
1430 }
1431
1432 SourceLocation getExceptionSpecLocEnd() const {
1433 return ExceptionSpecLocEnd;
1434 }
1435
1436 SourceRange getExceptionSpecRange() const {
1437 return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd());
1438 }
1439
1440 /// Retrieve the location of the ref-qualifier, if any.
1441 SourceLocation getRefQualifierLoc() const { return RefQualifierLoc; }
1442
1443 /// Retrieve the location of the 'const' qualifier.
1444 SourceLocation getConstQualifierLoc() const {
1445 assert(MethodQualifiers)(static_cast <bool> (MethodQualifiers) ? void (0) : __assert_fail
("MethodQualifiers", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 1445, __extension__ __PRETTY_FUNCTION__))
;
1446 return MethodQualifiers->getConstSpecLoc();
1447 }
1448
1449 /// Retrieve the location of the 'volatile' qualifier.
1450 SourceLocation getVolatileQualifierLoc() const {
1451 assert(MethodQualifiers)(static_cast <bool> (MethodQualifiers) ? void (0) : __assert_fail
("MethodQualifiers", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 1451, __extension__ __PRETTY_FUNCTION__))
;
1452 return MethodQualifiers->getVolatileSpecLoc();
1453 }
1454
1455 /// Retrieve the location of the 'restrict' qualifier.
1456 SourceLocation getRestrictQualifierLoc() const {
1457 assert(MethodQualifiers)(static_cast <bool> (MethodQualifiers) ? void (0) : __assert_fail
("MethodQualifiers", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 1457, __extension__ __PRETTY_FUNCTION__))
;
1458 return MethodQualifiers->getRestrictSpecLoc();
1459 }
1460
1461 /// Retrieve the location of the 'mutable' qualifier, if any.
1462 SourceLocation getMutableLoc() const { return MutableLoc; }
1463
1464 /// Determine whether this function declaration contains a
1465 /// ref-qualifier.
1466 bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
1467
1468 /// Determine whether this lambda-declarator contains a 'mutable'
1469 /// qualifier.
1470 bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
1471
1472 /// Determine whether this method has qualifiers.
1473 bool hasMethodTypeQualifiers() const {
1474 return MethodQualifiers && (MethodQualifiers->getTypeQualifiers() ||
1475 MethodQualifiers->getAttributes().size());
1476 }
1477
1478 /// Get the type of exception specification this function has.
1479 ExceptionSpecificationType getExceptionSpecType() const {
1480 return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
1481 }
1482
1483 /// Get the number of dynamic exception specifications.
1484 unsigned getNumExceptions() const {
1485 assert(ExceptionSpecType != EST_None)(static_cast <bool> (ExceptionSpecType != EST_None) ? void
(0) : __assert_fail ("ExceptionSpecType != EST_None", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 1485, __extension__ __PRETTY_FUNCTION__))
;
1486 return NumExceptionsOrDecls;
1487 }
1488
1489 /// Get the non-parameter decls defined within this function
1490 /// prototype. Typically these are tag declarations.
1491 ArrayRef<NamedDecl *> getDeclsInPrototype() const {
1492 assert(ExceptionSpecType == EST_None)(static_cast <bool> (ExceptionSpecType == EST_None) ? void
(0) : __assert_fail ("ExceptionSpecType == EST_None", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 1492, __extension__ __PRETTY_FUNCTION__))
;
1493 return llvm::makeArrayRef(DeclsInPrototype, NumExceptionsOrDecls);
1494 }
1495
1496 /// Determine whether this function declarator had a
1497 /// trailing-return-type.
1498 bool hasTrailingReturnType() const { return HasTrailingReturnType; }
1499
1500 /// Get the trailing-return-type for this function declarator.
1501 ParsedType getTrailingReturnType() const {
1502 assert(HasTrailingReturnType)(static_cast <bool> (HasTrailingReturnType) ? void (0) :
__assert_fail ("HasTrailingReturnType", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 1502, __extension__ __PRETTY_FUNCTION__))
;
1503 return TrailingReturnType;
1504 }
1505
1506 /// Get the trailing-return-type location for this function declarator.
1507 SourceLocation getTrailingReturnTypeLoc() const {
1508 assert(HasTrailingReturnType)(static_cast <bool> (HasTrailingReturnType) ? void (0) :
__assert_fail ("HasTrailingReturnType", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 1508, __extension__ __PRETTY_FUNCTION__))
;
1509 return TrailingReturnTypeLoc;
1510 }
1511 };
1512
1513 struct BlockPointerTypeInfo {
1514 /// For now, sema will catch these as invalid.
1515 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1516 unsigned TypeQuals : 5;
1517
1518 void destroy() {
1519 }
1520 };
1521
1522 struct MemberPointerTypeInfo {
1523 /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
1524 unsigned TypeQuals : 5;
1525 /// Location of the '*' token.
1526 SourceLocation StarLoc;
1527 // CXXScopeSpec has a constructor, so it can't be a direct member.
1528 // So we need some pointer-aligned storage and a bit of trickery.
1529 alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)];
1530 CXXScopeSpec &Scope() {
1531 return *reinterpret_cast<CXXScopeSpec *>(ScopeMem);
1532 }
1533 const CXXScopeSpec &Scope() const {
1534 return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem);
1535 }
1536 void destroy() {
1537 Scope().~CXXScopeSpec();
1538 }
1539 };
1540
1541 struct PipeTypeInfo {
1542 /// The access writes.
1543 unsigned AccessWrites : 3;
1544
1545 void destroy() {}
1546 };
1547
1548 union {
1549 PointerTypeInfo Ptr;
1550 ReferenceTypeInfo Ref;
1551 ArrayTypeInfo Arr;
1552 FunctionTypeInfo Fun;
1553 BlockPointerTypeInfo Cls;
1554 MemberPointerTypeInfo Mem;
1555 PipeTypeInfo PipeInfo;
1556 };
1557
1558 void destroy() {
1559 switch (Kind) {
1560 case DeclaratorChunk::Function: return Fun.destroy();
1561 case DeclaratorChunk::Pointer: return Ptr.destroy();
1562 case DeclaratorChunk::BlockPointer: return Cls.destroy();
1563 case DeclaratorChunk::Reference: return Ref.destroy();
1564 case DeclaratorChunk::Array: return Arr.destroy();
1565 case DeclaratorChunk::MemberPointer: return Mem.destroy();
1566 case DeclaratorChunk::Paren: return;
1567 case DeclaratorChunk::Pipe: return PipeInfo.destroy();
1568 }
1569 }
1570
1571 /// If there are attributes applied to this declaratorchunk, return
1572 /// them.
1573 const ParsedAttributesView &getAttrs() const { return AttrList; }
1574 ParsedAttributesView &getAttrs() { return AttrList; }
1575
1576 /// Return a DeclaratorChunk for a pointer.
1577 static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
1578 SourceLocation ConstQualLoc,
1579 SourceLocation VolatileQualLoc,
1580 SourceLocation RestrictQualLoc,
1581 SourceLocation AtomicQualLoc,
1582 SourceLocation UnalignedQualLoc) {
1583 DeclaratorChunk I;
1584 I.Kind = Pointer;
1585 I.Loc = Loc;
1586 new (&I.Ptr) PointerTypeInfo;
1587 I.Ptr.TypeQuals = TypeQuals;
1588 I.Ptr.ConstQualLoc = ConstQualLoc;
1589 I.Ptr.VolatileQualLoc = VolatileQualLoc;
1590 I.Ptr.RestrictQualLoc = RestrictQualLoc;
1591 I.Ptr.AtomicQualLoc = AtomicQualLoc;
1592 I.Ptr.UnalignedQualLoc = UnalignedQualLoc;
1593 return I;
1594 }
1595
1596 /// Return a DeclaratorChunk for a reference.
1597 static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
1598 bool lvalue) {
1599 DeclaratorChunk I;
1600 I.Kind = Reference;
1601 I.Loc = Loc;
1602 I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
1603 I.Ref.LValueRef = lvalue;
1604 return I;
1605 }
1606
1607 /// Return a DeclaratorChunk for an array.
1608 static DeclaratorChunk getArray(unsigned TypeQuals,
1609 bool isStatic, bool isStar, Expr *NumElts,
1610 SourceLocation LBLoc, SourceLocation RBLoc) {
1611 DeclaratorChunk I;
1612 I.Kind = Array;
1613 I.Loc = LBLoc;
1614 I.EndLoc = RBLoc;
1615 I.Arr.TypeQuals = TypeQuals;
1616 I.Arr.hasStatic = isStatic;
1617 I.Arr.isStar = isStar;
1618 I.Arr.NumElts = NumElts;
1619 return I;
1620 }
1621
1622 /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
1623 /// "TheDeclarator" is the declarator that this will be added to.
1624 static DeclaratorChunk getFunction(bool HasProto,
1625 bool IsAmbiguous,
1626 SourceLocation LParenLoc,
1627 ParamInfo *Params, unsigned NumParams,
1628 SourceLocation EllipsisLoc,
1629 SourceLocation RParenLoc,
1630 bool RefQualifierIsLvalueRef,
1631 SourceLocation RefQualifierLoc,
1632 SourceLocation MutableLoc,
1633 ExceptionSpecificationType ESpecType,
1634 SourceRange ESpecRange,
1635 ParsedType *Exceptions,
1636 SourceRange *ExceptionRanges,
1637 unsigned NumExceptions,
1638 Expr *NoexceptExpr,
1639 CachedTokens *ExceptionSpecTokens,
1640 ArrayRef<NamedDecl *> DeclsInPrototype,
1641 SourceLocation LocalRangeBegin,
1642 SourceLocation LocalRangeEnd,
1643 Declarator &TheDeclarator,
1644 TypeResult TrailingReturnType =
1645 TypeResult(),
1646 SourceLocation TrailingReturnTypeLoc =
1647 SourceLocation(),
1648 DeclSpec *MethodQualifiers = nullptr);
1649
1650 /// Return a DeclaratorChunk for a block.
1651 static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
1652 SourceLocation Loc) {
1653 DeclaratorChunk I;
1654 I.Kind = BlockPointer;
1655 I.Loc = Loc;
1656 I.Cls.TypeQuals = TypeQuals;
1657 return I;
1658 }
1659
1660 /// Return a DeclaratorChunk for a block.
1661 static DeclaratorChunk getPipe(unsigned TypeQuals,
1662 SourceLocation Loc) {
1663 DeclaratorChunk I;
1664 I.Kind = Pipe;
1665 I.Loc = Loc;
1666 I.Cls.TypeQuals = TypeQuals;
1667 return I;
1668 }
1669
1670 static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
1671 unsigned TypeQuals,
1672 SourceLocation StarLoc,
1673 SourceLocation EndLoc) {
1674 DeclaratorChunk I;
1675 I.Kind = MemberPointer;
1676 I.Loc = SS.getBeginLoc();
1677 I.EndLoc = EndLoc;
1678 new (&I.Mem) MemberPointerTypeInfo;
1679 I.Mem.StarLoc = StarLoc;
1680 I.Mem.TypeQuals = TypeQuals;
1681 new (I.Mem.ScopeMem) CXXScopeSpec(SS);
1682 return I;
1683 }
1684
1685 /// Return a DeclaratorChunk for a paren.
1686 static DeclaratorChunk getParen(SourceLocation LParenLoc,
1687 SourceLocation RParenLoc) {
1688 DeclaratorChunk I;
1689 I.Kind = Paren;
1690 I.Loc = LParenLoc;
1691 I.EndLoc = RParenLoc;
1692 return I;
1693 }
1694
1695 bool isParen() const {
1696 return Kind == Paren;
1697 }
1698};
1699
1700/// A parsed C++17 decomposition declarator of the form
1701/// '[' identifier-list ']'
1702class DecompositionDeclarator {
1703public:
1704 struct Binding {
1705 IdentifierInfo *Name;
1706 SourceLocation NameLoc;
1707 };
1708
1709private:
1710 /// The locations of the '[' and ']' tokens.
1711 SourceLocation LSquareLoc, RSquareLoc;
1712
1713 /// The bindings.
1714 Binding *Bindings;
1715 unsigned NumBindings : 31;
1716 unsigned DeleteBindings : 1;
1717
1718 friend class Declarator;
1719
1720public:
1721 DecompositionDeclarator()
1722 : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {}
1723 DecompositionDeclarator(const DecompositionDeclarator &G) = delete;
1724 DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete;
1725 ~DecompositionDeclarator() {
1726 if (DeleteBindings)
1727 delete[] Bindings;
1728 }
1729
1730 void clear() {
1731 LSquareLoc = RSquareLoc = SourceLocation();
1732 if (DeleteBindings)
1733 delete[] Bindings;
1734 Bindings = nullptr;
1735 NumBindings = 0;
1736 DeleteBindings = false;
1737 }
1738
1739 ArrayRef<Binding> bindings() const {
1740 return llvm::makeArrayRef(Bindings, NumBindings);
1741 }
1742
1743 bool isSet() const { return LSquareLoc.isValid(); }
1744
1745 SourceLocation getLSquareLoc() const { return LSquareLoc; }
1746 SourceLocation getRSquareLoc() const { return RSquareLoc; }
1747 SourceRange getSourceRange() const {
1748 return SourceRange(LSquareLoc, RSquareLoc);
1749 }
1750};
1751
1752/// Described the kind of function definition (if any) provided for
1753/// a function.
1754enum class FunctionDefinitionKind {
1755 Declaration,
1756 Definition,
1757 Defaulted,
1758 Deleted
1759};
1760
1761enum class DeclaratorContext {
1762 File, // File scope declaration.
1763 Prototype, // Within a function prototype.
1764 ObjCResult, // An ObjC method result type.
1765 ObjCParameter, // An ObjC method parameter type.
1766 KNRTypeList, // K&R type definition list for formals.
1767 TypeName, // Abstract declarator for types.
1768 FunctionalCast, // Type in a C++ functional cast expression.
1769 Member, // Struct/Union field.
1770 Block, // Declaration within a block in a function.
1771 ForInit, // Declaration within first part of a for loop.
1772 SelectionInit, // Declaration within optional init stmt of if/switch.
1773 Condition, // Condition declaration in a C++ if/switch/while/for.
1774 TemplateParam, // Within a template parameter list.
1775 CXXNew, // C++ new-expression.
1776 CXXCatch, // C++ catch exception-declaration
1777 ObjCCatch, // Objective-C catch exception-declaration
1778 BlockLiteral, // Block literal declarator.
1779 LambdaExpr, // Lambda-expression declarator.
1780 LambdaExprParameter, // Lambda-expression parameter declarator.
1781 ConversionId, // C++ conversion-type-id.
1782 TrailingReturn, // C++11 trailing-type-specifier.
1783 TrailingReturnVar, // C++11 trailing-type-specifier for variable.
1784 TemplateArg, // Any template argument (in template argument list).
1785 TemplateTypeArg, // Template type argument (in default argument).
1786 AliasDecl, // C++11 alias-declaration.
1787 AliasTemplate, // C++11 alias-declaration template.
1788 RequiresExpr // C++2a requires-expression.
1789};
1790
1791/// Information about one declarator, including the parsed type
1792/// information and the identifier.
1793///
1794/// When the declarator is fully formed, this is turned into the appropriate
1795/// Decl object.
1796///
1797/// Declarators come in two types: normal declarators and abstract declarators.
1798/// Abstract declarators are used when parsing types, and don't have an
1799/// identifier. Normal declarators do have ID's.
1800///
1801/// Instances of this class should be a transient object that lives on the
1802/// stack, not objects that are allocated in large quantities on the heap.
1803class Declarator {
1804
1805private:
1806 const DeclSpec &DS;
1807 CXXScopeSpec SS;
1808 UnqualifiedId Name;
1809 SourceRange Range;
1810
1811 /// Where we are parsing this declarator.
1812 DeclaratorContext Context;
1813
1814 /// The C++17 structured binding, if any. This is an alternative to a Name.
1815 DecompositionDeclarator BindingGroup;
1816
1817 /// DeclTypeInfo - This holds each type that the declarator includes as it is
1818 /// parsed. This is pushed from the identifier out, which means that element
1819 /// #0 will be the most closely bound to the identifier, and
1820 /// DeclTypeInfo.back() will be the least closely bound.
1821 SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
1822
1823 /// InvalidType - Set by Sema::GetTypeForDeclarator().
1824 unsigned InvalidType : 1;
1825
1826 /// GroupingParens - Set by Parser::ParseParenDeclarator().
1827 unsigned GroupingParens : 1;
1828
1829 /// FunctionDefinition - Is this Declarator for a function or member
1830 /// definition and, if so, what kind?
1831 ///
1832 /// Actually a FunctionDefinitionKind.
1833 unsigned FunctionDefinition : 2;
1834
1835 /// Is this Declarator a redeclaration?
1836 unsigned Redeclaration : 1;
1837
1838 /// true if the declaration is preceded by \c __extension__.
1839 unsigned Extension : 1;
1840
1841 /// Indicates whether this is an Objective-C instance variable.
1842 unsigned ObjCIvar : 1;
1843
1844 /// Indicates whether this is an Objective-C 'weak' property.
1845 unsigned ObjCWeakProperty : 1;
1846
1847 /// Indicates whether the InlineParams / InlineBindings storage has been used.
1848 unsigned InlineStorageUsed : 1;
1849
1850 /// Indicates whether this declarator has an initializer.
1851 unsigned HasInitializer : 1;
1852
1853 /// Attrs - Attributes.
1854 ParsedAttributes Attrs;
1855
1856 /// The asm label, if specified.
1857 Expr *AsmLabel;
1858
1859 /// \brief The constraint-expression specified by the trailing
1860 /// requires-clause, or null if no such clause was specified.
1861 Expr *TrailingRequiresClause;
1862
1863 /// If this declarator declares a template, its template parameter lists.
1864 ArrayRef<TemplateParameterList *> TemplateParameterLists;
1865
1866 /// If the declarator declares an abbreviated function template, the innermost
1867 /// template parameter list containing the invented and explicit template
1868 /// parameters (if any).
1869 TemplateParameterList *InventedTemplateParameterList;
1870
1871#ifndef _MSC_VER
1872 union {
1873#endif
1874 /// InlineParams - This is a local array used for the first function decl
1875 /// chunk to avoid going to the heap for the common case when we have one
1876 /// function chunk in the declarator.
1877 DeclaratorChunk::ParamInfo InlineParams[16];
1878 DecompositionDeclarator::Binding InlineBindings[16];
1879#ifndef _MSC_VER
1880 };
1881#endif
1882
1883 /// If this is the second or subsequent declarator in this declaration,
1884 /// the location of the comma before this declarator.
1885 SourceLocation CommaLoc;
1886
1887 /// If provided, the source location of the ellipsis used to describe
1888 /// this declarator as a parameter pack.
1889 SourceLocation EllipsisLoc;
1890
1891 friend struct DeclaratorChunk;
1892
1893public:
1894 Declarator(const DeclSpec &ds, DeclaratorContext C)
1895 : DS(ds), Range(ds.getSourceRange()), Context(C),
1896 InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
1897 GroupingParens(false), FunctionDefinition(static_cast<unsigned>(
1898 FunctionDefinitionKind::Declaration)),
1899 Redeclaration(false), Extension(false), ObjCIvar(false),
1900 ObjCWeakProperty(false), InlineStorageUsed(false),
1901 HasInitializer(false), Attrs(ds.getAttributePool().getFactory()),
1902 AsmLabel(nullptr), TrailingRequiresClause(nullptr),
1903 InventedTemplateParameterList(nullptr) {}
1904
1905 ~Declarator() {
1906 clear();
1907 }
1908 /// getDeclSpec - Return the declaration-specifier that this declarator was
1909 /// declared with.
1910 const DeclSpec &getDeclSpec() const { return DS; }
1911
1912 /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This
1913 /// should be used with extreme care: declspecs can often be shared between
1914 /// multiple declarators, so mutating the DeclSpec affects all of the
1915 /// Declarators. This should only be done when the declspec is known to not
1916 /// be shared or when in error recovery etc.
1917 DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
1918
1919 AttributePool &getAttributePool() const {
1920 return Attrs.getPool();
1921 }
1922
1923 /// getCXXScopeSpec - Return the C++ scope specifier (global scope or
1924 /// nested-name-specifier) that is part of the declarator-id.
1925 const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
1926 CXXScopeSpec &getCXXScopeSpec() { return SS; }
1927
1928 /// Retrieve the name specified by this declarator.
1929 UnqualifiedId &getName() { return Name; }
1930
1931 const DecompositionDeclarator &getDecompositionDeclarator() const {
1932 return BindingGroup;
1933 }
1934
1935 DeclaratorContext getContext() const { return Context; }
1936
1937 bool isPrototypeContext() const {
1938 return (Context == DeclaratorContext::Prototype ||
1939 Context == DeclaratorContext::ObjCParameter ||
1940 Context == DeclaratorContext::ObjCResult ||
1941 Context == DeclaratorContext::LambdaExprParameter);
1942 }
1943
1944 /// Get the source range that spans this declarator.
1945 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
1946 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
1947 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
1948
1949 void SetSourceRange(SourceRange R) { Range = R; }
1950 /// SetRangeBegin - Set the start of the source range to Loc, unless it's
1951 /// invalid.
1952 void SetRangeBegin(SourceLocation Loc) {
1953 if (!Loc.isInvalid())
1954 Range.setBegin(Loc);
1955 }
1956 /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
1957 void SetRangeEnd(SourceLocation Loc) {
1958 if (!Loc.isInvalid())
1959 Range.setEnd(Loc);
1960 }
1961 /// ExtendWithDeclSpec - Extend the declarator source range to include the
1962 /// given declspec, unless its location is invalid. Adopts the range start if
1963 /// the current range start is invalid.
1964 void ExtendWithDeclSpec(const DeclSpec &DS) {
1965 SourceRange SR = DS.getSourceRange();
1966 if (Range.getBegin().isInvalid())
1967 Range.setBegin(SR.getBegin());
1968 if (!SR.getEnd().isInvalid())
1969 Range.setEnd(SR.getEnd());
1970 }
1971
1972 /// Reset the contents of this Declarator.
1973 void clear() {
1974 SS.clear();
1975 Name.clear();
1976 Range = DS.getSourceRange();
1977 BindingGroup.clear();
1978
1979 for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
1980 DeclTypeInfo[i].destroy();
1981 DeclTypeInfo.clear();
1982 Attrs.clear();
1983 AsmLabel = nullptr;
1984 InlineStorageUsed = false;
1985 HasInitializer = false;
1986 ObjCIvar = false;
1987 ObjCWeakProperty = false;
1988 CommaLoc = SourceLocation();
1989 EllipsisLoc = SourceLocation();
1990 }
1991
1992 /// mayOmitIdentifier - Return true if the identifier is either optional or
1993 /// not allowed. This is true for typenames, prototypes, and template
1994 /// parameter lists.
1995 bool mayOmitIdentifier() const {
1996 switch (Context) {
1997 case DeclaratorContext::File:
1998 case DeclaratorContext::KNRTypeList:
1999 case DeclaratorContext::Member:
2000 case DeclaratorContext::Block:
2001 case DeclaratorContext::ForInit:
2002 case DeclaratorContext::SelectionInit:
2003 case DeclaratorContext::Condition:
2004 return false;
2005
2006 case DeclaratorContext::TypeName:
2007 case DeclaratorContext::FunctionalCast:
2008 case DeclaratorContext::AliasDecl:
2009 case DeclaratorContext::AliasTemplate:
2010 case DeclaratorContext::Prototype:
2011 case DeclaratorContext::LambdaExprParameter:
2012 case DeclaratorContext::ObjCParameter:
2013 case DeclaratorContext::ObjCResult:
2014 case DeclaratorContext::TemplateParam:
2015 case DeclaratorContext::CXXNew:
2016 case DeclaratorContext::CXXCatch:
2017 case DeclaratorContext::ObjCCatch:
2018 case DeclaratorContext::BlockLiteral:
2019 case DeclaratorContext::LambdaExpr:
2020 case DeclaratorContext::ConversionId:
2021 case DeclaratorContext::TemplateArg:
2022 case DeclaratorContext::TemplateTypeArg:
2023 case DeclaratorContext::TrailingReturn:
2024 case DeclaratorContext::TrailingReturnVar:
2025 case DeclaratorContext::RequiresExpr:
2026 return true;
2027 }
2028 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 2028)
;
2029 }
2030
2031 /// mayHaveIdentifier - Return true if the identifier is either optional or
2032 /// required. This is true for normal declarators and prototypes, but not
2033 /// typenames.
2034 bool mayHaveIdentifier() const {
2035 switch (Context) {
2036 case DeclaratorContext::File:
2037 case DeclaratorContext::KNRTypeList:
2038 case DeclaratorContext::Member:
2039 case DeclaratorContext::Block:
2040 case DeclaratorContext::ForInit:
2041 case DeclaratorContext::SelectionInit:
2042 case DeclaratorContext::Condition:
2043 case DeclaratorContext::Prototype:
2044 case DeclaratorContext::LambdaExprParameter:
2045 case DeclaratorContext::TemplateParam:
2046 case DeclaratorContext::CXXCatch:
2047 case DeclaratorContext::ObjCCatch:
2048 case DeclaratorContext::RequiresExpr:
2049 return true;
2050
2051 case DeclaratorContext::TypeName:
2052 case DeclaratorContext::FunctionalCast:
2053 case DeclaratorContext::CXXNew:
2054 case DeclaratorContext::AliasDecl:
2055 case DeclaratorContext::AliasTemplate:
2056 case DeclaratorContext::ObjCParameter:
2057 case DeclaratorContext::ObjCResult:
2058 case DeclaratorContext::BlockLiteral:
2059 case DeclaratorContext::LambdaExpr:
2060 case DeclaratorContext::ConversionId:
2061 case DeclaratorContext::TemplateArg:
2062 case DeclaratorContext::TemplateTypeArg:
2063 case DeclaratorContext::TrailingReturn:
2064 case DeclaratorContext::TrailingReturnVar:
2065 return false;
2066 }
2067 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 2067)
;
2068 }
2069
2070 /// Return true if the context permits a C++17 decomposition declarator.
2071 bool mayHaveDecompositionDeclarator() const {
2072 switch (Context) {
2073 case DeclaratorContext::File:
2074 // FIXME: It's not clear that the proposal meant to allow file-scope
2075 // structured bindings, but it does.
2076 case DeclaratorContext::Block:
2077 case DeclaratorContext::ForInit:
2078 case DeclaratorContext::SelectionInit:
2079 case DeclaratorContext::Condition:
2080 return true;
2081
2082 case DeclaratorContext::Member:
2083 case DeclaratorContext::Prototype:
2084 case DeclaratorContext::TemplateParam:
2085 case DeclaratorContext::RequiresExpr:
2086 // Maybe one day...
2087 return false;
2088
2089 // These contexts don't allow any kind of non-abstract declarator.
2090 case DeclaratorContext::KNRTypeList:
2091 case DeclaratorContext::TypeName:
2092 case DeclaratorContext::FunctionalCast:
2093 case DeclaratorContext::AliasDecl:
2094 case DeclaratorContext::AliasTemplate:
2095 case DeclaratorContext::LambdaExprParameter:
2096 case DeclaratorContext::ObjCParameter:
2097 case DeclaratorContext::ObjCResult:
2098 case DeclaratorContext::CXXNew:
2099 case DeclaratorContext::CXXCatch:
2100 case DeclaratorContext::ObjCCatch:
2101 case DeclaratorContext::BlockLiteral:
2102 case DeclaratorContext::LambdaExpr:
2103 case DeclaratorContext::ConversionId:
2104 case DeclaratorContext::TemplateArg:
2105 case DeclaratorContext::TemplateTypeArg:
2106 case DeclaratorContext::TrailingReturn:
2107 case DeclaratorContext::TrailingReturnVar:
2108 return false;
2109 }
2110 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 2110)
;
2111 }
2112
2113 /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
2114 /// followed by a C++ direct initializer, e.g. "int x(1);".
2115 bool mayBeFollowedByCXXDirectInit() const {
2116 if (hasGroupingParens()) return false;
2117
2118 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2119 return false;
2120
2121 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
2122 Context != DeclaratorContext::File)
2123 return false;
2124
2125 // Special names can't have direct initializers.
2126 if (Name.getKind() != UnqualifiedIdKind::IK_Identifier)
2127 return false;
2128
2129 switch (Context) {
2130 case DeclaratorContext::File:
2131 case DeclaratorContext::Block:
2132 case DeclaratorContext::ForInit:
2133 case DeclaratorContext::SelectionInit:
2134 case DeclaratorContext::TrailingReturnVar:
2135 return true;
2136
2137 case DeclaratorContext::Condition:
2138 // This may not be followed by a direct initializer, but it can't be a
2139 // function declaration either, and we'd prefer to perform a tentative
2140 // parse in order to produce the right diagnostic.
2141 return true;
2142
2143 case DeclaratorContext::KNRTypeList:
2144 case DeclaratorContext::Member:
2145 case DeclaratorContext::Prototype:
2146 case DeclaratorContext::LambdaExprParameter:
2147 case DeclaratorContext::ObjCParameter:
2148 case DeclaratorContext::ObjCResult:
2149 case DeclaratorContext::TemplateParam:
2150 case DeclaratorContext::CXXCatch:
2151 case DeclaratorContext::ObjCCatch:
2152 case DeclaratorContext::TypeName:
2153 case DeclaratorContext::FunctionalCast: // FIXME
2154 case DeclaratorContext::CXXNew:
2155 case DeclaratorContext::AliasDecl:
2156 case DeclaratorContext::AliasTemplate:
2157 case DeclaratorContext::BlockLiteral:
2158 case DeclaratorContext::LambdaExpr:
2159 case DeclaratorContext::ConversionId:
2160 case DeclaratorContext::TemplateArg:
2161 case DeclaratorContext::TemplateTypeArg:
2162 case DeclaratorContext::TrailingReturn:
2163 case DeclaratorContext::RequiresExpr:
2164 return false;
2165 }
2166 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 2166)
;
2167 }
2168
2169 /// isPastIdentifier - Return true if we have parsed beyond the point where
2170 /// the name would appear. (This may happen even if we haven't actually parsed
2171 /// a name, perhaps because this context doesn't require one.)
2172 bool isPastIdentifier() const { return Name.isValid(); }
2173
2174 /// hasName - Whether this declarator has a name, which might be an
2175 /// identifier (accessible via getIdentifier()) or some kind of
2176 /// special C++ name (constructor, destructor, etc.), or a structured
2177 /// binding (which is not exactly a name, but occupies the same position).
2178 bool hasName() const {
2179 return Name.getKind() != UnqualifiedIdKind::IK_Identifier ||
2180 Name.Identifier || isDecompositionDeclarator();
2181 }
2182
2183 /// Return whether this declarator is a decomposition declarator.
2184 bool isDecompositionDeclarator() const {
2185 return BindingGroup.isSet();
2186 }
2187
2188 IdentifierInfo *getIdentifier() const {
2189 if (Name.getKind() == UnqualifiedIdKind::IK_Identifier)
2190 return Name.Identifier;
2191
2192 return nullptr;
2193 }
2194 SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
2195
2196 /// Set the name of this declarator to be the given identifier.
2197 void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
2198 Name.setIdentifier(Id, IdLoc);
2199 }
2200
2201 /// Set the decomposition bindings for this declarator.
2202 void
2203 setDecompositionBindings(SourceLocation LSquareLoc,
2204 ArrayRef<DecompositionDeclarator::Binding> Bindings,
2205 SourceLocation RSquareLoc);
2206
2207 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2208 /// EndLoc, which should be the last token of the chunk.
2209 /// This function takes attrs by R-Value reference because it takes ownership
2210 /// of those attributes from the parameter.
2211 void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs,
2212 SourceLocation EndLoc) {
2213 DeclTypeInfo.push_back(TI);
2214 DeclTypeInfo.back().getAttrs().addAll(attrs.begin(), attrs.end());
2215 getAttributePool().takeAllFrom(attrs.getPool());
2216
2217 if (!EndLoc.isInvalid())
2218 SetRangeEnd(EndLoc);
2219 }
2220
2221 /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
2222 /// EndLoc, which should be the last token of the chunk.
2223 void AddTypeInfo(const DeclaratorChunk &TI, SourceLocation EndLoc) {
2224 DeclTypeInfo.push_back(TI);
2225
2226 if (!EndLoc.isInvalid())
2227 SetRangeEnd(EndLoc);
2228 }
2229
2230 /// Add a new innermost chunk to this declarator.
2231 void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
2232 DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
2233 }
2234
2235 /// Return the number of types applied to this declarator.
2236 unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
2237
2238 /// Return the specified TypeInfo from this declarator. TypeInfo #0 is
2239 /// closest to the identifier.
2240 const DeclaratorChunk &getTypeObject(unsigned i) const {
2241 assert(i < DeclTypeInfo.size() && "Invalid type chunk")(static_cast <bool> (i < DeclTypeInfo.size() &&
"Invalid type chunk") ? void (0) : __assert_fail ("i < DeclTypeInfo.size() && \"Invalid type chunk\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 2241, __extension__ __PRETTY_FUNCTION__))
;
2242 return DeclTypeInfo[i];
2243 }
2244 DeclaratorChunk &getTypeObject(unsigned i) {
2245 assert(i < DeclTypeInfo.size() && "Invalid type chunk")(static_cast <bool> (i < DeclTypeInfo.size() &&
"Invalid type chunk") ? void (0) : __assert_fail ("i < DeclTypeInfo.size() && \"Invalid type chunk\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 2245, __extension__ __PRETTY_FUNCTION__))
;
2246 return DeclTypeInfo[i];
2247 }
2248
2249 typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
2250 typedef llvm::iterator_range<type_object_iterator> type_object_range;
2251
2252 /// Returns the range of type objects, from the identifier outwards.
2253 type_object_range type_objects() const {
2254 return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
2255 }
2256
2257 void DropFirstTypeObject() {
2258 assert(!DeclTypeInfo.empty() && "No type chunks to drop.")(static_cast <bool> (!DeclTypeInfo.empty() && "No type chunks to drop."
) ? void (0) : __assert_fail ("!DeclTypeInfo.empty() && \"No type chunks to drop.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 2258, __extension__ __PRETTY_FUNCTION__))
;
2259 DeclTypeInfo.front().destroy();
2260 DeclTypeInfo.erase(DeclTypeInfo.begin());
2261 }
2262
2263 /// Return the innermost (closest to the declarator) chunk of this
2264 /// declarator that is not a parens chunk, or null if there are no
2265 /// non-parens chunks.
2266 const DeclaratorChunk *getInnermostNonParenChunk() const {
2267 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2268 if (!DeclTypeInfo[i].isParen())
2269 return &DeclTypeInfo[i];
2270 }
2271 return nullptr;
2272 }
2273
2274 /// Return the outermost (furthest from the declarator) chunk of
2275 /// this declarator that is not a parens chunk, or null if there are
2276 /// no non-parens chunks.
2277 const DeclaratorChunk *getOutermostNonParenChunk() const {
2278 for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
2279 if (!DeclTypeInfo[i-1].isParen())
2280 return &DeclTypeInfo[i-1];
2281 }
2282 return nullptr;
2283 }
2284
2285 /// isArrayOfUnknownBound - This method returns true if the declarator
2286 /// is a declarator for an array of unknown bound (looking through
2287 /// parentheses).
2288 bool isArrayOfUnknownBound() const {
2289 const DeclaratorChunk *chunk = getInnermostNonParenChunk();
2290 return (chunk && chunk->Kind == DeclaratorChunk::Array &&
2291 !chunk->Arr.NumElts);
2292 }
2293
2294 /// isFunctionDeclarator - This method returns true if the declarator
2295 /// is a function declarator (looking through parentheses).
2296 /// If true is returned, then the reference type parameter idx is
2297 /// assigned with the index of the declaration chunk.
2298 bool isFunctionDeclarator(unsigned& idx) const {
2299 for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
2300 switch (DeclTypeInfo[i].Kind) {
2301 case DeclaratorChunk::Function:
2302 idx = i;
2303 return true;
2304 case DeclaratorChunk::Paren:
2305 continue;
2306 case DeclaratorChunk::Pointer:
2307 case DeclaratorChunk::Reference:
2308 case DeclaratorChunk::Array:
2309 case DeclaratorChunk::BlockPointer:
2310 case DeclaratorChunk::MemberPointer:
2311 case DeclaratorChunk::Pipe:
2312 return false;
2313 }
2314 llvm_unreachable("Invalid type chunk")::llvm::llvm_unreachable_internal("Invalid type chunk", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 2314)
;
2315 }
2316 return false;
2317 }
2318
2319 /// isFunctionDeclarator - Once this declarator is fully parsed and formed,
2320 /// this method returns true if the identifier is a function declarator
2321 /// (looking through parentheses).
2322 bool isFunctionDeclarator() const {
2323 unsigned index;
2324 return isFunctionDeclarator(index);
2325 }
2326
2327 /// getFunctionTypeInfo - Retrieves the function type info object
2328 /// (looking through parentheses).
2329 DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
2330 assert(isFunctionDeclarator() && "Not a function declarator!")(static_cast <bool> (isFunctionDeclarator() && "Not a function declarator!"
) ? void (0) : __assert_fail ("isFunctionDeclarator() && \"Not a function declarator!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 2330, __extension__ __PRETTY_FUNCTION__))
;
2331 unsigned index = 0;
2332 isFunctionDeclarator(index);
2333 return DeclTypeInfo[index].Fun;
2334 }
2335
2336 /// getFunctionTypeInfo - Retrieves the function type info object
2337 /// (looking through parentheses).
2338 const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
2339 return const_cast<Declarator*>(this)->getFunctionTypeInfo();
2340 }
2341
2342 /// Determine whether the declaration that will be produced from
2343 /// this declaration will be a function.
2344 ///
2345 /// A declaration can declare a function even if the declarator itself
2346 /// isn't a function declarator, if the type specifier refers to a function
2347 /// type. This routine checks for both cases.
2348 bool isDeclarationOfFunction() const;
2349
2350 /// Return true if this declaration appears in a context where a
2351 /// function declarator would be a function declaration.
2352 bool isFunctionDeclarationContext() const {
2353 if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2354 return false;
2355
2356 switch (Context) {
2357 case DeclaratorContext::File:
2358 case DeclaratorContext::Member:
2359 case DeclaratorContext::Block:
2360 case DeclaratorContext::ForInit:
2361 case DeclaratorContext::SelectionInit:
2362 return true;
2363
2364 case DeclaratorContext::Condition:
2365 case DeclaratorContext::KNRTypeList:
2366 case DeclaratorContext::TypeName:
2367 case DeclaratorContext::FunctionalCast:
2368 case DeclaratorContext::AliasDecl:
2369 case DeclaratorContext::AliasTemplate:
2370 case DeclaratorContext::Prototype:
2371 case DeclaratorContext::LambdaExprParameter:
2372 case DeclaratorContext::ObjCParameter:
2373 case DeclaratorContext::ObjCResult:
2374 case DeclaratorContext::TemplateParam:
2375 case DeclaratorContext::CXXNew:
2376 case DeclaratorContext::CXXCatch:
2377 case DeclaratorContext::ObjCCatch:
2378 case DeclaratorContext::BlockLiteral:
2379 case DeclaratorContext::LambdaExpr:
2380 case DeclaratorContext::ConversionId:
2381 case DeclaratorContext::TemplateArg:
2382 case DeclaratorContext::TemplateTypeArg:
2383 case DeclaratorContext::TrailingReturn:
2384 case DeclaratorContext::TrailingReturnVar:
2385 case DeclaratorContext::RequiresExpr:
2386 return false;
2387 }
2388 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 2388)
;
2389 }
2390
2391 /// Determine whether this declaration appears in a context where an
2392 /// expression could appear.
2393 bool isExpressionContext() const {
2394 switch (Context) {
2395 case DeclaratorContext::File:
2396 case DeclaratorContext::KNRTypeList:
2397 case DeclaratorContext::Member:
2398
2399 // FIXME: sizeof(...) permits an expression.
2400 case DeclaratorContext::TypeName:
2401
2402 case DeclaratorContext::FunctionalCast:
2403 case DeclaratorContext::AliasDecl:
2404 case DeclaratorContext::AliasTemplate:
2405 case DeclaratorContext::Prototype:
2406 case DeclaratorContext::LambdaExprParameter:
2407 case DeclaratorContext::ObjCParameter:
2408 case DeclaratorContext::ObjCResult:
2409 case DeclaratorContext::TemplateParam:
2410 case DeclaratorContext::CXXNew:
2411 case DeclaratorContext::CXXCatch:
2412 case DeclaratorContext::ObjCCatch:
2413 case DeclaratorContext::BlockLiteral:
2414 case DeclaratorContext::LambdaExpr:
2415 case DeclaratorContext::ConversionId:
2416 case DeclaratorContext::TrailingReturn:
2417 case DeclaratorContext::TrailingReturnVar:
2418 case DeclaratorContext::TemplateTypeArg:
2419 case DeclaratorContext::RequiresExpr:
2420 return false;
2421
2422 case DeclaratorContext::Block:
2423 case DeclaratorContext::ForInit:
2424 case DeclaratorContext::SelectionInit:
2425 case DeclaratorContext::Condition:
2426 case DeclaratorContext::TemplateArg:
2427 return true;
2428 }
2429
2430 llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/Sema/DeclSpec.h"
, 2430)
;
2431 }
2432
2433 /// Return true if a function declarator at this position would be a
2434 /// function declaration.
2435 bool isFunctionDeclaratorAFunctionDeclaration() const {
2436 if (!isFunctionDeclarationContext())
2437 return false;
2438
2439 for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
2440 if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
2441 return false;
2442
2443 return true;
2444 }
2445
2446 /// Determine whether a trailing return type was written (at any
2447 /// level) within this declarator.
2448 bool hasTrailingReturnType() const {
2449 for (const auto &Chunk : type_objects())
2450 if (Chunk.Kind == DeclaratorChunk::Function &&
2451 Chunk.Fun.hasTrailingReturnType())
2452 return true;
2453 return false;
2454 }
2455 /// Get the trailing return type appearing (at any level) within this
2456 /// declarator.
2457 ParsedType getTrailingReturnType() const {
2458 for (const auto &Chunk : type_objects())
2459 if (Chunk.Kind == DeclaratorChunk::Function &&
2460 Chunk.Fun.hasTrailingReturnType())
2461 return Chunk.Fun.getTrailingReturnType();
2462 return ParsedType();
2463 }
2464
2465 /// \brief Sets a trailing requires clause for this declarator.
2466 void setTrailingRequiresClause(Expr *TRC) {
2467 TrailingRequiresClause = TRC;
2468
2469 SetRangeEnd(TRC->getEndLoc());
2470 }
2471
2472 /// \brief Sets a trailing requires clause for this declarator.
2473 Expr *getTrailingRequiresClause() {
2474 return TrailingRequiresClause;
2475 }
2476
2477 /// \brief Determine whether a trailing requires clause was written in this
2478 /// declarator.
2479 bool hasTrailingRequiresClause() const {
2480 return TrailingRequiresClause != nullptr;
2481 }
2482
2483 /// Sets the template parameter lists that preceded the declarator.
2484 void setTemplateParameterLists(ArrayRef<TemplateParameterList *> TPLs) {
2485 TemplateParameterLists = TPLs;
2486 }
2487
2488 /// The template parameter lists that preceded the declarator.
2489 ArrayRef<TemplateParameterList *> getTemplateParameterLists() const {
2490 return TemplateParameterLists;
2491 }
2492
2493 /// Sets the template parameter list generated from the explicit template
2494 /// parameters along with any invented template parameters from
2495 /// placeholder-typed parameters.
2496 void setInventedTemplateParameterList(TemplateParameterList *Invented) {
2497 InventedTemplateParameterList = Invented;
2498 }
2499
2500 /// The template parameter list generated from the explicit template
2501 /// parameters along with any invented template parameters from
2502 /// placeholder-typed parameters, if there were any such parameters.
2503 TemplateParameterList * getInventedTemplateParameterList() const {
2504 return InventedTemplateParameterList;
2505 }
2506
2507 /// takeAttributes - Takes attributes from the given parsed-attributes
2508 /// set and add them to this declarator.
2509 ///
2510 /// These examples both add 3 attributes to "var":
2511 /// short int var __attribute__((aligned(16),common,deprecated));
2512 /// short int x, __attribute__((aligned(16)) var
2513 /// __attribute__((common,deprecated));
2514 ///
2515 /// Also extends the range of the declarator.
2516 void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
2517 Attrs.takeAllFrom(attrs);
2518
2519 if (!lastLoc.isInvalid())
2520 SetRangeEnd(lastLoc);
2521 }
2522
2523 const ParsedAttributes &getAttributes() const { return Attrs; }
2524 ParsedAttributes &getAttributes() { return Attrs; }
2525
2526 /// hasAttributes - do we contain any attributes?
2527 bool hasAttributes() const {
2528 if (!getAttributes().empty() || getDeclSpec().hasAttributes())
2529 return true;
2530 for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
2531 if (!getTypeObject(i).getAttrs().empty())
2532 return true;
2533 return false;
2534 }
2535
2536 /// Return a source range list of C++11 attributes associated
2537 /// with the declarator.
2538 void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
2539 for (const ParsedAttr &AL : Attrs)
2540 if (AL.isCXX11Attribute())
2541 Ranges.push_back(AL.getRange());
2542 }
2543
2544 void setAsmLabel(Expr *E) { AsmLabel = E; }
2545 Expr *getAsmLabel() const { return AsmLabel; }
2546
2547 void setExtension(bool Val = true) { Extension = Val; }
2548 bool getExtension() const { return Extension; }
2549
2550 void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
2551 bool isObjCIvar() const { return ObjCIvar; }
2552
2553 void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
2554 bool isObjCWeakProperty() const { return ObjCWeakProperty; }
2555
2556 void setInvalidType(bool Val = true) { InvalidType = Val; }
2557 bool isInvalidType() const {
2558 return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
2559 }
2560
2561 void setGroupingParens(bool flag) { GroupingParens = flag; }
2562 bool hasGroupingParens() const { return GroupingParens; }
2563
2564 bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
2565 SourceLocation getCommaLoc() const { return CommaLoc; }
2566 void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
2567
2568 bool hasEllipsis() const { return EllipsisLoc.isValid(); }
2569 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
2570 void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
2571
2572 void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
2573 FunctionDefinition = static_cast<unsigned>(Val);
2574 }
2575
2576 bool isFunctionDefinition() const {
2577 return getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration;
2578 }
2579
2580 FunctionDefinitionKind getFunctionDefinitionKind() const {
2581 return (FunctionDefinitionKind)FunctionDefinition;
2582 }
2583
2584 void setHasInitializer(bool Val = true) { HasInitializer = Val; }
2585 bool hasInitializer() const { return HasInitializer; }
2586
2587 /// Returns true if this declares a real member and not a friend.
2588 bool isFirstDeclarationOfMember() {
2589 return getContext() == DeclaratorContext::Member &&
2590 !getDeclSpec().isFriendSpecified();
2591 }
2592
2593 /// Returns true if this declares a static member. This cannot be called on a
2594 /// declarator outside of a MemberContext because we won't know until
2595 /// redeclaration time if the decl is static.
2596 bool isStaticMember();
2597
2598 /// Returns true if this declares a constructor or a destructor.
2599 bool isCtorOrDtor();
2600
2601 void setRedeclaration(bool Val) { Redeclaration = Val; }
2602 bool isRedeclaration() const { return Redeclaration; }
2603};
2604
2605/// This little struct is used to capture information about
2606/// structure field declarators, which is basically just a bitfield size.
2607struct FieldDeclarator {
2608 Declarator D;
2609 Expr *BitfieldSize;
2610 explicit FieldDeclarator(const DeclSpec &DS)
2611 : D(DS, DeclaratorContext::Member), BitfieldSize(nullptr) {}
2612};
2613
2614/// Represents a C++11 virt-specifier-seq.
2615class VirtSpecifiers {
2616public:
2617 enum Specifier {
2618 VS_None = 0,
2619 VS_Override = 1,
2620 VS_Final = 2,
2621 VS_Sealed = 4,
2622 // Represents the __final keyword, which is legal for gcc in pre-C++11 mode.
2623 VS_GNU_Final = 8,
2624 VS_Abstract = 16
2625 };
2626
2627 VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { }
2628
2629 bool SetSpecifier(Specifier VS, SourceLocation Loc,
2630 const char *&PrevSpec);
2631
2632 bool isUnset() const { return Specifiers == 0; }
2633
2634 bool isOverrideSpecified() const { return Specifiers & VS_Override; }
2635 SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
2636
2637 bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); }
2638 bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
2639 SourceLocation getFinalLoc() const { return VS_finalLoc; }
2640 SourceLocation getAbstractLoc() const { return VS_abstractLoc; }
2641
2642 void clear() { Specifiers = 0; }
2643
2644 static const char *getSpecifierName(Specifier VS);
2645
2646 SourceLocation getFirstLocation() const { return FirstLocation; }
2647 SourceLocation getLastLocation() const { return LastLocation; }
2648 Specifier getLastSpecifier() const { return LastSpecifier; }
2649
2650private:
2651 unsigned Specifiers;
2652 Specifier LastSpecifier;
2653
2654 SourceLocation VS_overrideLoc, VS_finalLoc, VS_abstractLoc;
2655 SourceLocation FirstLocation;
2656 SourceLocation LastLocation;
2657};
2658
2659enum class LambdaCaptureInitKind {
2660 NoInit, //!< [a]
2661 CopyInit, //!< [a = b], [a = {b}]
2662 DirectInit, //!< [a(b)]
2663 ListInit //!< [a{b}]
2664};
2665
2666/// Represents a complete lambda introducer.
2667struct LambdaIntroducer {
2668 /// An individual capture in a lambda introducer.
2669 struct LambdaCapture {
2670 LambdaCaptureKind Kind;
2671 SourceLocation Loc;
2672 IdentifierInfo *Id;
2673 SourceLocation EllipsisLoc;
2674 LambdaCaptureInitKind InitKind;
2675 ExprResult Init;
2676 ParsedType InitCaptureType;
2677 SourceRange ExplicitRange;
2678
2679 LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
2680 IdentifierInfo *Id, SourceLocation EllipsisLoc,
2681 LambdaCaptureInitKind InitKind, ExprResult Init,
2682 ParsedType InitCaptureType,
2683 SourceRange ExplicitRange)
2684 : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc),
2685 InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType),
2686 ExplicitRange(ExplicitRange) {}
2687 };
2688
2689 SourceRange Range;
2690 SourceLocation DefaultLoc;
2691 LambdaCaptureDefault Default;
2692 SmallVector<LambdaCapture, 4> Captures;
2693
2694 LambdaIntroducer()
2695 : Default(LCD_None) {}
2696
2697 /// Append a capture in a lambda introducer.
2698 void addCapture(LambdaCaptureKind Kind,
2699 SourceLocation Loc,
2700 IdentifierInfo* Id,
2701 SourceLocation EllipsisLoc,
2702 LambdaCaptureInitKind InitKind,
2703 ExprResult Init,
2704 ParsedType InitCaptureType,
2705 SourceRange ExplicitRange) {
2706 Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
2707 InitCaptureType, ExplicitRange));
2708 }
2709};
2710
2711struct InventedTemplateParameterInfo {
2712 /// The number of parameters in the template parameter list that were
2713 /// explicitly specified by the user, as opposed to being invented by use
2714 /// of an auto parameter.
2715 unsigned NumExplicitTemplateParams = 0;
2716
2717 /// If this is a generic lambda or abbreviated function template, use this
2718 /// as the depth of each 'auto' parameter, during initial AST construction.
2719 unsigned AutoTemplateParameterDepth = 0;
2720
2721 /// Store the list of the template parameters for a generic lambda or an
2722 /// abbreviated function template.
2723 /// If this is a generic lambda or abbreviated function template, this holds
2724 /// the explicit template parameters followed by the auto parameters
2725 /// converted into TemplateTypeParmDecls.
2726 /// It can be used to construct the generic lambda or abbreviated template's
2727 /// template parameter list during initial AST construction.
2728 SmallVector<NamedDecl*, 4> TemplateParams;
2729};
2730
2731} // end namespace clang
2732
2733#endif // LLVM_CLANG_SEMA_DECLSPEC_H

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h

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/DependenceFlags.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/Basic/AddressSpaces.h"
24#include "clang/Basic/AttrKinds.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/ExceptionSpecificationType.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/Visibility.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/PointerLikeTypeTraits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include "llvm/Support/type_traits.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class ExtQuals;
61class QualType;
62class ConceptDecl;
63class TagDecl;
64class TemplateParameterList;
65class Type;
66
67enum {
68 TypeAlignmentInBits = 4,
69 TypeAlignment = 1 << TypeAlignmentInBits
70};
71
72namespace serialization {
73 template <class T> class AbstractTypeReader;
74 template <class T> class AbstractTypeWriter;
75}
76
77} // namespace clang
78
79namespace llvm {
80
81 template <typename T>
82 struct PointerLikeTypeTraits;
83 template<>
84 struct PointerLikeTypeTraits< ::clang::Type*> {
85 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
86
87 static inline ::clang::Type *getFromVoidPointer(void *P) {
88 return static_cast< ::clang::Type*>(P);
89 }
90
91 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
92 };
93
94 template<>
95 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
96 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
97
98 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
99 return static_cast< ::clang::ExtQuals*>(P);
100 }
101
102 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
103 };
104
105} // namespace llvm
106
107namespace clang {
108
109class ASTContext;
110template <typename> class CanQual;
111class CXXRecordDecl;
112class DeclContext;
113class EnumDecl;
114class Expr;
115class ExtQualsTypeCommonBase;
116class FunctionDecl;
117class IdentifierInfo;
118class NamedDecl;
119class ObjCInterfaceDecl;
120class ObjCProtocolDecl;
121class ObjCTypeParamDecl;
122struct PrintingPolicy;
123class RecordDecl;
124class Stmt;
125class TagDecl;
126class TemplateArgument;
127class TemplateArgumentListInfo;
128class TemplateArgumentLoc;
129class TemplateTypeParmDecl;
130class TypedefNameDecl;
131class UnresolvedUsingTypenameDecl;
132
133using CanQualType = CanQual<Type>;
134
135// Provide forward declarations for all of the *Type classes.
136#define TYPE(Class, Base) class Class##Type;
137#include "clang/AST/TypeNodes.inc"
138
139/// The collection of all-type qualifiers we support.
140/// Clang supports five independent qualifiers:
141/// * C99: const, volatile, and restrict
142/// * MS: __unaligned
143/// * Embedded C (TR18037): address spaces
144/// * Objective C: the GC attributes (none, weak, or strong)
145class Qualifiers {
146public:
147 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
148 Const = 0x1,
149 Restrict = 0x2,
150 Volatile = 0x4,
151 CVRMask = Const | Volatile | Restrict
152 };
153
154 enum GC {
155 GCNone = 0,
156 Weak,
157 Strong
158 };
159
160 enum ObjCLifetime {
161 /// There is no lifetime qualification on this type.
162 OCL_None,
163
164 /// This object can be modified without requiring retains or
165 /// releases.
166 OCL_ExplicitNone,
167
168 /// Assigning into this object requires the old value to be
169 /// released and the new value to be retained. The timing of the
170 /// release of the old value is inexact: it may be moved to
171 /// immediately after the last known point where the value is
172 /// live.
173 OCL_Strong,
174
175 /// Reading or writing from this object requires a barrier call.
176 OCL_Weak,
177
178 /// Assigning into this object requires a lifetime extension.
179 OCL_Autoreleasing
180 };
181
182 enum {
183 /// The maximum supported address space number.
184 /// 23 bits should be enough for anyone.
185 MaxAddressSpace = 0x7fffffu,
186
187 /// The width of the "fast" qualifier mask.
188 FastWidth = 3,
189
190 /// The fast qualifier mask.
191 FastMask = (1 << FastWidth) - 1
192 };
193
194 /// Returns the common set of qualifiers while removing them from
195 /// the given sets.
196 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
197 // If both are only CVR-qualified, bit operations are sufficient.
198 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
199 Qualifiers Q;
200 Q.Mask = L.Mask & R.Mask;
201 L.Mask &= ~Q.Mask;
202 R.Mask &= ~Q.Mask;
203 return Q;
204 }
205
206 Qualifiers Q;
207 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
208 Q.addCVRQualifiers(CommonCRV);
209 L.removeCVRQualifiers(CommonCRV);
210 R.removeCVRQualifiers(CommonCRV);
211
212 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
213 Q.setObjCGCAttr(L.getObjCGCAttr());
214 L.removeObjCGCAttr();
215 R.removeObjCGCAttr();
216 }
217
218 if (L.getObjCLifetime() == R.getObjCLifetime()) {
219 Q.setObjCLifetime(L.getObjCLifetime());
220 L.removeObjCLifetime();
221 R.removeObjCLifetime();
222 }
223
224 if (L.getAddressSpace() == R.getAddressSpace()) {
225 Q.setAddressSpace(L.getAddressSpace());
226 L.removeAddressSpace();
227 R.removeAddressSpace();
228 }
229 return Q;
230 }
231
232 static Qualifiers fromFastMask(unsigned Mask) {
233 Qualifiers Qs;
234 Qs.addFastQualifiers(Mask);
235 return Qs;
236 }
237
238 static Qualifiers fromCVRMask(unsigned CVR) {
239 Qualifiers Qs;
240 Qs.addCVRQualifiers(CVR);
241 return Qs;
242 }
243
244 static Qualifiers fromCVRUMask(unsigned CVRU) {
245 Qualifiers Qs;
246 Qs.addCVRUQualifiers(CVRU);
247 return Qs;
248 }
249
250 // Deserialize qualifiers from an opaque representation.
251 static Qualifiers fromOpaqueValue(unsigned opaque) {
252 Qualifiers Qs;
253 Qs.Mask = opaque;
254 return Qs;
255 }
256
257 // Serialize these qualifiers into an opaque representation.
258 unsigned getAsOpaqueValue() const {
259 return Mask;
260 }
261
262 bool hasConst() const { return Mask & Const; }
263 bool hasOnlyConst() const { return Mask == Const; }
264 void removeConst() { Mask &= ~Const; }
265 void addConst() { Mask |= Const; }
266
267 bool hasVolatile() const { return Mask & Volatile; }
268 bool hasOnlyVolatile() const { return Mask == Volatile; }
269 void removeVolatile() { Mask &= ~Volatile; }
270 void addVolatile() { Mask |= Volatile; }
271
272 bool hasRestrict() const { return Mask & Restrict; }
273 bool hasOnlyRestrict() const { return Mask == Restrict; }
274 void removeRestrict() { Mask &= ~Restrict; }
275 void addRestrict() { Mask |= Restrict; }
276
277 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
278 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
279 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
280
281 void setCVRQualifiers(unsigned mask) {
282 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 282, __extension__ __PRETTY_FUNCTION__))
;
283 Mask = (Mask & ~CVRMask) | mask;
284 }
285 void removeCVRQualifiers(unsigned mask) {
286 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 286, __extension__ __PRETTY_FUNCTION__))
;
287 Mask &= ~mask;
288 }
289 void removeCVRQualifiers() {
290 removeCVRQualifiers(CVRMask);
291 }
292 void addCVRQualifiers(unsigned mask) {
293 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 293, __extension__ __PRETTY_FUNCTION__))
;
294 Mask |= mask;
295 }
296 void addCVRUQualifiers(unsigned mask) {
297 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")(static_cast <bool> (!(mask & ~CVRMask & ~UMask
) && "bitmask contains non-CVRU bits") ? void (0) : __assert_fail
("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 297, __extension__ __PRETTY_FUNCTION__))
;
298 Mask |= mask;
299 }
300
301 bool hasUnaligned() const { return Mask & UMask; }
302 void setUnaligned(bool flag) {
303 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
304 }
305 void removeUnaligned() { Mask &= ~UMask; }
306 void addUnaligned() { Mask |= UMask; }
307
308 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
309 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
310 void setObjCGCAttr(GC type) {
311 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
312 }
313 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
314 void addObjCGCAttr(GC type) {
315 assert(type)(static_cast <bool> (type) ? void (0) : __assert_fail (
"type", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 315, __extension__ __PRETTY_FUNCTION__))
;
316 setObjCGCAttr(type);
317 }
318 Qualifiers withoutObjCGCAttr() const {
319 Qualifiers qs = *this;
320 qs.removeObjCGCAttr();
321 return qs;
322 }
323 Qualifiers withoutObjCLifetime() const {
324 Qualifiers qs = *this;
325 qs.removeObjCLifetime();
326 return qs;
327 }
328 Qualifiers withoutAddressSpace() const {
329 Qualifiers qs = *this;
330 qs.removeAddressSpace();
331 return qs;
332 }
333
334 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
335 ObjCLifetime getObjCLifetime() const {
336 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
337 }
338 void setObjCLifetime(ObjCLifetime type) {
339 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
340 }
341 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
342 void addObjCLifetime(ObjCLifetime type) {
343 assert(type)(static_cast <bool> (type) ? void (0) : __assert_fail (
"type", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 343, __extension__ __PRETTY_FUNCTION__))
;
344 assert(!hasObjCLifetime())(static_cast <bool> (!hasObjCLifetime()) ? void (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 344, __extension__ __PRETTY_FUNCTION__))
;
345 Mask |= (type << LifetimeShift);
346 }
347
348 /// True if the lifetime is neither None or ExplicitNone.
349 bool hasNonTrivialObjCLifetime() const {
350 ObjCLifetime lifetime = getObjCLifetime();
351 return (lifetime > OCL_ExplicitNone);
352 }
353
354 /// True if the lifetime is either strong or weak.
355 bool hasStrongOrWeakObjCLifetime() const {
356 ObjCLifetime lifetime = getObjCLifetime();
357 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
358 }
359
360 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
361 LangAS getAddressSpace() const {
362 return static_cast<LangAS>(Mask >> AddressSpaceShift);
363 }
364 bool hasTargetSpecificAddressSpace() const {
365 return isTargetAddressSpace(getAddressSpace());
366 }
367 /// Get the address space attribute value to be printed by diagnostics.
368 unsigned getAddressSpaceAttributePrintValue() const {
369 auto Addr = getAddressSpace();
370 // This function is not supposed to be used with language specific
371 // address spaces. If that happens, the diagnostic message should consider
372 // printing the QualType instead of the address space value.
373 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())(static_cast <bool> (Addr == LangAS::Default || hasTargetSpecificAddressSpace
()) ? void (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 373, __extension__ __PRETTY_FUNCTION__))
;
374 if (Addr != LangAS::Default)
375 return toTargetAddressSpace(Addr);
376 // TODO: The diagnostic messages where Addr may be 0 should be fixed
377 // since it cannot differentiate the situation where 0 denotes the default
378 // address space or user specified __attribute__((address_space(0))).
379 return 0;
380 }
381 void setAddressSpace(LangAS space) {
382 assert((unsigned)space <= MaxAddressSpace)(static_cast <bool> ((unsigned)space <= MaxAddressSpace
) ? void (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 382, __extension__ __PRETTY_FUNCTION__))
;
383 Mask = (Mask & ~AddressSpaceMask)
384 | (((uint32_t) space) << AddressSpaceShift);
385 }
386 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
387 void addAddressSpace(LangAS space) {
388 assert(space != LangAS::Default)(static_cast <bool> (space != LangAS::Default) ? void (
0) : __assert_fail ("space != LangAS::Default", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 388, __extension__ __PRETTY_FUNCTION__))
;
389 setAddressSpace(space);
390 }
391
392 // Fast qualifiers are those that can be allocated directly
393 // on a QualType object.
394 bool hasFastQualifiers() const { return getFastQualifiers(); }
395 unsigned getFastQualifiers() const { return Mask & FastMask; }
396 void setFastQualifiers(unsigned mask) {
397 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) &&
"bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail
("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 397, __extension__ __PRETTY_FUNCTION__))
;
398 Mask = (Mask & ~FastMask) | mask;
399 }
400 void removeFastQualifiers(unsigned mask) {
401 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) &&
"bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail
("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 401, __extension__ __PRETTY_FUNCTION__))
;
402 Mask &= ~mask;
403 }
404 void removeFastQualifiers() {
405 removeFastQualifiers(FastMask);
406 }
407 void addFastQualifiers(unsigned mask) {
408 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) &&
"bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail
("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 408, __extension__ __PRETTY_FUNCTION__))
;
409 Mask |= mask;
410 }
411
412 /// Return true if the set contains any qualifiers which require an ExtQuals
413 /// node to be allocated.
414 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
415 Qualifiers getNonFastQualifiers() const {
416 Qualifiers Quals = *this;
417 Quals.setFastQualifiers(0);
418 return Quals;
419 }
420
421 /// Return true if the set contains any qualifiers.
422 bool hasQualifiers() const { return Mask; }
423 bool empty() const { return !Mask; }
424
425 /// Add the qualifiers from the given set to this set.
426 void addQualifiers(Qualifiers Q) {
427 // If the other set doesn't have any non-boolean qualifiers, just
428 // bit-or it in.
429 if (!(Q.Mask & ~CVRMask))
430 Mask |= Q.Mask;
431 else {
432 Mask |= (Q.Mask & CVRMask);
433 if (Q.hasAddressSpace())
434 addAddressSpace(Q.getAddressSpace());
435 if (Q.hasObjCGCAttr())
436 addObjCGCAttr(Q.getObjCGCAttr());
437 if (Q.hasObjCLifetime())
438 addObjCLifetime(Q.getObjCLifetime());
439 }
440 }
441
442 /// Remove the qualifiers from the given set from this set.
443 void removeQualifiers(Qualifiers Q) {
444 // If the other set doesn't have any non-boolean qualifiers, just
445 // bit-and the inverse in.
446 if (!(Q.Mask & ~CVRMask))
447 Mask &= ~Q.Mask;
448 else {
449 Mask &= ~(Q.Mask & CVRMask);
450 if (getObjCGCAttr() == Q.getObjCGCAttr())
451 removeObjCGCAttr();
452 if (getObjCLifetime() == Q.getObjCLifetime())
453 removeObjCLifetime();
454 if (getAddressSpace() == Q.getAddressSpace())
455 removeAddressSpace();
456 }
457 }
458
459 /// Add the qualifiers from the given set to this set, given that
460 /// they don't conflict.
461 void addConsistentQualifiers(Qualifiers qs) {
462 assert(getAddressSpace() == qs.getAddressSpace() ||(static_cast <bool> (getAddressSpace() == qs.getAddressSpace
() || !hasAddressSpace() || !qs.hasAddressSpace()) ? void (0)
: __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 463, __extension__ __PRETTY_FUNCTION__))
463 !hasAddressSpace() || !qs.hasAddressSpace())(static_cast <bool> (getAddressSpace() == qs.getAddressSpace
() || !hasAddressSpace() || !qs.hasAddressSpace()) ? void (0)
: __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 463, __extension__ __PRETTY_FUNCTION__))
;
464 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||(static_cast <bool> (getObjCGCAttr() == qs.getObjCGCAttr
() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? void (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 465, __extension__ __PRETTY_FUNCTION__))
465 !hasObjCGCAttr() || !qs.hasObjCGCAttr())(static_cast <bool> (getObjCGCAttr() == qs.getObjCGCAttr
() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? void (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 465, __extension__ __PRETTY_FUNCTION__))
;
466 assert(getObjCLifetime() == qs.getObjCLifetime() ||(static_cast <bool> (getObjCLifetime() == qs.getObjCLifetime
() || !hasObjCLifetime() || !qs.hasObjCLifetime()) ? void (0)
: __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 467, __extension__ __PRETTY_FUNCTION__))
467 !hasObjCLifetime() || !qs.hasObjCLifetime())(static_cast <bool> (getObjCLifetime() == qs.getObjCLifetime
() || !hasObjCLifetime() || !qs.hasObjCLifetime()) ? void (0)
: __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 467, __extension__ __PRETTY_FUNCTION__))
;
468 Mask |= qs.Mask;
469 }
470
471 /// Returns true if address space A is equal to or a superset of B.
472 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
473 /// overlapping address spaces.
474 /// CL1.1 or CL1.2:
475 /// every address space is a superset of itself.
476 /// CL2.0 adds:
477 /// __generic is a superset of any address space except for __constant.
478 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
479 // Address spaces must match exactly.
480 return A == B ||
481 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
482 // for __constant can be used as __generic.
483 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
484 // We also define global_device and global_host address spaces,
485 // to distinguish global pointers allocated on host from pointers
486 // allocated on device, which are a subset of __global.
487 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
488 B == LangAS::opencl_global_host)) ||
489 (A == LangAS::sycl_global && (B == LangAS::sycl_global_device ||
490 B == LangAS::sycl_global_host)) ||
491 // Consider pointer size address spaces to be equivalent to default.
492 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
493 (isPtrSizeAddressSpace(B) || B == LangAS::Default)) ||
494 // Default is a superset of SYCL address spaces.
495 (A == LangAS::Default &&
496 (B == LangAS::sycl_private || B == LangAS::sycl_local ||
497 B == LangAS::sycl_global || B == LangAS::sycl_global_device ||
498 B == LangAS::sycl_global_host));
499 }
500
501 /// Returns true if the address space in these qualifiers is equal to or
502 /// a superset of the address space in the argument qualifiers.
503 bool isAddressSpaceSupersetOf(Qualifiers other) const {
504 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
505 }
506
507 /// Determines if these qualifiers compatibly include another set.
508 /// Generally this answers the question of whether an object with the other
509 /// qualifiers can be safely used as an object with these qualifiers.
510 bool compatiblyIncludes(Qualifiers other) const {
511 return isAddressSpaceSupersetOf(other) &&
512 // ObjC GC qualifiers can match, be added, or be removed, but can't
513 // be changed.
514 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
515 !other.hasObjCGCAttr()) &&
516 // ObjC lifetime qualifiers must match exactly.
517 getObjCLifetime() == other.getObjCLifetime() &&
518 // CVR qualifiers may subset.
519 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
520 // U qualifier may superset.
521 (!other.hasUnaligned() || hasUnaligned());
522 }
523
524 /// Determines if these qualifiers compatibly include another set of
525 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
526 ///
527 /// One set of Objective-C lifetime qualifiers compatibly includes the other
528 /// if the lifetime qualifiers match, or if both are non-__weak and the
529 /// including set also contains the 'const' qualifier, or both are non-__weak
530 /// and one is None (which can only happen in non-ARC modes).
531 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
532 if (getObjCLifetime() == other.getObjCLifetime())
533 return true;
534
535 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
536 return false;
537
538 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
539 return true;
540
541 return hasConst();
542 }
543
544 /// Determine whether this set of qualifiers is a strict superset of
545 /// another set of qualifiers, not considering qualifier compatibility.
546 bool isStrictSupersetOf(Qualifiers Other) const;
547
548 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
549 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
550
551 explicit operator bool() const { return hasQualifiers(); }
552
553 Qualifiers &operator+=(Qualifiers R) {
554 addQualifiers(R);
555 return *this;
556 }
557
558 // Union two qualifier sets. If an enumerated qualifier appears
559 // in both sets, use the one from the right.
560 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
561 L += R;
562 return L;
563 }
564
565 Qualifiers &operator-=(Qualifiers R) {
566 removeQualifiers(R);
567 return *this;
568 }
569
570 /// Compute the difference between two qualifier sets.
571 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
572 L -= R;
573 return L;
574 }
575
576 std::string getAsString() const;
577 std::string getAsString(const PrintingPolicy &Policy) const;
578
579 static std::string getAddrSpaceAsString(LangAS AS);
580
581 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
582 void print(raw_ostream &OS, const PrintingPolicy &Policy,
583 bool appendSpaceIfNonEmpty = false) const;
584
585 void Profile(llvm::FoldingSetNodeID &ID) const {
586 ID.AddInteger(Mask);
587 }
588
589private:
590 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
591 // |C R V|U|GCAttr|Lifetime|AddressSpace|
592 uint32_t Mask = 0;
593
594 static const uint32_t UMask = 0x8;
595 static const uint32_t UShift = 3;
596 static const uint32_t GCAttrMask = 0x30;
597 static const uint32_t GCAttrShift = 4;
598 static const uint32_t LifetimeMask = 0x1C0;
599 static const uint32_t LifetimeShift = 6;
600 static const uint32_t AddressSpaceMask =
601 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
602 static const uint32_t AddressSpaceShift = 9;
603};
604
605/// A std::pair-like structure for storing a qualified type split
606/// into its local qualifiers and its locally-unqualified type.
607struct SplitQualType {
608 /// The locally-unqualified type.
609 const Type *Ty = nullptr;
610
611 /// The local qualifiers.
612 Qualifiers Quals;
613
614 SplitQualType() = default;
615 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
616
617 SplitQualType getSingleStepDesugaredType() const; // end of this file
618
619 // Make std::tie work.
620 std::pair<const Type *,Qualifiers> asPair() const {
621 return std::pair<const Type *, Qualifiers>(Ty, Quals);
622 }
623
624 friend bool operator==(SplitQualType a, SplitQualType b) {
625 return a.Ty == b.Ty && a.Quals == b.Quals;
626 }
627 friend bool operator!=(SplitQualType a, SplitQualType b) {
628 return a.Ty != b.Ty || a.Quals != b.Quals;
629 }
630};
631
632/// The kind of type we are substituting Objective-C type arguments into.
633///
634/// The kind of substitution affects the replacement of type parameters when
635/// no concrete type information is provided, e.g., when dealing with an
636/// unspecialized type.
637enum class ObjCSubstitutionContext {
638 /// An ordinary type.
639 Ordinary,
640
641 /// The result type of a method or function.
642 Result,
643
644 /// The parameter type of a method or function.
645 Parameter,
646
647 /// The type of a property.
648 Property,
649
650 /// The superclass of a type.
651 Superclass,
652};
653
654/// A (possibly-)qualified type.
655///
656/// For efficiency, we don't store CV-qualified types as nodes on their
657/// own: instead each reference to a type stores the qualifiers. This
658/// greatly reduces the number of nodes we need to allocate for types (for
659/// example we only need one for 'int', 'const int', 'volatile int',
660/// 'const volatile int', etc).
661///
662/// As an added efficiency bonus, instead of making this a pair, we
663/// just store the two bits we care about in the low bits of the
664/// pointer. To handle the packing/unpacking, we make QualType be a
665/// simple wrapper class that acts like a smart pointer. A third bit
666/// indicates whether there are extended qualifiers present, in which
667/// case the pointer points to a special structure.
668class QualType {
669 friend class QualifierCollector;
670
671 // Thankfully, these are efficiently composable.
672 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
673 Qualifiers::FastWidth> Value;
674
675 const ExtQuals *getExtQualsUnsafe() const {
676 return Value.getPointer().get<const ExtQuals*>();
677 }
678
679 const Type *getTypePtrUnsafe() const {
680 return Value.getPointer().get<const Type*>();
681 }
682
683 const ExtQualsTypeCommonBase *getCommonPtr() const {
684 assert(!isNull() && "Cannot retrieve a NULL type pointer")(static_cast <bool> (!isNull() && "Cannot retrieve a NULL type pointer"
) ? void (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 684, __extension__ __PRETTY_FUNCTION__))
;
685 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
686 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
687 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
688 }
689
690public:
691 QualType() = default;
692 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
693 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
694
695 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
696 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
697
698 /// Retrieves a pointer to the underlying (unqualified) type.
699 ///
700 /// This function requires that the type not be NULL. If the type might be
701 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
702 const Type *getTypePtr() const;
703
704 const Type *getTypePtrOrNull() const;
705
706 /// Retrieves a pointer to the name of the base type.
707 const IdentifierInfo *getBaseTypeIdentifier() const;
708
709 /// Divides a QualType into its unqualified type and a set of local
710 /// qualifiers.
711 SplitQualType split() const;
712
713 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
714
715 static QualType getFromOpaquePtr(const void *Ptr) {
716 QualType T;
717 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
718 return T;
719 }
720
721 const Type &operator*() const {
722 return *getTypePtr();
723 }
724
725 const Type *operator->() const {
726 return getTypePtr();
727 }
728
729 bool isCanonical() const;
730 bool isCanonicalAsParam() const;
731
732 /// Return true if this QualType doesn't point to a type yet.
733 bool isNull() const {
734 return Value.getPointer().isNull();
38
Calling 'PointerUnion::isNull'
41
Returning from 'PointerUnion::isNull'
42
Returning zero, which participates in a condition later
49
Calling 'PointerUnion::isNull'
52
Returning from 'PointerUnion::isNull'
53
Returning zero, which participates in a condition later
57
Calling 'PointerUnion::isNull'
60
Returning from 'PointerUnion::isNull'
61
Returning the value 1, which participates in a condition later
735 }
736
737 /// Determine whether this particular QualType instance has the
738 /// "const" qualifier set, without looking through typedefs that may have
739 /// added "const" at a different level.
740 bool isLocalConstQualified() const {
741 return (getLocalFastQualifiers() & Qualifiers::Const);
742 }
743
744 /// Determine whether this type is const-qualified.
745 bool isConstQualified() const;
746
747 /// Determine whether this particular QualType instance has the
748 /// "restrict" qualifier set, without looking through typedefs that may have
749 /// added "restrict" at a different level.
750 bool isLocalRestrictQualified() const {
751 return (getLocalFastQualifiers() & Qualifiers::Restrict);
752 }
753
754 /// Determine whether this type is restrict-qualified.
755 bool isRestrictQualified() const;
756
757 /// Determine whether this particular QualType instance has the
758 /// "volatile" qualifier set, without looking through typedefs that may have
759 /// added "volatile" at a different level.
760 bool isLocalVolatileQualified() const {
761 return (getLocalFastQualifiers() & Qualifiers::Volatile);
762 }
763
764 /// Determine whether this type is volatile-qualified.
765 bool isVolatileQualified() const;
766
767 /// Determine whether this particular QualType instance has any
768 /// qualifiers, without looking through any typedefs that might add
769 /// qualifiers at a different level.
770 bool hasLocalQualifiers() const {
771 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
772 }
773
774 /// Determine whether this type has any qualifiers.
775 bool hasQualifiers() const;
776
777 /// Determine whether this particular QualType instance has any
778 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
779 /// instance.
780 bool hasLocalNonFastQualifiers() const {
781 return Value.getPointer().is<const ExtQuals*>();
782 }
783
784 /// Retrieve the set of qualifiers local to this particular QualType
785 /// instance, not including any qualifiers acquired through typedefs or
786 /// other sugar.
787 Qualifiers getLocalQualifiers() const;
788
789 /// Retrieve the set of qualifiers applied to this type.
790 Qualifiers getQualifiers() const;
791
792 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
793 /// local to this particular QualType instance, not including any qualifiers
794 /// acquired through typedefs or other sugar.
795 unsigned getLocalCVRQualifiers() const {
796 return getLocalFastQualifiers();
797 }
798
799 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
800 /// applied to this type.
801 unsigned getCVRQualifiers() const;
802
803 bool isConstant(const ASTContext& Ctx) const {
804 return QualType::isConstant(*this, Ctx);
805 }
806
807 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
808 bool isPODType(const ASTContext &Context) const;
809
810 /// Return true if this is a POD type according to the rules of the C++98
811 /// standard, regardless of the current compilation's language.
812 bool isCXX98PODType(const ASTContext &Context) const;
813
814 /// Return true if this is a POD type according to the more relaxed rules
815 /// of the C++11 standard, regardless of the current compilation's language.
816 /// (C++0x [basic.types]p9). Note that, unlike
817 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
818 bool isCXX11PODType(const ASTContext &Context) const;
819
820 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
821 bool isTrivialType(const ASTContext &Context) const;
822
823 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
824 bool isTriviallyCopyableType(const ASTContext &Context) const;
825
826
827 /// Returns true if it is a class and it might be dynamic.
828 bool mayBeDynamicClass() const;
829
830 /// Returns true if it is not a class or if the class might not be dynamic.
831 bool mayBeNotDynamicClass() const;
832
833 // Don't promise in the API that anything besides 'const' can be
834 // easily added.
835
836 /// Add the `const` type qualifier to this QualType.
837 void addConst() {
838 addFastQualifiers(Qualifiers::Const);
839 }
840 QualType withConst() const {
841 return withFastQualifiers(Qualifiers::Const);
842 }
843
844 /// Add the `volatile` type qualifier to this QualType.
845 void addVolatile() {
846 addFastQualifiers(Qualifiers::Volatile);
847 }
848 QualType withVolatile() const {
849 return withFastQualifiers(Qualifiers::Volatile);
850 }
851
852 /// Add the `restrict` qualifier to this QualType.
853 void addRestrict() {
854 addFastQualifiers(Qualifiers::Restrict);
855 }
856 QualType withRestrict() const {
857 return withFastQualifiers(Qualifiers::Restrict);
858 }
859
860 QualType withCVRQualifiers(unsigned CVR) const {
861 return withFastQualifiers(CVR);
862 }
863
864 void addFastQualifiers(unsigned TQs) {
865 assert(!(TQs & ~Qualifiers::FastMask)(static_cast <bool> (!(TQs & ~Qualifiers::FastMask)
&& "non-fast qualifier bits set in mask!") ? void (0
) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 866, __extension__ __PRETTY_FUNCTION__))
866 && "non-fast qualifier bits set in mask!")(static_cast <bool> (!(TQs & ~Qualifiers::FastMask)
&& "non-fast qualifier bits set in mask!") ? void (0
) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 866, __extension__ __PRETTY_FUNCTION__))
;
867 Value.setInt(Value.getInt() | TQs);
868 }
869
870 void removeLocalConst();
871 void removeLocalVolatile();
872 void removeLocalRestrict();
873 void removeLocalCVRQualifiers(unsigned Mask);
874
875 void removeLocalFastQualifiers() { Value.setInt(0); }
876 void removeLocalFastQualifiers(unsigned Mask) {
877 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")(static_cast <bool> (!(Mask & ~Qualifiers::FastMask
) && "mask has non-fast qualifiers") ? void (0) : __assert_fail
("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 877, __extension__ __PRETTY_FUNCTION__))
;
878 Value.setInt(Value.getInt() & ~Mask);
879 }
880
881 // Creates a type with the given qualifiers in addition to any
882 // qualifiers already on this type.
883 QualType withFastQualifiers(unsigned TQs) const {
884 QualType T = *this;
885 T.addFastQualifiers(TQs);
886 return T;
887 }
888
889 // Creates a type with exactly the given fast qualifiers, removing
890 // any existing fast qualifiers.
891 QualType withExactLocalFastQualifiers(unsigned TQs) const {
892 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
893 }
894
895 // Removes fast qualifiers, but leaves any extended qualifiers in place.
896 QualType withoutLocalFastQualifiers() const {
897 QualType T = *this;
898 T.removeLocalFastQualifiers();
899 return T;
900 }
901
902 QualType getCanonicalType() const;
903
904 /// Return this type with all of the instance-specific qualifiers
905 /// removed, but without removing any qualifiers that may have been applied
906 /// through typedefs.
907 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
908
909 /// Retrieve the unqualified variant of the given type,
910 /// removing as little sugar as possible.
911 ///
912 /// This routine looks through various kinds of sugar to find the
913 /// least-desugared type that is unqualified. For example, given:
914 ///
915 /// \code
916 /// typedef int Integer;
917 /// typedef const Integer CInteger;
918 /// typedef CInteger DifferenceType;
919 /// \endcode
920 ///
921 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
922 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
923 ///
924 /// The resulting type might still be qualified if it's sugar for an array
925 /// type. To strip qualifiers even from within a sugared array type, use
926 /// ASTContext::getUnqualifiedArrayType.
927 inline QualType getUnqualifiedType() const;
928
929 /// Retrieve the unqualified variant of the given type, removing as little
930 /// sugar as possible.
931 ///
932 /// Like getUnqualifiedType(), but also returns the set of
933 /// qualifiers that were built up.
934 ///
935 /// The resulting type might still be qualified if it's sugar for an array
936 /// type. To strip qualifiers even from within a sugared array type, use
937 /// ASTContext::getUnqualifiedArrayType.
938 inline SplitQualType getSplitUnqualifiedType() const;
939
940 /// Determine whether this type is more qualified than the other
941 /// given type, requiring exact equality for non-CVR qualifiers.
942 bool isMoreQualifiedThan(QualType Other) const;
943
944 /// Determine whether this type is at least as qualified as the other
945 /// given type, requiring exact equality for non-CVR qualifiers.
946 bool isAtLeastAsQualifiedAs(QualType Other) const;
947
948 QualType getNonReferenceType() const;
949
950 /// Determine the type of a (typically non-lvalue) expression with the
951 /// specified result type.
952 ///
953 /// This routine should be used for expressions for which the return type is
954 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
955 /// an lvalue. It removes a top-level reference (since there are no
956 /// expressions of reference type) and deletes top-level cvr-qualifiers
957 /// from non-class types (in C++) or all types (in C).
958 QualType getNonLValueExprType(const ASTContext &Context) const;
959
960 /// Remove an outer pack expansion type (if any) from this type. Used as part
961 /// of converting the type of a declaration to the type of an expression that
962 /// references that expression. It's meaningless for an expression to have a
963 /// pack expansion type.
964 QualType getNonPackExpansionType() const;
965
966 /// Return the specified type with any "sugar" removed from
967 /// the type. This takes off typedefs, typeof's etc. If the outer level of
968 /// the type is already concrete, it returns it unmodified. This is similar
969 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
970 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
971 /// concrete.
972 ///
973 /// Qualifiers are left in place.
974 QualType getDesugaredType(const ASTContext &Context) const {
975 return getDesugaredType(*this, Context);
976 }
977
978 SplitQualType getSplitDesugaredType() const {
979 return getSplitDesugaredType(*this);
980 }
981
982 /// Return the specified type with one level of "sugar" removed from
983 /// the type.
984 ///
985 /// This routine takes off the first typedef, typeof, etc. If the outer level
986 /// of the type is already concrete, it returns it unmodified.
987 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
988 return getSingleStepDesugaredTypeImpl(*this, Context);
989 }
990
991 /// Returns the specified type after dropping any
992 /// outer-level parentheses.
993 QualType IgnoreParens() const {
994 if (isa<ParenType>(*this))
995 return QualType::IgnoreParens(*this);
996 return *this;
997 }
998
999 /// Indicate whether the specified types and qualifiers are identical.
1000 friend bool operator==(const QualType &LHS, const QualType &RHS) {
1001 return LHS.Value == RHS.Value;
1002 }
1003 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
1004 return LHS.Value != RHS.Value;
1005 }
1006 friend bool operator<(const QualType &LHS, const QualType &RHS) {
1007 return LHS.Value < RHS.Value;
1008 }
1009
1010 static std::string getAsString(SplitQualType split,
1011 const PrintingPolicy &Policy) {
1012 return getAsString(split.Ty, split.Quals, Policy);
1013 }
1014 static std::string getAsString(const Type *ty, Qualifiers qs,
1015 const PrintingPolicy &Policy);
1016
1017 std::string getAsString() const;
1018 std::string getAsString(const PrintingPolicy &Policy) const;
1019
1020 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1021 const Twine &PlaceHolder = Twine(),
1022 unsigned Indentation = 0) const;
1023
1024 static void print(SplitQualType split, raw_ostream &OS,
1025 const PrintingPolicy &policy, const Twine &PlaceHolder,
1026 unsigned Indentation = 0) {
1027 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1028 }
1029
1030 static void print(const Type *ty, Qualifiers qs,
1031 raw_ostream &OS, const PrintingPolicy &policy,
1032 const Twine &PlaceHolder,
1033 unsigned Indentation = 0);
1034
1035 void getAsStringInternal(std::string &Str,
1036 const PrintingPolicy &Policy) const;
1037
1038 static void getAsStringInternal(SplitQualType split, std::string &out,
1039 const PrintingPolicy &policy) {
1040 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1041 }
1042
1043 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1044 std::string &out,
1045 const PrintingPolicy &policy);
1046
1047 class StreamedQualTypeHelper {
1048 const QualType &T;
1049 const PrintingPolicy &Policy;
1050 const Twine &PlaceHolder;
1051 unsigned Indentation;
1052
1053 public:
1054 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1055 const Twine &PlaceHolder, unsigned Indentation)
1056 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1057 Indentation(Indentation) {}
1058
1059 friend raw_ostream &operator<<(raw_ostream &OS,
1060 const StreamedQualTypeHelper &SQT) {
1061 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1062 return OS;
1063 }
1064 };
1065
1066 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1067 const Twine &PlaceHolder = Twine(),
1068 unsigned Indentation = 0) const {
1069 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1070 }
1071
1072 void dump(const char *s) const;
1073 void dump() const;
1074 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1075
1076 void Profile(llvm::FoldingSetNodeID &ID) const {
1077 ID.AddPointer(getAsOpaquePtr());
1078 }
1079
1080 /// Check if this type has any address space qualifier.
1081 inline bool hasAddressSpace() const;
1082
1083 /// Return the address space of this type.
1084 inline LangAS getAddressSpace() const;
1085
1086 /// Returns true if address space qualifiers overlap with T address space
1087 /// qualifiers.
1088 /// OpenCL C defines conversion rules for pointers to different address spaces
1089 /// and notion of overlapping address spaces.
1090 /// CL1.1 or CL1.2:
1091 /// address spaces overlap iff they are they same.
1092 /// OpenCL C v2.0 s6.5.5 adds:
1093 /// __generic overlaps with any address space except for __constant.
1094 bool isAddressSpaceOverlapping(QualType T) const {
1095 Qualifiers Q = getQualifiers();
1096 Qualifiers TQ = T.getQualifiers();
1097 // Address spaces overlap if at least one of them is a superset of another
1098 return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
1099 }
1100
1101 /// Returns gc attribute of this type.
1102 inline Qualifiers::GC getObjCGCAttr() const;
1103
1104 /// true when Type is objc's weak.
1105 bool isObjCGCWeak() const {
1106 return getObjCGCAttr() == Qualifiers::Weak;
1107 }
1108
1109 /// true when Type is objc's strong.
1110 bool isObjCGCStrong() const {
1111 return getObjCGCAttr() == Qualifiers::Strong;
1112 }
1113
1114 /// Returns lifetime attribute of this type.
1115 Qualifiers::ObjCLifetime getObjCLifetime() const {
1116 return getQualifiers().getObjCLifetime();
1117 }
1118
1119 bool hasNonTrivialObjCLifetime() const {
1120 return getQualifiers().hasNonTrivialObjCLifetime();
1121 }
1122
1123 bool hasStrongOrWeakObjCLifetime() const {
1124 return getQualifiers().hasStrongOrWeakObjCLifetime();
1125 }
1126
1127 // true when Type is objc's weak and weak is enabled but ARC isn't.
1128 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1129
1130 enum PrimitiveDefaultInitializeKind {
1131 /// The type does not fall into any of the following categories. Note that
1132 /// this case is zero-valued so that values of this enum can be used as a
1133 /// boolean condition for non-triviality.
1134 PDIK_Trivial,
1135
1136 /// The type is an Objective-C retainable pointer type that is qualified
1137 /// with the ARC __strong qualifier.
1138 PDIK_ARCStrong,
1139
1140 /// The type is an Objective-C retainable pointer type that is qualified
1141 /// with the ARC __weak qualifier.
1142 PDIK_ARCWeak,
1143
1144 /// The type is a struct containing a field whose type is not PCK_Trivial.
1145 PDIK_Struct
1146 };
1147
1148 /// Functions to query basic properties of non-trivial C struct types.
1149
1150 /// Check if this is a non-trivial type that would cause a C struct
1151 /// transitively containing this type to be non-trivial to default initialize
1152 /// and return the kind.
1153 PrimitiveDefaultInitializeKind
1154 isNonTrivialToPrimitiveDefaultInitialize() const;
1155
1156 enum PrimitiveCopyKind {
1157 /// The type does not fall into any of the following categories. Note that
1158 /// this case is zero-valued so that values of this enum can be used as a
1159 /// boolean condition for non-triviality.
1160 PCK_Trivial,
1161
1162 /// The type would be trivial except that it is volatile-qualified. Types
1163 /// that fall into one of the other non-trivial cases may additionally be
1164 /// volatile-qualified.
1165 PCK_VolatileTrivial,
1166
1167 /// The type is an Objective-C retainable pointer type that is qualified
1168 /// with the ARC __strong qualifier.
1169 PCK_ARCStrong,
1170
1171 /// The type is an Objective-C retainable pointer type that is qualified
1172 /// with the ARC __weak qualifier.
1173 PCK_ARCWeak,
1174
1175 /// The type is a struct containing a field whose type is neither
1176 /// PCK_Trivial nor PCK_VolatileTrivial.
1177 /// Note that a C++ struct type does not necessarily match this; C++ copying
1178 /// semantics are too complex to express here, in part because they depend
1179 /// on the exact constructor or assignment operator that is chosen by
1180 /// overload resolution to do the copy.
1181 PCK_Struct
1182 };
1183
1184 /// Check if this is a non-trivial type that would cause a C struct
1185 /// transitively containing this type to be non-trivial to copy and return the
1186 /// kind.
1187 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1188
1189 /// Check if this is a non-trivial type that would cause a C struct
1190 /// transitively containing this type to be non-trivial to destructively
1191 /// move and return the kind. Destructive move in this context is a C++-style
1192 /// move in which the source object is placed in a valid but unspecified state
1193 /// after it is moved, as opposed to a truly destructive move in which the
1194 /// source object is placed in an uninitialized state.
1195 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1196
1197 enum DestructionKind {
1198 DK_none,
1199 DK_cxx_destructor,
1200 DK_objc_strong_lifetime,
1201 DK_objc_weak_lifetime,
1202 DK_nontrivial_c_struct
1203 };
1204
1205 /// Returns a nonzero value if objects of this type require
1206 /// non-trivial work to clean up after. Non-zero because it's
1207 /// conceivable that qualifiers (objc_gc(weak)?) could make
1208 /// something require destruction.
1209 DestructionKind isDestructedType() const {
1210 return isDestructedTypeImpl(*this);
1211 }
1212
1213 /// Check if this is or contains a C union that is non-trivial to
1214 /// default-initialize, which is a union that has a member that is non-trivial
1215 /// to default-initialize. If this returns true,
1216 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1217 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1218
1219 /// Check if this is or contains a C union that is non-trivial to destruct,
1220 /// which is a union that has a member that is non-trivial to destruct. If
1221 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1222 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1223
1224 /// Check if this is or contains a C union that is non-trivial to copy, which
1225 /// is a union that has a member that is non-trivial to copy. If this returns
1226 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1227 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1228
1229 /// Determine whether expressions of the given type are forbidden
1230 /// from being lvalues in C.
1231 ///
1232 /// The expression types that are forbidden to be lvalues are:
1233 /// - 'void', but not qualified void
1234 /// - function types
1235 ///
1236 /// The exact rule here is C99 6.3.2.1:
1237 /// An lvalue is an expression with an object type or an incomplete
1238 /// type other than void.
1239 bool isCForbiddenLValueType() const;
1240
1241 /// Substitute type arguments for the Objective-C type parameters used in the
1242 /// subject type.
1243 ///
1244 /// \param ctx ASTContext in which the type exists.
1245 ///
1246 /// \param typeArgs The type arguments that will be substituted for the
1247 /// Objective-C type parameters in the subject type, which are generally
1248 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1249 /// parameters will be replaced with their bounds or id/Class, as appropriate
1250 /// for the context.
1251 ///
1252 /// \param context The context in which the subject type was written.
1253 ///
1254 /// \returns the resulting type.
1255 QualType substObjCTypeArgs(ASTContext &ctx,
1256 ArrayRef<QualType> typeArgs,
1257 ObjCSubstitutionContext context) const;
1258
1259 /// Substitute type arguments from an object type for the Objective-C type
1260 /// parameters used in the subject type.
1261 ///
1262 /// This operation combines the computation of type arguments for
1263 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1264 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1265 /// callers that need to perform a single substitution in isolation.
1266 ///
1267 /// \param objectType The type of the object whose member type we're
1268 /// substituting into. For example, this might be the receiver of a message
1269 /// or the base of a property access.
1270 ///
1271 /// \param dc The declaration context from which the subject type was
1272 /// retrieved, which indicates (for example) which type parameters should
1273 /// be substituted.
1274 ///
1275 /// \param context The context in which the subject type was written.
1276 ///
1277 /// \returns the subject type after replacing all of the Objective-C type
1278 /// parameters with their corresponding arguments.
1279 QualType substObjCMemberType(QualType objectType,
1280 const DeclContext *dc,
1281 ObjCSubstitutionContext context) const;
1282
1283 /// Strip Objective-C "__kindof" types from the given type.
1284 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1285
1286 /// Remove all qualifiers including _Atomic.
1287 QualType getAtomicUnqualifiedType() const;
1288
1289private:
1290 // These methods are implemented in a separate translation unit;
1291 // "static"-ize them to avoid creating temporary QualTypes in the
1292 // caller.
1293 static bool isConstant(QualType T, const ASTContext& Ctx);
1294 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1295 static SplitQualType getSplitDesugaredType(QualType T);
1296 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1297 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1298 const ASTContext &C);
1299 static QualType IgnoreParens(QualType T);
1300 static DestructionKind isDestructedTypeImpl(QualType type);
1301
1302 /// Check if \param RD is or contains a non-trivial C union.
1303 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1304 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1305 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1306};
1307
1308} // namespace clang
1309
1310namespace llvm {
1311
1312/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1313/// to a specific Type class.
1314template<> struct simplify_type< ::clang::QualType> {
1315 using SimpleType = const ::clang::Type *;
1316
1317 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1318 return Val.getTypePtr();
1319 }
1320};
1321
1322// Teach SmallPtrSet that QualType is "basically a pointer".
1323template<>
1324struct PointerLikeTypeTraits<clang::QualType> {
1325 static inline void *getAsVoidPointer(clang::QualType P) {
1326 return P.getAsOpaquePtr();
1327 }
1328
1329 static inline clang::QualType getFromVoidPointer(void *P) {
1330 return clang::QualType::getFromOpaquePtr(P);
1331 }
1332
1333 // Various qualifiers go in low bits.
1334 static constexpr int NumLowBitsAvailable = 0;
1335};
1336
1337} // namespace llvm
1338
1339namespace clang {
1340
1341/// Base class that is common to both the \c ExtQuals and \c Type
1342/// classes, which allows \c QualType to access the common fields between the
1343/// two.
1344class ExtQualsTypeCommonBase {
1345 friend class ExtQuals;
1346 friend class QualType;
1347 friend class Type;
1348
1349 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1350 /// a self-referential pointer (for \c Type).
1351 ///
1352 /// This pointer allows an efficient mapping from a QualType to its
1353 /// underlying type pointer.
1354 const Type *const BaseType;
1355
1356 /// The canonical type of this type. A QualType.
1357 QualType CanonicalType;
1358
1359 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1360 : BaseType(baseType), CanonicalType(canon) {}
1361};
1362
1363/// We can encode up to four bits in the low bits of a
1364/// type pointer, but there are many more type qualifiers that we want
1365/// to be able to apply to an arbitrary type. Therefore we have this
1366/// struct, intended to be heap-allocated and used by QualType to
1367/// store qualifiers.
1368///
1369/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1370/// in three low bits on the QualType pointer; a fourth bit records whether
1371/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1372/// Objective-C GC attributes) are much more rare.
1373class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1374 // NOTE: changing the fast qualifiers should be straightforward as
1375 // long as you don't make 'const' non-fast.
1376 // 1. Qualifiers:
1377 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1378 // Fast qualifiers must occupy the low-order bits.
1379 // b) Update Qualifiers::FastWidth and FastMask.
1380 // 2. QualType:
1381 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1382 // b) Update remove{Volatile,Restrict}, defined near the end of
1383 // this header.
1384 // 3. ASTContext:
1385 // a) Update get{Volatile,Restrict}Type.
1386
1387 /// The immutable set of qualifiers applied by this node. Always contains
1388 /// extended qualifiers.
1389 Qualifiers Quals;
1390
1391 ExtQuals *this_() { return this; }
1392
1393public:
1394 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1395 : ExtQualsTypeCommonBase(baseType,
1396 canon.isNull() ? QualType(this_(), 0) : canon),
1397 Quals(quals) {
1398 assert(Quals.hasNonFastQualifiers()(static_cast <bool> (Quals.hasNonFastQualifiers() &&
"ExtQuals created with no fast qualifiers") ? void (0) : __assert_fail
("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 1399, __extension__ __PRETTY_FUNCTION__))
1399 && "ExtQuals created with no fast qualifiers")(static_cast <bool> (Quals.hasNonFastQualifiers() &&
"ExtQuals created with no fast qualifiers") ? void (0) : __assert_fail
("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 1399, __extension__ __PRETTY_FUNCTION__))
;
1400 assert(!Quals.hasFastQualifiers()(static_cast <bool> (!Quals.hasFastQualifiers() &&
"ExtQuals created with fast qualifiers") ? void (0) : __assert_fail
("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 1401, __extension__ __PRETTY_FUNCTION__))
1401 && "ExtQuals created with fast qualifiers")(static_cast <bool> (!Quals.hasFastQualifiers() &&
"ExtQuals created with fast qualifiers") ? void (0) : __assert_fail
("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 1401, __extension__ __PRETTY_FUNCTION__))
;
1402 }
1403
1404 Qualifiers getQualifiers() const { return Quals; }
1405
1406 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1407 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1408
1409 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1410 Qualifiers::ObjCLifetime getObjCLifetime() const {
1411 return Quals.getObjCLifetime();
1412 }
1413
1414 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1415 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1416
1417 const Type *getBaseType() const { return BaseType; }
1418
1419public:
1420 void Profile(llvm::FoldingSetNodeID &ID) const {
1421 Profile(ID, getBaseType(), Quals);
1422 }
1423
1424 static void Profile(llvm::FoldingSetNodeID &ID,
1425 const Type *BaseType,
1426 Qualifiers Quals) {
1427 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")(static_cast <bool> (!Quals.hasFastQualifiers() &&
"fast qualifiers in ExtQuals hash!") ? void (0) : __assert_fail
("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 1427, __extension__ __PRETTY_FUNCTION__))
;
1428 ID.AddPointer(BaseType);
1429 Quals.Profile(ID);
1430 }
1431};
1432
1433/// The kind of C++11 ref-qualifier associated with a function type.
1434/// This determines whether a member function's "this" object can be an
1435/// lvalue, rvalue, or neither.
1436enum RefQualifierKind {
1437 /// No ref-qualifier was provided.
1438 RQ_None = 0,
1439
1440 /// An lvalue ref-qualifier was provided (\c &).
1441 RQ_LValue,
1442
1443 /// An rvalue ref-qualifier was provided (\c &&).
1444 RQ_RValue
1445};
1446
1447/// Which keyword(s) were used to create an AutoType.
1448enum class AutoTypeKeyword {
1449 /// auto
1450 Auto,
1451
1452 /// decltype(auto)
1453 DecltypeAuto,
1454
1455 /// __auto_type (GNU extension)
1456 GNUAutoType
1457};
1458
1459/// The base class of the type hierarchy.
1460///
1461/// A central concept with types is that each type always has a canonical
1462/// type. A canonical type is the type with any typedef names stripped out
1463/// of it or the types it references. For example, consider:
1464///
1465/// typedef int foo;
1466/// typedef foo* bar;
1467/// 'int *' 'foo *' 'bar'
1468///
1469/// There will be a Type object created for 'int'. Since int is canonical, its
1470/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1471/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1472/// there is a PointerType that represents 'int*', which, like 'int', is
1473/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1474/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1475/// is also 'int*'.
1476///
1477/// Non-canonical types are useful for emitting diagnostics, without losing
1478/// information about typedefs being used. Canonical types are useful for type
1479/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1480/// about whether something has a particular form (e.g. is a function type),
1481/// because they implicitly, recursively, strip all typedefs out of a type.
1482///
1483/// Types, once created, are immutable.
1484///
1485class alignas(8) Type : public ExtQualsTypeCommonBase {
1486public:
1487 enum TypeClass {
1488#define TYPE(Class, Base) Class,
1489#define LAST_TYPE(Class) TypeLast = Class
1490#define ABSTRACT_TYPE(Class, Base)
1491#include "clang/AST/TypeNodes.inc"
1492 };
1493
1494private:
1495 /// Bitfields required by the Type class.
1496 class TypeBitfields {
1497 friend class Type;
1498 template <class T> friend class TypePropertyCache;
1499
1500 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1501 unsigned TC : 8;
1502
1503 /// Store information on the type dependency.
1504 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1505
1506 /// True if the cache (i.e. the bitfields here starting with
1507 /// 'Cache') is valid.
1508 mutable unsigned CacheValid : 1;
1509
1510 /// Linkage of this type.
1511 mutable unsigned CachedLinkage : 3;
1512
1513 /// Whether this type involves and local or unnamed types.
1514 mutable unsigned CachedLocalOrUnnamed : 1;
1515
1516 /// Whether this type comes from an AST file.
1517 mutable unsigned FromAST : 1;
1518
1519 bool isCacheValid() const {
1520 return CacheValid;
1521 }
1522
1523 Linkage getLinkage() const {
1524 assert(isCacheValid() && "getting linkage from invalid cache")(static_cast <bool> (isCacheValid() && "getting linkage from invalid cache"
) ? void (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 1524, __extension__ __PRETTY_FUNCTION__))
;
1525 return static_cast<Linkage>(CachedLinkage);
1526 }
1527
1528 bool hasLocalOrUnnamedType() const {
1529 assert(isCacheValid() && "getting linkage from invalid cache")(static_cast <bool> (isCacheValid() && "getting linkage from invalid cache"
) ? void (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 1529, __extension__ __PRETTY_FUNCTION__))
;
1530 return CachedLocalOrUnnamed;
1531 }
1532 };
1533 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1534
1535protected:
1536 // These classes allow subclasses to somewhat cleanly pack bitfields
1537 // into Type.
1538
1539 class ArrayTypeBitfields {
1540 friend class ArrayType;
1541
1542 unsigned : NumTypeBits;
1543
1544 /// CVR qualifiers from declarations like
1545 /// 'int X[static restrict 4]'. For function parameters only.
1546 unsigned IndexTypeQuals : 3;
1547
1548 /// Storage class qualifiers from declarations like
1549 /// 'int X[static restrict 4]'. For function parameters only.
1550 /// Actually an ArrayType::ArraySizeModifier.
1551 unsigned SizeModifier : 3;
1552 };
1553
1554 class ConstantArrayTypeBitfields {
1555 friend class ConstantArrayType;
1556
1557 unsigned : NumTypeBits + 3 + 3;
1558
1559 /// Whether we have a stored size expression.
1560 unsigned HasStoredSizeExpr : 1;
1561 };
1562
1563 class BuiltinTypeBitfields {
1564 friend class BuiltinType;
1565
1566 unsigned : NumTypeBits;
1567
1568 /// The kind (BuiltinType::Kind) of builtin type this is.
1569 unsigned Kind : 8;
1570 };
1571
1572 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1573 /// Only common bits are stored here. Additional uncommon bits are stored
1574 /// in a trailing object after FunctionProtoType.
1575 class FunctionTypeBitfields {
1576 friend class FunctionProtoType;
1577 friend class FunctionType;
1578
1579 unsigned : NumTypeBits;
1580
1581 /// Extra information which affects how the function is called, like
1582 /// regparm and the calling convention.
1583 unsigned ExtInfo : 13;
1584
1585 /// The ref-qualifier associated with a \c FunctionProtoType.
1586 ///
1587 /// This is a value of type \c RefQualifierKind.
1588 unsigned RefQualifier : 2;
1589
1590 /// Used only by FunctionProtoType, put here to pack with the
1591 /// other bitfields.
1592 /// The qualifiers are part of FunctionProtoType because...
1593 ///
1594 /// C++ 8.3.5p4: The return type, the parameter type list and the
1595 /// cv-qualifier-seq, [...], are part of the function type.
1596 unsigned FastTypeQuals : Qualifiers::FastWidth;
1597 /// Whether this function has extended Qualifiers.
1598 unsigned HasExtQuals : 1;
1599
1600 /// The number of parameters this function has, not counting '...'.
1601 /// According to [implimits] 8 bits should be enough here but this is
1602 /// somewhat easy to exceed with metaprogramming and so we would like to
1603 /// keep NumParams as wide as reasonably possible.
1604 unsigned NumParams : 16;
1605
1606 /// The type of exception specification this function has.
1607 unsigned ExceptionSpecType : 4;
1608
1609 /// Whether this function has extended parameter information.
1610 unsigned HasExtParameterInfos : 1;
1611
1612 /// Whether the function is variadic.
1613 unsigned Variadic : 1;
1614
1615 /// Whether this function has a trailing return type.
1616 unsigned HasTrailingReturn : 1;
1617 };
1618
1619 class ObjCObjectTypeBitfields {
1620 friend class ObjCObjectType;
1621
1622 unsigned : NumTypeBits;
1623
1624 /// The number of type arguments stored directly on this object type.
1625 unsigned NumTypeArgs : 7;
1626
1627 /// The number of protocols stored directly on this object type.
1628 unsigned NumProtocols : 6;
1629
1630 /// Whether this is a "kindof" type.
1631 unsigned IsKindOf : 1;
1632 };
1633
1634 class ReferenceTypeBitfields {
1635 friend class ReferenceType;
1636
1637 unsigned : NumTypeBits;
1638
1639 /// True if the type was originally spelled with an lvalue sigil.
1640 /// This is never true of rvalue references but can also be false
1641 /// on lvalue references because of C++0x [dcl.typedef]p9,
1642 /// as follows:
1643 ///
1644 /// typedef int &ref; // lvalue, spelled lvalue
1645 /// typedef int &&rvref; // rvalue
1646 /// ref &a; // lvalue, inner ref, spelled lvalue
1647 /// ref &&a; // lvalue, inner ref
1648 /// rvref &a; // lvalue, inner ref, spelled lvalue
1649 /// rvref &&a; // rvalue, inner ref
1650 unsigned SpelledAsLValue : 1;
1651
1652 /// True if the inner type is a reference type. This only happens
1653 /// in non-canonical forms.
1654 unsigned InnerRef : 1;
1655 };
1656
1657 class TypeWithKeywordBitfields {
1658 friend class TypeWithKeyword;
1659
1660 unsigned : NumTypeBits;
1661
1662 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1663 unsigned Keyword : 8;
1664 };
1665
1666 enum { NumTypeWithKeywordBits = 8 };
1667
1668 class ElaboratedTypeBitfields {
1669 friend class ElaboratedType;
1670
1671 unsigned : NumTypeBits;
1672 unsigned : NumTypeWithKeywordBits;
1673
1674 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1675 unsigned HasOwnedTagDecl : 1;
1676 };
1677
1678 class VectorTypeBitfields {
1679 friend class VectorType;
1680 friend class DependentVectorType;
1681
1682 unsigned : NumTypeBits;
1683
1684 /// The kind of vector, either a generic vector type or some
1685 /// target-specific vector type such as for AltiVec or Neon.
1686 unsigned VecKind : 3;
1687 /// The number of elements in the vector.
1688 uint32_t NumElements;
1689 };
1690
1691 class AttributedTypeBitfields {
1692 friend class AttributedType;
1693
1694 unsigned : NumTypeBits;
1695
1696 /// An AttributedType::Kind
1697 unsigned AttrKind : 32 - NumTypeBits;
1698 };
1699
1700 class AutoTypeBitfields {
1701 friend class AutoType;
1702
1703 unsigned : NumTypeBits;
1704
1705 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1706 /// or '__auto_type'? AutoTypeKeyword value.
1707 unsigned Keyword : 2;
1708
1709 /// The number of template arguments in the type-constraints, which is
1710 /// expected to be able to hold at least 1024 according to [implimits].
1711 /// However as this limit is somewhat easy to hit with template
1712 /// metaprogramming we'd prefer to keep it as large as possible.
1713 /// At the moment it has been left as a non-bitfield since this type
1714 /// safely fits in 64 bits as an unsigned, so there is no reason to
1715 /// introduce the performance impact of a bitfield.
1716 unsigned NumArgs;
1717 };
1718
1719 class SubstTemplateTypeParmPackTypeBitfields {
1720 friend class SubstTemplateTypeParmPackType;
1721
1722 unsigned : NumTypeBits;
1723
1724 /// The number of template arguments in \c Arguments, which is
1725 /// expected to be able to hold at least 1024 according to [implimits].
1726 /// However as this limit is somewhat easy to hit with template
1727 /// metaprogramming we'd prefer to keep it as large as possible.
1728 /// At the moment it has been left as a non-bitfield since this type
1729 /// safely fits in 64 bits as an unsigned, so there is no reason to
1730 /// introduce the performance impact of a bitfield.
1731 unsigned NumArgs;
1732 };
1733
1734 class TemplateSpecializationTypeBitfields {
1735 friend class TemplateSpecializationType;
1736
1737 unsigned : NumTypeBits;
1738
1739 /// Whether this template specialization type is a substituted type alias.
1740 unsigned TypeAlias : 1;
1741
1742 /// The number of template arguments named in this class template
1743 /// specialization, which is expected to be able to hold at least 1024
1744 /// according to [implimits]. However, as this limit is somewhat easy to
1745 /// hit with template metaprogramming we'd prefer to keep it as large
1746 /// as possible. At the moment it has been left as a non-bitfield since
1747 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1748 /// to introduce the performance impact of a bitfield.
1749 unsigned NumArgs;
1750 };
1751
1752 class DependentTemplateSpecializationTypeBitfields {
1753 friend class DependentTemplateSpecializationType;
1754
1755 unsigned : NumTypeBits;
1756 unsigned : NumTypeWithKeywordBits;
1757
1758 /// The number of template arguments named in this class template
1759 /// specialization, which is expected to be able to hold at least 1024
1760 /// according to [implimits]. However, as this limit is somewhat easy to
1761 /// hit with template metaprogramming we'd prefer to keep it as large
1762 /// as possible. At the moment it has been left as a non-bitfield since
1763 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1764 /// to introduce the performance impact of a bitfield.
1765 unsigned NumArgs;
1766 };
1767
1768 class PackExpansionTypeBitfields {
1769 friend class PackExpansionType;
1770
1771 unsigned : NumTypeBits;
1772
1773 /// The number of expansions that this pack expansion will
1774 /// generate when substituted (+1), which is expected to be able to
1775 /// hold at least 1024 according to [implimits]. However, as this limit
1776 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1777 /// keep it as large as possible. At the moment it has been left as a
1778 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1779 /// there is no reason to introduce the performance impact of a bitfield.
1780 ///
1781 /// This field will only have a non-zero value when some of the parameter
1782 /// packs that occur within the pattern have been substituted but others
1783 /// have not.
1784 unsigned NumExpansions;
1785 };
1786
1787 union {
1788 TypeBitfields TypeBits;
1789 ArrayTypeBitfields ArrayTypeBits;
1790 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1791 AttributedTypeBitfields AttributedTypeBits;
1792 AutoTypeBitfields AutoTypeBits;
1793 BuiltinTypeBitfields BuiltinTypeBits;
1794 FunctionTypeBitfields FunctionTypeBits;
1795 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1796 ReferenceTypeBitfields ReferenceTypeBits;
1797 TypeWithKeywordBitfields TypeWithKeywordBits;
1798 ElaboratedTypeBitfields ElaboratedTypeBits;
1799 VectorTypeBitfields VectorTypeBits;
1800 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1801 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1802 DependentTemplateSpecializationTypeBitfields
1803 DependentTemplateSpecializationTypeBits;
1804 PackExpansionTypeBitfields PackExpansionTypeBits;
1805 };
1806
1807private:
1808 template <class T> friend class TypePropertyCache;
1809
1810 /// Set whether this type comes from an AST file.
1811 void setFromAST(bool V = true) const {
1812 TypeBits.FromAST = V;
1813 }
1814
1815protected:
1816 friend class ASTContext;
1817
1818 Type(TypeClass tc, QualType canon, TypeDependence Dependence)
1819 : ExtQualsTypeCommonBase(this,
1820 canon.isNull() ? QualType(this_(), 0) : canon) {
1821 static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1822 "changing bitfields changed sizeof(Type)!");
1823 static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1824 "Insufficient alignment!");
1825 TypeBits.TC = tc;
1826 TypeBits.Dependence = static_cast<unsigned>(Dependence);
1827 TypeBits.CacheValid = false;
1828 TypeBits.CachedLocalOrUnnamed = false;
1829 TypeBits.CachedLinkage = NoLinkage;
1830 TypeBits.FromAST = false;
1831 }
1832
1833 // silence VC++ warning C4355: 'this' : used in base member initializer list
1834 Type *this_() { return this; }
1835
1836 void setDependence(TypeDependence D) {
1837 TypeBits.Dependence = static_cast<unsigned>(D);
1838 }
1839
1840 void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
1841
1842public:
1843 friend class ASTReader;
1844 friend class ASTWriter;
1845 template <class T> friend class serialization::AbstractTypeReader;
1846 template <class T> friend class serialization::AbstractTypeWriter;
1847
1848 Type(const Type &) = delete;
1849 Type(Type &&) = delete;
1850 Type &operator=(const Type &) = delete;
1851 Type &operator=(Type &&) = delete;
1852
1853 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1854
1855 /// Whether this type comes from an AST file.
1856 bool isFromAST() const { return TypeBits.FromAST; }
1857
1858 /// Whether this type is or contains an unexpanded parameter
1859 /// pack, used to support C++0x variadic templates.
1860 ///
1861 /// A type that contains a parameter pack shall be expanded by the
1862 /// ellipsis operator at some point. For example, the typedef in the
1863 /// following example contains an unexpanded parameter pack 'T':
1864 ///
1865 /// \code
1866 /// template<typename ...T>
1867 /// struct X {
1868 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1869 /// };
1870 /// \endcode
1871 ///
1872 /// Note that this routine does not specify which
1873 bool containsUnexpandedParameterPack() const {
1874 return getDependence() & TypeDependence::UnexpandedPack;
1875 }
1876
1877 /// Determines if this type would be canonical if it had no further
1878 /// qualification.
1879 bool isCanonicalUnqualified() const {
1880 return CanonicalType == QualType(this, 0);
1881 }
1882
1883 /// Pull a single level of sugar off of this locally-unqualified type.
1884 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1885 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1886 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1887
1888 /// As an extension, we classify types as one of "sized" or "sizeless";
1889 /// every type is one or the other. Standard types are all sized;
1890 /// sizeless types are purely an extension.
1891 ///
1892 /// Sizeless types contain data with no specified size, alignment,
1893 /// or layout.
1894 bool isSizelessType() const;
1895 bool isSizelessBuiltinType() const;
1896
1897 /// Determines if this is a sizeless type supported by the
1898 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
1899 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
1900 bool isVLSTBuiltinType() const;
1901
1902 /// Returns the representative type for the element of an SVE builtin type.
1903 /// This is used to represent fixed-length SVE vectors created with the
1904 /// 'arm_sve_vector_bits' type attribute as VectorType.
1905 QualType getSveEltType(const ASTContext &Ctx) const;
1906
1907 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1908 /// object types, function types, and incomplete types.
1909
1910 /// Return true if this is an incomplete type.
1911 /// A type that can describe objects, but which lacks information needed to
1912 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1913 /// routine will need to determine if the size is actually required.
1914 ///
1915 /// Def If non-null, and the type refers to some kind of declaration
1916 /// that can be completed (such as a C struct, C++ class, or Objective-C
1917 /// class), will be set to the declaration.
1918 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1919
1920 /// Return true if this is an incomplete or object
1921 /// type, in other words, not a function type.
1922 bool isIncompleteOrObjectType() const {
1923 return !isFunctionType();
1924 }
1925
1926 /// Determine whether this type is an object type.
1927 bool isObjectType() const {
1928 // C++ [basic.types]p8:
1929 // An object type is a (possibly cv-qualified) type that is not a
1930 // function type, not a reference type, and not a void type.
1931 return !isReferenceType() && !isFunctionType() && !isVoidType();
1932 }
1933
1934 /// Return true if this is a literal type
1935 /// (C++11 [basic.types]p10)
1936 bool isLiteralType(const ASTContext &Ctx) const;
1937
1938 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
1939 bool isStructuralType() const;
1940
1941 /// Test if this type is a standard-layout type.
1942 /// (C++0x [basic.type]p9)
1943 bool isStandardLayoutType() const;
1944
1945 /// Helper methods to distinguish type categories. All type predicates
1946 /// operate on the canonical type, ignoring typedefs and qualifiers.
1947
1948 /// Returns true if the type is a builtin type.
1949 bool isBuiltinType() const;
1950
1951 /// Test for a particular builtin type.
1952 bool isSpecificBuiltinType(unsigned K) const;
1953
1954 /// Test for a type which does not represent an actual type-system type but
1955 /// is instead used as a placeholder for various convenient purposes within
1956 /// Clang. All such types are BuiltinTypes.
1957 bool isPlaceholderType() const;
1958 const BuiltinType *getAsPlaceholderType() const;
1959
1960 /// Test for a specific placeholder type.
1961 bool isSpecificPlaceholderType(unsigned K) const;
1962
1963 /// Test for a placeholder type other than Overload; see
1964 /// BuiltinType::isNonOverloadPlaceholderType.
1965 bool isNonOverloadPlaceholderType() const;
1966
1967 /// isIntegerType() does *not* include complex integers (a GCC extension).
1968 /// isComplexIntegerType() can be used to test for complex integers.
1969 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1970 bool isEnumeralType() const;
1971
1972 /// Determine whether this type is a scoped enumeration type.
1973 bool isScopedEnumeralType() const;
1974 bool isBooleanType() const;
1975 bool isCharType() const;
1976 bool isWideCharType() const;
1977 bool isChar8Type() const;
1978 bool isChar16Type() const;
1979 bool isChar32Type() const;
1980 bool isAnyCharacterType() const;
1981 bool isIntegralType(const ASTContext &Ctx) const;
1982
1983 /// Determine whether this type is an integral or enumeration type.
1984 bool isIntegralOrEnumerationType() const;
1985
1986 /// Determine whether this type is an integral or unscoped enumeration type.
1987 bool isIntegralOrUnscopedEnumerationType() const;
1988 bool isUnscopedEnumerationType() const;
1989
1990 /// Floating point categories.
1991 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1992 /// isComplexType() does *not* include complex integers (a GCC extension).
1993 /// isComplexIntegerType() can be used to test for complex integers.
1994 bool isComplexType() const; // C99 6.2.5p11 (complex)
1995 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1996 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1997 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1998 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1999 bool isBFloat16Type() const;
2000 bool isFloat128Type() const;
2001 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
2002 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
2003 bool isVoidType() const; // C99 6.2.5p19
2004 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
2005 bool isAggregateType() const;
2006 bool isFundamentalType() const;
2007 bool isCompoundType() const;
2008
2009 // Type Predicates: Check to see if this type is structurally the specified
2010 // type, ignoring typedefs and qualifiers.
2011 bool isFunctionType() const;
2012 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2013 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2014 bool isPointerType() const;
2015 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2016 bool isBlockPointerType() const;
2017 bool isVoidPointerType() const;
2018 bool isReferenceType() const;
2019 bool isLValueReferenceType() const;
2020 bool isRValueReferenceType() const;
2021 bool isObjectPointerType() const;
2022 bool isFunctionPointerType() const;
2023 bool isFunctionReferenceType() const;
2024 bool isMemberPointerType() const;
2025 bool isMemberFunctionPointerType() const;
2026 bool isMemberDataPointerType() const;
2027 bool isArrayType() const;
2028 bool isConstantArrayType() const;
2029 bool isIncompleteArrayType() const;
2030 bool isVariableArrayType() const;
2031 bool isDependentSizedArrayType() const;
2032 bool isRecordType() const;
2033 bool isClassType() const;
2034 bool isStructureType() const;
2035 bool isObjCBoxableRecordType() const;
2036 bool isInterfaceType() const;
2037 bool isStructureOrClassType() const;
2038 bool isUnionType() const;
2039 bool isComplexIntegerType() const; // GCC _Complex integer type.
2040 bool isVectorType() const; // GCC vector type.
2041 bool isExtVectorType() const; // Extended vector type.
2042 bool isMatrixType() const; // Matrix type.
2043 bool isConstantMatrixType() const; // Constant matrix type.
2044 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2045 bool isObjCObjectPointerType() const; // pointer to ObjC object
2046 bool isObjCRetainableType() const; // ObjC object or block pointer
2047 bool isObjCLifetimeType() const; // (array of)* retainable type
2048 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2049 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2050 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2051 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2052 // for the common case.
2053 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2054 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2055 bool isObjCQualifiedIdType() const; // id<foo>
2056 bool isObjCQualifiedClassType() const; // Class<foo>
2057 bool isObjCObjectOrInterfaceType() const;
2058 bool isObjCIdType() const; // id
2059 bool isDecltypeType() const;
2060 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2061 /// qualifier?
2062 ///
2063 /// This approximates the answer to the following question: if this
2064 /// translation unit were compiled in ARC, would this type be qualified
2065 /// with __unsafe_unretained?
2066 bool isObjCInertUnsafeUnretainedType() const {
2067 return hasAttr(attr::ObjCInertUnsafeUnretained);
2068 }
2069
2070 /// Whether the type is Objective-C 'id' or a __kindof type of an
2071 /// object type, e.g., __kindof NSView * or __kindof id
2072 /// <NSCopying>.
2073 ///
2074 /// \param bound Will be set to the bound on non-id subtype types,
2075 /// which will be (possibly specialized) Objective-C class type, or
2076 /// null for 'id.
2077 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2078 const ObjCObjectType *&bound) const;
2079
2080 bool isObjCClassType() const; // Class
2081
2082 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2083 /// Class type, e.g., __kindof Class <NSCopying>.
2084 ///
2085 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2086 /// here because Objective-C's type system cannot express "a class
2087 /// object for a subclass of NSFoo".
2088 bool isObjCClassOrClassKindOfType() const;
2089
2090 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2091 bool isObjCSelType() const; // Class
2092 bool isObjCBuiltinType() const; // 'id' or 'Class'
2093 bool isObjCARCBridgableType() const;
2094 bool isCARCBridgableType() const;
2095 bool isTemplateTypeParmType() const; // C++ template type parameter
2096 bool isNullPtrType() const; // C++11 std::nullptr_t
2097 bool isNothrowT() const; // C++ std::nothrow_t
2098 bool isAlignValT() const; // C++17 std::align_val_t
2099 bool isStdByteType() const; // C++17 std::byte
2100 bool isAtomicType() const; // C11 _Atomic()
2101 bool isUndeducedAutoType() const; // C++11 auto or
2102 // C++14 decltype(auto)
2103 bool isTypedefNameType() const; // typedef or alias template
2104
2105#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2106 bool is##Id##Type() const;
2107#include "clang/Basic/OpenCLImageTypes.def"
2108
2109 bool isImageType() const; // Any OpenCL image type
2110
2111 bool isSamplerT() const; // OpenCL sampler_t
2112 bool isEventT() const; // OpenCL event_t
2113 bool isClkEventT() const; // OpenCL clk_event_t
2114 bool isQueueT() const; // OpenCL queue_t
2115 bool isReserveIDT() const; // OpenCL reserve_id_t
2116
2117#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2118 bool is##Id##Type() const;
2119#include "clang/Basic/OpenCLExtensionTypes.def"
2120 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2121 bool isOCLIntelSubgroupAVCType() const;
2122 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2123
2124 bool isPipeType() const; // OpenCL pipe type
2125 bool isExtIntType() const; // Extended Int Type
2126 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2127
2128 /// Determines if this type, which must satisfy
2129 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2130 /// than implicitly __strong.
2131 bool isObjCARCImplicitlyUnretainedType() const;
2132
2133 /// Check if the type is the CUDA device builtin surface type.
2134 bool isCUDADeviceBuiltinSurfaceType() const;
2135 /// Check if the type is the CUDA device builtin texture type.
2136 bool isCUDADeviceBuiltinTextureType() const;
2137
2138 /// Return the implicit lifetime for this type, which must not be dependent.
2139 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2140
2141 enum ScalarTypeKind {
2142 STK_CPointer,
2143 STK_BlockPointer,
2144 STK_ObjCObjectPointer,
2145 STK_MemberPointer,
2146 STK_Bool,
2147 STK_Integral,
2148 STK_Floating,
2149 STK_IntegralComplex,
2150 STK_FloatingComplex,
2151 STK_FixedPoint
2152 };
2153
2154 /// Given that this is a scalar type, classify it.
2155 ScalarTypeKind getScalarTypeKind() const;
2156
2157 TypeDependence getDependence() const {
2158 return static_cast<TypeDependence>(TypeBits.Dependence);
2159 }
2160
2161 /// Whether this type is an error type.
2162 bool containsErrors() const {
2163 return getDependence() & TypeDependence::Error;
2164 }
2165
2166 /// Whether this type is a dependent type, meaning that its definition
2167 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2168 bool isDependentType() const {
2169 return getDependence() & TypeDependence::Dependent;
2170 }
2171
2172 /// Determine whether this type is an instantiation-dependent type,
2173 /// meaning that the type involves a template parameter (even if the
2174 /// definition does not actually depend on the type substituted for that
2175 /// template parameter).
2176 bool isInstantiationDependentType() const {
2177 return getDependence() & TypeDependence::Instantiation;
2178 }
2179
2180 /// Determine whether this type is an undeduced type, meaning that
2181 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2182 /// deduced.
2183 bool isUndeducedType() const;
2184
2185 /// Whether this type is a variably-modified type (C99 6.7.5).
2186 bool isVariablyModifiedType() const {
2187 return getDependence() & TypeDependence::VariablyModified;
2188 }
2189
2190 /// Whether this type involves a variable-length array type
2191 /// with a definite size.
2192 bool hasSizedVLAType() const;
2193
2194 /// Whether this type is or contains a local or unnamed type.
2195 bool hasUnnamedOrLocalType() const;
2196
2197 bool isOverloadableType() const;
2198
2199 /// Determine wither this type is a C++ elaborated-type-specifier.
2200 bool isElaboratedTypeSpecifier() const;
2201
2202 bool canDecayToPointerType() const;
2203
2204 /// Whether this type is represented natively as a pointer. This includes
2205 /// pointers, references, block pointers, and Objective-C interface,
2206 /// qualified id, and qualified interface types, as well as nullptr_t.
2207 bool hasPointerRepresentation() const;
2208
2209 /// Whether this type can represent an objective pointer type for the
2210 /// purpose of GC'ability
2211 bool hasObjCPointerRepresentation() const;
2212
2213 /// Determine whether this type has an integer representation
2214 /// of some sort, e.g., it is an integer type or a vector.
2215 bool hasIntegerRepresentation() const;
2216
2217 /// Determine whether this type has an signed integer representation
2218 /// of some sort, e.g., it is an signed integer type or a vector.
2219 bool hasSignedIntegerRepresentation() const;
2220
2221 /// Determine whether this type has an unsigned integer representation
2222 /// of some sort, e.g., it is an unsigned integer type or a vector.
2223 bool hasUnsignedIntegerRepresentation() const;
2224
2225 /// Determine whether this type has a floating-point representation
2226 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2227 bool hasFloatingRepresentation() const;
2228
2229 // Type Checking Functions: Check to see if this type is structurally the
2230 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2231 // the best type we can.
2232 const RecordType *getAsStructureType() const;
2233 /// NOTE: getAs*ArrayType are methods on ASTContext.
2234 const RecordType *getAsUnionType() const;
2235 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2236 const ObjCObjectType *getAsObjCInterfaceType() const;
2237
2238 // The following is a convenience method that returns an ObjCObjectPointerType
2239 // for object declared using an interface.
2240 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2241 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2242 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2243 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2244
2245 /// Retrieves the CXXRecordDecl that this type refers to, either
2246 /// because the type is a RecordType or because it is the injected-class-name
2247 /// type of a class template or class template partial specialization.
2248 CXXRecordDecl *getAsCXXRecordDecl() const;
2249
2250 /// Retrieves the RecordDecl this type refers to.
2251 RecordDecl *getAsRecordDecl() const;
2252
2253 /// Retrieves the TagDecl that this type refers to, either
2254 /// because the type is a TagType or because it is the injected-class-name
2255 /// type of a class template or class template partial specialization.
2256 TagDecl *getAsTagDecl() const;
2257
2258 /// If this is a pointer or reference to a RecordType, return the
2259 /// CXXRecordDecl that the type refers to.
2260 ///
2261 /// If this is not a pointer or reference, or the type being pointed to does
2262 /// not refer to a CXXRecordDecl, returns NULL.
2263 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2264
2265 /// Get the DeducedType whose type will be deduced for a variable with
2266 /// an initializer of this type. This looks through declarators like pointer
2267 /// types, but not through decltype or typedefs.
2268 DeducedType *getContainedDeducedType() const;
2269
2270 /// Get the AutoType whose type will be deduced for a variable with
2271 /// an initializer of this type. This looks through declarators like pointer
2272 /// types, but not through decltype or typedefs.
2273 AutoType *getContainedAutoType() const {
2274 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2275 }
2276
2277 /// Determine whether this type was written with a leading 'auto'
2278 /// corresponding to a trailing return type (possibly for a nested
2279 /// function type within a pointer to function type or similar).
2280 bool hasAutoForTrailingReturnType() const;
2281
2282 /// Member-template getAs<specific type>'. Look through sugar for
2283 /// an instance of \<specific type>. This scheme will eventually
2284 /// replace the specific getAsXXXX methods above.
2285 ///
2286 /// There are some specializations of this member template listed
2287 /// immediately following this class.
2288 template <typename T> const T *getAs() const;
2289
2290 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2291 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2292 /// This is used when you need to walk over sugar nodes that represent some
2293 /// kind of type adjustment from a type that was written as a \<specific type>
2294 /// to another type that is still canonically a \<specific type>.
2295 template <typename T> const T *getAsAdjusted() const;
2296
2297 /// A variant of getAs<> for array types which silently discards
2298 /// qualifiers from the outermost type.
2299 const ArrayType *getAsArrayTypeUnsafe() const;
2300
2301 /// Member-template castAs<specific type>. Look through sugar for
2302 /// the underlying instance of \<specific type>.
2303 ///
2304 /// This method has the same relationship to getAs<T> as cast<T> has
2305 /// to dyn_cast<T>; which is to say, the underlying type *must*
2306 /// have the intended type, and this method will never return null.
2307 template <typename T> const T *castAs() const;
2308
2309 /// A variant of castAs<> for array type which silently discards
2310 /// qualifiers from the outermost type.
2311 const ArrayType *castAsArrayTypeUnsafe() const;
2312
2313 /// Determine whether this type had the specified attribute applied to it
2314 /// (looking through top-level type sugar).
2315 bool hasAttr(attr::Kind AK) const;
2316
2317 /// Get the base element type of this type, potentially discarding type
2318 /// qualifiers. This should never be used when type qualifiers
2319 /// are meaningful.
2320 const Type *getBaseElementTypeUnsafe() const;
2321
2322 /// If this is an array type, return the element type of the array,
2323 /// potentially with type qualifiers missing.
2324 /// This should never be used when type qualifiers are meaningful.
2325 const Type *getArrayElementTypeNoTypeQual() const;
2326
2327 /// If this is a pointer type, return the pointee type.
2328 /// If this is an array type, return the array element type.
2329 /// This should never be used when type qualifiers are meaningful.
2330 const Type *getPointeeOrArrayElementType() const;
2331
2332 /// If this is a pointer, ObjC object pointer, or block
2333 /// pointer, this returns the respective pointee.
2334 QualType getPointeeType() const;
2335
2336 /// Return the specified type with any "sugar" removed from the type,
2337 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2338 const Type *getUnqualifiedDesugaredType() const;
2339
2340 /// More type predicates useful for type checking/promotion
2341 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2342
2343 /// Return true if this is an integer type that is
2344 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2345 /// or an enum decl which has a signed representation.
2346 bool isSignedIntegerType() const;
2347
2348 /// Return true if this is an integer type that is
2349 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2350 /// or an enum decl which has an unsigned representation.
2351 bool isUnsignedIntegerType() const;
2352
2353 /// Determines whether this is an integer type that is signed or an
2354 /// enumeration types whose underlying type is a signed integer type.
2355 bool isSignedIntegerOrEnumerationType() const;
2356
2357 /// Determines whether this is an integer type that is unsigned or an
2358 /// enumeration types whose underlying type is a unsigned integer type.
2359 bool isUnsignedIntegerOrEnumerationType() const;
2360
2361 /// Return true if this is a fixed point type according to
2362 /// ISO/IEC JTC1 SC22 WG14 N1169.
2363 bool isFixedPointType() const;
2364
2365 /// Return true if this is a fixed point or integer type.
2366 bool isFixedPointOrIntegerType() const;
2367
2368 /// Return true if this is a saturated fixed point type according to
2369 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2370 bool isSaturatedFixedPointType() const;
2371
2372 /// Return true if this is a saturated fixed point type according to
2373 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2374 bool isUnsaturatedFixedPointType() const;
2375
2376 /// Return true if this is a fixed point type that is signed according
2377 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2378 bool isSignedFixedPointType() const;
2379
2380 /// Return true if this is a fixed point type that is unsigned according
2381 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2382 bool isUnsignedFixedPointType() const;
2383
2384 /// Return true if this is not a variable sized type,
2385 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2386 /// incomplete types.
2387 bool isConstantSizeType() const;
2388
2389 /// Returns true if this type can be represented by some
2390 /// set of type specifiers.
2391 bool isSpecifierType() const;
2392
2393 /// Determine the linkage of this type.
2394 Linkage getLinkage() const;
2395
2396 /// Determine the visibility of this type.
2397 Visibility getVisibility() const {
2398 return getLinkageAndVisibility().getVisibility();
2399 }
2400
2401 /// Return true if the visibility was explicitly set is the code.
2402 bool isVisibilityExplicit() const {
2403 return getLinkageAndVisibility().isVisibilityExplicit();
2404 }
2405
2406 /// Determine the linkage and visibility of this type.
2407 LinkageInfo getLinkageAndVisibility() const;
2408
2409 /// True if the computed linkage is valid. Used for consistency
2410 /// checking. Should always return true.
2411 bool isLinkageValid() const;
2412
2413 /// Determine the nullability of the given type.
2414 ///
2415 /// Note that nullability is only captured as sugar within the type
2416 /// system, not as part of the canonical type, so nullability will
2417 /// be lost by canonicalization and desugaring.
2418 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2419
2420 /// Determine whether the given type can have a nullability
2421 /// specifier applied to it, i.e., if it is any kind of pointer type.
2422 ///
2423 /// \param ResultIfUnknown The value to return if we don't yet know whether
2424 /// this type can have nullability because it is dependent.
2425 bool canHaveNullability(bool ResultIfUnknown = true) const;
2426
2427 /// Retrieve the set of substitutions required when accessing a member
2428 /// of the Objective-C receiver type that is declared in the given context.
2429 ///
2430 /// \c *this is the type of the object we're operating on, e.g., the
2431 /// receiver for a message send or the base of a property access, and is
2432 /// expected to be of some object or object pointer type.
2433 ///
2434 /// \param dc The declaration context for which we are building up a
2435 /// substitution mapping, which should be an Objective-C class, extension,
2436 /// category, or method within.
2437 ///
2438 /// \returns an array of type arguments that can be substituted for
2439 /// the type parameters of the given declaration context in any type described
2440 /// within that context, or an empty optional to indicate that no
2441 /// substitution is required.
2442 Optional<ArrayRef<QualType>>
2443 getObjCSubstitutions(const DeclContext *dc) const;
2444
2445 /// Determines if this is an ObjC interface type that may accept type
2446 /// parameters.
2447 bool acceptsObjCTypeParams() const;
2448
2449 const char *getTypeClassName() const;
2450
2451 QualType getCanonicalTypeInternal() const {
2452 return CanonicalType;
2453 }
2454
2455 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2456 void dump() const;
2457 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2458};
2459
2460/// This will check for a TypedefType by removing any existing sugar
2461/// until it reaches a TypedefType or a non-sugared type.
2462template <> const TypedefType *Type::getAs() const;
2463
2464/// This will check for a TemplateSpecializationType by removing any
2465/// existing sugar until it reaches a TemplateSpecializationType or a
2466/// non-sugared type.
2467template <> const TemplateSpecializationType *Type::getAs() const;
2468
2469/// This will check for an AttributedType by removing any existing sugar
2470/// until it reaches an AttributedType or a non-sugared type.
2471template <> const AttributedType *Type::getAs() const;
2472
2473// We can do canonical leaf types faster, because we don't have to
2474// worry about preserving child type decoration.
2475#define TYPE(Class, Base)
2476#define LEAF_TYPE(Class) \
2477template <> inline const Class##Type *Type::getAs() const { \
2478 return dyn_cast<Class##Type>(CanonicalType); \
2479} \
2480template <> inline const Class##Type *Type::castAs() const { \
2481 return cast<Class##Type>(CanonicalType); \
2482}
2483#include "clang/AST/TypeNodes.inc"
2484
2485/// This class is used for builtin types like 'int'. Builtin
2486/// types are always canonical and have a literal name field.
2487class BuiltinType : public Type {
2488public:
2489 enum Kind {
2490// OpenCL image types
2491#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2492#include "clang/Basic/OpenCLImageTypes.def"
2493// OpenCL extension types
2494#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2495#include "clang/Basic/OpenCLExtensionTypes.def"
2496// SVE Types
2497#define SVE_TYPE(Name, Id, SingletonId) Id,
2498#include "clang/Basic/AArch64SVEACLETypes.def"
2499// PPC MMA Types
2500#define PPC_VECTOR_TYPE(Name, Id, Size) Id,
2501#include "clang/Basic/PPCTypes.def"
2502// RVV Types
2503#define RVV_TYPE(Name, Id, SingletonId) Id,
2504#include "clang/Basic/RISCVVTypes.def"
2505// All other builtin types
2506#define BUILTIN_TYPE(Id, SingletonId) Id,
2507#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2508#include "clang/AST/BuiltinTypes.def"
2509 };
2510
2511private:
2512 friend class ASTContext; // ASTContext creates these.
2513
2514 BuiltinType(Kind K)
2515 : Type(Builtin, QualType(),
2516 K == Dependent ? TypeDependence::DependentInstantiation
2517 : TypeDependence::None) {
2518 BuiltinTypeBits.Kind = K;
2519 }
2520
2521public:
2522 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2523 StringRef getName(const PrintingPolicy &Policy) const;
2524
2525 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2526 // The StringRef is null-terminated.
2527 StringRef str = getName(Policy);
2528 assert(!str.empty() && str.data()[str.size()] == '\0')(static_cast <bool> (!str.empty() && str.data()
[str.size()] == '\0') ? void (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 2528, __extension__ __PRETTY_FUNCTION__))
;
2529 return str.data();
2530 }
2531
2532 bool isSugared() const { return false; }
2533 QualType desugar() const { return QualType(this, 0); }
2534
2535 bool isInteger() const {
2536 return getKind() >= Bool && getKind() <= Int128;
2537 }
2538
2539 bool isSignedInteger() const {
2540 return getKind() >= Char_S && getKind() <= Int128;
2541 }
2542
2543 bool isUnsignedInteger() const {
2544 return getKind() >= Bool && getKind() <= UInt128;
2545 }
2546
2547 bool isFloatingPoint() const {
2548 return getKind() >= Half && getKind() <= Float128;
2549 }
2550
2551 /// Determines whether the given kind corresponds to a placeholder type.
2552 static bool isPlaceholderTypeKind(Kind K) {
2553 return K >= Overload;
2554 }
2555
2556 /// Determines whether this type is a placeholder type, i.e. a type
2557 /// which cannot appear in arbitrary positions in a fully-formed
2558 /// expression.
2559 bool isPlaceholderType() const {
2560 return isPlaceholderTypeKind(getKind());
2561 }
2562
2563 /// Determines whether this type is a placeholder type other than
2564 /// Overload. Most placeholder types require only syntactic
2565 /// information about their context in order to be resolved (e.g.
2566 /// whether it is a call expression), which means they can (and
2567 /// should) be resolved in an earlier "phase" of analysis.
2568 /// Overload expressions sometimes pick up further information
2569 /// from their context, like whether the context expects a
2570 /// specific function-pointer type, and so frequently need
2571 /// special treatment.
2572 bool isNonOverloadPlaceholderType() const {
2573 return getKind() > Overload;
2574 }
2575
2576 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2577};
2578
2579/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2580/// types (_Complex float etc) as well as the GCC integer complex extensions.
2581class ComplexType : public Type, public llvm::FoldingSetNode {
2582 friend class ASTContext; // ASTContext creates these.
2583
2584 QualType ElementType;
2585
2586 ComplexType(QualType Element, QualType CanonicalPtr)
2587 : Type(Complex, CanonicalPtr, Element->getDependence()),
2588 ElementType(Element) {}
2589
2590public:
2591 QualType getElementType() const { return ElementType; }
2592
2593 bool isSugared() const { return false; }
2594 QualType desugar() const { return QualType(this, 0); }
2595
2596 void Profile(llvm::FoldingSetNodeID &ID) {
2597 Profile(ID, getElementType());
2598 }
2599
2600 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2601 ID.AddPointer(Element.getAsOpaquePtr());
2602 }
2603
2604 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2605};
2606
2607/// Sugar for parentheses used when specifying types.
2608class ParenType : public Type, public llvm::FoldingSetNode {
2609 friend class ASTContext; // ASTContext creates these.
2610
2611 QualType Inner;
2612
2613 ParenType(QualType InnerType, QualType CanonType)
2614 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2615
2616public:
2617 QualType getInnerType() const { return Inner; }
2618
2619 bool isSugared() const { return true; }
2620 QualType desugar() const { return getInnerType(); }
2621
2622 void Profile(llvm::FoldingSetNodeID &ID) {
2623 Profile(ID, getInnerType());
2624 }
2625
2626 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2627 Inner.Profile(ID);
2628 }
2629
2630 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2631};
2632
2633/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2634class PointerType : public Type, public llvm::FoldingSetNode {
2635 friend class ASTContext; // ASTContext creates these.
2636
2637 QualType PointeeType;
2638
2639 PointerType(QualType Pointee, QualType CanonicalPtr)
2640 : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2641 PointeeType(Pointee) {}
2642
2643public:
2644 QualType getPointeeType() const { return PointeeType; }
2645
2646 bool isSugared() const { return false; }
2647 QualType desugar() const { return QualType(this, 0); }
2648
2649 void Profile(llvm::FoldingSetNodeID &ID) {
2650 Profile(ID, getPointeeType());
2651 }
2652
2653 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2654 ID.AddPointer(Pointee.getAsOpaquePtr());
2655 }
2656
2657 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2658};
2659
2660/// Represents a type which was implicitly adjusted by the semantic
2661/// engine for arbitrary reasons. For example, array and function types can
2662/// decay, and function types can have their calling conventions adjusted.
2663class AdjustedType : public Type, public llvm::FoldingSetNode {
2664 QualType OriginalTy;
2665 QualType AdjustedTy;
2666
2667protected:
2668 friend class ASTContext; // ASTContext creates these.
2669
2670 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2671 QualType CanonicalPtr)
2672 : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
2673 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2674
2675public:
2676 QualType getOriginalType() const { return OriginalTy; }
2677 QualType getAdjustedType() const { return AdjustedTy; }
2678
2679 bool isSugared() const { return true; }
2680 QualType desugar() const { return AdjustedTy; }
2681
2682 void Profile(llvm::FoldingSetNodeID &ID) {
2683 Profile(ID, OriginalTy, AdjustedTy);
2684 }
2685
2686 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2687 ID.AddPointer(Orig.getAsOpaquePtr());
2688 ID.AddPointer(New.getAsOpaquePtr());
2689 }
2690
2691 static bool classof(const Type *T) {
2692 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2693 }
2694};
2695
2696/// Represents a pointer type decayed from an array or function type.
2697class DecayedType : public AdjustedType {
2698 friend class ASTContext; // ASTContext creates these.
2699
2700 inline
2701 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2702
2703public:
2704 QualType getDecayedType() const { return getAdjustedType(); }
2705
2706 inline QualType getPointeeType() const;
2707
2708 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2709};
2710
2711/// Pointer to a block type.
2712/// This type is to represent types syntactically represented as
2713/// "void (^)(int)", etc. Pointee is required to always be a function type.
2714class BlockPointerType : public Type, public llvm::FoldingSetNode {
2715 friend class ASTContext; // ASTContext creates these.
2716
2717 // Block is some kind of pointer type
2718 QualType PointeeType;
2719
2720 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2721 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
2722 PointeeType(Pointee) {}
2723
2724public:
2725 // Get the pointee type. Pointee is required to always be a function type.
2726 QualType getPointeeType() const { return PointeeType; }
2727
2728 bool isSugared() const { return false; }
2729 QualType desugar() const { return QualType(this, 0); }
2730
2731 void Profile(llvm::FoldingSetNodeID &ID) {
2732 Profile(ID, getPointeeType());
2733 }
2734
2735 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2736 ID.AddPointer(Pointee.getAsOpaquePtr());
2737 }
2738
2739 static bool classof(const Type *T) {
2740 return T->getTypeClass() == BlockPointer;
2741 }
2742};
2743
2744/// Base for LValueReferenceType and RValueReferenceType
2745class ReferenceType : public Type, public llvm::FoldingSetNode {
2746 QualType PointeeType;
2747
2748protected:
2749 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2750 bool SpelledAsLValue)
2751 : Type(tc, CanonicalRef, Referencee->getDependence()),
2752 PointeeType(Referencee) {
2753 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2754 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2755 }
2756
2757public:
2758 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2759 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2760
2761 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2762
2763 QualType getPointeeType() const {
2764 // FIXME: this might strip inner qualifiers; okay?
2765 const ReferenceType *T = this;
2766 while (T->isInnerRef())
2767 T = T->PointeeType->castAs<ReferenceType>();
2768 return T->PointeeType;
2769 }
2770
2771 void Profile(llvm::FoldingSetNodeID &ID) {
2772 Profile(ID, PointeeType, isSpelledAsLValue());
2773 }
2774
2775 static void Profile(llvm::FoldingSetNodeID &ID,
2776 QualType Referencee,
2777 bool SpelledAsLValue) {
2778 ID.AddPointer(Referencee.getAsOpaquePtr());
2779 ID.AddBoolean(SpelledAsLValue);
2780 }
2781
2782 static bool classof(const Type *T) {
2783 return T->getTypeClass() == LValueReference ||
2784 T->getTypeClass() == RValueReference;
2785 }
2786};
2787
2788/// An lvalue reference type, per C++11 [dcl.ref].
2789class LValueReferenceType : public ReferenceType {
2790 friend class ASTContext; // ASTContext creates these
2791
2792 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2793 bool SpelledAsLValue)
2794 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2795 SpelledAsLValue) {}
2796
2797public:
2798 bool isSugared() const { return false; }
2799 QualType desugar() const { return QualType(this, 0); }
2800
2801 static bool classof(const Type *T) {
2802 return T->getTypeClass() == LValueReference;
2803 }
2804};
2805
2806/// An rvalue reference type, per C++11 [dcl.ref].
2807class RValueReferenceType : public ReferenceType {
2808 friend class ASTContext; // ASTContext creates these
2809
2810 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2811 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2812
2813public:
2814 bool isSugared() const { return false; }
2815 QualType desugar() const { return QualType(this, 0); }
2816
2817 static bool classof(const Type *T) {
2818 return T->getTypeClass() == RValueReference;
2819 }
2820};
2821
2822/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2823///
2824/// This includes both pointers to data members and pointer to member functions.
2825class MemberPointerType : public Type, public llvm::FoldingSetNode {
2826 friend class ASTContext; // ASTContext creates these.
2827
2828 QualType PointeeType;
2829
2830 /// The class of which the pointee is a member. Must ultimately be a
2831 /// RecordType, but could be a typedef or a template parameter too.
2832 const Type *Class;
2833
2834 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2835 : Type(MemberPointer, CanonicalPtr,
2836 (Cls->getDependence() & ~TypeDependence::VariablyModified) |
2837 Pointee->getDependence()),
2838 PointeeType(Pointee), Class(Cls) {}
2839
2840public:
2841 QualType getPointeeType() const { return PointeeType; }
2842
2843 /// Returns true if the member type (i.e. the pointee type) is a
2844 /// function type rather than a data-member type.
2845 bool isMemberFunctionPointer() const {
2846 return PointeeType->isFunctionProtoType();
2847 }
2848
2849 /// Returns true if the member type (i.e. the pointee type) is a
2850 /// data type rather than a function type.
2851 bool isMemberDataPointer() const {
2852 return !PointeeType->isFunctionProtoType();
2853 }
2854
2855 const Type *getClass() const { return Class; }
2856 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2857
2858 bool isSugared() const { return false; }
2859 QualType desugar() const { return QualType(this, 0); }
2860
2861 void Profile(llvm::FoldingSetNodeID &ID) {
2862 Profile(ID, getPointeeType(), getClass());
2863 }
2864
2865 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2866 const Type *Class) {
2867 ID.AddPointer(Pointee.getAsOpaquePtr());
2868 ID.AddPointer(Class);
2869 }
2870
2871 static bool classof(const Type *T) {
2872 return T->getTypeClass() == MemberPointer;
2873 }
2874};
2875
2876/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2877class ArrayType : public Type, public llvm::FoldingSetNode {
2878public:
2879 /// Capture whether this is a normal array (e.g. int X[4])
2880 /// an array with a static size (e.g. int X[static 4]), or an array
2881 /// with a star size (e.g. int X[*]).
2882 /// 'static' is only allowed on function parameters.
2883 enum ArraySizeModifier {
2884 Normal, Static, Star
2885 };
2886
2887private:
2888 /// The element type of the array.
2889 QualType ElementType;
2890
2891protected:
2892 friend class ASTContext; // ASTContext creates these.
2893
2894 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2895 unsigned tq, const Expr *sz = nullptr);
2896
2897public:
2898 QualType getElementType() const { return ElementType; }
2899
2900 ArraySizeModifier getSizeModifier() const {
2901 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2902 }
2903
2904 Qualifiers getIndexTypeQualifiers() const {
2905 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2906 }
2907
2908 unsigned getIndexTypeCVRQualifiers() const {
2909 return ArrayTypeBits.IndexTypeQuals;
2910 }
2911
2912 static bool classof(const Type *T) {
2913 return T->getTypeClass() == ConstantArray ||
2914 T->getTypeClass() == VariableArray ||
2915 T->getTypeClass() == IncompleteArray ||
2916 T->getTypeClass() == DependentSizedArray;
2917 }
2918};
2919
2920/// Represents the canonical version of C arrays with a specified constant size.
2921/// For example, the canonical type for 'int A[4 + 4*100]' is a
2922/// ConstantArrayType where the element type is 'int' and the size is 404.
2923class ConstantArrayType final
2924 : public ArrayType,
2925 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2926 friend class ASTContext; // ASTContext creates these.
2927 friend TrailingObjects;
2928
2929 llvm::APInt Size; // Allows us to unique the type.
2930
2931 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2932 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2933 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2934 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2935 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2936 assert(!can.isNull() && "canonical constant array should not have size")(static_cast <bool> (!can.isNull() && "canonical constant array should not have size"
) ? void (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 2936, __extension__ __PRETTY_FUNCTION__))
;
2937 *getTrailingObjects<const Expr*>() = sz;
2938 }
2939 }
2940
2941 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2942 return ConstantArrayTypeBits.HasStoredSizeExpr;
2943 }
2944
2945public:
2946 const llvm::APInt &getSize() const { return Size; }
2947 const Expr *getSizeExpr() const {
2948 return ConstantArrayTypeBits.HasStoredSizeExpr
2949 ? *getTrailingObjects<const Expr *>()
2950 : nullptr;
2951 }
2952 bool isSugared() const { return false; }
2953 QualType desugar() const { return QualType(this, 0); }
2954
2955 /// Determine the number of bits required to address a member of
2956 // an array with the given element type and number of elements.
2957 static unsigned getNumAddressingBits(const ASTContext &Context,
2958 QualType ElementType,
2959 const llvm::APInt &NumElements);
2960
2961 /// Determine the maximum number of active bits that an array's size
2962 /// can require, which limits the maximum size of the array.
2963 static unsigned getMaxSizeBits(const ASTContext &Context);
2964
2965 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2966 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
2967 getSizeModifier(), getIndexTypeCVRQualifiers());
2968 }
2969
2970 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2971 QualType ET, const llvm::APInt &ArraySize,
2972 const Expr *SizeExpr, ArraySizeModifier SizeMod,
2973 unsigned TypeQuals);
2974
2975 static bool classof(const Type *T) {
2976 return T->getTypeClass() == ConstantArray;
2977 }
2978};
2979
2980/// Represents a C array with an unspecified size. For example 'int A[]' has
2981/// an IncompleteArrayType where the element type is 'int' and the size is
2982/// unspecified.
2983class IncompleteArrayType : public ArrayType {
2984 friend class ASTContext; // ASTContext creates these.
2985
2986 IncompleteArrayType(QualType et, QualType can,
2987 ArraySizeModifier sm, unsigned tq)
2988 : ArrayType(IncompleteArray, et, can, sm, tq) {}
2989
2990public:
2991 friend class StmtIteratorBase;
2992
2993 bool isSugared() const { return false; }
2994 QualType desugar() const { return QualType(this, 0); }
2995
2996 static bool classof(const Type *T) {
2997 return T->getTypeClass() == IncompleteArray;
2998 }
2999
3000 void Profile(llvm::FoldingSetNodeID &ID) {
3001 Profile(ID, getElementType(), getSizeModifier(),
3002 getIndexTypeCVRQualifiers());
3003 }
3004
3005 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
3006 ArraySizeModifier SizeMod, unsigned TypeQuals) {
3007 ID.AddPointer(ET.getAsOpaquePtr());
3008 ID.AddInteger(SizeMod);
3009 ID.AddInteger(TypeQuals);
3010 }
3011};
3012
3013/// Represents a C array with a specified size that is not an
3014/// integer-constant-expression. For example, 'int s[x+foo()]'.
3015/// Since the size expression is an arbitrary expression, we store it as such.
3016///
3017/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3018/// should not be: two lexically equivalent variable array types could mean
3019/// different things, for example, these variables do not have the same type
3020/// dynamically:
3021///
3022/// void foo(int x) {
3023/// int Y[x];
3024/// ++x;
3025/// int Z[x];
3026/// }
3027class VariableArrayType : public ArrayType {
3028 friend class ASTContext; // ASTContext creates these.
3029
3030 /// An assignment-expression. VLA's are only permitted within
3031 /// a function block.
3032 Stmt *SizeExpr;
3033
3034 /// The range spanned by the left and right array brackets.
3035 SourceRange Brackets;
3036
3037 VariableArrayType(QualType et, QualType can, Expr *e,
3038 ArraySizeModifier sm, unsigned tq,
3039 SourceRange brackets)
3040 : ArrayType(VariableArray, et, can, sm, tq, e),
3041 SizeExpr((Stmt*) e), Brackets(brackets) {}
3042
3043public:
3044 friend class StmtIteratorBase;
3045
3046 Expr *getSizeExpr() const {
3047 // We use C-style casts instead of cast<> here because we do not wish
3048 // to have a dependency of Type.h on Stmt.h/Expr.h.
3049 return (Expr*) SizeExpr;
3050 }
3051
3052 SourceRange getBracketsRange() const { return Brackets; }
3053 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3054 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3055
3056 bool isSugared() const { return false; }
3057 QualType desugar() const { return QualType(this, 0); }
3058
3059 static bool classof(const Type *T) {
3060 return T->getTypeClass() == VariableArray;
3061 }
3062
3063 void Profile(llvm::FoldingSetNodeID &ID) {
3064 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 3064)
;
3065 }
3066};
3067
3068/// Represents an array type in C++ whose size is a value-dependent expression.
3069///
3070/// For example:
3071/// \code
3072/// template<typename T, int Size>
3073/// class array {
3074/// T data[Size];
3075/// };
3076/// \endcode
3077///
3078/// For these types, we won't actually know what the array bound is
3079/// until template instantiation occurs, at which point this will
3080/// become either a ConstantArrayType or a VariableArrayType.
3081class DependentSizedArrayType : public ArrayType {
3082 friend class ASTContext; // ASTContext creates these.
3083
3084 const ASTContext &Context;
3085
3086 /// An assignment expression that will instantiate to the
3087 /// size of the array.
3088 ///
3089 /// The expression itself might be null, in which case the array
3090 /// type will have its size deduced from an initializer.
3091 Stmt *SizeExpr;
3092
3093 /// The range spanned by the left and right array brackets.
3094 SourceRange Brackets;
3095
3096 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3097 Expr *e, ArraySizeModifier sm, unsigned tq,
3098 SourceRange brackets);
3099
3100public:
3101 friend class StmtIteratorBase;
3102
3103 Expr *getSizeExpr() const {
3104 // We use C-style casts instead of cast<> here because we do not wish
3105 // to have a dependency of Type.h on Stmt.h/Expr.h.
3106 return (Expr*) SizeExpr;
3107 }
3108
3109 SourceRange getBracketsRange() const { return Brackets; }
3110 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3111 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3112
3113 bool isSugared() const { return false; }
3114 QualType desugar() const { return QualType(this, 0); }
3115
3116 static bool classof(const Type *T) {
3117 return T->getTypeClass() == DependentSizedArray;
3118 }
3119
3120 void Profile(llvm::FoldingSetNodeID &ID) {
3121 Profile(ID, Context, getElementType(),
3122 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3123 }
3124
3125 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3126 QualType ET, ArraySizeModifier SizeMod,
3127 unsigned TypeQuals, Expr *E);
3128};
3129
3130/// Represents an extended address space qualifier where the input address space
3131/// value is dependent. Non-dependent address spaces are not represented with a
3132/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3133///
3134/// For example:
3135/// \code
3136/// template<typename T, int AddrSpace>
3137/// class AddressSpace {
3138/// typedef T __attribute__((address_space(AddrSpace))) type;
3139/// }
3140/// \endcode
3141class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3142 friend class ASTContext;
3143
3144 const ASTContext &Context;
3145 Expr *AddrSpaceExpr;
3146 QualType PointeeType;
3147 SourceLocation loc;
3148
3149 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3150 QualType can, Expr *AddrSpaceExpr,
3151 SourceLocation loc);
3152
3153public:
3154 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3155 QualType getPointeeType() const { return PointeeType; }
3156 SourceLocation getAttributeLoc() const { return loc; }
3157
3158 bool isSugared() const { return false; }
3159 QualType desugar() const { return QualType(this, 0); }
3160
3161 static bool classof(const Type *T) {
3162 return T->getTypeClass() == DependentAddressSpace;
3163 }
3164
3165 void Profile(llvm::FoldingSetNodeID &ID) {
3166 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3167 }
3168
3169 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3170 QualType PointeeType, Expr *AddrSpaceExpr);
3171};
3172
3173/// Represents an extended vector type where either the type or size is
3174/// dependent.
3175///
3176/// For example:
3177/// \code
3178/// template<typename T, int Size>
3179/// class vector {
3180/// typedef T __attribute__((ext_vector_type(Size))) type;
3181/// }
3182/// \endcode
3183class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3184 friend class ASTContext;
3185
3186 const ASTContext &Context;
3187 Expr *SizeExpr;
3188
3189 /// The element type of the array.
3190 QualType ElementType;
3191
3192 SourceLocation loc;
3193
3194 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3195 QualType can, Expr *SizeExpr, SourceLocation loc);
3196
3197public:
3198 Expr *getSizeExpr() const { return SizeExpr; }
3199 QualType getElementType() const { return ElementType; }
3200 SourceLocation getAttributeLoc() const { return loc; }
3201
3202 bool isSugared() const { return false; }
3203 QualType desugar() const { return QualType(this, 0); }
3204
3205 static bool classof(const Type *T) {
3206 return T->getTypeClass() == DependentSizedExtVector;
3207 }
3208
3209 void Profile(llvm::FoldingSetNodeID &ID) {
3210 Profile(ID, Context, getElementType(), getSizeExpr());
3211 }
3212
3213 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3214 QualType ElementType, Expr *SizeExpr);
3215};
3216
3217
3218/// Represents a GCC generic vector type. This type is created using
3219/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3220/// bytes; or from an Altivec __vector or vector declaration.
3221/// Since the constructor takes the number of vector elements, the
3222/// client is responsible for converting the size into the number of elements.
3223class VectorType : public Type, public llvm::FoldingSetNode {
3224public:
3225 enum VectorKind {
3226 /// not a target-specific vector type
3227 GenericVector,
3228
3229 /// is AltiVec vector
3230 AltiVecVector,
3231
3232 /// is AltiVec 'vector Pixel'
3233 AltiVecPixel,
3234
3235 /// is AltiVec 'vector bool ...'
3236 AltiVecBool,
3237
3238 /// is ARM Neon vector
3239 NeonVector,
3240
3241 /// is ARM Neon polynomial vector
3242 NeonPolyVector,
3243
3244 /// is AArch64 SVE fixed-length data vector
3245 SveFixedLengthDataVector,
3246
3247 /// is AArch64 SVE fixed-length predicate vector
3248 SveFixedLengthPredicateVector
3249 };
3250
3251protected:
3252 friend class ASTContext; // ASTContext creates these.
3253
3254 /// The element type of the vector.
3255 QualType ElementType;
3256
3257 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3258 VectorKind vecKind);
3259
3260 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3261 QualType canonType, VectorKind vecKind);
3262
3263public:
3264 QualType getElementType() const { return ElementType; }
3265 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3266
3267 bool isSugared() const { return false; }
3268 QualType desugar() const { return QualType(this, 0); }
3269
3270 VectorKind getVectorKind() const {
3271 return VectorKind(VectorTypeBits.VecKind);
3272 }
3273
3274 void Profile(llvm::FoldingSetNodeID &ID) {
3275 Profile(ID, getElementType(), getNumElements(),
3276 getTypeClass(), getVectorKind());
3277 }
3278
3279 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3280 unsigned NumElements, TypeClass TypeClass,
3281 VectorKind VecKind) {
3282 ID.AddPointer(ElementType.getAsOpaquePtr());
3283 ID.AddInteger(NumElements);
3284 ID.AddInteger(TypeClass);
3285 ID.AddInteger(VecKind);
3286 }
3287
3288 static bool classof(const Type *T) {
3289 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3290 }
3291};
3292
3293/// Represents a vector type where either the type or size is dependent.
3294////
3295/// For example:
3296/// \code
3297/// template<typename T, int Size>
3298/// class vector {
3299/// typedef T __attribute__((vector_size(Size))) type;
3300/// }
3301/// \endcode
3302class DependentVectorType : public Type, public llvm::FoldingSetNode {
3303 friend class ASTContext;
3304
3305 const ASTContext &Context;
3306 QualType ElementType;
3307 Expr *SizeExpr;
3308 SourceLocation Loc;
3309
3310 DependentVectorType(const ASTContext &Context, QualType ElementType,
3311 QualType CanonType, Expr *SizeExpr,
3312 SourceLocation Loc, VectorType::VectorKind vecKind);
3313
3314public:
3315 Expr *getSizeExpr() const { return SizeExpr; }
3316 QualType getElementType() const { return ElementType; }
3317 SourceLocation getAttributeLoc() const { return Loc; }
3318 VectorType::VectorKind getVectorKind() const {
3319 return VectorType::VectorKind(VectorTypeBits.VecKind);
3320 }
3321
3322 bool isSugared() const { return false; }
3323 QualType desugar() const { return QualType(this, 0); }
3324
3325 static bool classof(const Type *T) {
3326 return T->getTypeClass() == DependentVector;
3327 }
3328
3329 void Profile(llvm::FoldingSetNodeID &ID) {
3330 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3331 }
3332
3333 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3334 QualType ElementType, const Expr *SizeExpr,
3335 VectorType::VectorKind VecKind);
3336};
3337
3338/// ExtVectorType - Extended vector type. This type is created using
3339/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3340/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3341/// class enables syntactic extensions, like Vector Components for accessing
3342/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3343/// Shading Language).
3344class ExtVectorType : public VectorType {
3345 friend class ASTContext; // ASTContext creates these.
3346
3347 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3348 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3349
3350public:
3351 static int getPointAccessorIdx(char c) {
3352 switch (c) {
3353 default: return -1;
3354 case 'x': case 'r': return 0;
3355 case 'y': case 'g': return 1;
3356 case 'z': case 'b': return 2;
3357 case 'w': case 'a': return 3;
3358 }
3359 }
3360
3361 static int getNumericAccessorIdx(char c) {
3362 switch (c) {
3363 default: return -1;
3364 case '0': return 0;
3365 case '1': return 1;
3366 case '2': return 2;
3367 case '3': return 3;
3368 case '4': return 4;
3369 case '5': return 5;
3370 case '6': return 6;
3371 case '7': return 7;
3372 case '8': return 8;
3373 case '9': return 9;
3374 case 'A':
3375 case 'a': return 10;
3376 case 'B':
3377 case 'b': return 11;
3378 case 'C':
3379 case 'c': return 12;
3380 case 'D':
3381 case 'd': return 13;
3382 case 'E':
3383 case 'e': return 14;
3384 case 'F':
3385 case 'f': return 15;
3386 }
3387 }
3388
3389 static int getAccessorIdx(char c, bool isNumericAccessor) {
3390 if (isNumericAccessor)
3391 return getNumericAccessorIdx(c);
3392 else
3393 return getPointAccessorIdx(c);
3394 }
3395
3396 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3397 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3398 return unsigned(idx-1) < getNumElements();
3399 return false;
3400 }
3401
3402 bool isSugared() const { return false; }
3403 QualType desugar() const { return QualType(this, 0); }
3404
3405 static bool classof(const Type *T) {
3406 return T->getTypeClass() == ExtVector;
3407 }
3408};
3409
3410/// Represents a matrix type, as defined in the Matrix Types clang extensions.
3411/// __attribute__((matrix_type(rows, columns))), where "rows" specifies
3412/// number of rows and "columns" specifies the number of columns.
3413class MatrixType : public Type, public llvm::FoldingSetNode {
3414protected:
3415 friend class ASTContext;
3416
3417 /// The element type of the matrix.
3418 QualType ElementType;
3419
3420 MatrixType(QualType ElementTy, QualType CanonElementTy);
3421
3422 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
3423 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
3424
3425public:
3426 /// Returns type of the elements being stored in the matrix
3427 QualType getElementType() const { return ElementType; }
3428
3429 /// Valid elements types are the following:
3430 /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types
3431 /// and _Bool
3432 /// * the standard floating types float or double
3433 /// * a half-precision floating point type, if one is supported on the target
3434 static bool isValidElementType(QualType T) {
3435 return T->isDependentType() ||
3436 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
3437 }
3438
3439 bool isSugared() const { return false; }
3440 QualType desugar() const { return QualType(this, 0); }
3441
3442 static bool classof(const Type *T) {
3443 return T->getTypeClass() == ConstantMatrix ||
3444 T->getTypeClass() == DependentSizedMatrix;
3445 }
3446};
3447
3448/// Represents a concrete matrix type with constant number of rows and columns
3449class ConstantMatrixType final : public MatrixType {
3450protected:
3451 friend class ASTContext;
3452
3453 /// The element type of the matrix.
3454 // FIXME: Appears to be unused? There is also MatrixType::ElementType...
3455 QualType ElementType;
3456
3457 /// Number of rows and columns.
3458 unsigned NumRows;
3459 unsigned NumColumns;
3460
3461 static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
3462
3463 ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
3464 unsigned NColumns, QualType CanonElementType);
3465
3466 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
3467 unsigned NColumns, QualType CanonElementType);
3468
3469public:
3470 /// Returns the number of rows in the matrix.
3471 unsigned getNumRows() const { return NumRows; }
3472
3473 /// Returns the number of columns in the matrix.
3474 unsigned getNumColumns() const { return NumColumns; }
3475
3476 /// Returns the number of elements required to embed the matrix into a vector.
3477 unsigned getNumElementsFlattened() const {
3478 return getNumRows() * getNumColumns();
3479 }
3480
3481 /// Returns true if \p NumElements is a valid matrix dimension.
3482 static constexpr bool isDimensionValid(size_t NumElements) {
3483 return NumElements > 0 && NumElements <= MaxElementsPerDimension;
3484 }
3485
3486 /// Returns the maximum number of elements per dimension.
3487 static constexpr unsigned getMaxElementsPerDimension() {
3488 return MaxElementsPerDimension;
3489 }
3490
3491 void Profile(llvm::FoldingSetNodeID &ID) {
3492 Profile(ID, getElementType(), getNumRows(), getNumColumns(),
3493 getTypeClass());
3494 }
3495
3496 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3497 unsigned NumRows, unsigned NumColumns,
3498 TypeClass TypeClass) {
3499 ID.AddPointer(ElementType.getAsOpaquePtr());
3500 ID.AddInteger(NumRows);
3501 ID.AddInteger(NumColumns);
3502 ID.AddInteger(TypeClass);
3503 }
3504
3505 static bool classof(const Type *T) {
3506 return T->getTypeClass() == ConstantMatrix;
3507 }
3508};
3509
3510/// Represents a matrix type where the type and the number of rows and columns
3511/// is dependent on a template.
3512class DependentSizedMatrixType final : public MatrixType {
3513 friend class ASTContext;
3514
3515 const ASTContext &Context;
3516 Expr *RowExpr;
3517 Expr *ColumnExpr;
3518
3519 SourceLocation loc;
3520
3521 DependentSizedMatrixType(const ASTContext &Context, QualType ElementType,
3522 QualType CanonicalType, Expr *RowExpr,
3523 Expr *ColumnExpr, SourceLocation loc);
3524
3525public:
3526 QualType getElementType() const { return ElementType; }
3527 Expr *getRowExpr() const { return RowExpr; }
3528 Expr *getColumnExpr() const { return ColumnExpr; }
3529 SourceLocation getAttributeLoc() const { return loc; }
3530
3531 bool isSugared() const { return false; }
3532 QualType desugar() const { return QualType(this, 0); }
3533
3534 static bool classof(const Type *T) {
3535 return T->getTypeClass() == DependentSizedMatrix;
3536 }
3537
3538 void Profile(llvm::FoldingSetNodeID &ID) {
3539 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
3540 }
3541
3542 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3543 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
3544};
3545
3546/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3547/// class of FunctionNoProtoType and FunctionProtoType.
3548class FunctionType : public Type {
3549 // The type returned by the function.
3550 QualType ResultType;
3551
3552public:
3553 /// Interesting information about a specific parameter that can't simply
3554 /// be reflected in parameter's type. This is only used by FunctionProtoType
3555 /// but is in FunctionType to make this class available during the
3556 /// specification of the bases of FunctionProtoType.
3557 ///
3558 /// It makes sense to model language features this way when there's some
3559 /// sort of parameter-specific override (such as an attribute) that
3560 /// affects how the function is called. For example, the ARC ns_consumed
3561 /// attribute changes whether a parameter is passed at +0 (the default)
3562 /// or +1 (ns_consumed). This must be reflected in the function type,
3563 /// but isn't really a change to the parameter type.
3564 ///
3565 /// One serious disadvantage of modelling language features this way is
3566 /// that they generally do not work with language features that attempt
3567 /// to destructure types. For example, template argument deduction will
3568 /// not be able to match a parameter declared as
3569 /// T (*)(U)
3570 /// against an argument of type
3571 /// void (*)(__attribute__((ns_consumed)) id)
3572 /// because the substitution of T=void, U=id into the former will
3573 /// not produce the latter.
3574 class ExtParameterInfo {
3575 enum {
3576 ABIMask = 0x0F,
3577 IsConsumed = 0x10,
3578 HasPassObjSize = 0x20,
3579 IsNoEscape = 0x40,
3580 };
3581 unsigned char Data = 0;
3582
3583 public:
3584 ExtParameterInfo() = default;
3585
3586 /// Return the ABI treatment of this parameter.
3587 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3588 ExtParameterInfo withABI(ParameterABI kind) const {
3589 ExtParameterInfo copy = *this;
3590 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3591 return copy;
3592 }
3593
3594 /// Is this parameter considered "consumed" by Objective-C ARC?
3595 /// Consumed parameters must have retainable object type.
3596 bool isConsumed() const { return (Data & IsConsumed); }
3597 ExtParameterInfo withIsConsumed(bool consumed) const {
3598 ExtParameterInfo copy = *this;
3599 if (consumed)
3600 copy.Data |= IsConsumed;
3601 else
3602 copy.Data &= ~IsConsumed;
3603 return copy;
3604 }
3605
3606 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3607 ExtParameterInfo withHasPassObjectSize() const {
3608 ExtParameterInfo Copy = *this;
3609 Copy.Data |= HasPassObjSize;
3610 return Copy;
3611 }
3612
3613 bool isNoEscape() const { return Data & IsNoEscape; }
3614 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3615 ExtParameterInfo Copy = *this;
3616 if (NoEscape)
3617 Copy.Data |= IsNoEscape;
3618 else
3619 Copy.Data &= ~IsNoEscape;
3620 return Copy;
3621 }
3622
3623 unsigned char getOpaqueValue() const { return Data; }
3624 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3625 ExtParameterInfo result;
3626 result.Data = data;
3627 return result;
3628 }
3629
3630 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3631 return lhs.Data == rhs.Data;
3632 }
3633
3634 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3635 return lhs.Data != rhs.Data;
3636 }
3637 };
3638
3639 /// A class which abstracts out some details necessary for
3640 /// making a call.
3641 ///
3642 /// It is not actually used directly for storing this information in
3643 /// a FunctionType, although FunctionType does currently use the
3644 /// same bit-pattern.
3645 ///
3646 // If you add a field (say Foo), other than the obvious places (both,
3647 // constructors, compile failures), what you need to update is
3648 // * Operator==
3649 // * getFoo
3650 // * withFoo
3651 // * functionType. Add Foo, getFoo.
3652 // * ASTContext::getFooType
3653 // * ASTContext::mergeFunctionTypes
3654 // * FunctionNoProtoType::Profile
3655 // * FunctionProtoType::Profile
3656 // * TypePrinter::PrintFunctionProto
3657 // * AST read and write
3658 // * Codegen
3659 class ExtInfo {
3660 friend class FunctionType;
3661
3662 // Feel free to rearrange or add bits, but if you go over 16, you'll need to
3663 // adjust the Bits field below, and if you add bits, you'll need to adjust
3664 // Type::FunctionTypeBitfields::ExtInfo as well.
3665
3666 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
3667 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 |
3668 //
3669 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3670 enum { CallConvMask = 0x1F };
3671 enum { NoReturnMask = 0x20 };
3672 enum { ProducesResultMask = 0x40 };
3673 enum { NoCallerSavedRegsMask = 0x80 };
3674 enum {
3675 RegParmMask = 0x700,
3676 RegParmOffset = 8
3677 };
3678 enum { NoCfCheckMask = 0x800 };
3679 enum { CmseNSCallMask = 0x1000 };
3680 uint16_t Bits = CC_C;
3681
3682 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3683
3684 public:
3685 // Constructor with no defaults. Use this when you know that you
3686 // have all the elements (when reading an AST file for example).
3687 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3688 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck,
3689 bool cmseNSCall) {
3690 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(static_cast <bool> ((!hasRegParm || regParm < 7) &&
"Invalid regparm value") ? void (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 3690, __extension__ __PRETTY_FUNCTION__))
;
3691 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3692 (producesResult ? ProducesResultMask : 0) |
3693 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3694 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3695 (NoCfCheck ? NoCfCheckMask : 0) |
3696 (cmseNSCall ? CmseNSCallMask : 0);
3697 }
3698
3699 // Constructor with all defaults. Use when for example creating a
3700 // function known to use defaults.
3701 ExtInfo() = default;
3702
3703 // Constructor with just the calling convention, which is an important part
3704 // of the canonical type.
3705 ExtInfo(CallingConv CC) : Bits(CC) {}
3706
3707 bool getNoReturn() const { return Bits & NoReturnMask; }
3708 bool getProducesResult() const { return Bits & ProducesResultMask; }
3709 bool getCmseNSCall() const { return Bits & CmseNSCallMask; }
3710 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3711 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3712 bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; }
3713
3714 unsigned getRegParm() const {
3715 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3716 if (RegParm > 0)
3717 --RegParm;
3718 return RegParm;
3719 }
3720
3721 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3722
3723 bool operator==(ExtInfo Other) const {
3724 return Bits == Other.Bits;
3725 }
3726 bool operator!=(ExtInfo Other) const {
3727 return Bits != Other.Bits;
3728 }
3729
3730 // Note that we don't have setters. That is by design, use
3731 // the following with methods instead of mutating these objects.
3732
3733 ExtInfo withNoReturn(bool noReturn) const {
3734 if (noReturn)
3735 return ExtInfo(Bits | NoReturnMask);
3736 else
3737 return ExtInfo(Bits & ~NoReturnMask);
3738 }
3739
3740 ExtInfo withProducesResult(bool producesResult) const {
3741 if (producesResult)
3742 return ExtInfo(Bits | ProducesResultMask);
3743 else
3744 return ExtInfo(Bits & ~ProducesResultMask);
3745 }
3746
3747 ExtInfo withCmseNSCall(bool cmseNSCall) const {
3748 if (cmseNSCall)
3749 return ExtInfo(Bits | CmseNSCallMask);
3750 else
3751 return ExtInfo(Bits & ~CmseNSCallMask);
3752 }
3753
3754 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3755 if (noCallerSavedRegs)
3756 return ExtInfo(Bits | NoCallerSavedRegsMask);
3757 else
3758 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3759 }
3760
3761 ExtInfo withNoCfCheck(bool noCfCheck) const {
3762 if (noCfCheck)
3763 return ExtInfo(Bits | NoCfCheckMask);
3764 else
3765 return ExtInfo(Bits & ~NoCfCheckMask);
3766 }
3767
3768 ExtInfo withRegParm(unsigned RegParm) const {
3769 assert(RegParm < 7 && "Invalid regparm value")(static_cast <bool> (RegParm < 7 && "Invalid regparm value"
) ? void (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 3769, __extension__ __PRETTY_FUNCTION__))
;
3770 return ExtInfo((Bits & ~RegParmMask) |
3771 ((RegParm + 1) << RegParmOffset));
3772 }
3773
3774 ExtInfo withCallingConv(CallingConv cc) const {
3775 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3776 }
3777
3778 void Profile(llvm::FoldingSetNodeID &ID) const {
3779 ID.AddInteger(Bits);
3780 }
3781 };
3782
3783 /// A simple holder for a QualType representing a type in an
3784 /// exception specification. Unfortunately needed by FunctionProtoType
3785 /// because TrailingObjects cannot handle repeated types.
3786 struct ExceptionType { QualType Type; };
3787
3788 /// A simple holder for various uncommon bits which do not fit in
3789 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3790 /// alignment of subsequent objects in TrailingObjects. You must update
3791 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3792 struct alignas(void *) FunctionTypeExtraBitfields {
3793 /// The number of types in the exception specification.
3794 /// A whole unsigned is not needed here and according to
3795 /// [implimits] 8 bits would be enough here.
3796 unsigned NumExceptionType;
3797 };
3798
3799protected:
3800 FunctionType(TypeClass tc, QualType res, QualType Canonical,
3801 TypeDependence Dependence, ExtInfo Info)
3802 : Type(tc, Canonical, Dependence), ResultType(res) {
3803 FunctionTypeBits.ExtInfo = Info.Bits;
3804 }
3805
3806 Qualifiers getFastTypeQuals() const {
3807 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3808 }
3809
3810public:
3811 QualType getReturnType() const { return ResultType; }
3812
3813 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3814 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3815
3816 /// Determine whether this function type includes the GNU noreturn
3817 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3818 /// type.
3819 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3820
3821 bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); }
3822 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3823 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3824
3825 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3826 "Const, volatile and restrict are assumed to be a subset of "
3827 "the fast qualifiers.");
3828
3829 bool isConst() const { return getFastTypeQuals().hasConst(); }
3830 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3831 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3832
3833 /// Determine the type of an expression that calls a function of
3834 /// this type.
3835 QualType getCallResultType(const ASTContext &Context) const {
3836 return getReturnType().getNonLValueExprType(Context);
3837 }
3838
3839 static StringRef getNameForCallConv(CallingConv CC);
3840
3841 static bool classof(const Type *T) {
3842 return T->getTypeClass() == FunctionNoProto ||
3843 T->getTypeClass() == FunctionProto;
3844 }
3845};
3846
3847/// Represents a K&R-style 'int foo()' function, which has
3848/// no information available about its arguments.
3849class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3850 friend class ASTContext; // ASTContext creates these.
3851
3852 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3853 : FunctionType(FunctionNoProto, Result, Canonical,
3854 Result->getDependence() &
3855 ~(TypeDependence::DependentInstantiation |
3856 TypeDependence::UnexpandedPack),
3857 Info) {}
3858
3859public:
3860 // No additional state past what FunctionType provides.
3861
3862 bool isSugared() const { return false; }
3863 QualType desugar() const { return QualType(this, 0); }
3864
3865 void Profile(llvm::FoldingSetNodeID &ID) {
3866 Profile(ID, getReturnType(), getExtInfo());
3867 }
3868
3869 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3870 ExtInfo Info) {
3871 Info.Profile(ID);
3872 ID.AddPointer(ResultType.getAsOpaquePtr());
3873 }
3874
3875 static bool classof(const Type *T) {
3876 return T->getTypeClass() == FunctionNoProto;
3877 }
3878};
3879
3880/// Represents a prototype with parameter type info, e.g.
3881/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3882/// parameters, not as having a single void parameter. Such a type can have
3883/// an exception specification, but this specification is not part of the
3884/// canonical type. FunctionProtoType has several trailing objects, some of
3885/// which optional. For more information about the trailing objects see
3886/// the first comment inside FunctionProtoType.
3887class FunctionProtoType final
3888 : public FunctionType,
3889 public llvm::FoldingSetNode,
3890 private llvm::TrailingObjects<
3891 FunctionProtoType, QualType, SourceLocation,
3892 FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType,
3893 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
3894 friend class ASTContext; // ASTContext creates these.
3895 friend TrailingObjects;
3896
3897 // FunctionProtoType is followed by several trailing objects, some of
3898 // which optional. They are in order:
3899 //
3900 // * An array of getNumParams() QualType holding the parameter types.
3901 // Always present. Note that for the vast majority of FunctionProtoType,
3902 // these will be the only trailing objects.
3903 //
3904 // * Optionally if the function is variadic, the SourceLocation of the
3905 // ellipsis.
3906 //
3907 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3908 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3909 // a single FunctionTypeExtraBitfields. Present if and only if
3910 // hasExtraBitfields() is true.
3911 //
3912 // * Optionally exactly one of:
3913 // * an array of getNumExceptions() ExceptionType,
3914 // * a single Expr *,
3915 // * a pair of FunctionDecl *,
3916 // * a single FunctionDecl *
3917 // used to store information about the various types of exception
3918 // specification. See getExceptionSpecSize for the details.
3919 //
3920 // * Optionally an array of getNumParams() ExtParameterInfo holding
3921 // an ExtParameterInfo for each of the parameters. Present if and
3922 // only if hasExtParameterInfos() is true.
3923 //
3924 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3925 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3926 // if hasExtQualifiers() is true.
3927 //
3928 // The optional FunctionTypeExtraBitfields has to be before the data
3929 // related to the exception specification since it contains the number
3930 // of exception types.
3931 //
3932 // We put the ExtParameterInfos last. If all were equal, it would make
3933 // more sense to put these before the exception specification, because
3934 // it's much easier to skip past them compared to the elaborate switch
3935 // required to skip the exception specification. However, all is not
3936 // equal; ExtParameterInfos are used to model very uncommon features,
3937 // and it's better not to burden the more common paths.
3938
3939public:
3940 /// Holds information about the various types of exception specification.
3941 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3942 /// used to group together the various bits of information about the
3943 /// exception specification.
3944 struct ExceptionSpecInfo {
3945 /// The kind of exception specification this is.
3946 ExceptionSpecificationType Type = EST_None;
3947
3948 /// Explicitly-specified list of exception types.
3949 ArrayRef<QualType> Exceptions;
3950
3951 /// Noexcept expression, if this is a computed noexcept specification.
3952 Expr *NoexceptExpr = nullptr;
3953
3954 /// The function whose exception specification this is, for
3955 /// EST_Unevaluated and EST_Uninstantiated.
3956 FunctionDecl *SourceDecl = nullptr;
3957
3958 /// The function template whose exception specification this is instantiated
3959 /// from, for EST_Uninstantiated.
3960 FunctionDecl *SourceTemplate = nullptr;
3961
3962 ExceptionSpecInfo() = default;
3963
3964 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3965 };
3966
3967 /// Extra information about a function prototype. ExtProtoInfo is not
3968 /// stored as such in FunctionProtoType but is used to group together
3969 /// the various bits of extra information about a function prototype.
3970 struct ExtProtoInfo {
3971 FunctionType::ExtInfo ExtInfo;
3972 bool Variadic : 1;
3973 bool HasTrailingReturn : 1;
3974 Qualifiers TypeQuals;
3975 RefQualifierKind RefQualifier = RQ_None;
3976 ExceptionSpecInfo ExceptionSpec;
3977 const ExtParameterInfo *ExtParameterInfos = nullptr;
3978 SourceLocation EllipsisLoc;
3979
3980 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3981
3982 ExtProtoInfo(CallingConv CC)
3983 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3984
3985 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3986 ExtProtoInfo Result(*this);
3987 Result.ExceptionSpec = ESI;
3988 return Result;
3989 }
3990 };
3991
3992private:
3993 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3994 return getNumParams();
3995 }
3996
3997 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
3998 return isVariadic();
3999 }
4000
4001 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
4002 return hasExtraBitfields();
4003 }
4004
4005 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
4006 return getExceptionSpecSize().NumExceptionType;
4007 }
4008
4009 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
4010 return getExceptionSpecSize().NumExprPtr;
4011 }
4012
4013 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
4014 return getExceptionSpecSize().NumFunctionDeclPtr;
4015 }
4016
4017 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
4018 return hasExtParameterInfos() ? getNumParams() : 0;
4019 }
4020
4021 /// Determine whether there are any argument types that
4022 /// contain an unexpanded parameter pack.
4023 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
4024 unsigned numArgs) {
4025 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
4026 if (ArgArray[Idx]->containsUnexpandedParameterPack())
4027 return true;
4028
4029 return false;
4030 }
4031
4032 FunctionProtoType(QualType result, ArrayRef<QualType> params,
4033 QualType canonical, const ExtProtoInfo &epi);
4034
4035 /// This struct is returned by getExceptionSpecSize and is used to
4036 /// translate an ExceptionSpecificationType to the number and kind
4037 /// of trailing objects related to the exception specification.
4038 struct ExceptionSpecSizeHolder {
4039 unsigned NumExceptionType;
4040 unsigned NumExprPtr;
4041 unsigned NumFunctionDeclPtr;
4042 };
4043
4044 /// Return the number and kind of trailing objects
4045 /// related to the exception specification.
4046 static ExceptionSpecSizeHolder
4047 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
4048 switch (EST) {
4049 case EST_None:
4050 case EST_DynamicNone:
4051 case EST_MSAny:
4052 case EST_BasicNoexcept:
4053 case EST_Unparsed:
4054 case EST_NoThrow:
4055 return {0, 0, 0};
4056
4057 case EST_Dynamic:
4058 return {NumExceptions, 0, 0};
4059
4060 case EST_DependentNoexcept:
4061 case EST_NoexceptFalse:
4062 case EST_NoexceptTrue:
4063 return {0, 1, 0};
4064
4065 case EST_Uninstantiated:
4066 return {0, 0, 2};
4067
4068 case EST_Unevaluated:
4069 return {0, 0, 1};
4070 }
4071 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 4071)
;
4072 }
4073
4074 /// Return the number and kind of trailing objects
4075 /// related to the exception specification.
4076 ExceptionSpecSizeHolder getExceptionSpecSize() const {
4077 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
4078 }
4079
4080 /// Whether the trailing FunctionTypeExtraBitfields is present.
4081 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
4082 // If the exception spec type is EST_Dynamic then we have > 0 exception
4083 // types and the exact number is stored in FunctionTypeExtraBitfields.
4084 return EST == EST_Dynamic;
4085 }
4086
4087 /// Whether the trailing FunctionTypeExtraBitfields is present.
4088 bool hasExtraBitfields() const {
4089 return hasExtraBitfields(getExceptionSpecType());
4090 }
4091
4092 bool hasExtQualifiers() const {
4093 return FunctionTypeBits.HasExtQuals;
4094 }
4095
4096public:
4097 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
4098
4099 QualType getParamType(unsigned i) const {
4100 assert(i < getNumParams() && "invalid parameter index")(static_cast <bool> (i < getNumParams() && "invalid parameter index"
) ? void (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 4100, __extension__ __PRETTY_FUNCTION__))
;
4101 return param_type_begin()[i];
4102 }
4103
4104 ArrayRef<QualType> getParamTypes() const {
4105 return llvm::makeArrayRef(param_type_begin(), param_type_end());
4106 }
4107
4108 ExtProtoInfo getExtProtoInfo() const {
4109 ExtProtoInfo EPI;
4110 EPI.ExtInfo = getExtInfo();
4111 EPI.Variadic = isVariadic();
4112 EPI.EllipsisLoc = getEllipsisLoc();
4113 EPI.HasTrailingReturn = hasTrailingReturn();
4114 EPI.ExceptionSpec = getExceptionSpecInfo();
4115 EPI.TypeQuals = getMethodQuals();
4116 EPI.RefQualifier = getRefQualifier();
4117 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
4118 return EPI;
4119 }
4120
4121 /// Get the kind of exception specification on this function.
4122 ExceptionSpecificationType getExceptionSpecType() const {
4123 return static_cast<ExceptionSpecificationType>(
4124 FunctionTypeBits.ExceptionSpecType);
4125 }
4126
4127 /// Return whether this function has any kind of exception spec.
4128 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4129
4130 /// Return whether this function has a dynamic (throw) exception spec.
4131 bool hasDynamicExceptionSpec() const {
4132 return isDynamicExceptionSpec(getExceptionSpecType());
4133 }
4134
4135 /// Return whether this function has a noexcept exception spec.
4136 bool hasNoexceptExceptionSpec() const {
4137 return isNoexceptExceptionSpec(getExceptionSpecType());
4138 }
4139
4140 /// Return whether this function has a dependent exception spec.
4141 bool hasDependentExceptionSpec() const;
4142
4143 /// Return whether this function has an instantiation-dependent exception
4144 /// spec.
4145 bool hasInstantiationDependentExceptionSpec() const;
4146
4147 /// Return all the available information about this type's exception spec.
4148 ExceptionSpecInfo getExceptionSpecInfo() const {
4149 ExceptionSpecInfo Result;
4150 Result.Type = getExceptionSpecType();
4151 if (Result.Type == EST_Dynamic) {
4152 Result.Exceptions = exceptions();
4153 } else if (isComputedNoexcept(Result.Type)) {
4154 Result.NoexceptExpr = getNoexceptExpr();
4155 } else if (Result.Type == EST_Uninstantiated) {
4156 Result.SourceDecl = getExceptionSpecDecl();
4157 Result.SourceTemplate = getExceptionSpecTemplate();
4158 } else if (Result.Type == EST_Unevaluated) {
4159 Result.SourceDecl = getExceptionSpecDecl();
4160 }
4161 return Result;
4162 }
4163
4164 /// Return the number of types in the exception specification.
4165 unsigned getNumExceptions() const {
4166 return getExceptionSpecType() == EST_Dynamic
4167 ? getTrailingObjects<FunctionTypeExtraBitfields>()
4168 ->NumExceptionType
4169 : 0;
4170 }
4171
4172 /// Return the ith exception type, where 0 <= i < getNumExceptions().
4173 QualType getExceptionType(unsigned i) const {
4174 assert(i < getNumExceptions() && "Invalid exception number!")(static_cast <bool> (i < getNumExceptions() &&
"Invalid exception number!") ? void (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 4174, __extension__ __PRETTY_FUNCTION__))
;
4175 return exception_begin()[i];
4176 }
4177
4178 /// Return the expression inside noexcept(expression), or a null pointer
4179 /// if there is none (because the exception spec is not of this form).
4180 Expr *getNoexceptExpr() const {
4181 if (!isComputedNoexcept(getExceptionSpecType()))
4182 return nullptr;
4183 return *getTrailingObjects<Expr *>();
4184 }
4185
4186 /// If this function type has an exception specification which hasn't
4187 /// been determined yet (either because it has not been evaluated or because
4188 /// it has not been instantiated), this is the function whose exception
4189 /// specification is represented by this type.
4190 FunctionDecl *getExceptionSpecDecl() const {
4191 if (getExceptionSpecType() != EST_Uninstantiated &&
4192 getExceptionSpecType() != EST_Unevaluated)
4193 return nullptr;
4194 return getTrailingObjects<FunctionDecl *>()[0];
4195 }
4196
4197 /// If this function type has an uninstantiated exception
4198 /// specification, this is the function whose exception specification
4199 /// should be instantiated to find the exception specification for
4200 /// this type.
4201 FunctionDecl *getExceptionSpecTemplate() const {
4202 if (getExceptionSpecType() != EST_Uninstantiated)
4203 return nullptr;
4204 return getTrailingObjects<FunctionDecl *>()[1];
4205 }
4206
4207 /// Determine whether this function type has a non-throwing exception
4208 /// specification.
4209 CanThrowResult canThrow() const;
4210
4211 /// Determine whether this function type has a non-throwing exception
4212 /// specification. If this depends on template arguments, returns
4213 /// \c ResultIfDependent.
4214 bool isNothrow(bool ResultIfDependent = false) const {
4215 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4216 }
4217
4218 /// Whether this function prototype is variadic.
4219 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4220
4221 SourceLocation getEllipsisLoc() const {
4222 return isVariadic() ? *getTrailingObjects<SourceLocation>()
4223 : SourceLocation();
4224 }
4225
4226 /// Determines whether this function prototype contains a
4227 /// parameter pack at the end.
4228 ///
4229 /// A function template whose last parameter is a parameter pack can be
4230 /// called with an arbitrary number of arguments, much like a variadic
4231 /// function.
4232 bool isTemplateVariadic() const;
4233
4234 /// Whether this function prototype has a trailing return type.
4235 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4236
4237 Qualifiers getMethodQuals() const {
4238 if (hasExtQualifiers())
4239 return *getTrailingObjects<Qualifiers>();
4240 else
4241 return getFastTypeQuals();
4242 }
4243
4244 /// Retrieve the ref-qualifier associated with this function type.
4245 RefQualifierKind getRefQualifier() const {
4246 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4247 }
4248
4249 using param_type_iterator = const QualType *;
4250 using param_type_range = llvm::iterator_range<param_type_iterator>;
4251
4252 param_type_range param_types() const {
4253 return param_type_range(param_type_begin(), param_type_end());
4254 }
4255
4256 param_type_iterator param_type_begin() const {
4257 return getTrailingObjects<QualType>();
4258 }
4259
4260 param_type_iterator param_type_end() const {
4261 return param_type_begin() + getNumParams();
4262 }
4263
4264 using exception_iterator = const QualType *;
4265
4266 ArrayRef<QualType> exceptions() const {
4267 return llvm::makeArrayRef(exception_begin(), exception_end());
4268 }
4269
4270 exception_iterator exception_begin() const {
4271 return reinterpret_cast<exception_iterator>(
4272 getTrailingObjects<ExceptionType>());
4273 }
4274
4275 exception_iterator exception_end() const {
4276 return exception_begin() + getNumExceptions();
4277 }
4278
4279 /// Is there any interesting extra information for any of the parameters
4280 /// of this function type?
4281 bool hasExtParameterInfos() const {
4282 return FunctionTypeBits.HasExtParameterInfos;
4283 }
4284
4285 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4286 assert(hasExtParameterInfos())(static_cast <bool> (hasExtParameterInfos()) ? void (0)
: __assert_fail ("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 4286, __extension__ __PRETTY_FUNCTION__))
;
4287 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4288 getNumParams());
4289 }
4290
4291 /// Return a pointer to the beginning of the array of extra parameter
4292 /// information, if present, or else null if none of the parameters
4293 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4294 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4295 if (!hasExtParameterInfos())
4296 return nullptr;
4297 return getTrailingObjects<ExtParameterInfo>();
4298 }
4299
4300 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4301 assert(I < getNumParams() && "parameter index out of range")(static_cast <bool> (I < getNumParams() && "parameter index out of range"
) ? void (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 4301, __extension__ __PRETTY_FUNCTION__))
;
4302 if (hasExtParameterInfos())
4303 return getTrailingObjects<ExtParameterInfo>()[I];
4304 return ExtParameterInfo();
4305 }
4306
4307 ParameterABI getParameterABI(unsigned I) const {
4308 assert(I < getNumParams() && "parameter index out of range")(static_cast <bool> (I < getNumParams() && "parameter index out of range"
) ? void (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 4308, __extension__ __PRETTY_FUNCTION__))
;
4309 if (hasExtParameterInfos())
4310 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4311 return ParameterABI::Ordinary;
4312 }
4313
4314 bool isParamConsumed(unsigned I) const {
4315 assert(I < getNumParams() && "parameter index out of range")(static_cast <bool> (I < getNumParams() && "parameter index out of range"
) ? void (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 4315, __extension__ __PRETTY_FUNCTION__))
;
4316 if (hasExtParameterInfos())
4317 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4318 return false;
4319 }
4320
4321 bool isSugared() const { return false; }
4322 QualType desugar() const { return QualType(this, 0); }
4323
4324 void printExceptionSpecification(raw_ostream &OS,
4325 const PrintingPolicy &Policy) const;
4326
4327 static bool classof(const Type *T) {
4328 return T->getTypeClass() == FunctionProto;
4329 }
4330
4331 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4332 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4333 param_type_iterator ArgTys, unsigned NumArgs,
4334 const ExtProtoInfo &EPI, const ASTContext &Context,
4335 bool Canonical);
4336};
4337
4338/// Represents the dependent type named by a dependently-scoped
4339/// typename using declaration, e.g.
4340/// using typename Base<T>::foo;
4341///
4342/// Template instantiation turns these into the underlying type.
4343class UnresolvedUsingType : public Type {
4344 friend class ASTContext; // ASTContext creates these.
4345
4346 UnresolvedUsingTypenameDecl *Decl;
4347
4348 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4349 : Type(UnresolvedUsing, QualType(),
4350 TypeDependence::DependentInstantiation),
4351 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {}
4352
4353public:
4354 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4355
4356 bool isSugared() const { return false; }
4357 QualType desugar() const { return QualType(this, 0); }
4358
4359 static bool classof(const Type *T) {
4360 return T->getTypeClass() == UnresolvedUsing;
4361 }
4362
4363 void Profile(llvm::FoldingSetNodeID &ID) {
4364 return Profile(ID, Decl);
4365 }
4366
4367 static void Profile(llvm::FoldingSetNodeID &ID,
4368 UnresolvedUsingTypenameDecl *D) {
4369 ID.AddPointer(D);
4370 }
4371};
4372
4373class TypedefType : public Type {
4374 TypedefNameDecl *Decl;
4375
4376private:
4377 friend class ASTContext; // ASTContext creates these.
4378
4379 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType underlying,
4380 QualType can);
4381
4382public:
4383 TypedefNameDecl *getDecl() const { return Decl; }
4384
4385 bool isSugared() const { return true; }
4386 QualType desugar() const;
4387
4388 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4389};
4390
4391/// Sugar type that represents a type that was qualified by a qualifier written
4392/// as a macro invocation.
4393class MacroQualifiedType : public Type {
4394 friend class ASTContext; // ASTContext creates these.
4395
4396 QualType UnderlyingTy;
4397 const IdentifierInfo *MacroII;
4398
4399 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4400 const IdentifierInfo *MacroII)
4401 : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()),
4402 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4403 assert(isa<AttributedType>(UnderlyingTy) &&(static_cast <bool> (isa<AttributedType>(UnderlyingTy
) && "Expected a macro qualified type to only wrap attributed types."
) ? void (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 4404, __extension__ __PRETTY_FUNCTION__))
4404 "Expected a macro qualified type to only wrap attributed types.")(static_cast <bool> (isa<AttributedType>(UnderlyingTy
) && "Expected a macro qualified type to only wrap attributed types."
) ? void (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 4404, __extension__ __PRETTY_FUNCTION__))
;
4405 }
4406
4407public:
4408 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4409 QualType getUnderlyingType() const { return UnderlyingTy; }
4410
4411 /// Return this attributed type's modified type with no qualifiers attached to
4412 /// it.
4413 QualType getModifiedType() const;
4414
4415 bool isSugared() const { return true; }
4416 QualType desugar() const;
4417
4418 static bool classof(const Type *T) {
4419 return T->getTypeClass() == MacroQualified;
4420 }
4421};
4422
4423/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4424class TypeOfExprType : public Type {
4425 Expr *TOExpr;
4426
4427protected:
4428 friend class ASTContext; // ASTContext creates these.
4429
4430 TypeOfExprType(Expr *E, QualType can = QualType());
4431
4432public:
4433 Expr *getUnderlyingExpr() const { return TOExpr; }
4434
4435 /// Remove a single level of sugar.
4436 QualType desugar() const;
4437
4438 /// Returns whether this type directly provides sugar.
4439 bool isSugared() const;
4440
4441 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4442};
4443
4444/// Internal representation of canonical, dependent
4445/// `typeof(expr)` types.
4446///
4447/// This class is used internally by the ASTContext to manage
4448/// canonical, dependent types, only. Clients will only see instances
4449/// of this class via TypeOfExprType nodes.
4450class DependentTypeOfExprType
4451 : public TypeOfExprType, public llvm::FoldingSetNode {
4452 const ASTContext &Context;
4453
4454public:
4455 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4456 : TypeOfExprType(E), Context(Context) {}
4457
4458 void Profile(llvm::FoldingSetNodeID &ID) {
4459 Profile(ID, Context, getUnderlyingExpr());
4460 }
4461
4462 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4463 Expr *E);
4464};
4465
4466/// Represents `typeof(type)`, a GCC extension.
4467class TypeOfType : public Type {
4468 friend class ASTContext; // ASTContext creates these.
4469
4470 QualType TOType;
4471
4472 TypeOfType(QualType T, QualType can)
4473 : Type(TypeOf, can, T->getDependence()), TOType(T) {
4474 assert(!isa<TypedefType>(can) && "Invalid canonical type")(static_cast <bool> (!isa<TypedefType>(can) &&
"Invalid canonical type") ? void (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 4474, __extension__ __PRETTY_FUNCTION__))
;
4475 }
4476
4477public:
4478 QualType getUnderlyingType() const { return TOType; }
4479
4480 /// Remove a single level of sugar.
4481 QualType desugar() const { return getUnderlyingType(); }
4482
4483 /// Returns whether this type directly provides sugar.
4484 bool isSugared() const { return true; }
4485
4486 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4487};
4488
4489/// Represents the type `decltype(expr)` (C++11).
4490class DecltypeType : public Type {
4491 Expr *E;
4492 QualType UnderlyingType;
4493
4494protected:
4495 friend class ASTContext; // ASTContext creates these.
4496
4497 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4498
4499public:
4500 Expr *getUnderlyingExpr() const { return E; }
4501 QualType getUnderlyingType() const { return UnderlyingType; }
4502
4503 /// Remove a single level of sugar.
4504 QualType desugar() const;
4505
4506 /// Returns whether this type directly provides sugar.
4507 bool isSugared() const;
4508
4509 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4510};
4511
4512/// Internal representation of canonical, dependent
4513/// decltype(expr) types.
4514///
4515/// This class is used internally by the ASTContext to manage
4516/// canonical, dependent types, only. Clients will only see instances
4517/// of this class via DecltypeType nodes.
4518class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4519 const ASTContext &Context;
4520
4521public:
4522 DependentDecltypeType(const ASTContext &Context, Expr *E);
4523
4524 void Profile(llvm::FoldingSetNodeID &ID) {
4525 Profile(ID, Context, getUnderlyingExpr());
4526 }
4527
4528 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4529 Expr *E);
4530};
4531
4532/// A unary type transform, which is a type constructed from another.
4533class UnaryTransformType : public Type {
4534public:
4535 enum UTTKind {
4536 EnumUnderlyingType
4537 };
4538
4539private:
4540 /// The untransformed type.
4541 QualType BaseType;
4542
4543 /// The transformed type if not dependent, otherwise the same as BaseType.
4544 QualType UnderlyingType;
4545
4546 UTTKind UKind;
4547
4548protected:
4549 friend class ASTContext;
4550
4551 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4552 QualType CanonicalTy);
4553
4554public:
4555 bool isSugared() const { return !isDependentType(); }
4556 QualType desugar() const { return UnderlyingType; }
4557
4558 QualType getUnderlyingType() const { return UnderlyingType; }
4559 QualType getBaseType() const { return BaseType; }
4560
4561 UTTKind getUTTKind() const { return UKind; }
4562
4563 static bool classof(const Type *T) {
4564 return T->getTypeClass() == UnaryTransform;
4565 }
4566};
4567
4568/// Internal representation of canonical, dependent
4569/// __underlying_type(type) types.
4570///
4571/// This class is used internally by the ASTContext to manage
4572/// canonical, dependent types, only. Clients will only see instances
4573/// of this class via UnaryTransformType nodes.
4574class DependentUnaryTransformType : public UnaryTransformType,
4575 public llvm::FoldingSetNode {
4576public:
4577 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4578 UTTKind UKind);
4579
4580 void Profile(llvm::FoldingSetNodeID &ID) {
4581 Profile(ID, getBaseType(), getUTTKind());
4582 }
4583
4584 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4585 UTTKind UKind) {
4586 ID.AddPointer(BaseType.getAsOpaquePtr());
4587 ID.AddInteger((unsigned)UKind);
4588 }
4589};
4590
4591class TagType : public Type {
4592 friend class ASTReader;
4593 template <class T> friend class serialization::AbstractTypeReader;
4594
4595 /// Stores the TagDecl associated with this type. The decl may point to any
4596 /// TagDecl that declares the entity.
4597 TagDecl *decl;
4598
4599protected:
4600 TagType(TypeClass TC, const TagDecl *D, QualType can);
4601
4602public:
4603 TagDecl *getDecl() const;
4604
4605 /// Determines whether this type is in the process of being defined.
4606 bool isBeingDefined() const;
4607
4608 static bool classof(const Type *T) {
4609 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4610 }
4611};
4612
4613/// A helper class that allows the use of isa/cast/dyncast
4614/// to detect TagType objects of structs/unions/classes.
4615class RecordType : public TagType {
4616protected:
4617 friend class ASTContext; // ASTContext creates these.
4618
4619 explicit RecordType(const RecordDecl *D)
4620 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4621 explicit RecordType(TypeClass TC, RecordDecl *D)
4622 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4623
4624public:
4625 RecordDecl *getDecl() const {
4626 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4627 }
4628
4629 /// Recursively check all fields in the record for const-ness. If any field
4630 /// is declared const, return true. Otherwise, return false.
4631 bool hasConstFields() const;
4632
4633 bool isSugared() const { return false; }
4634 QualType desugar() const { return QualType(this, 0); }
4635
4636 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4637};
4638
4639/// A helper class that allows the use of isa/cast/dyncast
4640/// to detect TagType objects of enums.
4641class EnumType : public TagType {
4642 friend class ASTContext; // ASTContext creates these.
4643
4644 explicit EnumType(const EnumDecl *D)
4645 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4646
4647public:
4648 EnumDecl *getDecl() const {
4649 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4650 }
4651
4652 bool isSugared() const { return false; }
4653 QualType desugar() const { return QualType(this, 0); }
4654
4655 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4656};
4657
4658/// An attributed type is a type to which a type attribute has been applied.
4659///
4660/// The "modified type" is the fully-sugared type to which the attributed
4661/// type was applied; generally it is not canonically equivalent to the
4662/// attributed type. The "equivalent type" is the minimally-desugared type
4663/// which the type is canonically equivalent to.
4664///
4665/// For example, in the following attributed type:
4666/// int32_t __attribute__((vector_size(16)))
4667/// - the modified type is the TypedefType for int32_t
4668/// - the equivalent type is VectorType(16, int32_t)
4669/// - the canonical type is VectorType(16, int)
4670class AttributedType : public Type, public llvm::FoldingSetNode {
4671public:
4672 using Kind = attr::Kind;
4673
4674private:
4675 friend class ASTContext; // ASTContext creates these
4676
4677 QualType ModifiedType;
4678 QualType EquivalentType;
4679
4680 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4681 QualType equivalent)
4682 : Type(Attributed, canon, equivalent->getDependence()),
4683 ModifiedType(modified), EquivalentType(equivalent) {
4684 AttributedTypeBits.AttrKind = attrKind;
4685 }
4686
4687public:
4688 Kind getAttrKind() const {
4689 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4690 }
4691
4692 QualType getModifiedType() const { return ModifiedType; }
4693 QualType getEquivalentType() const { return EquivalentType; }
4694
4695 bool isSugared() const { return true; }
4696 QualType desugar() const { return getEquivalentType(); }
4697
4698 /// Does this attribute behave like a type qualifier?
4699 ///
4700 /// A type qualifier adjusts a type to provide specialized rules for
4701 /// a specific object, like the standard const and volatile qualifiers.
4702 /// This includes attributes controlling things like nullability,
4703 /// address spaces, and ARC ownership. The value of the object is still
4704 /// largely described by the modified type.
4705 ///
4706 /// In contrast, many type attributes "rewrite" their modified type to
4707 /// produce a fundamentally different type, not necessarily related in any
4708 /// formalizable way to the original type. For example, calling convention
4709 /// and vector attributes are not simple type qualifiers.
4710 ///
4711 /// Type qualifiers are often, but not always, reflected in the canonical
4712 /// type.
4713 bool isQualifier() const;
4714
4715 bool isMSTypeSpec() const;
4716
4717 bool isCallingConv() const;
4718
4719 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4720
4721 /// Retrieve the attribute kind corresponding to the given
4722 /// nullability kind.
4723 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4724 switch (kind) {
4725 case NullabilityKind::NonNull:
4726 return attr::TypeNonNull;
4727
4728 case NullabilityKind::Nullable:
4729 return attr::TypeNullable;
4730
4731 case NullabilityKind::NullableResult:
4732 return attr::TypeNullableResult;
4733
4734 case NullabilityKind::Unspecified:
4735 return attr::TypeNullUnspecified;
4736 }
4737 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 4737)
;
4738 }
4739
4740 /// Strip off the top-level nullability annotation on the given
4741 /// type, if it's there.
4742 ///
4743 /// \param T The type to strip. If the type is exactly an
4744 /// AttributedType specifying nullability (without looking through
4745 /// type sugar), the nullability is returned and this type changed
4746 /// to the underlying modified type.
4747 ///
4748 /// \returns the top-level nullability, if present.
4749 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4750
4751 void Profile(llvm::FoldingSetNodeID &ID) {
4752 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4753 }
4754
4755 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4756 QualType modified, QualType equivalent) {
4757 ID.AddInteger(attrKind);
4758 ID.AddPointer(modified.getAsOpaquePtr());
4759 ID.AddPointer(equivalent.getAsOpaquePtr());
4760 }
4761
4762 static bool classof(const Type *T) {
4763 return T->getTypeClass() == Attributed;
4764 }
4765};
4766
4767class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4768 friend class ASTContext; // ASTContext creates these
4769
4770 // Helper data collector for canonical types.
4771 struct CanonicalTTPTInfo {
4772 unsigned Depth : 15;
4773 unsigned ParameterPack : 1;
4774 unsigned Index : 16;
4775 };
4776
4777 union {
4778 // Info for the canonical type.
4779 CanonicalTTPTInfo CanTTPTInfo;
4780
4781 // Info for the non-canonical type.
4782 TemplateTypeParmDecl *TTPDecl;
4783 };
4784
4785 /// Build a non-canonical type.
4786 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4787 : Type(TemplateTypeParm, Canon,
4788 TypeDependence::DependentInstantiation |
4789 (Canon->getDependence() & TypeDependence::UnexpandedPack)),
4790 TTPDecl(TTPDecl) {}
4791
4792 /// Build the canonical type.
4793 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4794 : Type(TemplateTypeParm, QualType(this, 0),
4795 TypeDependence::DependentInstantiation |
4796 (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) {
4797 CanTTPTInfo.Depth = D;
4798 CanTTPTInfo.Index = I;
4799 CanTTPTInfo.ParameterPack = PP;
4800 }
4801
4802 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4803 QualType Can = getCanonicalTypeInternal();
4804 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4805 }
4806
4807public:
4808 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4809 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4810 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4811
4812 TemplateTypeParmDecl *getDecl() const {
4813 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4814 }
4815
4816 IdentifierInfo *getIdentifier() const;
4817
4818 bool isSugared() const { return false; }
4819 QualType desugar() const { return QualType(this, 0); }
4820
4821 void Profile(llvm::FoldingSetNodeID &ID) {
4822 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4823 }
4824
4825 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4826 unsigned Index, bool ParameterPack,
4827 TemplateTypeParmDecl *TTPDecl) {
4828 ID.AddInteger(Depth);
4829 ID.AddInteger(Index);
4830 ID.AddBoolean(ParameterPack);
4831 ID.AddPointer(TTPDecl);
4832 }
4833
4834 static bool classof(const Type *T) {
4835 return T->getTypeClass() == TemplateTypeParm;
4836 }
4837};
4838
4839/// Represents the result of substituting a type for a template
4840/// type parameter.
4841///
4842/// Within an instantiated template, all template type parameters have
4843/// been replaced with these. They are used solely to record that a
4844/// type was originally written as a template type parameter;
4845/// therefore they are never canonical.
4846class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4847 friend class ASTContext;
4848
4849 // The original type parameter.
4850 const TemplateTypeParmType *Replaced;
4851
4852 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4853 : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()),
4854 Replaced(Param) {}
4855
4856public:
4857 /// Gets the template parameter that was substituted for.
4858 const TemplateTypeParmType *getReplacedParameter() const {
4859 return Replaced;
4860 }
4861
4862 /// Gets the type that was substituted for the template
4863 /// parameter.
4864 QualType getReplacementType() const {
4865 return getCanonicalTypeInternal();
4866 }
4867
4868 bool isSugared() const { return true; }
4869 QualType desugar() const { return getReplacementType(); }
4870
4871 void Profile(llvm::FoldingSetNodeID &ID) {
4872 Profile(ID, getReplacedParameter(), getReplacementType());
4873 }
4874
4875 static void Profile(llvm::FoldingSetNodeID &ID,
4876 const TemplateTypeParmType *Replaced,
4877 QualType Replacement) {
4878 ID.AddPointer(Replaced);
4879 ID.AddPointer(Replacement.getAsOpaquePtr());
4880 }
4881
4882 static bool classof(const Type *T) {
4883 return T->getTypeClass() == SubstTemplateTypeParm;
4884 }
4885};
4886
4887/// Represents the result of substituting a set of types for a template
4888/// type parameter pack.
4889///
4890/// When a pack expansion in the source code contains multiple parameter packs
4891/// and those parameter packs correspond to different levels of template
4892/// parameter lists, this type node is used to represent a template type
4893/// parameter pack from an outer level, which has already had its argument pack
4894/// substituted but that still lives within a pack expansion that itself
4895/// could not be instantiated. When actually performing a substitution into
4896/// that pack expansion (e.g., when all template parameters have corresponding
4897/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4898/// at the current pack substitution index.
4899class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4900 friend class ASTContext;
4901
4902 /// The original type parameter.
4903 const TemplateTypeParmType *Replaced;
4904
4905 /// A pointer to the set of template arguments that this
4906 /// parameter pack is instantiated with.
4907 const TemplateArgument *Arguments;
4908
4909 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4910 QualType Canon,
4911 const TemplateArgument &ArgPack);
4912
4913public:
4914 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4915
4916 /// Gets the template parameter that was substituted for.
4917 const TemplateTypeParmType *getReplacedParameter() const {
4918 return Replaced;
4919 }
4920
4921 unsigned getNumArgs() const {
4922 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4923 }
4924
4925 bool isSugared() const { return false; }
4926 QualType desugar() const { return QualType(this, 0); }
4927
4928 TemplateArgument getArgumentPack() const;
4929
4930 void Profile(llvm::FoldingSetNodeID &ID);
4931 static void Profile(llvm::FoldingSetNodeID &ID,
4932 const TemplateTypeParmType *Replaced,
4933 const TemplateArgument &ArgPack);
4934
4935 static bool classof(const Type *T) {
4936 return T->getTypeClass() == SubstTemplateTypeParmPack;
4937 }
4938};
4939
4940/// Common base class for placeholders for types that get replaced by
4941/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4942/// class template types, and constrained type names.
4943///
4944/// These types are usually a placeholder for a deduced type. However, before
4945/// the initializer is attached, or (usually) if the initializer is
4946/// type-dependent, there is no deduced type and the type is canonical. In
4947/// the latter case, it is also a dependent type.
4948class DeducedType : public Type {
4949protected:
4950 DeducedType(TypeClass TC, QualType DeducedAsType,
4951 TypeDependence ExtraDependence)
4952 : Type(TC,
4953 // FIXME: Retain the sugared deduced type?
4954 DeducedAsType.isNull() ? QualType(this, 0)
4955 : DeducedAsType.getCanonicalType(),
4956 ExtraDependence | (DeducedAsType.isNull()
4957 ? TypeDependence::None
4958 : DeducedAsType->getDependence() &
4959 ~TypeDependence::VariablyModified)) {}
4960
4961public:
4962 bool isSugared() const { return !isCanonicalUnqualified(); }
4963 QualType desugar() const { return getCanonicalTypeInternal(); }
4964
4965 /// Get the type deduced for this placeholder type, or null if it's
4966 /// either not been deduced or was deduced to a dependent type.
4967 QualType getDeducedType() const {
4968 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4969 }
4970 bool isDeduced() const {
4971 return !isCanonicalUnqualified() || isDependentType();
4972 }
4973
4974 static bool classof(const Type *T) {
4975 return T->getTypeClass() == Auto ||
4976 T->getTypeClass() == DeducedTemplateSpecialization;
4977 }
4978};
4979
4980/// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained
4981/// by a type-constraint.
4982class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode {
4983 friend class ASTContext; // ASTContext creates these
4984
4985 ConceptDecl *TypeConstraintConcept;
4986
4987 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4988 TypeDependence ExtraDependence, ConceptDecl *CD,
4989 ArrayRef<TemplateArgument> TypeConstraintArgs);
4990
4991 const TemplateArgument *getArgBuffer() const {
4992 return reinterpret_cast<const TemplateArgument*>(this+1);
4993 }
4994
4995 TemplateArgument *getArgBuffer() {
4996 return reinterpret_cast<TemplateArgument*>(this+1);
4997 }
4998
4999public:
5000 /// Retrieve the template arguments.
5001 const TemplateArgument *getArgs() const {
5002 return getArgBuffer();
5003 }
5004
5005 /// Retrieve the number of template arguments.
5006 unsigned getNumArgs() const {
5007 return AutoTypeBits.NumArgs;
5008 }
5009
5010 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5011
5012 ArrayRef<TemplateArgument> getTypeConstraintArguments() const {
5013 return {getArgs(), getNumArgs()};
5014 }
5015
5016 ConceptDecl *getTypeConstraintConcept() const {
5017 return TypeConstraintConcept;
5018 }
5019
5020 bool isConstrained() const {
5021 return TypeConstraintConcept != nullptr;
5022 }
5023
5024 bool isDecltypeAuto() const {
5025 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
5026 }
5027
5028 AutoTypeKeyword getKeyword() const {
5029 return (AutoTypeKeyword)AutoTypeBits.Keyword;
5030 }
5031
5032 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5033 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
5034 getTypeConstraintConcept(), getTypeConstraintArguments());
5035 }
5036
5037 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5038 QualType Deduced, AutoTypeKeyword Keyword,
5039 bool IsDependent, ConceptDecl *CD,
5040 ArrayRef<TemplateArgument> Arguments);
5041
5042 static bool classof(const Type *T) {
5043 return T->getTypeClass() == Auto;
5044 }
5045};
5046
5047/// Represents a C++17 deduced template specialization type.
5048class DeducedTemplateSpecializationType : public DeducedType,
5049 public llvm::FoldingSetNode {
5050 friend class ASTContext; // ASTContext creates these
5051
5052 /// The name of the template whose arguments will be deduced.
5053 TemplateName Template;
5054
5055 DeducedTemplateSpecializationType(TemplateName Template,
5056 QualType DeducedAsType,
5057 bool IsDeducedAsDependent)
5058 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
5059 toTypeDependence(Template.getDependence()) |
5060 (IsDeducedAsDependent
5061 ? TypeDependence::DependentInstantiation
5062 : TypeDependence::None)),
5063 Template(Template) {}
5064
5065public:
5066 /// Retrieve the name of the template that we are deducing.
5067 TemplateName getTemplateName() const { return Template;}
5068
5069 void Profile(llvm::FoldingSetNodeID &ID) {
5070 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
5071 }
5072
5073 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
5074 QualType Deduced, bool IsDependent) {
5075 Template.Profile(ID);
5076 ID.AddPointer(Deduced.getAsOpaquePtr());
5077 ID.AddBoolean(IsDependent);
5078 }
5079
5080 static bool classof(const Type *T) {
5081 return T->getTypeClass() == DeducedTemplateSpecialization;
5082 }
5083};
5084
5085/// Represents a type template specialization; the template
5086/// must be a class template, a type alias template, or a template
5087/// template parameter. A template which cannot be resolved to one of
5088/// these, e.g. because it is written with a dependent scope
5089/// specifier, is instead represented as a
5090/// @c DependentTemplateSpecializationType.
5091///
5092/// A non-dependent template specialization type is always "sugar",
5093/// typically for a \c RecordType. For example, a class template
5094/// specialization type of \c vector<int> will refer to a tag type for
5095/// the instantiation \c std::vector<int, std::allocator<int>>
5096///
5097/// Template specializations are dependent if either the template or
5098/// any of the template arguments are dependent, in which case the
5099/// type may also be canonical.
5100///
5101/// Instances of this type are allocated with a trailing array of
5102/// TemplateArguments, followed by a QualType representing the
5103/// non-canonical aliased type when the template is a type alias
5104/// template.
5105class alignas(8) TemplateSpecializationType
5106 : public Type,
5107 public llvm::FoldingSetNode {
5108 friend class ASTContext; // ASTContext creates these
5109
5110 /// The name of the template being specialized. This is
5111 /// either a TemplateName::Template (in which case it is a
5112 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
5113 /// TypeAliasTemplateDecl*), a
5114 /// TemplateName::SubstTemplateTemplateParmPack, or a
5115 /// TemplateName::SubstTemplateTemplateParm (in which case the
5116 /// replacement must, recursively, be one of these).
5117 TemplateName Template;
5118
5119 TemplateSpecializationType(TemplateName T,
5120 ArrayRef<TemplateArgument> Args,
5121 QualType Canon,
5122 QualType Aliased);
5123
5124public:
5125 /// Determine whether any of the given template arguments are dependent.
5126 ///
5127 /// The converted arguments should be supplied when known; whether an
5128 /// argument is dependent can depend on the conversions performed on it
5129 /// (for example, a 'const int' passed as a template argument might be
5130 /// dependent if the parameter is a reference but non-dependent if the
5131 /// parameter is an int).
5132 ///
5133 /// Note that the \p Args parameter is unused: this is intentional, to remind
5134 /// the caller that they need to pass in the converted arguments, not the
5135 /// specified arguments.
5136 static bool
5137 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
5138 ArrayRef<TemplateArgument> Converted);
5139 static bool
5140 anyDependentTemplateArguments(const TemplateArgumentListInfo &,
5141 ArrayRef<TemplateArgument> Converted);
5142 static bool anyInstantiationDependentTemplateArguments(
5143 ArrayRef<TemplateArgumentLoc> Args);
5144
5145 /// True if this template specialization type matches a current
5146 /// instantiation in the context in which it is found.
5147 bool isCurrentInstantiation() const {
5148 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
5149 }
5150
5151 /// Determine if this template specialization type is for a type alias
5152 /// template that has been substituted.
5153 ///
5154 /// Nearly every template specialization type whose template is an alias
5155 /// template will be substituted. However, this is not the case when
5156 /// the specialization contains a pack expansion but the template alias
5157 /// does not have a corresponding parameter pack, e.g.,
5158 ///
5159 /// \code
5160 /// template<typename T, typename U, typename V> struct S;
5161 /// template<typename T, typename U> using A = S<T, int, U>;
5162 /// template<typename... Ts> struct X {
5163 /// typedef A<Ts...> type; // not a type alias
5164 /// };
5165 /// \endcode
5166 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
5167
5168 /// Get the aliased type, if this is a specialization of a type alias
5169 /// template.
5170 QualType getAliasedType() const {
5171 assert(isTypeAlias() && "not a type alias template specialization")(static_cast <bool> (isTypeAlias() && "not a type alias template specialization"
) ? void (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 5171, __extension__ __PRETTY_FUNCTION__))
;
5172 return *reinterpret_cast<const QualType*>(end());
5173 }
5174
5175 using iterator = const TemplateArgument *;
5176
5177 iterator begin() const { return getArgs(); }
5178 iterator end() const; // defined inline in TemplateBase.h
5179
5180 /// Retrieve the name of the template that we are specializing.
5181 TemplateName getTemplateName() const { return Template; }
5182
5183 /// Retrieve the template arguments.
5184 const TemplateArgument *getArgs() const {
5185 return reinterpret_cast<const TemplateArgument *>(this + 1);
5186 }
5187
5188 /// Retrieve the number of template arguments.
5189 unsigned getNumArgs() const {
5190 return TemplateSpecializationTypeBits.NumArgs;
5191 }
5192
5193 /// Retrieve a specific template argument as a type.
5194 /// \pre \c isArgType(Arg)
5195 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5196
5197 ArrayRef<TemplateArgument> template_arguments() const {
5198 return {getArgs(), getNumArgs()};
5199 }
5200
5201 bool isSugared() const {
5202 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5203 }
5204
5205 QualType desugar() const {
5206 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5207 }
5208
5209 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5210 Profile(ID, Template, template_arguments(), Ctx);
5211 if (isTypeAlias())
5212 getAliasedType().Profile(ID);
5213 }
5214
5215 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5216 ArrayRef<TemplateArgument> Args,
5217 const ASTContext &Context);
5218
5219 static bool classof(const Type *T) {
5220 return T->getTypeClass() == TemplateSpecialization;
5221 }
5222};
5223
5224/// Print a template argument list, including the '<' and '>'
5225/// enclosing the template arguments.
5226void printTemplateArgumentList(raw_ostream &OS,
5227 ArrayRef<TemplateArgument> Args,
5228 const PrintingPolicy &Policy,
5229 const TemplateParameterList *TPL = nullptr);
5230
5231void printTemplateArgumentList(raw_ostream &OS,
5232 ArrayRef<TemplateArgumentLoc> Args,
5233 const PrintingPolicy &Policy,
5234 const TemplateParameterList *TPL = nullptr);
5235
5236void printTemplateArgumentList(raw_ostream &OS,
5237 const TemplateArgumentListInfo &Args,
5238 const PrintingPolicy &Policy,
5239 const TemplateParameterList *TPL = nullptr);
5240
5241/// The injected class name of a C++ class template or class
5242/// template partial specialization. Used to record that a type was
5243/// spelled with a bare identifier rather than as a template-id; the
5244/// equivalent for non-templated classes is just RecordType.
5245///
5246/// Injected class name types are always dependent. Template
5247/// instantiation turns these into RecordTypes.
5248///
5249/// Injected class name types are always canonical. This works
5250/// because it is impossible to compare an injected class name type
5251/// with the corresponding non-injected template type, for the same
5252/// reason that it is impossible to directly compare template
5253/// parameters from different dependent contexts: injected class name
5254/// types can only occur within the scope of a particular templated
5255/// declaration, and within that scope every template specialization
5256/// will canonicalize to the injected class name (when appropriate
5257/// according to the rules of the language).
5258class InjectedClassNameType : public Type {
5259 friend class ASTContext; // ASTContext creates these.
5260 friend class ASTNodeImporter;
5261 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5262 // currently suitable for AST reading, too much
5263 // interdependencies.
5264 template <class T> friend class serialization::AbstractTypeReader;
5265
5266 CXXRecordDecl *Decl;
5267
5268 /// The template specialization which this type represents.
5269 /// For example, in
5270 /// template <class T> class A { ... };
5271 /// this is A<T>, whereas in
5272 /// template <class X, class Y> class A<B<X,Y> > { ... };
5273 /// this is A<B<X,Y> >.
5274 ///
5275 /// It is always unqualified, always a template specialization type,
5276 /// and always dependent.
5277 QualType InjectedType;
5278
5279 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5280 : Type(InjectedClassName, QualType(),
5281 TypeDependence::DependentInstantiation),
5282 Decl(D), InjectedType(TST) {
5283 assert(isa<TemplateSpecializationType>(TST))(static_cast <bool> (isa<TemplateSpecializationType>
(TST)) ? void (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 5283, __extension__ __PRETTY_FUNCTION__))
;
5284 assert(!TST.hasQualifiers())(static_cast <bool> (!TST.hasQualifiers()) ? void (0) :
__assert_fail ("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 5284, __extension__ __PRETTY_FUNCTION__))
;
5285 assert(TST->isDependentType())(static_cast <bool> (TST->isDependentType()) ? void (
0) : __assert_fail ("TST->isDependentType()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 5285, __extension__ __PRETTY_FUNCTION__))
;
5286 }
5287
5288public:
5289 QualType getInjectedSpecializationType() const { return InjectedType; }
5290
5291 const TemplateSpecializationType *getInjectedTST() const {
5292 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5293 }
5294
5295 TemplateName getTemplateName() const {
5296 return getInjectedTST()->getTemplateName();
5297 }
5298
5299 CXXRecordDecl *getDecl() const;
5300
5301 bool isSugared() const { return false; }
5302 QualType desugar() const { return QualType(this, 0); }
5303
5304 static bool classof(const Type *T) {
5305 return T->getTypeClass() == InjectedClassName;
5306 }
5307};
5308
5309/// The kind of a tag type.
5310enum TagTypeKind {
5311 /// The "struct" keyword.
5312 TTK_Struct,
5313
5314 /// The "__interface" keyword.
5315 TTK_Interface,
5316
5317 /// The "union" keyword.
5318 TTK_Union,
5319
5320 /// The "class" keyword.
5321 TTK_Class,
5322
5323 /// The "enum" keyword.
5324 TTK_Enum
5325};
5326
5327/// The elaboration keyword that precedes a qualified type name or
5328/// introduces an elaborated-type-specifier.
5329enum ElaboratedTypeKeyword {
5330 /// The "struct" keyword introduces the elaborated-type-specifier.
5331 ETK_Struct,
5332
5333 /// The "__interface" keyword introduces the elaborated-type-specifier.
5334 ETK_Interface,
5335
5336 /// The "union" keyword introduces the elaborated-type-specifier.
5337 ETK_Union,
5338
5339 /// The "class" keyword introduces the elaborated-type-specifier.
5340 ETK_Class,
5341
5342 /// The "enum" keyword introduces the elaborated-type-specifier.
5343 ETK_Enum,
5344
5345 /// The "typename" keyword precedes the qualified type name, e.g.,
5346 /// \c typename T::type.
5347 ETK_Typename,
5348
5349 /// No keyword precedes the qualified type name.
5350 ETK_None
5351};
5352
5353/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5354/// The keyword in stored in the free bits of the base class.
5355/// Also provides a few static helpers for converting and printing
5356/// elaborated type keyword and tag type kind enumerations.
5357class TypeWithKeyword : public Type {
5358protected:
5359 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5360 QualType Canonical, TypeDependence Dependence)
5361 : Type(tc, Canonical, Dependence) {
5362 TypeWithKeywordBits.Keyword = Keyword;
5363 }
5364
5365public:
5366 ElaboratedTypeKeyword getKeyword() const {
5367 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5368 }
5369
5370 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5371 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5372
5373 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5374 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5375 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5376
5377 /// Converts a TagTypeKind into an elaborated type keyword.
5378 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5379
5380 /// Converts an elaborated type keyword into a TagTypeKind.
5381 /// It is an error to provide an elaborated type keyword
5382 /// which *isn't* a tag kind here.
5383 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5384
5385 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5386
5387 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5388
5389 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5390 return getKeywordName(getKeywordForTagTypeKind(Kind));
5391 }
5392
5393 class CannotCastToThisType {};
5394 static CannotCastToThisType classof(const Type *);
5395};
5396
5397/// Represents a type that was referred to using an elaborated type
5398/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5399/// or both.
5400///
5401/// This type is used to keep track of a type name as written in the
5402/// source code, including tag keywords and any nested-name-specifiers.
5403/// The type itself is always "sugar", used to express what was written
5404/// in the source code but containing no additional semantic information.
5405class ElaboratedType final
5406 : public TypeWithKeyword,
5407 public llvm::FoldingSetNode,
5408 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5409 friend class ASTContext; // ASTContext creates these
5410 friend TrailingObjects;
5411
5412 /// The nested name specifier containing the qualifier.
5413 NestedNameSpecifier *NNS;
5414
5415 /// The type that this qualified name refers to.
5416 QualType NamedType;
5417
5418 /// The (re)declaration of this tag type owned by this occurrence is stored
5419 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5420 /// it, or obtain a null pointer if there is none.
5421
5422 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5423 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5424 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5425 // Any semantic dependence on the qualifier will have
5426 // been incorporated into NamedType. We still need to
5427 // track syntactic (instantiation / error / pack)
5428 // dependence on the qualifier.
5429 NamedType->getDependence() |
5430 (NNS ? toSyntacticDependence(
5431 toTypeDependence(NNS->getDependence()))
5432 : TypeDependence::None)),
5433 NNS(NNS), NamedType(NamedType) {
5434 ElaboratedTypeBits.HasOwnedTagDecl = false;
5435 if (OwnedTagDecl) {
5436 ElaboratedTypeBits.HasOwnedTagDecl = true;
5437 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5438 }
5439 assert(!(Keyword == ETK_None && NNS == nullptr) &&(static_cast <bool> (!(Keyword == ETK_None && NNS
== nullptr) && "ElaboratedType cannot have elaborated type keyword "
"and name qualifier both null.") ? void (0) : __assert_fail (
"!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 5441, __extension__ __PRETTY_FUNCTION__))
5440 "ElaboratedType cannot have elaborated type keyword "(static_cast <bool> (!(Keyword == ETK_None && NNS
== nullptr) && "ElaboratedType cannot have elaborated type keyword "
"and name qualifier both null.") ? void (0) : __assert_fail (
"!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 5441, __extension__ __PRETTY_FUNCTION__))
5441 "and name qualifier both null.")(static_cast <bool> (!(Keyword == ETK_None && NNS
== nullptr) && "ElaboratedType cannot have elaborated type keyword "
"and name qualifier both null.") ? void (0) : __assert_fail (
"!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 5441, __extension__ __PRETTY_FUNCTION__))
;
5442 }
5443
5444public:
5445 /// Retrieve the qualification on this type.
5446 NestedNameSpecifier *getQualifier() const { return NNS; }
5447
5448 /// Retrieve the type named by the qualified-id.
5449 QualType getNamedType() const { return NamedType; }
5450
5451 /// Remove a single level of sugar.
5452 QualType desugar() const { return getNamedType(); }
5453
5454 /// Returns whether this type directly provides sugar.
5455 bool isSugared() const { return true; }
5456
5457 /// Return the (re)declaration of this type owned by this occurrence of this
5458 /// type, or nullptr if there is none.
5459 TagDecl *getOwnedTagDecl() const {
5460 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5461 : nullptr;
5462 }
5463
5464 void Profile(llvm::FoldingSetNodeID &ID) {
5465 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5466 }
5467
5468 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5469 NestedNameSpecifier *NNS, QualType NamedType,
5470 TagDecl *OwnedTagDecl) {
5471 ID.AddInteger(Keyword);
5472 ID.AddPointer(NNS);
5473 NamedType.Profile(ID);
5474 ID.AddPointer(OwnedTagDecl);
5475 }
5476
5477 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5478};
5479
5480/// Represents a qualified type name for which the type name is
5481/// dependent.
5482///
5483/// DependentNameType represents a class of dependent types that involve a
5484/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5485/// name of a type. The DependentNameType may start with a "typename" (for a
5486/// typename-specifier), "class", "struct", "union", or "enum" (for a
5487/// dependent elaborated-type-specifier), or nothing (in contexts where we
5488/// know that we must be referring to a type, e.g., in a base class specifier).
5489/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5490/// mode, this type is used with non-dependent names to delay name lookup until
5491/// instantiation.
5492class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5493 friend class ASTContext; // ASTContext creates these
5494
5495 /// The nested name specifier containing the qualifier.
5496 NestedNameSpecifier *NNS;
5497
5498 /// The type that this typename specifier refers to.
5499 const IdentifierInfo *Name;
5500
5501 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5502 const IdentifierInfo *Name, QualType CanonType)
5503 : TypeWithKeyword(Keyword, DependentName, CanonType,
5504 TypeDependence::DependentInstantiation |
5505 toTypeDependence(NNS->getDependence())),
5506 NNS(NNS), Name(Name) {}
5507
5508public:
5509 /// Retrieve the qualification on this type.
5510 NestedNameSpecifier *getQualifier() const { return NNS; }
5511
5512 /// Retrieve the type named by the typename specifier as an identifier.
5513 ///
5514 /// This routine will return a non-NULL identifier pointer when the
5515 /// form of the original typename was terminated by an identifier,
5516 /// e.g., "typename T::type".
5517 const IdentifierInfo *getIdentifier() const {
5518 return Name;
5519 }
5520
5521 bool isSugared() const { return false; }
5522 QualType desugar() const { return QualType(this, 0); }
5523
5524 void Profile(llvm::FoldingSetNodeID &ID) {
5525 Profile(ID, getKeyword(), NNS, Name);
5526 }
5527
5528 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5529 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5530 ID.AddInteger(Keyword);
5531 ID.AddPointer(NNS);
5532 ID.AddPointer(Name);
5533 }
5534
5535 static bool classof(const Type *T) {
5536 return T->getTypeClass() == DependentName;
5537 }
5538};
5539
5540/// Represents a template specialization type whose template cannot be
5541/// resolved, e.g.
5542/// A<T>::template B<T>
5543class alignas(8) DependentTemplateSpecializationType
5544 : public TypeWithKeyword,
5545 public llvm::FoldingSetNode {
5546 friend class ASTContext; // ASTContext creates these
5547
5548 /// The nested name specifier containing the qualifier.
5549 NestedNameSpecifier *NNS;
5550
5551 /// The identifier of the template.
5552 const IdentifierInfo *Name;
5553
5554 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5555 NestedNameSpecifier *NNS,
5556 const IdentifierInfo *Name,
5557 ArrayRef<TemplateArgument> Args,
5558 QualType Canon);
5559
5560 const TemplateArgument *getArgBuffer() const {
5561 return reinterpret_cast<const TemplateArgument*>(this+1);
5562 }
5563
5564 TemplateArgument *getArgBuffer() {
5565 return reinterpret_cast<TemplateArgument*>(this+1);
5566 }
5567
5568public:
5569 NestedNameSpecifier *getQualifier() const { return NNS; }
5570 const IdentifierInfo *getIdentifier() const { return Name; }
5571
5572 /// Retrieve the template arguments.
5573 const TemplateArgument *getArgs() const {
5574 return getArgBuffer();
5575 }
5576
5577 /// Retrieve the number of template arguments.
5578 unsigned getNumArgs() const {
5579 return DependentTemplateSpecializationTypeBits.NumArgs;
5580 }
5581
5582 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5583
5584 ArrayRef<TemplateArgument> template_arguments() const {
5585 return {getArgs(), getNumArgs()};
5586 }
5587
5588 using iterator = const TemplateArgument *;
5589
5590 iterator begin() const { return getArgs(); }
5591 iterator end() const; // inline in TemplateBase.h
5592
5593 bool isSugared() const { return false; }
5594 QualType desugar() const { return QualType(this, 0); }
5595
5596 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5597 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5598 }
5599
5600 static void Profile(llvm::FoldingSetNodeID &ID,
5601 const ASTContext &Context,
5602 ElaboratedTypeKeyword Keyword,
5603 NestedNameSpecifier *Qualifier,
5604 const IdentifierInfo *Name,
5605 ArrayRef<TemplateArgument> Args);
5606
5607 static bool classof(const Type *T) {
5608 return T->getTypeClass() == DependentTemplateSpecialization;
5609 }
5610};
5611
5612/// Represents a pack expansion of types.
5613///
5614/// Pack expansions are part of C++11 variadic templates. A pack
5615/// expansion contains a pattern, which itself contains one or more
5616/// "unexpanded" parameter packs. When instantiated, a pack expansion
5617/// produces a series of types, each instantiated from the pattern of
5618/// the expansion, where the Ith instantiation of the pattern uses the
5619/// Ith arguments bound to each of the unexpanded parameter packs. The
5620/// pack expansion is considered to "expand" these unexpanded
5621/// parameter packs.
5622///
5623/// \code
5624/// template<typename ...Types> struct tuple;
5625///
5626/// template<typename ...Types>
5627/// struct tuple_of_references {
5628/// typedef tuple<Types&...> type;
5629/// };
5630/// \endcode
5631///
5632/// Here, the pack expansion \c Types&... is represented via a
5633/// PackExpansionType whose pattern is Types&.
5634class PackExpansionType : public Type, public llvm::FoldingSetNode {
5635 friend class ASTContext; // ASTContext creates these
5636
5637 /// The pattern of the pack expansion.
5638 QualType Pattern;
5639
5640 PackExpansionType(QualType Pattern, QualType Canon,
5641 Optional<unsigned> NumExpansions)
5642 : Type(PackExpansion, Canon,
5643 (Pattern->getDependence() | TypeDependence::Dependent |
5644 TypeDependence::Instantiation) &
5645 ~TypeDependence::UnexpandedPack),
5646 Pattern(Pattern) {
5647 PackExpansionTypeBits.NumExpansions =
5648 NumExpansions ? *NumExpansions + 1 : 0;
5649 }
5650
5651public:
5652 /// Retrieve the pattern of this pack expansion, which is the
5653 /// type that will be repeatedly instantiated when instantiating the
5654 /// pack expansion itself.
5655 QualType getPattern() const { return Pattern; }
5656
5657 /// Retrieve the number of expansions that this pack expansion will
5658 /// generate, if known.
5659 Optional<unsigned> getNumExpansions() const {
5660 if (PackExpansionTypeBits.NumExpansions)
5661 return PackExpansionTypeBits.NumExpansions - 1;
5662 return None;
5663 }
5664
5665 bool isSugared() const { return false; }
5666 QualType desugar() const { return QualType(this, 0); }
5667
5668 void Profile(llvm::FoldingSetNodeID &ID) {
5669 Profile(ID, getPattern(), getNumExpansions());
5670 }
5671
5672 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5673 Optional<unsigned> NumExpansions) {
5674 ID.AddPointer(Pattern.getAsOpaquePtr());
5675 ID.AddBoolean(NumExpansions.hasValue());
5676 if (NumExpansions)
5677 ID.AddInteger(*NumExpansions);
5678 }
5679
5680 static bool classof(const Type *T) {
5681 return T->getTypeClass() == PackExpansion;
5682 }
5683};
5684
5685/// This class wraps the list of protocol qualifiers. For types that can
5686/// take ObjC protocol qualifers, they can subclass this class.
5687template <class T>
5688class ObjCProtocolQualifiers {
5689protected:
5690 ObjCProtocolQualifiers() = default;
5691
5692 ObjCProtocolDecl * const *getProtocolStorage() const {
5693 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5694 }
5695
5696 ObjCProtocolDecl **getProtocolStorage() {
5697 return static_cast<T*>(this)->getProtocolStorageImpl();
5698 }
5699
5700 void setNumProtocols(unsigned N) {
5701 static_cast<T*>(this)->setNumProtocolsImpl(N);
5702 }
5703
5704 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5705 setNumProtocols(protocols.size());
5706 assert(getNumProtocols() == protocols.size() &&(static_cast <bool> (getNumProtocols() == protocols.size
() && "bitfield overflow in protocol count") ? void (
0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 5707, __extension__ __PRETTY_FUNCTION__))
5707 "bitfield overflow in protocol count")(static_cast <bool> (getNumProtocols() == protocols.size
() && "bitfield overflow in protocol count") ? void (
0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 5707, __extension__ __PRETTY_FUNCTION__))
;
5708 if (!protocols.empty())
5709 memcpy(getProtocolStorage(), protocols.data(),
5710 protocols.size() * sizeof(ObjCProtocolDecl*));
5711 }
5712
5713public:
5714 using qual_iterator = ObjCProtocolDecl * const *;
5715 using qual_range = llvm::iterator_range<qual_iterator>;
5716
5717 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5718 qual_iterator qual_begin() const { return getProtocolStorage(); }
5719 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5720
5721 bool qual_empty() const { return getNumProtocols() == 0; }
5722
5723 /// Return the number of qualifying protocols in this type, or 0 if
5724 /// there are none.
5725 unsigned getNumProtocols() const {
5726 return static_cast<const T*>(this)->getNumProtocolsImpl();
5727 }
5728
5729 /// Fetch a protocol by index.
5730 ObjCProtocolDecl *getProtocol(unsigned I) const {
5731 assert(I < getNumProtocols() && "Out-of-range protocol access")(static_cast <bool> (I < getNumProtocols() &&
"Out-of-range protocol access") ? void (0) : __assert_fail (
"I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 5731, __extension__ __PRETTY_FUNCTION__))
;
5732 return qual_begin()[I];
5733 }
5734
5735 /// Retrieve all of the protocol qualifiers.
5736 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5737 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5738 }
5739};
5740
5741/// Represents a type parameter type in Objective C. It can take
5742/// a list of protocols.
5743class ObjCTypeParamType : public Type,
5744 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5745 public llvm::FoldingSetNode {
5746 friend class ASTContext;
5747 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5748
5749 /// The number of protocols stored on this type.
5750 unsigned NumProtocols : 6;
5751
5752 ObjCTypeParamDecl *OTPDecl;
5753
5754 /// The protocols are stored after the ObjCTypeParamType node. In the
5755 /// canonical type, the list of protocols are sorted alphabetically
5756 /// and uniqued.
5757 ObjCProtocolDecl **getProtocolStorageImpl();
5758
5759 /// Return the number of qualifying protocols in this interface type,
5760 /// or 0 if there are none.
5761 unsigned getNumProtocolsImpl() const {
5762 return NumProtocols;
5763 }
5764
5765 void setNumProtocolsImpl(unsigned N) {
5766 NumProtocols = N;
5767 }
5768
5769 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5770 QualType can,
5771 ArrayRef<ObjCProtocolDecl *> protocols);
5772
5773public:
5774 bool isSugared() const { return true; }
5775 QualType desugar() const { return getCanonicalTypeInternal(); }
5776
5777 static bool classof(const Type *T) {
5778 return T->getTypeClass() == ObjCTypeParam;
5779 }
5780
5781 void Profile(llvm::FoldingSetNodeID &ID);
5782 static void Profile(llvm::FoldingSetNodeID &ID,
5783 const ObjCTypeParamDecl *OTPDecl,
5784 QualType CanonicalType,
5785 ArrayRef<ObjCProtocolDecl *> protocols);
5786
5787 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5788};
5789
5790/// Represents a class type in Objective C.
5791///
5792/// Every Objective C type is a combination of a base type, a set of
5793/// type arguments (optional, for parameterized classes) and a list of
5794/// protocols.
5795///
5796/// Given the following declarations:
5797/// \code
5798/// \@class C<T>;
5799/// \@protocol P;
5800/// \endcode
5801///
5802/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5803/// with base C and no protocols.
5804///
5805/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5806/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5807/// protocol list.
5808/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5809/// and protocol list [P].
5810///
5811/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5812/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5813/// and no protocols.
5814///
5815/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5816/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5817/// this should get its own sugar class to better represent the source.
5818class ObjCObjectType : public Type,
5819 public ObjCProtocolQualifiers<ObjCObjectType> {
5820 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5821
5822 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5823 // after the ObjCObjectPointerType node.
5824 // ObjCObjectType.NumProtocols - the number of protocols stored
5825 // after the type arguments of ObjCObjectPointerType node.
5826 //
5827 // These protocols are those written directly on the type. If
5828 // protocol qualifiers ever become additive, the iterators will need
5829 // to get kindof complicated.
5830 //
5831 // In the canonical object type, these are sorted alphabetically
5832 // and uniqued.
5833
5834 /// Either a BuiltinType or an InterfaceType or sugar for either.
5835 QualType BaseType;
5836
5837 /// Cached superclass type.
5838 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5839 CachedSuperClassType;
5840
5841 QualType *getTypeArgStorage();
5842 const QualType *getTypeArgStorage() const {
5843 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5844 }
5845
5846 ObjCProtocolDecl **getProtocolStorageImpl();
5847 /// Return the number of qualifying protocols in this interface type,
5848 /// or 0 if there are none.
5849 unsigned getNumProtocolsImpl() const {
5850 return ObjCObjectTypeBits.NumProtocols;
5851 }
5852 void setNumProtocolsImpl(unsigned N) {
5853 ObjCObjectTypeBits.NumProtocols = N;
5854 }
5855
5856protected:
5857 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5858
5859 ObjCObjectType(QualType Canonical, QualType Base,
5860 ArrayRef<QualType> typeArgs,
5861 ArrayRef<ObjCProtocolDecl *> protocols,
5862 bool isKindOf);
5863
5864 ObjCObjectType(enum Nonce_ObjCInterface)
5865 : Type(ObjCInterface, QualType(), TypeDependence::None),
5866 BaseType(QualType(this_(), 0)) {
5867 ObjCObjectTypeBits.NumProtocols = 0;
5868 ObjCObjectTypeBits.NumTypeArgs = 0;
5869 ObjCObjectTypeBits.IsKindOf = 0;
5870 }
5871
5872 void computeSuperClassTypeSlow() const;
5873
5874public:
5875 /// Gets the base type of this object type. This is always (possibly
5876 /// sugar for) one of:
5877 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5878 /// user, which is a typedef for an ObjCObjectPointerType)
5879 /// - the 'Class' builtin type (same caveat)
5880 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5881 QualType getBaseType() const { return BaseType; }
5882
5883 bool isObjCId() const {
5884 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5885 }
5886
5887 bool isObjCClass() const {
5888 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5889 }
5890
5891 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5892 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5893 bool isObjCUnqualifiedIdOrClass() const {
5894 if (!qual_empty()) return false;
5895 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5896 return T->getKind() == BuiltinType::ObjCId ||
5897 T->getKind() == BuiltinType::ObjCClass;
5898 return false;
5899 }
5900 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5901 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5902
5903 /// Gets the interface declaration for this object type, if the base type
5904 /// really is an interface.
5905 ObjCInterfaceDecl *getInterface() const;
5906
5907 /// Determine whether this object type is "specialized", meaning
5908 /// that it has type arguments.
5909 bool isSpecialized() const;
5910
5911 /// Determine whether this object type was written with type arguments.
5912 bool isSpecializedAsWritten() const {
5913 return ObjCObjectTypeBits.NumTypeArgs > 0;
5914 }
5915
5916 /// Determine whether this object type is "unspecialized", meaning
5917 /// that it has no type arguments.
5918 bool isUnspecialized() const { return !isSpecialized(); }
5919
5920 /// Determine whether this object type is "unspecialized" as
5921 /// written, meaning that it has no type arguments.
5922 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5923
5924 /// Retrieve the type arguments of this object type (semantically).
5925 ArrayRef<QualType> getTypeArgs() const;
5926
5927 /// Retrieve the type arguments of this object type as they were
5928 /// written.
5929 ArrayRef<QualType> getTypeArgsAsWritten() const {
5930 return llvm::makeArrayRef(getTypeArgStorage(),
5931 ObjCObjectTypeBits.NumTypeArgs);
5932 }
5933
5934 /// Whether this is a "__kindof" type as written.
5935 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5936
5937 /// Whether this ia a "__kindof" type (semantically).
5938 bool isKindOfType() const;
5939
5940 /// Retrieve the type of the superclass of this object type.
5941 ///
5942 /// This operation substitutes any type arguments into the
5943 /// superclass of the current class type, potentially producing a
5944 /// specialization of the superclass type. Produces a null type if
5945 /// there is no superclass.
5946 QualType getSuperClassType() const {
5947 if (!CachedSuperClassType.getInt())
5948 computeSuperClassTypeSlow();
5949
5950 assert(CachedSuperClassType.getInt() && "Superclass not set?")(static_cast <bool> (CachedSuperClassType.getInt() &&
"Superclass not set?") ? void (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 5950, __extension__ __PRETTY_FUNCTION__))
;
5951 return QualType(CachedSuperClassType.getPointer(), 0);
5952 }
5953
5954 /// Strip off the Objective-C "kindof" type and (with it) any
5955 /// protocol qualifiers.
5956 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5957
5958 bool isSugared() const { return false; }
5959 QualType desugar() const { return QualType(this, 0); }
5960
5961 static bool classof(const Type *T) {
5962 return T->getTypeClass() == ObjCObject ||
5963 T->getTypeClass() == ObjCInterface;
5964 }
5965};
5966
5967/// A class providing a concrete implementation
5968/// of ObjCObjectType, so as to not increase the footprint of
5969/// ObjCInterfaceType. Code outside of ASTContext and the core type
5970/// system should not reference this type.
5971class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5972 friend class ASTContext;
5973
5974 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5975 // will need to be modified.
5976
5977 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5978 ArrayRef<QualType> typeArgs,
5979 ArrayRef<ObjCProtocolDecl *> protocols,
5980 bool isKindOf)
5981 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5982
5983public:
5984 void Profile(llvm::FoldingSetNodeID &ID);
5985 static void Profile(llvm::FoldingSetNodeID &ID,
5986 QualType Base,
5987 ArrayRef<QualType> typeArgs,
5988 ArrayRef<ObjCProtocolDecl *> protocols,
5989 bool isKindOf);
5990};
5991
5992inline QualType *ObjCObjectType::getTypeArgStorage() {
5993 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5994}
5995
5996inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5997 return reinterpret_cast<ObjCProtocolDecl**>(
5998 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5999}
6000
6001inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
6002 return reinterpret_cast<ObjCProtocolDecl**>(
6003 static_cast<ObjCTypeParamType*>(this)+1);
6004}
6005
6006/// Interfaces are the core concept in Objective-C for object oriented design.
6007/// They basically correspond to C++ classes. There are two kinds of interface
6008/// types: normal interfaces like `NSString`, and qualified interfaces, which
6009/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
6010///
6011/// ObjCInterfaceType guarantees the following properties when considered
6012/// as a subtype of its superclass, ObjCObjectType:
6013/// - There are no protocol qualifiers. To reinforce this, code which
6014/// tries to invoke the protocol methods via an ObjCInterfaceType will
6015/// fail to compile.
6016/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
6017/// T->getBaseType() == QualType(T, 0).
6018class ObjCInterfaceType : public ObjCObjectType {
6019 friend class ASTContext; // ASTContext creates these.
6020 friend class ASTReader;
6021 friend class ObjCInterfaceDecl;
6022 template <class T> friend class serialization::AbstractTypeReader;
6023
6024 mutable ObjCInterfaceDecl *Decl;
6025
6026 ObjCInterfaceType(const ObjCInterfaceDecl *D)
6027 : ObjCObjectType(Nonce_ObjCInterface),
6028 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
6029
6030public:
6031 /// Get the declaration of this interface.
6032 ObjCInterfaceDecl *getDecl() const { return Decl; }
6033
6034 bool isSugared() const { return false; }
6035 QualType desugar() const { return QualType(this, 0); }
6036
6037 static bool classof(const Type *T) {
6038 return T->getTypeClass() == ObjCInterface;
6039 }
6040
6041 // Nonsense to "hide" certain members of ObjCObjectType within this
6042 // class. People asking for protocols on an ObjCInterfaceType are
6043 // not going to get what they want: ObjCInterfaceTypes are
6044 // guaranteed to have no protocols.
6045 enum {
6046 qual_iterator,
6047 qual_begin,
6048 qual_end,
6049 getNumProtocols,
6050 getProtocol
6051 };
6052};
6053
6054inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
6055 QualType baseType = getBaseType();
6056 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
6057 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
6058 return T->getDecl();
6059
6060 baseType = ObjT->getBaseType();
6061 }
6062
6063 return nullptr;
6064}
6065
6066/// Represents a pointer to an Objective C object.
6067///
6068/// These are constructed from pointer declarators when the pointee type is
6069/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
6070/// types are typedefs for these, and the protocol-qualified types 'id<P>'
6071/// and 'Class<P>' are translated into these.
6072///
6073/// Pointers to pointers to Objective C objects are still PointerTypes;
6074/// only the first level of pointer gets it own type implementation.
6075class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
6076 friend class ASTContext; // ASTContext creates these.
6077
6078 QualType PointeeType;
6079
6080 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
6081 : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()),
6082 PointeeType(Pointee) {}
6083
6084public:
6085 /// Gets the type pointed to by this ObjC pointer.
6086 /// The result will always be an ObjCObjectType or sugar thereof.
6087 QualType getPointeeType() const { return PointeeType; }
6088
6089 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
6090 ///
6091 /// This method is equivalent to getPointeeType() except that
6092 /// it discards any typedefs (or other sugar) between this
6093 /// type and the "outermost" object type. So for:
6094 /// \code
6095 /// \@class A; \@protocol P; \@protocol Q;
6096 /// typedef A<P> AP;
6097 /// typedef A A1;
6098 /// typedef A1<P> A1P;
6099 /// typedef A1P<Q> A1PQ;
6100 /// \endcode
6101 /// For 'A*', getObjectType() will return 'A'.
6102 /// For 'A<P>*', getObjectType() will return 'A<P>'.
6103 /// For 'AP*', getObjectType() will return 'A<P>'.
6104 /// For 'A1*', getObjectType() will return 'A'.
6105 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
6106 /// For 'A1P*', getObjectType() will return 'A1<P>'.
6107 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
6108 /// adding protocols to a protocol-qualified base discards the
6109 /// old qualifiers (for now). But if it didn't, getObjectType()
6110 /// would return 'A1P<Q>' (and we'd have to make iterating over
6111 /// qualifiers more complicated).
6112 const ObjCObjectType *getObjectType() const {
6113 return PointeeType->castAs<ObjCObjectType>();
6114 }
6115
6116 /// If this pointer points to an Objective C
6117 /// \@interface type, gets the type for that interface. Any protocol
6118 /// qualifiers on the interface are ignored.
6119 ///
6120 /// \return null if the base type for this pointer is 'id' or 'Class'
6121 const ObjCInterfaceType *getInterfaceType() const;
6122
6123 /// If this pointer points to an Objective \@interface
6124 /// type, gets the declaration for that interface.
6125 ///
6126 /// \return null if the base type for this pointer is 'id' or 'Class'
6127 ObjCInterfaceDecl *getInterfaceDecl() const {
6128 return getObjectType()->getInterface();
6129 }
6130
6131 /// True if this is equivalent to the 'id' type, i.e. if
6132 /// its object type is the primitive 'id' type with no protocols.
6133 bool isObjCIdType() const {
6134 return getObjectType()->isObjCUnqualifiedId();
6135 }
6136
6137 /// True if this is equivalent to the 'Class' type,
6138 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
6139 bool isObjCClassType() const {
6140 return getObjectType()->isObjCUnqualifiedClass();
6141 }
6142
6143 /// True if this is equivalent to the 'id' or 'Class' type,
6144 bool isObjCIdOrClassType() const {
6145 return getObjectType()->isObjCUnqualifiedIdOrClass();
6146 }
6147
6148 /// True if this is equivalent to 'id<P>' for some non-empty set of
6149 /// protocols.
6150 bool isObjCQualifiedIdType() const {
6151 return getObjectType()->isObjCQualifiedId();
6152 }
6153
6154 /// True if this is equivalent to 'Class<P>' for some non-empty set of
6155 /// protocols.
6156 bool isObjCQualifiedClassType() const {
6157 return getObjectType()->isObjCQualifiedClass();
6158 }
6159
6160 /// Whether this is a "__kindof" type.
6161 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
6162
6163 /// Whether this type is specialized, meaning that it has type arguments.
6164 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
6165
6166 /// Whether this type is specialized, meaning that it has type arguments.
6167 bool isSpecializedAsWritten() const {
6168 return getObjectType()->isSpecializedAsWritten();
6169 }
6170
6171 /// Whether this type is unspecialized, meaning that is has no type arguments.
6172 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
6173
6174 /// Determine whether this object type is "unspecialized" as
6175 /// written, meaning that it has no type arguments.
6176 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
6177
6178 /// Retrieve the type arguments for this type.
6179 ArrayRef<QualType> getTypeArgs() const {
6180 return getObjectType()->getTypeArgs();
6181 }
6182
6183 /// Retrieve the type arguments for this type.
6184 ArrayRef<QualType> getTypeArgsAsWritten() const {
6185 return getObjectType()->getTypeArgsAsWritten();
6186 }
6187
6188 /// An iterator over the qualifiers on the object type. Provided
6189 /// for convenience. This will always iterate over the full set of
6190 /// protocols on a type, not just those provided directly.
6191 using qual_iterator = ObjCObjectType::qual_iterator;
6192 using qual_range = llvm::iterator_range<qual_iterator>;
6193
6194 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
6195
6196 qual_iterator qual_begin() const {
6197 return getObjectType()->qual_begin();
6198 }
6199
6200 qual_iterator qual_end() const {
6201 return getObjectType()->qual_end();
6202 }
6203
6204 bool qual_empty() const { return getObjectType()->qual_empty(); }
6205
6206 /// Return the number of qualifying protocols on the object type.
6207 unsigned getNumProtocols() const {
6208 return getObjectType()->getNumProtocols();
6209 }
6210
6211 /// Retrieve a qualifying protocol by index on the object type.
6212 ObjCProtocolDecl *getProtocol(unsigned I) const {
6213 return getObjectType()->getProtocol(I);
6214 }
6215
6216 bool isSugared() const { return false; }
6217 QualType desugar() const { return QualType(this, 0); }
6218
6219 /// Retrieve the type of the superclass of this object pointer type.
6220 ///
6221 /// This operation substitutes any type arguments into the
6222 /// superclass of the current class type, potentially producing a
6223 /// pointer to a specialization of the superclass type. Produces a
6224 /// null type if there is no superclass.
6225 QualType getSuperClassType() const;
6226
6227 /// Strip off the Objective-C "kindof" type and (with it) any
6228 /// protocol qualifiers.
6229 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6230 const ASTContext &ctx) const;
6231
6232 void Profile(llvm::FoldingSetNodeID &ID) {
6233 Profile(ID, getPointeeType());
6234 }
6235
6236 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6237 ID.AddPointer(T.getAsOpaquePtr());
6238 }
6239
6240 static bool classof(const Type *T) {
6241 return T->getTypeClass() == ObjCObjectPointer;
6242 }
6243};
6244
6245class AtomicType : public Type, public llvm::FoldingSetNode {
6246 friend class ASTContext; // ASTContext creates these.
6247
6248 QualType ValueType;
6249
6250 AtomicType(QualType ValTy, QualType Canonical)
6251 : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {}
6252
6253public:
6254 /// Gets the type contained by this atomic type, i.e.
6255 /// the type returned by performing an atomic load of this atomic type.
6256 QualType getValueType() const { return ValueType; }
6257
6258 bool isSugared() const { return false; }
6259 QualType desugar() const { return QualType(this, 0); }
6260
6261 void Profile(llvm::FoldingSetNodeID &ID) {
6262 Profile(ID, getValueType());
6263 }
6264
6265 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6266 ID.AddPointer(T.getAsOpaquePtr());
6267 }
6268
6269 static bool classof(const Type *T) {
6270 return T->getTypeClass() == Atomic;
6271 }
6272};
6273
6274/// PipeType - OpenCL20.
6275class PipeType : public Type, public llvm::FoldingSetNode {
6276 friend class ASTContext; // ASTContext creates these.
6277
6278 QualType ElementType;
6279 bool isRead;
6280
6281 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6282 : Type(Pipe, CanonicalPtr, elemType->getDependence()),
6283 ElementType(elemType), isRead(isRead) {}
6284
6285public:
6286 QualType getElementType() const { return ElementType; }
6287
6288 bool isSugared() const { return false; }
6289
6290 QualType desugar() const { return QualType(this, 0); }
6291
6292 void Profile(llvm::FoldingSetNodeID &ID) {
6293 Profile(ID, getElementType(), isReadOnly());
6294 }
6295
6296 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6297 ID.AddPointer(T.getAsOpaquePtr());
6298 ID.AddBoolean(isRead);
6299 }
6300
6301 static bool classof(const Type *T) {
6302 return T->getTypeClass() == Pipe;
6303 }
6304
6305 bool isReadOnly() const { return isRead; }
6306};
6307
6308/// A fixed int type of a specified bitwidth.
6309class ExtIntType final : public Type, public llvm::FoldingSetNode {
6310 friend class ASTContext;
6311 unsigned IsUnsigned : 1;
6312 unsigned NumBits : 24;
6313
6314protected:
6315 ExtIntType(bool isUnsigned, unsigned NumBits);
6316
6317public:
6318 bool isUnsigned() const { return IsUnsigned; }
6319 bool isSigned() const { return !IsUnsigned; }
6320 unsigned getNumBits() const { return NumBits; }
6321
6322 bool isSugared() const { return false; }
6323 QualType desugar() const { return QualType(this, 0); }
6324
6325 void Profile(llvm::FoldingSetNodeID &ID) {
6326 Profile(ID, isUnsigned(), getNumBits());
6327 }
6328
6329 static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned,
6330 unsigned NumBits) {
6331 ID.AddBoolean(IsUnsigned);
6332 ID.AddInteger(NumBits);
6333 }
6334
6335 static bool classof(const Type *T) { return T->getTypeClass() == ExtInt; }
6336};
6337
6338class DependentExtIntType final : public Type, public llvm::FoldingSetNode {
6339 friend class ASTContext;
6340 const ASTContext &Context;
6341 llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned;
6342
6343protected:
6344 DependentExtIntType(const ASTContext &Context, bool IsUnsigned,
6345 Expr *NumBits);
6346
6347public:
6348 bool isUnsigned() const;
6349 bool isSigned() const { return !isUnsigned(); }
6350 Expr *getNumBitsExpr() const;
6351
6352 bool isSugared() const { return false; }
6353 QualType desugar() const { return QualType(this, 0); }
6354
6355 void Profile(llvm::FoldingSetNodeID &ID) {
6356 Profile(ID, Context, isUnsigned(), getNumBitsExpr());
6357 }
6358 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
6359 bool IsUnsigned, Expr *NumBitsExpr);
6360
6361 static bool classof(const Type *T) {
6362 return T->getTypeClass() == DependentExtInt;
6363 }
6364};
6365
6366/// A qualifier set is used to build a set of qualifiers.
6367class QualifierCollector : public Qualifiers {
6368public:
6369 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6370
6371 /// Collect any qualifiers on the given type and return an
6372 /// unqualified type. The qualifiers are assumed to be consistent
6373 /// with those already in the type.
6374 const Type *strip(QualType type) {
6375 addFastQualifiers(type.getLocalFastQualifiers());
6376 if (!type.hasLocalNonFastQualifiers())
6377 return type.getTypePtrUnsafe();
6378
6379 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6380 addConsistentQualifiers(extQuals->getQualifiers());
6381 return extQuals->getBaseType();
6382 }
6383
6384 /// Apply the collected qualifiers to the given type.
6385 QualType apply(const ASTContext &Context, QualType QT) const;
6386
6387 /// Apply the collected qualifiers to the given type.
6388 QualType apply(const ASTContext &Context, const Type* T) const;
6389};
6390
6391/// A container of type source information.
6392///
6393/// A client can read the relevant info using TypeLoc wrappers, e.g:
6394/// @code
6395/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
6396/// TL.getBeginLoc().print(OS, SrcMgr);
6397/// @endcode
6398class alignas(8) TypeSourceInfo {
6399 // Contains a memory block after the class, used for type source information,
6400 // allocated by ASTContext.
6401 friend class ASTContext;
6402
6403 QualType Ty;
6404
6405 TypeSourceInfo(QualType ty) : Ty(ty) {}
6406
6407public:
6408 /// Return the type wrapped by this type source info.
6409 QualType getType() const { return Ty; }
6410
6411 /// Return the TypeLoc wrapper for the type source info.
6412 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
6413
6414 /// Override the type stored in this TypeSourceInfo. Use with caution!
6415 void overrideType(QualType T) { Ty = T; }
6416};
6417
6418// Inline function definitions.
6419
6420inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6421 SplitQualType desugar =
6422 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6423 desugar.Quals.addConsistentQualifiers(Quals);
6424 return desugar;
6425}
6426
6427inline const Type *QualType::getTypePtr() const {
6428 return getCommonPtr()->BaseType;
6429}
6430
6431inline const Type *QualType::getTypePtrOrNull() const {
6432 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6433}
6434
6435inline SplitQualType QualType::split() const {
6436 if (!hasLocalNonFastQualifiers())
6437 return SplitQualType(getTypePtrUnsafe(),
6438 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6439
6440 const ExtQuals *eq = getExtQualsUnsafe();
6441 Qualifiers qs = eq->getQualifiers();
6442 qs.addFastQualifiers(getLocalFastQualifiers());
6443 return SplitQualType(eq->getBaseType(), qs);
6444}
6445
6446inline Qualifiers QualType::getLocalQualifiers() const {
6447 Qualifiers Quals;
6448 if (hasLocalNonFastQualifiers())
6449 Quals = getExtQualsUnsafe()->getQualifiers();
6450 Quals.addFastQualifiers(getLocalFastQualifiers());
6451 return Quals;
6452}
6453
6454inline Qualifiers QualType::getQualifiers() const {
6455 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6456 quals.addFastQualifiers(getLocalFastQualifiers());
6457 return quals;
6458}
6459
6460inline unsigned QualType::getCVRQualifiers() const {
6461 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6462 cvr |= getLocalCVRQualifiers();
6463 return cvr;
6464}
6465
6466inline QualType QualType::getCanonicalType() const {
6467 QualType canon = getCommonPtr()->CanonicalType;
6468 return canon.withFastQualifiers(getLocalFastQualifiers());
6469}
6470
6471inline bool QualType::isCanonical() const {
6472 return getTypePtr()->isCanonicalUnqualified();
6473}
6474
6475inline bool QualType::isCanonicalAsParam() const {
6476 if (!isCanonical()) return false;
6477 if (hasLocalQualifiers()) return false;
6478
6479 const Type *T = getTypePtr();
6480 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6481 return false;
6482
6483 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6484}
6485
6486inline bool QualType::isConstQualified() const {
6487 return isLocalConstQualified() ||
6488 getCommonPtr()->CanonicalType.isLocalConstQualified();
6489}
6490
6491inline bool QualType::isRestrictQualified() const {
6492 return isLocalRestrictQualified() ||
6493 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6494}
6495
6496
6497inline bool QualType::isVolatileQualified() const {
6498 return isLocalVolatileQualified() ||
6499 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6500}
6501
6502inline bool QualType::hasQualifiers() const {
6503 return hasLocalQualifiers() ||
6504 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6505}
6506
6507inline QualType QualType::getUnqualifiedType() const {
6508 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6509 return QualType(getTypePtr(), 0);
6510
6511 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6512}
6513
6514inline SplitQualType QualType::getSplitUnqualifiedType() const {
6515 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6516 return split();
6517
6518 return getSplitUnqualifiedTypeImpl(*this);
6519}
6520
6521inline void QualType::removeLocalConst() {
6522 removeLocalFastQualifiers(Qualifiers::Const);
6523}
6524
6525inline void QualType::removeLocalRestrict() {
6526 removeLocalFastQualifiers(Qualifiers::Restrict);
6527}
6528
6529inline void QualType::removeLocalVolatile() {
6530 removeLocalFastQualifiers(Qualifiers::Volatile);
6531}
6532
6533inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6534 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")(static_cast <bool> (!(Mask & ~Qualifiers::CVRMask)
&& "mask has non-CVR bits") ? void (0) : __assert_fail
("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 6534, __extension__ __PRETTY_FUNCTION__))
;
6535 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6536 "Fast bits differ from CVR bits!");
6537
6538 // Fast path: we don't need to touch the slow qualifiers.
6539 removeLocalFastQualifiers(Mask);
6540}
6541
6542/// Check if this type has any address space qualifier.
6543inline bool QualType::hasAddressSpace() const {
6544 return getQualifiers().hasAddressSpace();
6545}
6546
6547/// Return the address space of this type.
6548inline LangAS QualType::getAddressSpace() const {
6549 return getQualifiers().getAddressSpace();
6550}
6551
6552/// Return the gc attribute of this type.
6553inline Qualifiers::GC QualType::getObjCGCAttr() const {
6554 return getQualifiers().getObjCGCAttr();
6555}
6556
6557inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6558 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6559 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6560 return false;
6561}
6562
6563inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6564 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6565 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6566 return false;
6567}
6568
6569inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6570 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6571 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6572 return false;
6573}
6574
6575inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6576 if (const auto *PT = t.getAs<PointerType>()) {
6577 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6578 return FT->getExtInfo();
6579 } else if (const auto *FT = t.getAs<FunctionType>())
6580 return FT->getExtInfo();
6581
6582 return FunctionType::ExtInfo();
6583}
6584
6585inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6586 return getFunctionExtInfo(*t);
6587}
6588
6589/// Determine whether this type is more
6590/// qualified than the Other type. For example, "const volatile int"
6591/// is more qualified than "const int", "volatile int", and
6592/// "int". However, it is not more qualified than "const volatile
6593/// int".
6594inline bool QualType::isMoreQualifiedThan(QualType other) const {
6595 Qualifiers MyQuals = getQualifiers();
6596 Qualifiers OtherQuals = other.getQualifiers();
6597 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6598}
6599
6600/// Determine whether this type is at last
6601/// as qualified as the Other type. For example, "const volatile
6602/// int" is at least as qualified as "const int", "volatile int",
6603/// "int", and "const volatile int".
6604inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6605 Qualifiers OtherQuals = other.getQualifiers();
6606
6607 // Ignore __unaligned qualifier if this type is a void.
6608 if (getUnqualifiedType()->isVoidType())
6609 OtherQuals.removeUnaligned();
6610
6611 return getQualifiers().compatiblyIncludes(OtherQuals);
6612}
6613
6614/// If Type is a reference type (e.g., const
6615/// int&), returns the type that the reference refers to ("const
6616/// int"). Otherwise, returns the type itself. This routine is used
6617/// throughout Sema to implement C++ 5p6:
6618///
6619/// If an expression initially has the type "reference to T" (8.3.2,
6620/// 8.5.3), the type is adjusted to "T" prior to any further
6621/// analysis, the expression designates the object or function
6622/// denoted by the reference, and the expression is an lvalue.
6623inline QualType QualType::getNonReferenceType() const {
6624 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6625 return RefType->getPointeeType();
6626 else
6627 return *this;
6628}
6629
6630inline bool QualType::isCForbiddenLValueType() const {
6631 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6632 getTypePtr()->isFunctionType());
6633}
6634
6635/// Tests whether the type is categorized as a fundamental type.
6636///
6637/// \returns True for types specified in C++0x [basic.fundamental].
6638inline bool Type::isFundamentalType() const {
6639 return isVoidType() ||
6640 isNullPtrType() ||
6641 // FIXME: It's really annoying that we don't have an
6642 // 'isArithmeticType()' which agrees with the standard definition.
6643 (isArithmeticType() && !isEnumeralType());
6644}
6645
6646/// Tests whether the type is categorized as a compound type.
6647///
6648/// \returns True for types specified in C++0x [basic.compound].
6649inline bool Type::isCompoundType() const {
6650 // C++0x [basic.compound]p1:
6651 // Compound types can be constructed in the following ways:
6652 // -- arrays of objects of a given type [...];
6653 return isArrayType() ||
6654 // -- functions, which have parameters of given types [...];
6655 isFunctionType() ||
6656 // -- pointers to void or objects or functions [...];
6657 isPointerType() ||
6658 // -- references to objects or functions of a given type. [...]
6659 isReferenceType() ||
6660 // -- classes containing a sequence of objects of various types, [...];
6661 isRecordType() ||
6662 // -- unions, which are classes capable of containing objects of different
6663 // types at different times;
6664 isUnionType() ||
6665 // -- enumerations, which comprise a set of named constant values. [...];
6666 isEnumeralType() ||
6667 // -- pointers to non-static class members, [...].
6668 isMemberPointerType();
6669}
6670
6671inline bool Type::isFunctionType() const {
6672 return isa<FunctionType>(CanonicalType);
6673}
6674
6675inline bool Type::isPointerType() const {
6676 return isa<PointerType>(CanonicalType);
6677}
6678
6679inline bool Type::isAnyPointerType() const {
6680 return isPointerType() || isObjCObjectPointerType();
6681}
6682
6683inline bool Type::isBlockPointerType() const {
6684 return isa<BlockPointerType>(CanonicalType);
6685}
6686
6687inline bool Type::isReferenceType() const {
6688 return isa<ReferenceType>(CanonicalType);
6689}
6690
6691inline bool Type::isLValueReferenceType() const {
6692 return isa<LValueReferenceType>(CanonicalType);
6693}
6694
6695inline bool Type::isRValueReferenceType() const {
6696 return isa<RValueReferenceType>(CanonicalType);
6697}
6698
6699inline bool Type::isObjectPointerType() const {
6700 // Note: an "object pointer type" is not the same thing as a pointer to an
6701 // object type; rather, it is a pointer to an object type or a pointer to cv
6702 // void.
6703 if (const auto *T = getAs<PointerType>())
6704 return !T->getPointeeType()->isFunctionType();
6705 else
6706 return false;
6707}
6708
6709inline bool Type::isFunctionPointerType() const {
6710 if (const auto *T = getAs<PointerType>())
6711 return T->getPointeeType()->isFunctionType();
6712 else
6713 return false;
6714}
6715
6716inline bool Type::isFunctionReferenceType() const {
6717 if (const auto *T = getAs<ReferenceType>())
6718 return T->getPointeeType()->isFunctionType();
6719 else
6720 return false;
6721}
6722
6723inline bool Type::isMemberPointerType() const {
6724 return isa<MemberPointerType>(CanonicalType);
6725}
6726
6727inline bool Type::isMemberFunctionPointerType() const {
6728 if (const auto *T = getAs<MemberPointerType>())
6729 return T->isMemberFunctionPointer();
6730 else
6731 return false;
6732}
6733
6734inline bool Type::isMemberDataPointerType() const {
6735 if (const auto *T = getAs<MemberPointerType>())
6736 return T->isMemberDataPointer();
6737 else
6738 return false;
6739}
6740
6741inline bool Type::isArrayType() const {
6742 return isa<ArrayType>(CanonicalType);
6743}
6744
6745inline bool Type::isConstantArrayType() const {
6746 return isa<ConstantArrayType>(CanonicalType);
6747}
6748
6749inline bool Type::isIncompleteArrayType() const {
6750 return isa<IncompleteArrayType>(CanonicalType);
6751}
6752
6753inline bool Type::isVariableArrayType() const {
6754 return isa<VariableArrayType>(CanonicalType);
6755}
6756
6757inline bool Type::isDependentSizedArrayType() const {
6758 return isa<DependentSizedArrayType>(CanonicalType);
6759}
6760
6761inline bool Type::isBuiltinType() const {
6762 return isa<BuiltinType>(CanonicalType);
6763}
6764
6765inline bool Type::isRecordType() const {
6766 return isa<RecordType>(CanonicalType);
6767}
6768
6769inline bool Type::isEnumeralType() const {
6770 return isa<EnumType>(CanonicalType);
6771}
6772
6773inline bool Type::isAnyComplexType() const {
6774 return isa<ComplexType>(CanonicalType);
6775}
6776
6777inline bool Type::isVectorType() const {
6778 return isa<VectorType>(CanonicalType);
6779}
6780
6781inline bool Type::isExtVectorType() const {
6782 return isa<ExtVectorType>(CanonicalType);
6783}
6784
6785inline bool Type::isMatrixType() const {
6786 return isa<MatrixType>(CanonicalType);
6787}
6788
6789inline bool Type::isConstantMatrixType() const {
6790 return isa<ConstantMatrixType>(CanonicalType);
6791}
6792
6793inline bool Type::isDependentAddressSpaceType() const {
6794 return isa<DependentAddressSpaceType>(CanonicalType);
6795}
6796
6797inline bool Type::isObjCObjectPointerType() const {
6798 return isa<ObjCObjectPointerType>(CanonicalType);
6799}
6800
6801inline bool Type::isObjCObjectType() const {
6802 return isa<ObjCObjectType>(CanonicalType);
6803}
6804
6805inline bool Type::isObjCObjectOrInterfaceType() const {
6806 return isa<ObjCInterfaceType>(CanonicalType) ||
6807 isa<ObjCObjectType>(CanonicalType);
6808}
6809
6810inline bool Type::isAtomicType() const {
6811 return isa<AtomicType>(CanonicalType);
6812}
6813
6814inline bool Type::isUndeducedAutoType() const {
6815 return isa<AutoType>(CanonicalType);
6816}
6817
6818inline bool Type::isObjCQualifiedIdType() const {
6819 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6820 return OPT->isObjCQualifiedIdType();
6821 return false;
6822}
6823
6824inline bool Type::isObjCQualifiedClassType() const {
6825 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6826 return OPT->isObjCQualifiedClassType();
6827 return false;
6828}
6829
6830inline bool Type::isObjCIdType() const {
6831 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6832 return OPT->isObjCIdType();
6833 return false;
6834}
6835
6836inline bool Type::isObjCClassType() const {
6837 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6838 return OPT->isObjCClassType();
6839 return false;
6840}
6841
6842inline bool Type::isObjCSelType() const {
6843 if (const auto *OPT = getAs<PointerType>())
6844 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6845 return false;
6846}
6847
6848inline bool Type::isObjCBuiltinType() const {
6849 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6850}
6851
6852inline bool Type::isDecltypeType() const {
6853 return isa<DecltypeType>(this);
6854}
6855
6856#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6857 inline bool Type::is##Id##Type() const { \
6858 return isSpecificBuiltinType(BuiltinType::Id); \
6859 }
6860#include "clang/Basic/OpenCLImageTypes.def"
6861
6862inline bool Type::isSamplerT() const {
6863 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6864}
6865
6866inline bool Type::isEventT() const {
6867 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6868}
6869
6870inline bool Type::isClkEventT() const {
6871 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6872}
6873
6874inline bool Type::isQueueT() const {
6875 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6876}
6877
6878inline bool Type::isReserveIDT() const {
6879 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6880}
6881
6882inline bool Type::isImageType() const {
6883#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6884 return
6885#include "clang/Basic/OpenCLImageTypes.def"
6886 false; // end boolean or operation
6887}
6888
6889inline bool Type::isPipeType() const {
6890 return isa<PipeType>(CanonicalType);
6891}
6892
6893inline bool Type::isExtIntType() const {
6894 return isa<ExtIntType>(CanonicalType);
6895}
6896
6897#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6898 inline bool Type::is##Id##Type() const { \
6899 return isSpecificBuiltinType(BuiltinType::Id); \
6900 }
6901#include "clang/Basic/OpenCLExtensionTypes.def"
6902
6903inline bool Type::isOCLIntelSubgroupAVCType() const {
6904#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6905 isOCLIntelSubgroupAVC##Id##Type() ||
6906 return
6907#include "clang/Basic/OpenCLExtensionTypes.def"
6908 false; // end of boolean or operation
6909}
6910
6911inline bool Type::isOCLExtOpaqueType() const {
6912#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6913 return
6914#include "clang/Basic/OpenCLExtensionTypes.def"
6915 false; // end of boolean or operation
6916}
6917
6918inline bool Type::isOpenCLSpecificType() const {
6919 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6920 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6921}
6922
6923inline bool Type::isTemplateTypeParmType() const {
6924 return isa<TemplateTypeParmType>(CanonicalType);
6925}
6926
6927inline bool Type::isSpecificBuiltinType(unsigned K) const {
6928 if (const BuiltinType *BT = getAs<BuiltinType>()) {
6929 return BT->getKind() == static_cast<BuiltinType::Kind>(K);
6930 }
6931 return false;
6932}
6933
6934inline bool Type::isPlaceholderType() const {
6935 if (const auto *BT = dyn_cast<BuiltinType>(this))
6936 return BT->isPlaceholderType();
6937 return false;
6938}
6939
6940inline const BuiltinType *Type::getAsPlaceholderType() const {
6941 if (const auto *BT = dyn_cast<BuiltinType>(this))
6942 if (BT->isPlaceholderType())
6943 return BT;
6944 return nullptr;
6945}
6946
6947inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6948 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))(static_cast <bool> (BuiltinType::isPlaceholderTypeKind
((BuiltinType::Kind) K)) ? void (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 6948, __extension__ __PRETTY_FUNCTION__))
;
6949 return isSpecificBuiltinType(K);
6950}
6951
6952inline bool Type::isNonOverloadPlaceholderType() const {
6953 if (const auto *BT = dyn_cast<BuiltinType>(this))
6954 return BT->isNonOverloadPlaceholderType();
6955 return false;
6956}
6957
6958inline bool Type::isVoidType() const {
6959 return isSpecificBuiltinType(BuiltinType::Void);
6960}
6961
6962inline bool Type::isHalfType() const {
6963 // FIXME: Should we allow complex __fp16? Probably not.
6964 return isSpecificBuiltinType(BuiltinType::Half);
6965}
6966
6967inline bool Type::isFloat16Type() const {
6968 return isSpecificBuiltinType(BuiltinType::Float16);
6969}
6970
6971inline bool Type::isBFloat16Type() const {
6972 return isSpecificBuiltinType(BuiltinType::BFloat16);
6973}
6974
6975inline bool Type::isFloat128Type() const {
6976 return isSpecificBuiltinType(BuiltinType::Float128);
6977}
6978
6979inline bool Type::isNullPtrType() const {
6980 return isSpecificBuiltinType(BuiltinType::NullPtr);
6981}
6982
6983bool IsEnumDeclComplete(EnumDecl *);
6984bool IsEnumDeclScoped(EnumDecl *);
6985
6986inline bool Type::isIntegerType() const {
6987 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6988 return BT->getKind() >= BuiltinType::Bool &&
6989 BT->getKind() <= BuiltinType::Int128;
6990 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6991 // Incomplete enum types are not treated as integer types.
6992 // FIXME: In C++, enum types are never integer types.
6993 return IsEnumDeclComplete(ET->getDecl()) &&
6994 !IsEnumDeclScoped(ET->getDecl());
6995 }
6996 return isExtIntType();
6997}
6998
6999inline bool Type::isFixedPointType() const {
7000 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7001 return BT->getKind() >= BuiltinType::ShortAccum &&
7002 BT->getKind() <= BuiltinType::SatULongFract;
7003 }
7004 return false;
7005}
7006
7007inline bool Type::isFixedPointOrIntegerType() const {
7008 return isFixedPointType() || isIntegerType();
7009}
7010
7011inline bool Type::isSaturatedFixedPointType() const {
7012 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7013 return BT->getKind() >= BuiltinType::SatShortAccum &&
7014 BT->getKind() <= BuiltinType::SatULongFract;
7015 }
7016 return false;
7017}
7018
7019inline bool Type::isUnsaturatedFixedPointType() const {
7020 return isFixedPointType() && !isSaturatedFixedPointType();
7021}
7022
7023inline bool Type::isSignedFixedPointType() const {
7024 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7025 return ((BT->getKind() >= BuiltinType::ShortAccum &&
7026 BT->getKind() <= BuiltinType::LongAccum) ||
7027 (BT->getKind() >= BuiltinType::ShortFract &&
7028 BT->getKind() <= BuiltinType::LongFract) ||
7029 (BT->getKind() >= BuiltinType::SatShortAccum &&
7030 BT->getKind() <= BuiltinType::SatLongAccum) ||
7031 (BT->getKind() >= BuiltinType::SatShortFract &&
7032 BT->getKind() <= BuiltinType::SatLongFract));
7033 }
7034 return false;
7035}
7036
7037inline bool Type::isUnsignedFixedPointType() const {
7038 return isFixedPointType() && !isSignedFixedPointType();
7039}
7040
7041inline bool Type::isScalarType() const {
7042 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7043 return BT->getKind() > BuiltinType::Void &&
7044 BT->getKind() <= BuiltinType::NullPtr;
7045 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
7046 // Enums are scalar types, but only if they are defined. Incomplete enums
7047 // are not treated as scalar types.
7048 return IsEnumDeclComplete(ET->getDecl());
7049 return isa<PointerType>(CanonicalType) ||
7050 isa<BlockPointerType>(CanonicalType) ||
7051 isa<MemberPointerType>(CanonicalType) ||
7052 isa<ComplexType>(CanonicalType) ||
7053 isa<ObjCObjectPointerType>(CanonicalType) ||
7054 isExtIntType();
7055}
7056
7057inline bool Type::isIntegralOrEnumerationType() const {
7058 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7059 return BT->getKind() >= BuiltinType::Bool &&
7060 BT->getKind() <= BuiltinType::Int128;
7061
7062 // Check for a complete enum type; incomplete enum types are not properly an
7063 // enumeration type in the sense required here.
7064 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
7065 return IsEnumDeclComplete(ET->getDecl());
7066
7067 return isExtIntType();
7068}
7069
7070inline bool Type::isBooleanType() const {
7071 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7072 return BT->getKind() == BuiltinType::Bool;
7073 return false;
7074}
7075
7076inline bool Type::isUndeducedType() const {
7077 auto *DT = getContainedDeducedType();
7078 return DT && !DT->isDeduced();
7079}
7080
7081/// Determines whether this is a type for which one can define
7082/// an overloaded operator.
7083inline bool Type::isOverloadableType() const {
7084 return isDependentType() || isRecordType() || isEnumeralType();
7085}
7086
7087/// Determines whether this type is written as a typedef-name.
7088inline bool Type::isTypedefNameType() const {
7089 if (getAs<TypedefType>())
7090 return true;
7091 if (auto *TST = getAs<TemplateSpecializationType>())
7092 return TST->isTypeAlias();
7093 return false;
7094}
7095
7096/// Determines whether this type can decay to a pointer type.
7097inline bool Type::canDecayToPointerType() const {
7098 return isFunctionType() || isArrayType();
7099}
7100
7101inline bool Type::hasPointerRepresentation() const {
7102 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
7103 isObjCObjectPointerType() || isNullPtrType());
7104}
7105
7106inline bool Type::hasObjCPointerRepresentation() const {
7107 return isObjCObjectPointerType();
7108}
7109
7110inline const Type *Type::getBaseElementTypeUnsafe() const {
7111 const Type *type = this;
7112 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
7113 type = arrayType->getElementType().getTypePtr();
7114 return type;
7115}
7116
7117inline const Type *Type::getPointeeOrArrayElementType() const {
7118 const Type *type = this;
7119 if (type->isAnyPointerType())
7120 return type->getPointeeType().getTypePtr();
7121 else if (type->isArrayType())
7122 return type->getBaseElementTypeUnsafe();
7123 return type;
7124}
7125/// Insertion operator for partial diagnostics. This allows sending adress
7126/// spaces into a diagnostic with <<.
7127inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7128 LangAS AS) {
7129 PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
7130 DiagnosticsEngine::ArgumentKind::ak_addrspace);
7131 return PD;
7132}
7133
7134/// Insertion operator for partial diagnostics. This allows sending Qualifiers
7135/// into a diagnostic with <<.
7136inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7137 Qualifiers Q) {
7138 PD.AddTaggedVal(Q.getAsOpaqueValue(),
7139 DiagnosticsEngine::ArgumentKind::ak_qual);
7140 return PD;
7141}
7142
7143/// Insertion operator for partial diagnostics. This allows sending QualType's
7144/// into a diagnostic with <<.
7145inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7146 QualType T) {
7147 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
7148 DiagnosticsEngine::ak_qualtype);
7149 return PD;
7150}
7151
7152// Helper class template that is used by Type::getAs to ensure that one does
7153// not try to look through a qualified type to get to an array type.
7154template <typename T>
7155using TypeIsArrayType =
7156 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
7157 std::is_base_of<ArrayType, T>::value>;
7158
7159// Member-template getAs<specific type>'.
7160template <typename T> const T *Type::getAs() const {
7161 static_assert(!TypeIsArrayType<T>::value,
7162 "ArrayType cannot be used with getAs!");
7163
7164 // If this is directly a T type, return it.
7165 if (const auto *Ty = dyn_cast<T>(this))
7166 return Ty;
7167
7168 // If the canonical form of this type isn't the right kind, reject it.
7169 if (!isa<T>(CanonicalType))
7170 return nullptr;
7171
7172 // If this is a typedef for the type, strip the typedef off without
7173 // losing all typedef information.
7174 return cast<T>(getUnqualifiedDesugaredType());
7175}
7176
7177template <typename T> const T *Type::getAsAdjusted() const {
7178 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
7179
7180 // If this is directly a T type, return it.
7181 if (const auto *Ty = dyn_cast<T>(this))
7182 return Ty;
7183
7184 // If the canonical form of this type isn't the right kind, reject it.
7185 if (!isa<T>(CanonicalType))
7186 return nullptr;
7187
7188 // Strip off type adjustments that do not modify the underlying nature of the
7189 // type.
7190 const Type *Ty = this;
7191 while (Ty) {
7192 if (const auto *A = dyn_cast<AttributedType>(Ty))
7193 Ty = A->getModifiedType().getTypePtr();
7194 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
7195 Ty = E->desugar().getTypePtr();
7196 else if (const auto *P = dyn_cast<ParenType>(Ty))
7197 Ty = P->desugar().getTypePtr();
7198 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
7199 Ty = A->desugar().getTypePtr();
7200 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
7201 Ty = M->desugar().getTypePtr();
7202 else
7203 break;
7204 }
7205
7206 // Just because the canonical type is correct does not mean we can use cast<>,
7207 // since we may not have stripped off all the sugar down to the base type.
7208 return dyn_cast<T>(Ty);
7209}
7210
7211inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
7212 // If this is directly an array type, return it.
7213 if (const auto *arr = dyn_cast<ArrayType>(this))
7214 return arr;
7215
7216 // If the canonical form of this type isn't the right kind, reject it.
7217 if (!isa<ArrayType>(CanonicalType))
7218 return nullptr;
7219
7220 // If this is a typedef for the type, strip the typedef off without
7221 // losing all typedef information.
7222 return cast<ArrayType>(getUnqualifiedDesugaredType());
7223}
7224
7225template <typename T> const T *Type::castAs() const {
7226 static_assert(!TypeIsArrayType<T>::value,
7227 "ArrayType cannot be used with castAs!");
7228
7229 if (const auto *ty = dyn_cast<T>(this)) return ty;
7230 assert(isa<T>(CanonicalType))(static_cast <bool> (isa<T>(CanonicalType)) ? void
(0) : __assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 7230, __extension__ __PRETTY_FUNCTION__))
;
7231 return cast<T>(getUnqualifiedDesugaredType());
7232}
7233
7234inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
7235 assert(isa<ArrayType>(CanonicalType))(static_cast <bool> (isa<ArrayType>(CanonicalType
)) ? void (0) : __assert_fail ("isa<ArrayType>(CanonicalType)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 7235, __extension__ __PRETTY_FUNCTION__))
;
7236 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
7237 return cast<ArrayType>(getUnqualifiedDesugaredType());
7238}
7239
7240DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
7241 QualType CanonicalPtr)
7242 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
7243#ifndef NDEBUG
7244 QualType Adjusted = getAdjustedType();
7245 (void)AttributedType::stripOuterNullability(Adjusted);
7246 assert(isa<PointerType>(Adjusted))(static_cast <bool> (isa<PointerType>(Adjusted)) ?
void (0) : __assert_fail ("isa<PointerType>(Adjusted)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include/clang/AST/Type.h"
, 7246, __extension__ __PRETTY_FUNCTION__))
;
7247#endif
7248}
7249
7250QualType DecayedType::getPointeeType() const {
7251 QualType Decayed = getDecayedType();
7252 (void)AttributedType::stripOuterNullability(Decayed);
7253 return cast<PointerType>(Decayed)->getPointeeType();
7254}
7255
7256// Get the decimal string representation of a fixed point type, represented
7257// as a scaled integer.
7258// TODO: At some point, we should change the arguments to instead just accept an
7259// APFixedPoint instead of APSInt and scale.
7260void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
7261 unsigned Scale);
7262
7263} // namespace clang
7264
7265#endif // LLVM_CLANG_AST_TYPE_H

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerUnion.h

1//===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- 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// This file defines the PointerUnion class, which is a discriminated union of
10// pointer types.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_POINTERUNION_H
15#define LLVM_ADT_POINTERUNION_H
16
17#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/Support/PointerLikeTypeTraits.h"
20#include <cassert>
21#include <cstddef>
22#include <cstdint>
23
24namespace llvm {
25
26template <typename T> struct PointerUnionTypeSelectorReturn {
27 using Return = T;
28};
29
30/// Get a type based on whether two types are the same or not.
31///
32/// For:
33///
34/// \code
35/// using Ret = typename PointerUnionTypeSelector<T1, T2, EQ, NE>::Return;
36/// \endcode
37///
38/// Ret will be EQ type if T1 is same as T2 or NE type otherwise.
39template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
40struct PointerUnionTypeSelector {
41 using Return = typename PointerUnionTypeSelectorReturn<RET_NE>::Return;
42};
43
44template <typename T, typename RET_EQ, typename RET_NE>
45struct PointerUnionTypeSelector<T, T, RET_EQ, RET_NE> {
46 using Return = typename PointerUnionTypeSelectorReturn<RET_EQ>::Return;
47};
48
49template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
50struct PointerUnionTypeSelectorReturn<
51 PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>> {
52 using Return =
53 typename PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>::Return;
54};
55
56namespace pointer_union_detail {
57 /// Determine the number of bits required to store integers with values < n.
58 /// This is ceil(log2(n)).
59 constexpr int bitsRequired(unsigned n) {
60 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
61 }
62
63 template <typename... Ts> constexpr int lowBitsAvailable() {
64 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
65 }
66
67 /// Find the index of a type in a list of types. TypeIndex<T, Us...>::Index
68 /// is the index of T in Us, or sizeof...(Us) if T does not appear in the
69 /// list.
70 template <typename T, typename ...Us> struct TypeIndex;
71 template <typename T, typename ...Us> struct TypeIndex<T, T, Us...> {
72 static constexpr int Index = 0;
73 };
74 template <typename T, typename U, typename... Us>
75 struct TypeIndex<T, U, Us...> {
76 static constexpr int Index = 1 + TypeIndex<T, Us...>::Index;
77 };
78 template <typename T> struct TypeIndex<T> {
79 static constexpr int Index = 0;
80 };
81
82 /// Find the first type in a list of types.
83 template <typename T, typename...> struct GetFirstType {
84 using type = T;
85 };
86
87 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
88 /// for the template arguments.
89 template <typename ...PTs> class PointerUnionUIntTraits {
90 public:
91 static inline void *getAsVoidPointer(void *P) { return P; }
92 static inline void *getFromVoidPointer(void *P) { return P; }
93 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
94 };
95
96 template <typename Derived, typename ValTy, int I, typename ...Types>
97 class PointerUnionMembers;
98
99 template <typename Derived, typename ValTy, int I>
100 class PointerUnionMembers<Derived, ValTy, I> {
101 protected:
102 ValTy Val;
103 PointerUnionMembers() = default;
104 PointerUnionMembers(ValTy Val) : Val(Val) {}
105
106 friend struct PointerLikeTypeTraits<Derived>;
107 };
108
109 template <typename Derived, typename ValTy, int I, typename Type,
110 typename ...Types>
111 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
112 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
113 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
114 public:
115 using Base::Base;
116 PointerUnionMembers() = default;
117 PointerUnionMembers(Type V)
118 : Base(ValTy(const_cast<void *>(
119 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
120 I)) {}
121
122 using Base::operator=;
123 Derived &operator=(Type V) {
124 this->Val = ValTy(
125 const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
126 I);
127 return static_cast<Derived &>(*this);
128 };
129 };
130}
131
132/// A discriminated union of two or more pointer types, with the discriminator
133/// in the low bit of the pointer.
134///
135/// This implementation is extremely efficient in space due to leveraging the
136/// low bits of the pointer, while exposing a natural and type-safe API.
137///
138/// Common use patterns would be something like this:
139/// PointerUnion<int*, float*> P;
140/// P = (int*)0;
141/// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
142/// X = P.get<int*>(); // ok.
143/// Y = P.get<float*>(); // runtime assertion failure.
144/// Z = P.get<double*>(); // compile time failure.
145/// P = (float*)0;
146/// Y = P.get<float*>(); // ok.
147/// X = P.get<int*>(); // runtime assertion failure.
148template <typename... PTs>
149class PointerUnion
150 : public pointer_union_detail::PointerUnionMembers<
151 PointerUnion<PTs...>,
152 PointerIntPair<
153 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
154 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
155 0, PTs...> {
156 // The first type is special because we want to directly cast a pointer to a
157 // default-initialized union to a pointer to the first type. But we don't
158 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
159 // because it's much more convenient to have a name for the whole pack. So
160 // split off the first type here.
161 using First = typename pointer_union_detail::GetFirstType<PTs...>::type;
162 using Base = typename PointerUnion::PointerUnionMembers;
163
164public:
165 PointerUnion() = default;
166
167 PointerUnion(std::nullptr_t) : PointerUnion() {}
168 using Base::Base;
169
170 /// Test if the pointer held in the union is null, regardless of
171 /// which type it is.
172 bool isNull() const { return !this->Val.getPointer(); }
39
Assuming the condition is false
40
Returning zero, which participates in a condition later
50
Assuming the condition is false
51
Returning zero, which participates in a condition later
58
Assuming the condition is true
59
Returning the value 1, which participates in a condition later
173
174 explicit operator bool() const { return !isNull(); }
175
176 /// Test if the Union currently holds the type matching T.
177 template <typename T> bool is() const {
178 constexpr int Index = pointer_union_detail::TypeIndex<T, PTs...>::Index;
179 static_assert(Index < sizeof...(PTs),
180 "PointerUnion::is<T> given type not in the union");
181 return this->Val.getInt() == Index;
182 }
183
184 /// Returns the value of the specified pointer type.
185 ///
186 /// If the specified pointer type is incorrect, assert.
187 template <typename T> T get() const {
188 assert(is<T>() && "Invalid accessor called")(static_cast <bool> (is<T>() && "Invalid accessor called"
) ? void (0) : __assert_fail ("is<T>() && \"Invalid accessor called\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerUnion.h"
, 188, __extension__ __PRETTY_FUNCTION__))
;
189 return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer());
190 }
191
192 /// Returns the current pointer if it is of the specified pointer type,
193 /// otherwise returns null.
194 template <typename T> T dyn_cast() const {
195 if (is<T>())
196 return get<T>();
197 return T();
198 }
199
200 /// If the union is set to the first pointer type get an address pointing to
201 /// it.
202 First const *getAddrOfPtr1() const {
203 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
204 }
205
206 /// If the union is set to the first pointer type get an address pointing to
207 /// it.
208 First *getAddrOfPtr1() {
209 assert(is<First>() && "Val is not the first pointer")(static_cast <bool> (is<First>() && "Val is not the first pointer"
) ? void (0) : __assert_fail ("is<First>() && \"Val is not the first pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerUnion.h"
, 209, __extension__ __PRETTY_FUNCTION__))
;
210 assert((static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerUnion.h"
, 213, __extension__ __PRETTY_FUNCTION__))
211 PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==(static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerUnion.h"
, 213, __extension__ __PRETTY_FUNCTION__))
212 this->Val.getPointer() &&(static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerUnion.h"
, 213, __extension__ __PRETTY_FUNCTION__))
213 "Can't get the address because PointerLikeTypeTraits changes the ptr")(static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/ADT/PointerUnion.h"
, 213, __extension__ __PRETTY_FUNCTION__))
;
214 return const_cast<First *>(
215 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
216 }
217
218 /// Assignment from nullptr which just clears the union.
219 const PointerUnion &operator=(std::nullptr_t) {
220 this->Val.initWithPointer(nullptr);
221 return *this;
222 }
223
224 /// Assignment from elements of the union.
225 using Base::operator=;
226
227 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
228 static inline PointerUnion getFromOpaqueValue(void *VP) {
229 PointerUnion V;
230 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
231 return V;
232 }
233};
234
235template <typename ...PTs>
236bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
237 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
238}
239
240template <typename ...PTs>
241bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
242 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
243}
244
245template <typename ...PTs>
246bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
247 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
248}
249
250// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
251// # low bits available = min(PT1bits,PT2bits)-1.
252template <typename ...PTs>
253struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
254 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
255 return P.getOpaqueValue();
256 }
257
258 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
259 return PointerUnion<PTs...>::getFromOpaqueValue(P);
260 }
261
262 // The number of bits available are the min of the pointer types minus the
263 // bits needed for the discriminator.
264 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
265 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
266};
267
268// Teach DenseMap how to use PointerUnions as keys.
269template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
270 using Union = PointerUnion<PTs...>;
271 using FirstInfo =
272 DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
273
274 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
275
276 static inline Union getTombstoneKey() {
277 return Union(FirstInfo::getTombstoneKey());
278 }
279
280 static unsigned getHashValue(const Union &UnionVal) {
281 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
282 return DenseMapInfo<intptr_t>::getHashValue(key);
283 }
284
285 static bool isEqual(const Union &LHS, const Union &RHS) {
286 return LHS == RHS;
287 }
288};
289
290} // end namespace llvm
291
292#endif // LLVM_ADT_POINTERUNION_H