Bug Summary

File:build/source/clang/include/clang/AST/ExprCXX.h
Warning:line 4927, column 18
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 -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaCoroutine.cpp -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 -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -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-17/lib/clang/17/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 -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1679915782 -O3 -Wno-unused-command-line-argument -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 -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -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-2023-03-27-130437-16335-1 -x c++ /build/source/clang/lib/Sema/SemaCoroutine.cpp

/build/source/clang/lib/Sema/SemaCoroutine.cpp

1//===-- SemaCoroutine.cpp - Semantic Analysis for Coroutines --------------===//
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++ Coroutines.
10//
11// This file contains references to sections of the Coroutines TS, which
12// can be found at http://wg21.link/coroutines.
13//
14//===----------------------------------------------------------------------===//
15
16#include "CoroutineStmtBuilder.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/StmtCXX.h"
21#include "clang/Basic/Builtins.h"
22#include "clang/Lex/Preprocessor.h"
23#include "clang/Sema/Initialization.h"
24#include "clang/Sema/Overload.h"
25#include "clang/Sema/ScopeInfo.h"
26#include "clang/Sema/SemaInternal.h"
27#include "llvm/ADT/SmallSet.h"
28
29using namespace clang;
30using namespace sema;
31
32static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
33 SourceLocation Loc, bool &Res) {
34 DeclarationName DN = S.PP.getIdentifierInfo(Name);
35 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
36 // Suppress diagnostics when a private member is selected. The same warnings
37 // will be produced again when building the call.
38 LR.suppressDiagnostics();
39 Res = S.LookupQualifiedName(LR, RD);
40 return LR;
41}
42
43static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
44 SourceLocation Loc) {
45 bool Res;
46 lookupMember(S, Name, RD, Loc, Res);
47 return Res;
48}
49
50/// Look up the std::coroutine_traits<...>::promise_type for the given
51/// function type.
52static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
53 SourceLocation KwLoc) {
54 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
55 const SourceLocation FuncLoc = FD->getLocation();
56
57 ClassTemplateDecl *CoroTraits =
58 S.lookupCoroutineTraits(KwLoc, FuncLoc);
59 if (!CoroTraits)
60 return QualType();
61
62 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
63 // to [dcl.fct.def.coroutine]3
64 TemplateArgumentListInfo Args(KwLoc, KwLoc);
65 auto AddArg = [&](QualType T) {
66 Args.addArgument(TemplateArgumentLoc(
67 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
68 };
69 AddArg(FnType->getReturnType());
70 // If the function is a non-static member function, add the type
71 // of the implicit object parameter before the formal parameters.
72 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
73 if (MD->isInstance()) {
74 // [over.match.funcs]4
75 // For non-static member functions, the type of the implicit object
76 // parameter is
77 // -- "lvalue reference to cv X" for functions declared without a
78 // ref-qualifier or with the & ref-qualifier
79 // -- "rvalue reference to cv X" for functions declared with the &&
80 // ref-qualifier
81 QualType T = MD->getThisType()->castAs<PointerType>()->getPointeeType();
82 T = FnType->getRefQualifier() == RQ_RValue
83 ? S.Context.getRValueReferenceType(T)
84 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
85 AddArg(T);
86 }
87 }
88 for (QualType T : FnType->getParamTypes())
89 AddArg(T);
90
91 // Build the template-id.
92 QualType CoroTrait =
93 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
94 if (CoroTrait.isNull())
95 return QualType();
96 if (S.RequireCompleteType(KwLoc, CoroTrait,
97 diag::err_coroutine_type_missing_specialization))
98 return QualType();
99
100 auto *RD = CoroTrait->getAsCXXRecordDecl();
101 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?\""
, "clang/lib/Sema/SemaCoroutine.cpp", 101, __extension__ __PRETTY_FUNCTION__
))
;
102
103 // Look up the ::promise_type member.
104 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
105 Sema::LookupOrdinaryName);
106 S.LookupQualifiedName(R, RD);
107 auto *Promise = R.getAsSingle<TypeDecl>();
108 if (!Promise) {
109 S.Diag(FuncLoc,
110 diag::err_implied_std_coroutine_traits_promise_type_not_found)
111 << RD;
112 return QualType();
113 }
114 // The promise type is required to be a class type.
115 QualType PromiseType = S.Context.getTypeDeclType(Promise);
116
117 auto buildElaboratedType = [&]() {
118 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, S.getStdNamespace());
119 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
120 CoroTrait.getTypePtr());
121 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
122 };
123
124 if (!PromiseType->getAsCXXRecordDecl()) {
125 S.Diag(FuncLoc,
126 diag::err_implied_std_coroutine_traits_promise_type_not_class)
127 << buildElaboratedType();
128 return QualType();
129 }
130 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
131 diag::err_coroutine_promise_type_incomplete))
132 return QualType();
133
134 return PromiseType;
135}
136
137/// Look up the std::coroutine_handle<PromiseType>.
138static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
139 SourceLocation Loc) {
140 if (PromiseType.isNull())
141 return QualType();
142
143 NamespaceDecl *CoroNamespace = S.getStdNamespace();
144 assert(CoroNamespace && "Should already be diagnosed")(static_cast <bool> (CoroNamespace && "Should already be diagnosed"
) ? void (0) : __assert_fail ("CoroNamespace && \"Should already be diagnosed\""
, "clang/lib/Sema/SemaCoroutine.cpp", 144, __extension__ __PRETTY_FUNCTION__
))
;
145
146 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
147 Loc, Sema::LookupOrdinaryName);
148 if (!S.LookupQualifiedName(Result, CoroNamespace)) {
149 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
150 << "std::coroutine_handle";
151 return QualType();
152 }
153
154 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
155 if (!CoroHandle) {
156 Result.suppressDiagnostics();
157 // We found something weird. Complain about the first thing we found.
158 NamedDecl *Found = *Result.begin();
159 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
160 return QualType();
161 }
162
163 // Form template argument list for coroutine_handle<Promise>.
164 TemplateArgumentListInfo Args(Loc, Loc);
165 Args.addArgument(TemplateArgumentLoc(
166 TemplateArgument(PromiseType),
167 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
168
169 // Build the template-id.
170 QualType CoroHandleType =
171 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
172 if (CoroHandleType.isNull())
173 return QualType();
174 if (S.RequireCompleteType(Loc, CoroHandleType,
175 diag::err_coroutine_type_missing_specialization))
176 return QualType();
177
178 return CoroHandleType;
179}
180
181static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
182 StringRef Keyword) {
183 // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
184 // a function body.
185 // FIXME: This also covers [expr.await]p2: "An await-expression shall not
186 // appear in a default argument." But the diagnostic QoI here could be
187 // improved to inform the user that default arguments specifically are not
188 // allowed.
189 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
190 if (!FD) {
191 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
192 ? diag::err_coroutine_objc_method
193 : diag::err_coroutine_outside_function) << Keyword;
194 return false;
195 }
196
197 // An enumeration for mapping the diagnostic type to the correct diagnostic
198 // selection index.
199 enum InvalidFuncDiag {
200 DiagCtor = 0,
201 DiagDtor,
202 DiagMain,
203 DiagConstexpr,
204 DiagAutoRet,
205 DiagVarargs,
206 DiagConsteval,
207 };
208 bool Diagnosed = false;
209 auto DiagInvalid = [&](InvalidFuncDiag ID) {
210 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
211 Diagnosed = true;
212 return false;
213 };
214
215 // Diagnose when a constructor, destructor
216 // or the function 'main' are declared as a coroutine.
217 auto *MD = dyn_cast<CXXMethodDecl>(FD);
218 // [class.ctor]p11: "A constructor shall not be a coroutine."
219 if (MD && isa<CXXConstructorDecl>(MD))
220 return DiagInvalid(DiagCtor);
221 // [class.dtor]p17: "A destructor shall not be a coroutine."
222 else if (MD && isa<CXXDestructorDecl>(MD))
223 return DiagInvalid(DiagDtor);
224 // [basic.start.main]p3: "The function main shall not be a coroutine."
225 else if (FD->isMain())
226 return DiagInvalid(DiagMain);
227
228 // Emit a diagnostics for each of the following conditions which is not met.
229 // [expr.const]p2: "An expression e is a core constant expression unless the
230 // evaluation of e [...] would evaluate one of the following expressions:
231 // [...] an await-expression [...] a yield-expression."
232 if (FD->isConstexpr())
233 DiagInvalid(FD->isConsteval() ? DiagConsteval : DiagConstexpr);
234 // [dcl.spec.auto]p15: "A function declared with a return type that uses a
235 // placeholder type shall not be a coroutine."
236 if (FD->getReturnType()->isUndeducedType())
237 DiagInvalid(DiagAutoRet);
238 // [dcl.fct.def.coroutine]p1
239 // The parameter-declaration-clause of the coroutine shall not terminate with
240 // an ellipsis that is not part of a parameter-declaration.
241 if (FD->isVariadic())
242 DiagInvalid(DiagVarargs);
243
244 return !Diagnosed;
245}
246
247/// Build a call to 'operator co_await' if there is a suitable operator for
248/// the given expression.
249ExprResult Sema::BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
250 UnresolvedLookupExpr *Lookup) {
251 UnresolvedSet<16> Functions;
252 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
253 return CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
254}
255
256static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
257 SourceLocation Loc, Expr *E) {
258 ExprResult R = SemaRef.BuildOperatorCoawaitLookupExpr(S, Loc);
259 if (R.isInvalid())
260 return ExprError();
261 return SemaRef.BuildOperatorCoawaitCall(Loc, E,
262 cast<UnresolvedLookupExpr>(R.get()));
263}
264
265static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
266 SourceLocation Loc) {
267 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
268 if (CoroHandleType.isNull())
269 return ExprError();
270
271 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
272 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
273 Sema::LookupOrdinaryName);
274 if (!S.LookupQualifiedName(Found, LookupCtx)) {
275 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
276 << "from_address";
277 return ExprError();
278 }
279
280 Expr *FramePtr =
281 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
282
283 CXXScopeSpec SS;
284 ExprResult FromAddr =
285 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
286 if (FromAddr.isInvalid())
287 return ExprError();
288
289 return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
290}
291
292struct ReadySuspendResumeResult {
293 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
294 Expr *Results[3];
295 OpaqueValueExpr *OpaqueValue;
296 bool IsInvalid;
297};
298
299static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
300 StringRef Name, MultiExprArg Args) {
301 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
302
303 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
304 CXXScopeSpec SS;
305 ExprResult Result = S.BuildMemberReferenceExpr(
306 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
307 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
308 /*Scope=*/nullptr);
309 if (Result.isInvalid())
310 return ExprError();
311
312 // We meant exactly what we asked for. No need for typo correction.
313 if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
314 S.clearDelayedTypo(TE);
315 S.Diag(Loc, diag::err_no_member)
316 << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
317 << Base->getSourceRange();
318 return ExprError();
319 }
320
321 return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
322}
323
324// See if return type is coroutine-handle and if so, invoke builtin coro-resume
325// on its address. This is to enable the support for coroutine-handle
326// returning await_suspend that results in a guaranteed tail call to the target
327// coroutine.
328static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
329 SourceLocation Loc) {
330 if (RetType->isReferenceType())
331 return nullptr;
332 Type const *T = RetType.getTypePtr();
333 if (!T->isClassType() && !T->isStructureType())
334 return nullptr;
335
336 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
337 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
338 // a private function in SemaExprCXX.cpp
339
340 ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", std::nullopt);
341 if (AddressExpr.isInvalid())
342 return nullptr;
343
344 Expr *JustAddress = AddressExpr.get();
345
346 // Check that the type of AddressExpr is void*
347 if (!JustAddress->getType().getTypePtr()->isVoidPointerType())
348 S.Diag(cast<CallExpr>(JustAddress)->getCalleeDecl()->getLocation(),
349 diag::warn_coroutine_handle_address_invalid_return_type)
350 << JustAddress->getType();
351
352 // Clean up temporary objects so that they don't live across suspension points
353 // unnecessarily. We choose to clean up before the call to
354 // __builtin_coro_resume so that the cleanup code are not inserted in-between
355 // the resume call and return instruction, which would interfere with the
356 // musttail call contract.
357 JustAddress = S.MaybeCreateExprWithCleanups(JustAddress);
358 return S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_resume,
359 JustAddress);
360}
361
362/// Build calls to await_ready, await_suspend, and await_resume for a co_await
363/// expression.
364/// The generated AST tries to clean up temporary objects as early as
365/// possible so that they don't live across suspension points if possible.
366/// Having temporary objects living across suspension points unnecessarily can
367/// lead to large frame size, and also lead to memory corruptions if the
368/// coroutine frame is destroyed after coming back from suspension. This is done
369/// by wrapping both the await_ready call and the await_suspend call with
370/// ExprWithCleanups. In the end of this function, we also need to explicitly
371/// set cleanup state so that the CoawaitExpr is also wrapped with an
372/// ExprWithCleanups to clean up the awaiter associated with the co_await
373/// expression.
374static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
375 SourceLocation Loc, Expr *E) {
376 OpaqueValueExpr *Operand = new (S.Context)
377 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
378
379 // Assume valid until we see otherwise.
380 // Further operations are responsible for setting IsInalid to true.
381 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/false};
31
'Calls.IsInvalid' initialized to 0, which participates in a condition later
32
Initializing to a null pointer value
33
'Calls' initialized here
382
383 using ACT = ReadySuspendResumeResult::AwaitCallType;
384
385 auto BuildSubExpr = [&](ACT CallType, StringRef Func,
386 MultiExprArg Arg) -> Expr * {
387 ExprResult Result = buildMemberCall(S, Operand, Loc, Func, Arg);
388 if (Result.isInvalid()) {
389 Calls.IsInvalid = true;
390 return nullptr;
391 }
392 Calls.Results[CallType] = Result.get();
393 return Result.get();
394 };
395
396 CallExpr *AwaitReady = cast_or_null<CallExpr>(
34
Assuming null pointer is passed into cast
397 BuildSubExpr(ACT::ACT_Ready, "await_ready", std::nullopt));
398 if (!AwaitReady
34.1
'AwaitReady' is null
34.1
'AwaitReady' is null
34.1
'AwaitReady' is null
)
35
Taking true branch
399 return Calls;
36
The value 0 is assigned to 'RSS.IsInvalid', which participates in a condition later
37
Storing null pointer value
400 if (!AwaitReady->getType()->isDependentType()) {
401 // [expr.await]p3 [...]
402 // — await-ready is the expression e.await_ready(), contextually converted
403 // to bool.
404 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
405 if (Conv.isInvalid()) {
406 S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
407 diag::note_await_ready_no_bool_conversion);
408 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
409 << AwaitReady->getDirectCallee() << E->getSourceRange();
410 Calls.IsInvalid = true;
411 } else
412 Calls.Results[ACT::ACT_Ready] = S.MaybeCreateExprWithCleanups(Conv.get());
413 }
414
415 ExprResult CoroHandleRes =
416 buildCoroutineHandle(S, CoroPromise->getType(), Loc);
417 if (CoroHandleRes.isInvalid()) {
418 Calls.IsInvalid = true;
419 return Calls;
420 }
421 Expr *CoroHandle = CoroHandleRes.get();
422 CallExpr *AwaitSuspend = cast_or_null<CallExpr>(
423 BuildSubExpr(ACT::ACT_Suspend, "await_suspend", CoroHandle));
424 if (!AwaitSuspend)
425 return Calls;
426 if (!AwaitSuspend->getType()->isDependentType()) {
427 // [expr.await]p3 [...]
428 // - await-suspend is the expression e.await_suspend(h), which shall be
429 // a prvalue of type void, bool, or std::coroutine_handle<Z> for some
430 // type Z.
431 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
432
433 // Support for coroutine_handle returning await_suspend.
434 if (Expr *TailCallSuspend =
435 maybeTailCall(S, RetType, AwaitSuspend, Loc))
436 // Note that we don't wrap the expression with ExprWithCleanups here
437 // because that might interfere with tailcall contract (e.g. inserting
438 // clean up instructions in-between tailcall and return). Instead
439 // ExprWithCleanups is wrapped within maybeTailCall() prior to the resume
440 // call.
441 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
442 else {
443 // non-class prvalues always have cv-unqualified types
444 if (RetType->isReferenceType() ||
445 (!RetType->isBooleanType() && !RetType->isVoidType())) {
446 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
447 diag::err_await_suspend_invalid_return_type)
448 << RetType;
449 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
450 << AwaitSuspend->getDirectCallee();
451 Calls.IsInvalid = true;
452 } else
453 Calls.Results[ACT::ACT_Suspend] =
454 S.MaybeCreateExprWithCleanups(AwaitSuspend);
455 }
456 }
457
458 BuildSubExpr(ACT::ACT_Resume, "await_resume", std::nullopt);
459
460 // Make sure the awaiter object gets a chance to be cleaned up.
461 S.Cleanup.setExprNeedsCleanups(true);
462
463 return Calls;
464}
465
466static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
467 SourceLocation Loc, StringRef Name,
468 MultiExprArg Args) {
469
470 // Form a reference to the promise.
471 ExprResult PromiseRef = S.BuildDeclRefExpr(
472 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
473 if (PromiseRef.isInvalid())
474 return ExprError();
475
476 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
477}
478
479VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
480 assert(isa<FunctionDecl>(CurContext) && "not in a function scope")(static_cast <bool> (isa<FunctionDecl>(CurContext
) && "not in a function scope") ? void (0) : __assert_fail
("isa<FunctionDecl>(CurContext) && \"not in a function scope\""
, "clang/lib/Sema/SemaCoroutine.cpp", 480, __extension__ __PRETTY_FUNCTION__
))
;
481 auto *FD = cast<FunctionDecl>(CurContext);
482 bool IsThisDependentType = [&] {
483 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
484 return MD->isInstance() && MD->getThisType()->isDependentType();
485 else
486 return false;
487 }();
488
489 QualType T = FD->getType()->isDependentType() || IsThisDependentType
490 ? Context.DependentTy
491 : lookupPromiseType(*this, FD, Loc);
492 if (T.isNull())
493 return nullptr;
494
495 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
496 &PP.getIdentifierTable().get("__promise"), T,
497 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
498 VD->setImplicit();
499 CheckVariableDeclarationType(VD);
500 if (VD->isInvalidDecl())
501 return nullptr;
502
503 auto *ScopeInfo = getCurFunction();
504
505 // Build a list of arguments, based on the coroutine function's arguments,
506 // that if present will be passed to the promise type's constructor.
507 llvm::SmallVector<Expr *, 4> CtorArgExprs;
508
509 // Add implicit object parameter.
510 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
511 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
512 ExprResult ThisExpr = ActOnCXXThis(Loc);
513 if (ThisExpr.isInvalid())
514 return nullptr;
515 ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
516 if (ThisExpr.isInvalid())
517 return nullptr;
518 CtorArgExprs.push_back(ThisExpr.get());
519 }
520 }
521
522 // Add the coroutine function's parameters.
523 auto &Moves = ScopeInfo->CoroutineParameterMoves;
524 for (auto *PD : FD->parameters()) {
525 if (PD->getType()->isDependentType())
526 continue;
527
528 auto RefExpr = ExprEmpty();
529 auto Move = Moves.find(PD);
530 assert(Move != Moves.end() &&(static_cast <bool> (Move != Moves.end() && "Coroutine function parameter not inserted into move map"
) ? void (0) : __assert_fail ("Move != Moves.end() && \"Coroutine function parameter not inserted into move map\""
, "clang/lib/Sema/SemaCoroutine.cpp", 531, __extension__ __PRETTY_FUNCTION__
))
531 "Coroutine function parameter not inserted into move map")(static_cast <bool> (Move != Moves.end() && "Coroutine function parameter not inserted into move map"
) ? void (0) : __assert_fail ("Move != Moves.end() && \"Coroutine function parameter not inserted into move map\""
, "clang/lib/Sema/SemaCoroutine.cpp", 531, __extension__ __PRETTY_FUNCTION__
))
;
532 // If a reference to the function parameter exists in the coroutine
533 // frame, use that reference.
534 auto *MoveDecl =
535 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
536 RefExpr =
537 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
538 ExprValueKind::VK_LValue, FD->getLocation());
539 if (RefExpr.isInvalid())
540 return nullptr;
541 CtorArgExprs.push_back(RefExpr.get());
542 }
543
544 // If we have a non-zero number of constructor arguments, try to use them.
545 // Otherwise, fall back to the promise type's default constructor.
546 if (!CtorArgExprs.empty()) {
547 // Create an initialization sequence for the promise type using the
548 // constructor arguments, wrapped in a parenthesized list expression.
549 Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
550 CtorArgExprs, FD->getLocation());
551 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
552 InitializationKind Kind = InitializationKind::CreateForInit(
553 VD->getLocation(), /*DirectInit=*/true, PLE);
554 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
555 /*TopLevelOfInitList=*/false,
556 /*TreatUnavailableAsInvalid=*/false);
557
558 // [dcl.fct.def.coroutine]5.7
559 // promise-constructor-arguments is determined as follows: overload
560 // resolution is performed on a promise constructor call created by
561 // assembling an argument list q_1 ... q_n . If a viable constructor is
562 // found ([over.match.viable]), then promise-constructor-arguments is ( q_1
563 // , ..., q_n ), otherwise promise-constructor-arguments is empty.
564 if (InitSeq) {
565 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
566 if (Result.isInvalid()) {
567 VD->setInvalidDecl();
568 } else if (Result.get()) {
569 VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
570 VD->setInitStyle(VarDecl::CallInit);
571 CheckCompleteVariableDeclaration(VD);
572 }
573 } else
574 ActOnUninitializedDecl(VD);
575 } else
576 ActOnUninitializedDecl(VD);
577
578 FD->addDecl(VD);
579 return VD;
580}
581
582/// Check that this is a context in which a coroutine suspension can appear.
583static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
584 StringRef Keyword,
585 bool IsImplicit = false) {
586 if (!isValidCoroutineContext(S, Loc, Keyword))
587 return nullptr;
588
589 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope")(static_cast <bool> (isa<FunctionDecl>(S.CurContext
) && "not in a function scope") ? void (0) : __assert_fail
("isa<FunctionDecl>(S.CurContext) && \"not in a function scope\""
, "clang/lib/Sema/SemaCoroutine.cpp", 589, __extension__ __PRETTY_FUNCTION__
))
;
9
Taking false branch
10
Field 'CurContext' is a 'FunctionDecl'
11
'?' condition is true
590
591 auto *ScopeInfo = S.getCurFunction();
12
Calling 'Sema::getCurFunction'
15
Returning from 'Sema::getCurFunction'
592 assert(ScopeInfo && "missing function scope for function")(static_cast <bool> (ScopeInfo && "missing function scope for function"
) ? void (0) : __assert_fail ("ScopeInfo && \"missing function scope for function\""
, "clang/lib/Sema/SemaCoroutine.cpp", 592, __extension__ __PRETTY_FUNCTION__
))
;
16
Assuming 'ScopeInfo' is non-null
17
'?' condition is true
593
594 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
595 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
596
597 if (ScopeInfo->CoroutinePromise)
18
Assuming field 'CoroutinePromise' is null
19
Taking false branch
598 return ScopeInfo;
599
600 if (!S.buildCoroutineParameterMoves(Loc))
20
Taking false branch
601 return nullptr;
602
603 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
604 if (!ScopeInfo->CoroutinePromise)
21
Assuming field 'CoroutinePromise' is non-null
22
Taking false branch
605 return nullptr;
606
607 return ScopeInfo;
23
Returning pointer (loaded from 'ScopeInfo'), which participates in a condition later
608}
609
610/// Recursively check \p E and all its children to see if any call target
611/// (including constructor call) is declared noexcept. Also any value returned
612/// from the call has a noexcept destructor.
613static void checkNoThrow(Sema &S, const Stmt *E,
614 llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) {
615 auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) {
616 // In the case of dtor, the call to dtor is implicit and hence we should
617 // pass nullptr to canCalleeThrow.
618 if (Sema::canCalleeThrow(S, IsDtor ? nullptr : cast<Expr>(E), D)) {
619 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
620 // co_await promise.final_suspend() could end up calling
621 // __builtin_coro_resume for symmetric transfer if await_suspend()
622 // returns a handle. In that case, even __builtin_coro_resume is not
623 // declared as noexcept and may throw, it does not throw _into_ the
624 // coroutine that just suspended, but rather throws back out from
625 // whoever called coroutine_handle::resume(), hence we claim that
626 // logically it does not throw.
627 if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume)
628 return;
629 }
630 if (ThrowingDecls.empty()) {
631 // [dcl.fct.def.coroutine]p15
632 // The expression co_await promise.final_suspend() shall not be
633 // potentially-throwing ([except.spec]).
634 //
635 // First time seeing an error, emit the error message.
636 S.Diag(cast<FunctionDecl>(S.CurContext)->getLocation(),
637 diag::err_coroutine_promise_final_suspend_requires_nothrow);
638 }
639 ThrowingDecls.insert(D);
640 }
641 };
642
643 if (auto *CE = dyn_cast<CXXConstructExpr>(E)) {
644 CXXConstructorDecl *Ctor = CE->getConstructor();
645 checkDeclNoexcept(Ctor);
646 // Check the corresponding destructor of the constructor.
647 checkDeclNoexcept(Ctor->getParent()->getDestructor(), /*IsDtor=*/true);
648 } else if (auto *CE = dyn_cast<CallExpr>(E)) {
649 if (CE->isTypeDependent())
650 return;
651
652 checkDeclNoexcept(CE->getCalleeDecl());
653 QualType ReturnType = CE->getCallReturnType(S.getASTContext());
654 // Check the destructor of the call return type, if any.
655 if (ReturnType.isDestructedType() ==
656 QualType::DestructionKind::DK_cxx_destructor) {
657 const auto *T =
658 cast<RecordType>(ReturnType.getCanonicalType().getTypePtr());
659 checkDeclNoexcept(cast<CXXRecordDecl>(T->getDecl())->getDestructor(),
660 /*IsDtor=*/true);
661 }
662 } else
663 for (const auto *Child : E->children()) {
664 if (!Child)
665 continue;
666 checkNoThrow(S, Child, ThrowingDecls);
667 }
668}
669
670bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) {
671 llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls;
672 // We first collect all declarations that should not throw but not declared
673 // with noexcept. We then sort them based on the location before printing.
674 // This is to avoid emitting the same note multiple times on the same
675 // declaration, and also provide a deterministic order for the messages.
676 checkNoThrow(*this, FinalSuspend, ThrowingDecls);
677 auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(),
678 ThrowingDecls.end()};
679 sort(SortedDecls, [](const Decl *A, const Decl *B) {
680 return A->getEndLoc() < B->getEndLoc();
681 });
682 for (const auto *D : SortedDecls) {
683 Diag(D->getEndLoc(), diag::note_coroutine_function_declare_noexcept);
684 }
685 return ThrowingDecls.empty();
686}
687
688bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
689 StringRef Keyword) {
690 if (!checkCoroutineContext(*this, KWLoc, Keyword))
691 return false;
692 auto *ScopeInfo = getCurFunction();
693 assert(ScopeInfo->CoroutinePromise)(static_cast <bool> (ScopeInfo->CoroutinePromise) ? void
(0) : __assert_fail ("ScopeInfo->CoroutinePromise", "clang/lib/Sema/SemaCoroutine.cpp"
, 693, __extension__ __PRETTY_FUNCTION__))
;
694
695 // If we have existing coroutine statements then we have already built
696 // the initial and final suspend points.
697 if (!ScopeInfo->NeedsCoroutineSuspends)
698 return true;
699
700 ScopeInfo->setNeedsCoroutineSuspends(false);
701
702 auto *Fn = cast<FunctionDecl>(CurContext);
703 SourceLocation Loc = Fn->getLocation();
704 // Build the initial suspend point
705 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
706 ExprResult Operand = buildPromiseCall(*this, ScopeInfo->CoroutinePromise,
707 Loc, Name, std::nullopt);
708 if (Operand.isInvalid())
709 return StmtError();
710 ExprResult Suspend =
711 buildOperatorCoawaitCall(*this, SC, Loc, Operand.get());
712 if (Suspend.isInvalid())
713 return StmtError();
714 Suspend = BuildResolvedCoawaitExpr(Loc, Operand.get(), Suspend.get(),
715 /*IsImplicit*/ true);
716 Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
717 if (Suspend.isInvalid()) {
718 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
719 << ((Name == "initial_suspend") ? 0 : 1);
720 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
721 return StmtError();
722 }
723 return cast<Stmt>(Suspend.get());
724 };
725
726 StmtResult InitSuspend = buildSuspends("initial_suspend");
727 if (InitSuspend.isInvalid())
728 return true;
729
730 StmtResult FinalSuspend = buildSuspends("final_suspend");
731 if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend.get()))
732 return true;
733
734 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
735
736 return true;
737}
738
739// Recursively walks up the scope hierarchy until either a 'catch' or a function
740// scope is found, whichever comes first.
741static bool isWithinCatchScope(Scope *S) {
742 // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
743 // lambdas that use 'co_await' are allowed. The loop below ends when a
744 // function scope is found in order to ensure the following behavior:
745 //
746 // void foo() { // <- function scope
747 // try { //
748 // co_await x; // <- 'co_await' is OK within a function scope
749 // } catch { // <- catch scope
750 // co_await x; // <- 'co_await' is not OK within a catch scope
751 // []() { // <- function scope
752 // co_await x; // <- 'co_await' is OK within a function scope
753 // }();
754 // }
755 // }
756 while (S && !S->isFunctionScope()) {
757 if (S->isCatchScope())
758 return true;
759 S = S->getParent();
760 }
761 return false;
762}
763
764// [expr.await]p2, emphasis added: "An await-expression shall appear only in
765// a *potentially evaluated* expression within the compound-statement of a
766// function-body *outside of a handler* [...] A context within a function
767// where an await-expression can appear is called a suspension context of the
768// function."
769static bool checkSuspensionContext(Sema &S, SourceLocation Loc,
770 StringRef Keyword) {
771 // First emphasis of [expr.await]p2: must be a potentially evaluated context.
772 // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
773 // \c sizeof.
774 if (S.isUnevaluatedContext()) {
775 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
776 return false;
777 }
778
779 // Second emphasis of [expr.await]p2: must be outside of an exception handler.
780 if (isWithinCatchScope(S.getCurScope())) {
781 S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
782 return false;
783 }
784
785 return true;
786}
787
788ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
789 if (!checkSuspensionContext(*this, Loc, "co_await"))
790 return ExprError();
791
792 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
793 CorrectDelayedTyposInExpr(E);
794 return ExprError();
795 }
796
797 if (E->hasPlaceholderType()) {
798 ExprResult R = CheckPlaceholderExpr(E);
799 if (R.isInvalid()) return ExprError();
800 E = R.get();
801 }
802 ExprResult Lookup = BuildOperatorCoawaitLookupExpr(S, Loc);
803 if (Lookup.isInvalid())
804 return ExprError();
805 return BuildUnresolvedCoawaitExpr(Loc, E,
806 cast<UnresolvedLookupExpr>(Lookup.get()));
807}
808
809ExprResult Sema::BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc) {
810 DeclarationName OpName =
811 Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
812 LookupResult Operators(*this, OpName, SourceLocation(),
813 Sema::LookupOperatorName);
814 LookupName(Operators, S);
815
816 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous")(static_cast <bool> (!Operators.isAmbiguous() &&
"Operator lookup cannot be ambiguous") ? void (0) : __assert_fail
("!Operators.isAmbiguous() && \"Operator lookup cannot be ambiguous\""
, "clang/lib/Sema/SemaCoroutine.cpp", 816, __extension__ __PRETTY_FUNCTION__
))
;
817 const auto &Functions = Operators.asUnresolvedSet();
818 bool IsOverloaded =
819 Functions.size() > 1 ||
820 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
821 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
822 Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
823 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
824 Functions.begin(), Functions.end());
825 assert(CoawaitOp)(static_cast <bool> (CoawaitOp) ? void (0) : __assert_fail
("CoawaitOp", "clang/lib/Sema/SemaCoroutine.cpp", 825, __extension__
__PRETTY_FUNCTION__))
;
826 return CoawaitOp;
827}
828
829// Attempts to resolve and build a CoawaitExpr from "raw" inputs, bailing out to
830// DependentCoawaitExpr if needed.
831ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
832 UnresolvedLookupExpr *Lookup) {
833 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
834 if (!FSI)
835 return ExprError();
836
837 if (Operand->hasPlaceholderType()) {
838 ExprResult R = CheckPlaceholderExpr(Operand);
839 if (R.isInvalid())
840 return ExprError();
841 Operand = R.get();
842 }
843
844 auto *Promise = FSI->CoroutinePromise;
845 if (Promise->getType()->isDependentType()) {
846 Expr *Res = new (Context)
847 DependentCoawaitExpr(Loc, Context.DependentTy, Operand, Lookup);
848 return Res;
849 }
850
851 auto *RD = Promise->getType()->getAsCXXRecordDecl();
852 auto *Transformed = Operand;
853 if (lookupMember(*this, "await_transform", RD, Loc)) {
854 ExprResult R =
855 buildPromiseCall(*this, Promise, Loc, "await_transform", Operand);
856 if (R.isInvalid()) {
857 Diag(Loc,
858 diag::note_coroutine_promise_implicit_await_transform_required_here)
859 << Operand->getSourceRange();
860 return ExprError();
861 }
862 Transformed = R.get();
863 }
864 ExprResult Awaiter = BuildOperatorCoawaitCall(Loc, Transformed, Lookup);
865 if (Awaiter.isInvalid())
866 return ExprError();
867
868 return BuildResolvedCoawaitExpr(Loc, Operand, Awaiter.get());
869}
870
871ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
872 Expr *Awaiter, bool IsImplicit) {
873 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
874 if (!Coroutine)
875 return ExprError();
876
877 if (Awaiter->hasPlaceholderType()) {
878 ExprResult R = CheckPlaceholderExpr(Awaiter);
879 if (R.isInvalid()) return ExprError();
880 Awaiter = R.get();
881 }
882
883 if (Awaiter->getType()->isDependentType()) {
884 Expr *Res = new (Context)
885 CoawaitExpr(Loc, Context.DependentTy, Operand, Awaiter, IsImplicit);
886 return Res;
887 }
888
889 // If the expression is a temporary, materialize it as an lvalue so that we
890 // can use it multiple times.
891 if (Awaiter->isPRValue())
892 Awaiter = CreateMaterializeTemporaryExpr(Awaiter->getType(), Awaiter, true);
893
894 // The location of the `co_await` token cannot be used when constructing
895 // the member call expressions since it's before the location of `Expr`, which
896 // is used as the start of the member call expression.
897 SourceLocation CallLoc = Awaiter->getExprLoc();
898
899 // Build the await_ready, await_suspend, await_resume calls.
900 ReadySuspendResumeResult RSS =
901 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, Awaiter);
902 if (RSS.IsInvalid)
903 return ExprError();
904
905 Expr *Res = new (Context)
906 CoawaitExpr(Loc, Operand, Awaiter, RSS.Results[0], RSS.Results[1],
907 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
908
909 return Res;
910}
911
912ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
913 if (!checkSuspensionContext(*this, Loc, "co_yield"))
1
Taking false branch
914 return ExprError();
915
916 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
2
Taking false branch
917 CorrectDelayedTyposInExpr(E);
918 return ExprError();
919 }
920
921 // Build yield_value call.
922 ExprResult Awaitable = buildPromiseCall(
923 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
924 if (Awaitable.isInvalid())
3
Assuming the condition is false
4
Taking false branch
925 return ExprError();
926
927 // Build 'operator co_await' call.
928 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
929 if (Awaitable.isInvalid())
5
Assuming the condition is false
6
Taking false branch
930 return ExprError();
931
932 return BuildCoyieldExpr(Loc, Awaitable.get());
7
Calling 'Sema::BuildCoyieldExpr'
933}
934ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
935 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
8
Calling 'checkCoroutineContext'
24
Returning from 'checkCoroutineContext'
936 if (!Coroutine
24.1
'Coroutine' is non-null
24.1
'Coroutine' is non-null
24.1
'Coroutine' is non-null
)
25
Taking false branch
937 return ExprError();
938
939 if (E->hasPlaceholderType()) {
26
Taking false branch
940 ExprResult R = CheckPlaceholderExpr(E);
941 if (R.isInvalid()) return ExprError();
942 E = R.get();
943 }
944
945 Expr *Operand = E;
946
947 if (E->getType()->isDependentType()) {
27
Assuming the condition is false
28
Taking false branch
948 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, Operand, E);
949 return Res;
950 }
951
952 // If the expression is a temporary, materialize it as an lvalue so that we
953 // can use it multiple times.
954 if (E->isPRValue())
29
Taking false branch
955 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
956
957 // Build the await_ready, await_suspend, await_resume calls.
958 ReadySuspendResumeResult RSS = buildCoawaitCalls(
30
Calling 'buildCoawaitCalls'
38
Returning from 'buildCoawaitCalls'
959 *this, Coroutine->CoroutinePromise, Loc, E);
960 if (RSS.IsInvalid
38.1
Field 'IsInvalid' is false
38.1
Field 'IsInvalid' is false
38.1
Field 'IsInvalid' is false
)
39
Taking false branch
961 return ExprError();
962
963 Expr *Res =
964 new (Context) CoyieldExpr(Loc, Operand, E, RSS.Results[0], RSS.Results[1],
41
Calling constructor for 'CoyieldExpr'
965 RSS.Results[2], RSS.OpaqueValue);
40
Passing null pointer value via 6th parameter 'Resume'
966
967 return Res;
968}
969
970StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
971 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
972 CorrectDelayedTyposInExpr(E);
973 return StmtError();
974 }
975 return BuildCoreturnStmt(Loc, E);
976}
977
978StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
979 bool IsImplicit) {
980 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
981 if (!FSI)
982 return StmtError();
983
984 if (E && E->hasPlaceholderType() &&
985 !E->hasPlaceholderType(BuiltinType::Overload)) {
986 ExprResult R = CheckPlaceholderExpr(E);
987 if (R.isInvalid()) return StmtError();
988 E = R.get();
989 }
990
991 VarDecl *Promise = FSI->CoroutinePromise;
992 ExprResult PC;
993 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
994 getNamedReturnInfo(E, SimplerImplicitMoveMode::ForceOn);
995 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
996 } else {
997 E = MakeFullDiscardedValueExpr(E).get();
998 PC = buildPromiseCall(*this, Promise, Loc, "return_void", std::nullopt);
999 }
1000 if (PC.isInvalid())
1001 return StmtError();
1002
1003 Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
1004
1005 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
1006 return Res;
1007}
1008
1009/// Look up the std::nothrow object.
1010static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
1011 NamespaceDecl *Std = S.getStdNamespace();
1012 assert(Std && "Should already be diagnosed")(static_cast <bool> (Std && "Should already be diagnosed"
) ? void (0) : __assert_fail ("Std && \"Should already be diagnosed\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1012, __extension__ __PRETTY_FUNCTION__
))
;
1013
1014 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
1015 Sema::LookupOrdinaryName);
1016 if (!S.LookupQualifiedName(Result, Std)) {
1017 // <coroutine> is not requred to include <new>, so we couldn't omit
1018 // the check here.
1019 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
1020 return nullptr;
1021 }
1022
1023 auto *VD = Result.getAsSingle<VarDecl>();
1024 if (!VD) {
1025 Result.suppressDiagnostics();
1026 // We found something weird. Complain about the first thing we found.
1027 NamedDecl *Found = *Result.begin();
1028 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
1029 return nullptr;
1030 }
1031
1032 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
1033 if (DR.isInvalid())
1034 return nullptr;
1035
1036 return DR.get();
1037}
1038
1039static TypeSourceInfo *getTypeSourceInfoForStdAlignValT(Sema &S,
1040 SourceLocation Loc) {
1041 EnumDecl *StdAlignValT = S.getStdAlignValT();
1042 QualType StdAlignValDecl = S.Context.getTypeDeclType(StdAlignValT);
1043 return S.Context.getTrivialTypeSourceInfo(StdAlignValDecl);
1044}
1045
1046// Find an appropriate delete for the promise.
1047static bool findDeleteForPromise(Sema &S, SourceLocation Loc, QualType PromiseType,
1048 FunctionDecl *&OperatorDelete) {
1049 DeclarationName DeleteName =
1050 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1051
1052 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
1053 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type")(static_cast <bool> (PointeeRD && "PromiseType must be a CxxRecordDecl type"
) ? void (0) : __assert_fail ("PointeeRD && \"PromiseType must be a CxxRecordDecl type\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1053, __extension__ __PRETTY_FUNCTION__
))
;
1054
1055 const bool Overaligned = S.getLangOpts().CoroAlignedAllocation;
1056
1057 // [dcl.fct.def.coroutine]p12
1058 // The deallocation function's name is looked up by searching for it in the
1059 // scope of the promise type. If nothing is found, a search is performed in
1060 // the global scope.
1061 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete,
1062 /*Diagnose*/ true, /*WantSize*/ true,
1063 /*WantAligned*/ Overaligned))
1064 return false;
1065
1066 // [dcl.fct.def.coroutine]p12
1067 // If both a usual deallocation function with only a pointer parameter and a
1068 // usual deallocation function with both a pointer parameter and a size
1069 // parameter are found, then the selected deallocation function shall be the
1070 // one with two parameters. Otherwise, the selected deallocation function
1071 // shall be the function with one parameter.
1072 if (!OperatorDelete) {
1073 // Look for a global declaration.
1074 // Coroutines can always provide their required size.
1075 const bool CanProvideSize = true;
1076 // Sema::FindUsualDeallocationFunction will try to find the one with two
1077 // parameters first. It will return the deallocation function with one
1078 // parameter if failed.
1079 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
1080 Overaligned, DeleteName);
1081
1082 if (!OperatorDelete)
1083 return false;
1084 }
1085
1086 S.MarkFunctionReferenced(Loc, OperatorDelete);
1087 return true;
1088}
1089
1090
1091void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
1092 FunctionScopeInfo *Fn = getCurFunction();
1093 assert(Fn && Fn->isCoroutine() && "not a coroutine")(static_cast <bool> (Fn && Fn->isCoroutine()
&& "not a coroutine") ? void (0) : __assert_fail ("Fn && Fn->isCoroutine() && \"not a coroutine\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1093, __extension__ __PRETTY_FUNCTION__
))
;
1094 if (!Body) {
1095 assert(FD->isInvalidDecl() &&(static_cast <bool> (FD->isInvalidDecl() && "a null body is only allowed for invalid declarations"
) ? void (0) : __assert_fail ("FD->isInvalidDecl() && \"a null body is only allowed for invalid declarations\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1096, __extension__ __PRETTY_FUNCTION__
))
1096 "a null body is only allowed for invalid declarations")(static_cast <bool> (FD->isInvalidDecl() && "a null body is only allowed for invalid declarations"
) ? void (0) : __assert_fail ("FD->isInvalidDecl() && \"a null body is only allowed for invalid declarations\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1096, __extension__ __PRETTY_FUNCTION__
))
;
1097 return;
1098 }
1099 // We have a function that uses coroutine keywords, but we failed to build
1100 // the promise type.
1101 if (!Fn->CoroutinePromise)
1102 return FD->setInvalidDecl();
1103
1104 if (isa<CoroutineBodyStmt>(Body)) {
1105 // Nothing todo. the body is already a transformed coroutine body statement.
1106 return;
1107 }
1108
1109 // The always_inline attribute doesn't reliably apply to a coroutine,
1110 // because the coroutine will be split into pieces and some pieces
1111 // might be called indirectly, as in a virtual call. Even the ramp
1112 // function cannot be inlined at -O0, due to pipeline ordering
1113 // problems (see https://llvm.org/PR53413). Tell the user about it.
1114 if (FD->hasAttr<AlwaysInlineAttr>())
1115 Diag(FD->getLocation(), diag::warn_always_inline_coroutine);
1116
1117 // [stmt.return.coroutine]p1:
1118 // A coroutine shall not enclose a return statement ([stmt.return]).
1119 if (Fn->FirstReturnLoc.isValid()) {
1120 assert(Fn->FirstCoroutineStmtLoc.isValid() &&(static_cast <bool> (Fn->FirstCoroutineStmtLoc.isValid
() && "first coroutine location not set") ? void (0) :
__assert_fail ("Fn->FirstCoroutineStmtLoc.isValid() && \"first coroutine location not set\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1121, __extension__ __PRETTY_FUNCTION__
))
1121 "first coroutine location not set")(static_cast <bool> (Fn->FirstCoroutineStmtLoc.isValid
() && "first coroutine location not set") ? void (0) :
__assert_fail ("Fn->FirstCoroutineStmtLoc.isValid() && \"first coroutine location not set\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1121, __extension__ __PRETTY_FUNCTION__
))
;
1122 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
1123 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1124 << Fn->getFirstCoroutineStmtKeyword();
1125 }
1126
1127 // Coroutines will get splitted into pieces. The GNU address of label
1128 // extension wouldn't be meaningful in coroutines.
1129 for (AddrLabelExpr *ALE : Fn->AddrLabels)
1130 Diag(ALE->getBeginLoc(), diag::err_coro_invalid_addr_of_label);
1131
1132 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
1133 if (Builder.isInvalid() || !Builder.buildStatements())
1134 return FD->setInvalidDecl();
1135
1136 // Build body for the coroutine wrapper statement.
1137 Body = CoroutineBodyStmt::Create(Context, Builder);
1138}
1139
1140CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
1141 sema::FunctionScopeInfo &Fn,
1142 Stmt *Body)
1143 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
1144 IsPromiseDependentType(
1145 !Fn.CoroutinePromise ||
1146 Fn.CoroutinePromise->getType()->isDependentType()) {
1147 this->Body = Body;
1148
1149 for (auto KV : Fn.CoroutineParameterMoves)
1150 this->ParamMovesVector.push_back(KV.second);
1151 this->ParamMoves = this->ParamMovesVector;
1152
1153 if (!IsPromiseDependentType) {
1154 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
1155 assert(PromiseRecordDecl && "Type should have already been checked")(static_cast <bool> (PromiseRecordDecl && "Type should have already been checked"
) ? void (0) : __assert_fail ("PromiseRecordDecl && \"Type should have already been checked\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1155, __extension__ __PRETTY_FUNCTION__
))
;
1156 }
1157 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
1158}
1159
1160bool CoroutineStmtBuilder::buildStatements() {
1161 assert(this->IsValid && "coroutine already invalid")(static_cast <bool> (this->IsValid && "coroutine already invalid"
) ? void (0) : __assert_fail ("this->IsValid && \"coroutine already invalid\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1161, __extension__ __PRETTY_FUNCTION__
))
;
1162 this->IsValid = makeReturnObject();
1163 if (this->IsValid && !IsPromiseDependentType)
1164 buildDependentStatements();
1165 return this->IsValid;
1166}
1167
1168bool CoroutineStmtBuilder::buildDependentStatements() {
1169 assert(this->IsValid && "coroutine already invalid")(static_cast <bool> (this->IsValid && "coroutine already invalid"
) ? void (0) : __assert_fail ("this->IsValid && \"coroutine already invalid\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1169, __extension__ __PRETTY_FUNCTION__
))
;
1170 assert(!this->IsPromiseDependentType &&(static_cast <bool> (!this->IsPromiseDependentType &&
"coroutine cannot have a dependent promise type") ? void (0)
: __assert_fail ("!this->IsPromiseDependentType && \"coroutine cannot have a dependent promise type\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1171, __extension__ __PRETTY_FUNCTION__
))
1171 "coroutine cannot have a dependent promise type")(static_cast <bool> (!this->IsPromiseDependentType &&
"coroutine cannot have a dependent promise type") ? void (0)
: __assert_fail ("!this->IsPromiseDependentType && \"coroutine cannot have a dependent promise type\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1171, __extension__ __PRETTY_FUNCTION__
))
;
1172 this->IsValid = makeOnException() && makeOnFallthrough() &&
1173 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1174 makeNewAndDeleteExpr();
1175 return this->IsValid;
1176}
1177
1178bool CoroutineStmtBuilder::makePromiseStmt() {
1179 // Form a declaration statement for the promise declaration, so that AST
1180 // visitors can more easily find it.
1181 StmtResult PromiseStmt =
1182 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
1183 if (PromiseStmt.isInvalid())
1184 return false;
1185
1186 this->Promise = PromiseStmt.get();
1187 return true;
1188}
1189
1190bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
1191 if (Fn.hasInvalidCoroutineSuspends())
1192 return false;
1193 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1194 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1195 return true;
1196}
1197
1198static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1199 CXXRecordDecl *PromiseRecordDecl,
1200 FunctionScopeInfo &Fn) {
1201 auto Loc = E->getExprLoc();
1202 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1203 auto *Decl = DeclRef->getDecl();
1204 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1205 if (Method->isStatic())
1206 return true;
1207 else
1208 Loc = Decl->getLocation();
1209 }
1210 }
1211
1212 S.Diag(
1213 Loc,
1214 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1215 << PromiseRecordDecl;
1216 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1217 << Fn.getFirstCoroutineStmtKeyword();
1218 return false;
1219}
1220
1221bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1222 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1223, __extension__ __PRETTY_FUNCTION__
))
1223 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1223, __extension__ __PRETTY_FUNCTION__
))
;
1224
1225 // [dcl.fct.def.coroutine]p10
1226 // If a search for the name get_return_object_on_allocation_failure in
1227 // the scope of the promise type ([class.member.lookup]) finds any
1228 // declarations, then the result of a call to an allocation function used to
1229 // obtain storage for the coroutine state is assumed to return nullptr if it
1230 // fails to obtain storage, ... If the allocation function returns nullptr,
1231 // ... and the return value is obtained by a call to
1232 // T::get_return_object_on_allocation_failure(), where T is the
1233 // promise type.
1234 DeclarationName DN =
1235 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1236 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
1237 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1238 return true;
1239
1240 CXXScopeSpec SS;
1241 ExprResult DeclNameExpr =
1242 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
1243 if (DeclNameExpr.isInvalid())
1244 return false;
1245
1246 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1247 return false;
1248
1249 ExprResult ReturnObjectOnAllocationFailure =
1250 S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
1251 if (ReturnObjectOnAllocationFailure.isInvalid())
1252 return false;
1253
1254 StmtResult ReturnStmt =
1255 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
1256 if (ReturnStmt.isInvalid()) {
1257 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1258 << DN;
1259 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1260 << Fn.getFirstCoroutineStmtKeyword();
1261 return false;
1262 }
1263
1264 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1265 return true;
1266}
1267
1268// Collect placement arguments for allocation function of coroutine FD.
1269// Return true if we collect placement arguments succesfully. Return false,
1270// otherwise.
1271static bool collectPlacementArgs(Sema &S, FunctionDecl &FD, SourceLocation Loc,
1272 SmallVectorImpl<Expr *> &PlacementArgs) {
1273 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1274 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1275 ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1276 if (ThisExpr.isInvalid())
1277 return false;
1278 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1279 if (ThisExpr.isInvalid())
1280 return false;
1281 PlacementArgs.push_back(ThisExpr.get());
1282 }
1283 }
1284
1285 for (auto *PD : FD.parameters()) {
1286 if (PD->getType()->isDependentType())
1287 continue;
1288
1289 // Build a reference to the parameter.
1290 auto PDLoc = PD->getLocation();
1291 ExprResult PDRefExpr =
1292 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1293 ExprValueKind::VK_LValue, PDLoc);
1294 if (PDRefExpr.isInvalid())
1295 return false;
1296
1297 PlacementArgs.push_back(PDRefExpr.get());
1298 }
1299
1300 return true;
1301}
1302
1303bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
1304 // Form and check allocation and deallocation calls.
1305 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1306, __extension__ __PRETTY_FUNCTION__
))
1306 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1306, __extension__ __PRETTY_FUNCTION__
))
;
1307 QualType PromiseType = Fn.CoroutinePromise->getType();
1308
1309 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1310 return false;
1311
1312 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1313
1314 // According to [dcl.fct.def.coroutine]p9, Lookup allocation functions using a
1315 // parameter list composed of the requested size of the coroutine state being
1316 // allocated, followed by the coroutine function's arguments. If a matching
1317 // allocation function exists, use it. Otherwise, use an allocation function
1318 // that just takes the requested size.
1319 //
1320 // [dcl.fct.def.coroutine]p9
1321 // An implementation may need to allocate additional storage for a
1322 // coroutine.
1323 // This storage is known as the coroutine state and is obtained by calling a
1324 // non-array allocation function ([basic.stc.dynamic.allocation]). The
1325 // allocation function's name is looked up by searching for it in the scope of
1326 // the promise type.
1327 // - If any declarations are found, overload resolution is performed on a
1328 // function call created by assembling an argument list. The first argument is
1329 // the amount of space requested, and has type std::size_t. The
1330 // lvalues p1 ... pn are the succeeding arguments.
1331 //
1332 // ...where "p1 ... pn" are defined earlier as:
1333 //
1334 // [dcl.fct.def.coroutine]p3
1335 // The promise type of a coroutine is `std::coroutine_traits<R, P1, ...,
1336 // Pn>`
1337 // , where R is the return type of the function, and `P1, ..., Pn` are the
1338 // sequence of types of the non-object function parameters, preceded by the
1339 // type of the object parameter ([dcl.fct]) if the coroutine is a non-static
1340 // member function. [dcl.fct.def.coroutine]p4 In the following, p_i is an
1341 // lvalue of type P_i, where p1 denotes the object parameter and p_i+1 denotes
1342 // the i-th non-object function parameter for a non-static member function,
1343 // and p_i denotes the i-th function parameter otherwise. For a non-static
1344 // member function, q_1 is an lvalue that denotes *this; any other q_i is an
1345 // lvalue that denotes the parameter copy corresponding to p_i.
1346
1347 FunctionDecl *OperatorNew = nullptr;
1348 SmallVector<Expr *, 1> PlacementArgs;
1349
1350 const bool PromiseContainsNew = [this, &PromiseType]() -> bool {
1351 DeclarationName NewName =
1352 S.getASTContext().DeclarationNames.getCXXOperatorName(OO_New);
1353 LookupResult R(S, NewName, Loc, Sema::LookupOrdinaryName);
1354
1355 if (PromiseType->isRecordType())
1356 S.LookupQualifiedName(R, PromiseType->getAsCXXRecordDecl());
1357
1358 return !R.empty() && !R.isAmbiguous();
1359 }();
1360
1361 // Helper function to indicate whether the last lookup found the aligned
1362 // allocation function.
1363 bool PassAlignment = S.getLangOpts().CoroAlignedAllocation;
1364 auto LookupAllocationFunction = [&](Sema::AllocationFunctionScope NewScope =
1365 Sema::AFS_Both,
1366 bool WithoutPlacementArgs = false,
1367 bool ForceNonAligned = false) {
1368 // [dcl.fct.def.coroutine]p9
1369 // The allocation function's name is looked up by searching for it in the
1370 // scope of the promise type.
1371 // - If any declarations are found, ...
1372 // - If no declarations are found in the scope of the promise type, a search
1373 // is performed in the global scope.
1374 if (NewScope == Sema::AFS_Both)
1375 NewScope = PromiseContainsNew ? Sema::AFS_Class : Sema::AFS_Global;
1376
1377 PassAlignment = !ForceNonAligned && S.getLangOpts().CoroAlignedAllocation;
1378 FunctionDecl *UnusedResult = nullptr;
1379 S.FindAllocationFunctions(Loc, SourceRange(), NewScope,
1380 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1381 /*isArray*/ false, PassAlignment,
1382 WithoutPlacementArgs ? MultiExprArg{}
1383 : PlacementArgs,
1384 OperatorNew, UnusedResult, /*Diagnose*/ false);
1385 };
1386
1387 // We don't expect to call to global operator new with (size, p0, …, pn).
1388 // So if we choose to lookup the allocation function in global scope, we
1389 // shouldn't lookup placement arguments.
1390 if (PromiseContainsNew && !collectPlacementArgs(S, FD, Loc, PlacementArgs))
1391 return false;
1392
1393 LookupAllocationFunction();
1394
1395 if (PromiseContainsNew && !PlacementArgs.empty()) {
1396 // [dcl.fct.def.coroutine]p9
1397 // If no viable function is found ([over.match.viable]), overload
1398 // resolution
1399 // is performed again on a function call created by passing just the amount
1400 // of space required as an argument of type std::size_t.
1401 //
1402 // Proposed Change of [dcl.fct.def.coroutine]p9 in P2014R0:
1403 // Otherwise, overload resolution is performed again on a function call
1404 // created
1405 // by passing the amount of space requested as an argument of type
1406 // std::size_t as the first argument, and the requested alignment as
1407 // an argument of type std:align_val_t as the second argument.
1408 if (!OperatorNew ||
1409 (S.getLangOpts().CoroAlignedAllocation && !PassAlignment))
1410 LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,
1411 /*WithoutPlacementArgs*/ true);
1412 }
1413
1414 // Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:
1415 // Otherwise, overload resolution is performed again on a function call
1416 // created
1417 // by passing the amount of space requested as an argument of type
1418 // std::size_t as the first argument, and the lvalues p1 ... pn as the
1419 // succeeding arguments. Otherwise, overload resolution is performed again
1420 // on a function call created by passing just the amount of space required as
1421 // an argument of type std::size_t.
1422 //
1423 // So within the proposed change in P2014RO, the priority order of aligned
1424 // allocation functions wiht promise_type is:
1425 //
1426 // void* operator new( std::size_t, std::align_val_t, placement_args... );
1427 // void* operator new( std::size_t, std::align_val_t);
1428 // void* operator new( std::size_t, placement_args... );
1429 // void* operator new( std::size_t);
1430
1431 // Helper variable to emit warnings.
1432 bool FoundNonAlignedInPromise = false;
1433 if (PromiseContainsNew && S.getLangOpts().CoroAlignedAllocation)
1434 if (!OperatorNew || !PassAlignment) {
1435 FoundNonAlignedInPromise = OperatorNew;
1436
1437 LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,
1438 /*WithoutPlacementArgs*/ false,
1439 /*ForceNonAligned*/ true);
1440
1441 if (!OperatorNew && !PlacementArgs.empty())
1442 LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,
1443 /*WithoutPlacementArgs*/ true,
1444 /*ForceNonAligned*/ true);
1445 }
1446
1447 bool IsGlobalOverload =
1448 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1449 // If we didn't find a class-local new declaration and non-throwing new
1450 // was is required then we need to lookup the non-throwing global operator
1451 // instead.
1452 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1453 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1454 if (!StdNoThrow)
1455 return false;
1456 PlacementArgs = {StdNoThrow};
1457 OperatorNew = nullptr;
1458 LookupAllocationFunction(Sema::AFS_Global);
1459 }
1460
1461 // If we found a non-aligned allocation function in the promise_type,
1462 // it indicates the user forgot to update the allocation function. Let's emit
1463 // a warning here.
1464 if (FoundNonAlignedInPromise) {
1465 S.Diag(OperatorNew->getLocation(),
1466 diag::warn_non_aligned_allocation_function)
1467 << &FD;
1468 }
1469
1470 if (!OperatorNew) {
1471 if (PromiseContainsNew)
1472 S.Diag(Loc, diag::err_coroutine_unusable_new) << PromiseType << &FD;
1473 else if (RequiresNoThrowAlloc)
1474 S.Diag(Loc, diag::err_coroutine_unfound_nothrow_new)
1475 << &FD << S.getLangOpts().CoroAlignedAllocation;
1476
1477 return false;
1478 }
1479
1480 if (RequiresNoThrowAlloc) {
1481 const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>();
1482 if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
1483 S.Diag(OperatorNew->getLocation(),
1484 diag::err_coroutine_promise_new_requires_nothrow)
1485 << OperatorNew;
1486 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1487 << OperatorNew;
1488 return false;
1489 }
1490 }
1491
1492 FunctionDecl *OperatorDelete = nullptr;
1493 if (!findDeleteForPromise(S, Loc, PromiseType, OperatorDelete)) {
1494 // FIXME: We should add an error here. According to:
1495 // [dcl.fct.def.coroutine]p12
1496 // If no usual deallocation function is found, the program is ill-formed.
1497 return false;
1498 }
1499
1500 Expr *FramePtr =
1501 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
1502
1503 Expr *FrameSize =
1504 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_size, {});
1505
1506 Expr *FrameAlignment = nullptr;
1507
1508 if (S.getLangOpts().CoroAlignedAllocation) {
1509 FrameAlignment =
1510 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_align, {});
1511
1512 TypeSourceInfo *AlignValTy = getTypeSourceInfoForStdAlignValT(S, Loc);
1513 if (!AlignValTy)
1514 return false;
1515
1516 FrameAlignment = S.BuildCXXNamedCast(Loc, tok::kw_static_cast, AlignValTy,
1517 FrameAlignment, SourceRange(Loc, Loc),
1518 SourceRange(Loc, Loc))
1519 .get();
1520 }
1521
1522 // Make new call.
1523 ExprResult NewRef =
1524 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1525 if (NewRef.isInvalid())
1526 return false;
1527
1528 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1529 if (S.getLangOpts().CoroAlignedAllocation && PassAlignment)
1530 NewArgs.push_back(FrameAlignment);
1531
1532 if (OperatorNew->getNumParams() > NewArgs.size())
1533 llvm::append_range(NewArgs, PlacementArgs);
1534
1535 ExprResult NewExpr =
1536 S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1537 NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
1538 if (NewExpr.isInvalid())
1539 return false;
1540
1541 // Make delete call.
1542
1543 QualType OpDeleteQualType = OperatorDelete->getType();
1544
1545 ExprResult DeleteRef =
1546 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1547 if (DeleteRef.isInvalid())
1548 return false;
1549
1550 Expr *CoroFree =
1551 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1552
1553 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1554
1555 // [dcl.fct.def.coroutine]p12
1556 // The selected deallocation function shall be called with the address of
1557 // the block of storage to be reclaimed as its first argument. If a
1558 // deallocation function with a parameter of type std::size_t is
1559 // used, the size of the block is passed as the corresponding argument.
1560 const auto *OpDeleteType =
1561 OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>();
1562 if (OpDeleteType->getNumParams() > DeleteArgs.size() &&
1563 S.getASTContext().hasSameUnqualifiedType(
1564 OpDeleteType->getParamType(DeleteArgs.size()), FrameSize->getType()))
1565 DeleteArgs.push_back(FrameSize);
1566
1567 // Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:
1568 // If deallocation function lookup finds a usual deallocation function with
1569 // a pointer parameter, size parameter and alignment parameter then this
1570 // will be the selected deallocation function, otherwise if lookup finds a
1571 // usual deallocation function with both a pointer parameter and a size
1572 // parameter, then this will be the selected deallocation function.
1573 // Otherwise, if lookup finds a usual deallocation function with only a
1574 // pointer parameter, then this will be the selected deallocation
1575 // function.
1576 //
1577 // So we are not forced to pass alignment to the deallocation function.
1578 if (S.getLangOpts().CoroAlignedAllocation &&
1579 OpDeleteType->getNumParams() > DeleteArgs.size() &&
1580 S.getASTContext().hasSameUnqualifiedType(
1581 OpDeleteType->getParamType(DeleteArgs.size()),
1582 FrameAlignment->getType()))
1583 DeleteArgs.push_back(FrameAlignment);
1584
1585 ExprResult DeleteExpr =
1586 S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
1587 DeleteExpr =
1588 S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
1589 if (DeleteExpr.isInvalid())
1590 return false;
1591
1592 this->Allocate = NewExpr.get();
1593 this->Deallocate = DeleteExpr.get();
1594
1595 return true;
1596}
1597
1598bool CoroutineStmtBuilder::makeOnFallthrough() {
1599 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1600, __extension__ __PRETTY_FUNCTION__
))
1600 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1600, __extension__ __PRETTY_FUNCTION__
))
;
1601
1602 // [dcl.fct.def.coroutine]/p6
1603 // If searches for the names return_void and return_value in the scope of
1604 // the promise type each find any declarations, the program is ill-formed.
1605 // [Note 1: If return_void is found, flowing off the end of a coroutine is
1606 // equivalent to a co_return with no operand. Otherwise, flowing off the end
1607 // of a coroutine results in undefined behavior ([stmt.return.coroutine]). —
1608 // end note]
1609 bool HasRVoid, HasRValue;
1610 LookupResult LRVoid =
1611 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1612 LookupResult LRValue =
1613 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
1614
1615 StmtResult Fallthrough;
1616 if (HasRVoid && HasRValue) {
1617 // FIXME Improve this diagnostic
1618 S.Diag(FD.getLocation(),
1619 diag::err_coroutine_promise_incompatible_return_functions)
1620 << PromiseRecordDecl;
1621 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1622 diag::note_member_first_declared_here)
1623 << LRVoid.getLookupName();
1624 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1625 diag::note_member_first_declared_here)
1626 << LRValue.getLookupName();
1627 return false;
1628 } else if (!HasRVoid && !HasRValue) {
1629 // We need to set 'Fallthrough'. Otherwise the other analysis part might
1630 // think the coroutine has defined a return_value method. So it might emit
1631 // **false** positive warning. e.g.,
1632 //
1633 // promise_without_return_func foo() {
1634 // co_await something();
1635 // }
1636 //
1637 // Then AnalysisBasedWarning would emit a warning about `foo()` lacking a
1638 // co_return statements, which isn't correct.
1639 Fallthrough = S.ActOnNullStmt(PromiseRecordDecl->getLocation());
1640 if (Fallthrough.isInvalid())
1641 return false;
1642 } else if (HasRVoid) {
1643 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1644 /*IsImplicit*/false);
1645 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1646 if (Fallthrough.isInvalid())
1647 return false;
1648 }
1649
1650 this->OnFallthrough = Fallthrough.get();
1651 return true;
1652}
1653
1654bool CoroutineStmtBuilder::makeOnException() {
1655 // Try to form 'p.unhandled_exception();'
1656 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1657, __extension__ __PRETTY_FUNCTION__
))
1657 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1657, __extension__ __PRETTY_FUNCTION__
))
;
1658
1659 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1660
1661 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1662 auto DiagID =
1663 RequireUnhandledException
1664 ? diag::err_coroutine_promise_unhandled_exception_required
1665 : diag::
1666 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1667 S.Diag(Loc, DiagID) << PromiseRecordDecl;
1668 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1669 << PromiseRecordDecl;
1670 return !RequireUnhandledException;
1671 }
1672
1673 // If exceptions are disabled, don't try to build OnException.
1674 if (!S.getLangOpts().CXXExceptions)
1675 return true;
1676
1677 ExprResult UnhandledException = buildPromiseCall(
1678 S, Fn.CoroutinePromise, Loc, "unhandled_exception", std::nullopt);
1679 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
1680 /*DiscardedValue*/ false);
1681 if (UnhandledException.isInvalid())
1682 return false;
1683
1684 // Since the body of the coroutine will be wrapped in try-catch, it will
1685 // be incompatible with SEH __try if present in a function.
1686 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1687 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1688 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1689 << Fn.getFirstCoroutineStmtKeyword();
1690 return false;
1691 }
1692
1693 this->OnException = UnhandledException.get();
1694 return true;
1695}
1696
1697bool CoroutineStmtBuilder::makeReturnObject() {
1698 // [dcl.fct.def.coroutine]p7
1699 // The expression promise.get_return_object() is used to initialize the
1700 // returned reference or prvalue result object of a call to a coroutine.
1701 ExprResult ReturnObject = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1702 "get_return_object", std::nullopt);
1703 if (ReturnObject.isInvalid())
1704 return false;
1705
1706 this->ReturnValue = ReturnObject.get();
1707 return true;
1708}
1709
1710static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1711 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1712 auto *MethodDecl = MbrRef->getMethodDecl();
1713 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1714 << MethodDecl;
1715 }
1716 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1717 << Fn.getFirstCoroutineStmtKeyword();
1718}
1719
1720bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1721 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1722, __extension__ __PRETTY_FUNCTION__
))
1722 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1722, __extension__ __PRETTY_FUNCTION__
))
;
1723 assert(this->ReturnValue && "ReturnValue must be already formed")(static_cast <bool> (this->ReturnValue && "ReturnValue must be already formed"
) ? void (0) : __assert_fail ("this->ReturnValue && \"ReturnValue must be already formed\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1723, __extension__ __PRETTY_FUNCTION__
))
;
1724
1725 QualType const GroType = this->ReturnValue->getType();
1726 assert(!GroType->isDependentType() &&(static_cast <bool> (!GroType->isDependentType() &&
"get_return_object type must no longer be dependent") ? void
(0) : __assert_fail ("!GroType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1727, __extension__ __PRETTY_FUNCTION__
))
1727 "get_return_object type must no longer be dependent")(static_cast <bool> (!GroType->isDependentType() &&
"get_return_object type must no longer be dependent") ? void
(0) : __assert_fail ("!GroType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1727, __extension__ __PRETTY_FUNCTION__
))
;
1728
1729 QualType const FnRetType = FD.getReturnType();
1730 assert(!FnRetType->isDependentType() &&(static_cast <bool> (!FnRetType->isDependentType() &&
"get_return_object type must no longer be dependent") ? void
(0) : __assert_fail ("!FnRetType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1731, __extension__ __PRETTY_FUNCTION__
))
1731 "get_return_object type must no longer be dependent")(static_cast <bool> (!FnRetType->isDependentType() &&
"get_return_object type must no longer be dependent") ? void
(0) : __assert_fail ("!FnRetType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1731, __extension__ __PRETTY_FUNCTION__
))
;
1732
1733 // The call to get_­return_­object is sequenced before the call to
1734 // initial_­suspend and is invoked at most once, but there are caveats
1735 // regarding on whether the prvalue result object may be initialized
1736 // directly/eager or delayed, depending on the types involved.
1737 //
1738 // More info at https://github.com/cplusplus/papers/issues/1414
1739 bool GroMatchesRetType = S.getASTContext().hasSameType(GroType, FnRetType);
1740
1741 if (FnRetType->isVoidType()) {
1742 ExprResult Res =
1743 S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
1744 if (Res.isInvalid())
1745 return false;
1746
1747 if (!GroMatchesRetType)
1748 this->ResultDecl = Res.get();
1749 return true;
1750 }
1751
1752 if (GroType->isVoidType()) {
1753 // Trigger a nice error message.
1754 InitializedEntity Entity =
1755 InitializedEntity::InitializeResult(Loc, FnRetType);
1756 S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);
1757 noteMemberDeclaredHere(S, ReturnValue, Fn);
1758 return false;
1759 }
1760
1761 StmtResult ReturnStmt;
1762 clang::VarDecl *GroDecl = nullptr;
1763 if (GroMatchesRetType) {
1764 ReturnStmt = S.BuildReturnStmt(Loc, ReturnValue);
1765 } else {
1766 GroDecl = VarDecl::Create(
1767 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1768 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1769 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1770 GroDecl->setImplicit();
1771
1772 S.CheckVariableDeclarationType(GroDecl);
1773 if (GroDecl->isInvalidDecl())
1774 return false;
1775
1776 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1777 ExprResult Res =
1778 S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);
1779 if (Res.isInvalid())
1780 return false;
1781
1782 Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);
1783 if (Res.isInvalid())
1784 return false;
1785
1786 S.AddInitializerToDecl(GroDecl, Res.get(),
1787 /*DirectInit=*/false);
1788
1789 S.FinalizeDeclaration(GroDecl);
1790
1791 // Form a declaration statement for the return declaration, so that AST
1792 // visitors can more easily find it.
1793 StmtResult GroDeclStmt =
1794 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1795 if (GroDeclStmt.isInvalid())
1796 return false;
1797
1798 this->ResultDecl = GroDeclStmt.get();
1799
1800 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1801 if (declRef.isInvalid())
1802 return false;
1803
1804 ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1805 }
1806
1807 if (ReturnStmt.isInvalid()) {
1808 noteMemberDeclaredHere(S, ReturnValue, Fn);
1809 return false;
1810 }
1811
1812 if (!GroMatchesRetType &&
1813 cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1814 GroDecl->setNRVOVariable(true);
1815
1816 this->ReturnStmt = ReturnStmt.get();
1817 return true;
1818}
1819
1820// Create a static_cast\<T&&>(expr).
1821static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1822 if (T.isNull())
1823 T = E->getType();
1824 QualType TargetType = S.BuildReferenceType(
1825 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1826 SourceLocation ExprLoc = E->getBeginLoc();
1827 TypeSourceInfo *TargetLoc =
1828 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1829
1830 return S
1831 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1832 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1833 .get();
1834}
1835
1836/// Build a variable declaration for move parameter.
1837static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1838 IdentifierInfo *II) {
1839 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1840 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1841 TInfo, SC_None);
1842 Decl->setImplicit();
1843 return Decl;
1844}
1845
1846// Build statements that move coroutine function parameters to the coroutine
1847// frame, and store them on the function scope info.
1848bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1849 assert(isa<FunctionDecl>(CurContext) && "not in a function scope")(static_cast <bool> (isa<FunctionDecl>(CurContext
) && "not in a function scope") ? void (0) : __assert_fail
("isa<FunctionDecl>(CurContext) && \"not in a function scope\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1849, __extension__ __PRETTY_FUNCTION__
))
;
1850 auto *FD = cast<FunctionDecl>(CurContext);
1851
1852 auto *ScopeInfo = getCurFunction();
1853 if (!ScopeInfo->CoroutineParameterMoves.empty())
1854 return false;
1855
1856 // [dcl.fct.def.coroutine]p13
1857 // When a coroutine is invoked, after initializing its parameters
1858 // ([expr.call]), a copy is created for each coroutine parameter. For a
1859 // parameter of type cv T, the copy is a variable of type cv T with
1860 // automatic storage duration that is direct-initialized from an xvalue of
1861 // type T referring to the parameter.
1862 for (auto *PD : FD->parameters()) {
1863 if (PD->getType()->isDependentType())
1864 continue;
1865
1866 ExprResult PDRefExpr =
1867 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1868 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1869 if (PDRefExpr.isInvalid())
1870 return false;
1871
1872 Expr *CExpr = nullptr;
1873 if (PD->getType()->getAsCXXRecordDecl() ||
1874 PD->getType()->isRValueReferenceType())
1875 CExpr = castForMoving(*this, PDRefExpr.get());
1876 else
1877 CExpr = PDRefExpr.get();
1878 // [dcl.fct.def.coroutine]p13
1879 // The initialization and destruction of each parameter copy occurs in the
1880 // context of the called coroutine.
1881 auto *D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1882 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
1883
1884 // Convert decl to a statement.
1885 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1886 if (Stmt.isInvalid())
1887 return false;
1888
1889 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
1890 }
1891 return true;
1892}
1893
1894StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1895 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1896 if (!Res)
1897 return StmtError();
1898 return Res;
1899}
1900
1901ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
1902 SourceLocation FuncLoc) {
1903 if (StdCoroutineTraitsCache)
1904 return StdCoroutineTraitsCache;
1905
1906 IdentifierInfo const &TraitIdent =
1907 PP.getIdentifierTable().get("coroutine_traits");
1908
1909 NamespaceDecl *StdSpace = getStdNamespace();
1910 LookupResult Result(*this, &TraitIdent, FuncLoc, LookupOrdinaryName);
1911 bool Found = StdSpace && LookupQualifiedName(Result, StdSpace);
1912
1913 if (!Found) {
1914 // The goggles, we found nothing!
1915 Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
1916 << "std::coroutine_traits";
1917 return nullptr;
1918 }
1919
1920 // coroutine_traits is required to be a class template.
1921 StdCoroutineTraitsCache = Result.getAsSingle<ClassTemplateDecl>();
1922 if (!StdCoroutineTraitsCache) {
1923 Result.suppressDiagnostics();
1924 NamedDecl *Found = *Result.begin();
1925 Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
1926 return nullptr;
1927 }
1928
1929 return StdCoroutineTraitsCache;
1930}

/build/source/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- 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 Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Availability.h"
21#include "clang/AST/ComparisonCategories.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprConcepts.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LocInfoType.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/PrettyPrinter.h"
34#include "clang/AST/StmtCXX.h"
35#include "clang/AST/StmtOpenMP.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/TypeOrdering.h"
38#include "clang/Basic/BitmaskEnum.h"
39#include "clang/Basic/Builtins.h"
40#include "clang/Basic/DarwinSDKInfo.h"
41#include "clang/Basic/ExpressionTraits.h"
42#include "clang/Basic/Module.h"
43#include "clang/Basic/OpenCLOptions.h"
44#include "clang/Basic/OpenMPKinds.h"
45#include "clang/Basic/PragmaKinds.h"
46#include "clang/Basic/Specifiers.h"
47#include "clang/Basic/TemplateKinds.h"
48#include "clang/Basic/TypeTraits.h"
49#include "clang/Sema/AnalysisBasedWarnings.h"
50#include "clang/Sema/CleanupInfo.h"
51#include "clang/Sema/DeclSpec.h"
52#include "clang/Sema/ExternalSemaSource.h"
53#include "clang/Sema/IdentifierResolver.h"
54#include "clang/Sema/ObjCMethodList.h"
55#include "clang/Sema/Ownership.h"
56#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaConcept.h"
58#include "clang/Sema/TypoCorrection.h"
59#include "clang/Sema/Weak.h"
60#include "llvm/ADT/ArrayRef.h"
61#include "llvm/ADT/SetVector.h"
62#include "llvm/ADT/SmallBitVector.h"
63#include "llvm/ADT/SmallPtrSet.h"
64#include "llvm/ADT/SmallSet.h"
65#include "llvm/ADT/SmallVector.h"
66#include "llvm/ADT/TinyPtrVector.h"
67#include "llvm/Frontend/OpenMP/OMPConstants.h"
68#include <deque>
69#include <memory>
70#include <optional>
71#include <string>
72#include <tuple>
73#include <vector>
74
75namespace llvm {
76 class APSInt;
77 template <typename ValueT, typename ValueInfoT> class DenseSet;
78 class SmallBitVector;
79 struct InlineAsmIdentifierInfo;
80}
81
82namespace clang {
83 class ADLResult;
84 class ASTConsumer;
85 class ASTContext;
86 class ASTMutationListener;
87 class ASTReader;
88 class ASTWriter;
89 class ArrayType;
90 class ParsedAttr;
91 class BindingDecl;
92 class BlockDecl;
93 class CapturedDecl;
94 class CXXBasePath;
95 class CXXBasePaths;
96 class CXXBindTemporaryExpr;
97 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
98 class CXXConstructorDecl;
99 class CXXConversionDecl;
100 class CXXDeleteExpr;
101 class CXXDestructorDecl;
102 class CXXFieldCollector;
103 class CXXMemberCallExpr;
104 class CXXMethodDecl;
105 class CXXScopeSpec;
106 class CXXTemporary;
107 class CXXTryStmt;
108 class CallExpr;
109 class ClassTemplateDecl;
110 class ClassTemplatePartialSpecializationDecl;
111 class ClassTemplateSpecializationDecl;
112 class VarTemplatePartialSpecializationDecl;
113 class CodeCompleteConsumer;
114 class CodeCompletionAllocator;
115 class CodeCompletionTUInfo;
116 class CodeCompletionResult;
117 class CoroutineBodyStmt;
118 class Decl;
119 class DeclAccessPair;
120 class DeclContext;
121 class DeclRefExpr;
122 class DeclaratorDecl;
123 class DeducedTemplateArgument;
124 class DependentDiagnostic;
125 class DesignatedInitExpr;
126 class Designation;
127 class EnableIfAttr;
128 class EnumConstantDecl;
129 class Expr;
130 class ExtVectorType;
131 class FormatAttr;
132 class FriendDecl;
133 class FunctionDecl;
134 class FunctionProtoType;
135 class FunctionTemplateDecl;
136 class ImplicitConversionSequence;
137 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
138 class InitListExpr;
139 class InitializationKind;
140 class InitializationSequence;
141 class InitializedEntity;
142 class IntegerLiteral;
143 class LabelStmt;
144 class LambdaExpr;
145 class LangOptions;
146 class LocalInstantiationScope;
147 class LookupResult;
148 class MacroInfo;
149 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
150 class ModuleLoader;
151 class MultiLevelTemplateArgumentList;
152 class NamedDecl;
153 class ObjCCategoryDecl;
154 class ObjCCategoryImplDecl;
155 class ObjCCompatibleAliasDecl;
156 class ObjCContainerDecl;
157 class ObjCImplDecl;
158 class ObjCImplementationDecl;
159 class ObjCInterfaceDecl;
160 class ObjCIvarDecl;
161 template <class T> class ObjCList;
162 class ObjCMessageExpr;
163 class ObjCMethodDecl;
164 class ObjCPropertyDecl;
165 class ObjCProtocolDecl;
166 class OMPThreadPrivateDecl;
167 class OMPRequiresDecl;
168 class OMPDeclareReductionDecl;
169 class OMPDeclareSimdDecl;
170 class OMPClause;
171 struct OMPVarListLocTy;
172 struct OverloadCandidate;
173 enum class OverloadCandidateParamOrder : char;
174 enum OverloadCandidateRewriteKind : unsigned;
175 class OverloadCandidateSet;
176 class OverloadExpr;
177 class ParenListExpr;
178 class ParmVarDecl;
179 class Preprocessor;
180 class PseudoDestructorTypeStorage;
181 class PseudoObjectExpr;
182 class QualType;
183 class StandardConversionSequence;
184 class Stmt;
185 class StringLiteral;
186 class SwitchStmt;
187 class TemplateArgument;
188 class TemplateArgumentList;
189 class TemplateArgumentLoc;
190 class TemplateDecl;
191 class TemplateInstantiationCallback;
192 class TemplateParameterList;
193 class TemplatePartialOrderingContext;
194 class TemplateTemplateParmDecl;
195 class Token;
196 class TypeAliasDecl;
197 class TypedefDecl;
198 class TypedefNameDecl;
199 class TypeLoc;
200 class TypoCorrectionConsumer;
201 class UnqualifiedId;
202 class UnresolvedLookupExpr;
203 class UnresolvedMemberExpr;
204 class UnresolvedSetImpl;
205 class UnresolvedSetIterator;
206 class UsingDecl;
207 class UsingShadowDecl;
208 class ValueDecl;
209 class VarDecl;
210 class VarTemplateSpecializationDecl;
211 class VisibilityAttr;
212 class VisibleDeclConsumer;
213 class IndirectFieldDecl;
214 struct DeductionFailureInfo;
215 class TemplateSpecCandidateSet;
216
217namespace sema {
218 class AccessedEntity;
219 class BlockScopeInfo;
220 class Capture;
221 class CapturedRegionScopeInfo;
222 class CapturingScopeInfo;
223 class CompoundScopeInfo;
224 class DelayedDiagnostic;
225 class DelayedDiagnosticPool;
226 class FunctionScopeInfo;
227 class LambdaScopeInfo;
228 class PossiblyUnreachableDiag;
229 class RISCVIntrinsicManager;
230 class SemaPPCallbacks;
231 class TemplateDeductionInfo;
232}
233
234namespace threadSafety {
235 class BeforeSet;
236 void threadSafetyCleanup(BeforeSet* Cache);
237}
238
239// FIXME: No way to easily map from TemplateTypeParmTypes to
240// TemplateTypeParmDecls, so we have this horrible PointerUnion.
241typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>,
242 SourceLocation>
243 UnexpandedParameterPack;
244
245/// Describes whether we've seen any nullability information for the given
246/// file.
247struct FileNullability {
248 /// The first pointer declarator (of any pointer kind) in the file that does
249 /// not have a corresponding nullability annotation.
250 SourceLocation PointerLoc;
251
252 /// The end location for the first pointer declarator in the file. Used for
253 /// placing fix-its.
254 SourceLocation PointerEndLoc;
255
256 /// Which kind of pointer declarator we saw.
257 uint8_t PointerKind;
258
259 /// Whether we saw any type nullability annotations in the given file.
260 bool SawTypeNullability = false;
261};
262
263/// A mapping from file IDs to a record of whether we've seen nullability
264/// information in that file.
265class FileNullabilityMap {
266 /// A mapping from file IDs to the nullability information for each file ID.
267 llvm::DenseMap<FileID, FileNullability> Map;
268
269 /// A single-element cache based on the file ID.
270 struct {
271 FileID File;
272 FileNullability Nullability;
273 } Cache;
274
275public:
276 FileNullability &operator[](FileID file) {
277 // Check the single-element cache.
278 if (file == Cache.File)
279 return Cache.Nullability;
280
281 // It's not in the single-element cache; flush the cache if we have one.
282 if (!Cache.File.isInvalid()) {
283 Map[Cache.File] = Cache.Nullability;
284 }
285
286 // Pull this entry into the cache.
287 Cache.File = file;
288 Cache.Nullability = Map[file];
289 return Cache.Nullability;
290 }
291};
292
293/// Tracks expected type during expression parsing, for use in code completion.
294/// The type is tied to a particular token, all functions that update or consume
295/// the type take a start location of the token they are looking at as a
296/// parameter. This avoids updating the type on hot paths in the parser.
297class PreferredTypeBuilder {
298public:
299 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
300
301 void enterCondition(Sema &S, SourceLocation Tok);
302 void enterReturn(Sema &S, SourceLocation Tok);
303 void enterVariableInit(SourceLocation Tok, Decl *D);
304 /// Handles e.g. BaseType{ .D = Tok...
305 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
306 const Designation &D);
307 /// Computing a type for the function argument may require running
308 /// overloading, so we postpone its computation until it is actually needed.
309 ///
310 /// Clients should be very careful when using this function, as it stores a
311 /// function_ref, clients should make sure all calls to get() with the same
312 /// location happen while function_ref is alive.
313 ///
314 /// The callback should also emit signature help as a side-effect, but only
315 /// if the completion point has been reached.
316 void enterFunctionArgument(SourceLocation Tok,
317 llvm::function_ref<QualType()> ComputeType);
318
319 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
320 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
321 SourceLocation OpLoc);
322 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
323 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
324 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
325 /// Handles all type casts, including C-style cast, C++ casts, etc.
326 void enterTypeCast(SourceLocation Tok, QualType CastType);
327
328 /// Get the expected type associated with this location, if any.
329 ///
330 /// If the location is a function argument, determining the expected type
331 /// involves considering all function overloads and the arguments so far.
332 /// In this case, signature help for these function overloads will be reported
333 /// as a side-effect (only if the completion point has been reached).
334 QualType get(SourceLocation Tok) const {
335 if (!Enabled || Tok != ExpectedLoc)
336 return QualType();
337 if (!Type.isNull())
338 return Type;
339 if (ComputeType)
340 return ComputeType();
341 return QualType();
342 }
343
344private:
345 bool Enabled;
346 /// Start position of a token for which we store expected type.
347 SourceLocation ExpectedLoc;
348 /// Expected type for a token starting at ExpectedLoc.
349 QualType Type;
350 /// A function to compute expected type at ExpectedLoc. It is only considered
351 /// if Type is null.
352 llvm::function_ref<QualType()> ComputeType;
353};
354
355/// Sema - This implements semantic analysis and AST building for C.
356class Sema final {
357 Sema(const Sema &) = delete;
358 void operator=(const Sema &) = delete;
359
360 ///Source of additional semantic information.
361 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
362
363 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
364
365 /// Determine whether two declarations should be linked together, given that
366 /// the old declaration might not be visible and the new declaration might
367 /// not have external linkage.
368 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
369 const NamedDecl *New) {
370 if (isVisible(Old))
371 return true;
372 // See comment in below overload for why it's safe to compute the linkage
373 // of the new declaration here.
374 if (New->isExternallyDeclarable()) {
375 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 376, __extension__ __PRETTY_FUNCTION__
))
376 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 376, __extension__ __PRETTY_FUNCTION__
))
;
377 return true;
378 }
379 return false;
380 }
381 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
382
383 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
384 QualType ResultTy,
385 ArrayRef<QualType> Args);
386
387public:
388 /// The maximum alignment, same as in llvm::Value. We duplicate them here
389 /// because that allows us not to duplicate the constants in clang code,
390 /// which we must to since we can't directly use the llvm constants.
391 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
392 ///
393 /// This is the greatest alignment value supported by load, store, and alloca
394 /// instructions, and global values.
395 static const unsigned MaxAlignmentExponent = 32;
396 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
397
398 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
399 typedef OpaquePtr<TemplateName> TemplateTy;
400 typedef OpaquePtr<QualType> TypeTy;
401
402 OpenCLOptions OpenCLFeatures;
403 FPOptions CurFPFeatures;
404
405 const LangOptions &LangOpts;
406 Preprocessor &PP;
407 ASTContext &Context;
408 ASTConsumer &Consumer;
409 DiagnosticsEngine &Diags;
410 SourceManager &SourceMgr;
411
412 /// Flag indicating whether or not to collect detailed statistics.
413 bool CollectStats;
414
415 /// Code-completion consumer.
416 CodeCompleteConsumer *CodeCompleter;
417
418 /// CurContext - This is the current declaration context of parsing.
419 DeclContext *CurContext;
420
421 /// Generally null except when we temporarily switch decl contexts,
422 /// like in \see ActOnObjCTemporaryExitContainerContext.
423 DeclContext *OriginalLexicalContext;
424
425 /// VAListTagName - The declaration name corresponding to __va_list_tag.
426 /// This is used as part of a hack to omit that class from ADL results.
427 DeclarationName VAListTagName;
428
429 bool MSStructPragmaOn; // True when \#pragma ms_struct on
430
431 /// Controls member pointer representation format under the MS ABI.
432 LangOptions::PragmaMSPointersToMembersKind
433 MSPointerToMemberRepresentationMethod;
434
435 /// Stack of active SEH __finally scopes. Can be empty.
436 SmallVector<Scope*, 2> CurrentSEHFinally;
437
438 /// Source location for newly created implicit MSInheritanceAttrs
439 SourceLocation ImplicitMSInheritanceAttrLoc;
440
441 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
442 /// `TransformTypos` in order to keep track of any TypoExprs that are created
443 /// recursively during typo correction and wipe them away if the correction
444 /// fails.
445 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
446
447 /// pragma clang section kind
448 enum PragmaClangSectionKind {
449 PCSK_Invalid = 0,
450 PCSK_BSS = 1,
451 PCSK_Data = 2,
452 PCSK_Rodata = 3,
453 PCSK_Text = 4,
454 PCSK_Relro = 5
455 };
456
457 enum PragmaClangSectionAction {
458 PCSA_Set = 0,
459 PCSA_Clear = 1
460 };
461
462 struct PragmaClangSection {
463 std::string SectionName;
464 bool Valid = false;
465 SourceLocation PragmaLocation;
466 };
467
468 PragmaClangSection PragmaClangBSSSection;
469 PragmaClangSection PragmaClangDataSection;
470 PragmaClangSection PragmaClangRodataSection;
471 PragmaClangSection PragmaClangRelroSection;
472 PragmaClangSection PragmaClangTextSection;
473
474 enum PragmaMsStackAction {
475 PSK_Reset = 0x0, // #pragma ()
476 PSK_Set = 0x1, // #pragma (value)
477 PSK_Push = 0x2, // #pragma (push[, id])
478 PSK_Pop = 0x4, // #pragma (pop[, id])
479 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
480 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
481 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
482 };
483
484 struct PragmaPackInfo {
485 PragmaMsStackAction Action;
486 StringRef SlotLabel;
487 Token Alignment;
488 };
489
490 // #pragma pack and align.
491 class AlignPackInfo {
492 public:
493 // `Native` represents default align mode, which may vary based on the
494 // platform.
495 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
496
497 // #pragma pack info constructor
498 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
499 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
500 assert(Num == PackNumber && "The pack number has been truncated.")(static_cast <bool> (Num == PackNumber && "The pack number has been truncated."
) ? void (0) : __assert_fail ("Num == PackNumber && \"The pack number has been truncated.\""
, "clang/include/clang/Sema/Sema.h", 500, __extension__ __PRETTY_FUNCTION__
))
;
501 }
502
503 // #pragma align info constructor
504 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
505 : PackAttr(false), AlignMode(M),
506 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
507
508 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
509
510 AlignPackInfo() : AlignPackInfo(Native, false) {}
511
512 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
513 // integer encoding for it. This should only be passed to
514 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
515 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
516 std::uint32_t Encoding{};
517 if (Info.IsXLStack())
518 Encoding |= IsXLMask;
519
520 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
521
522 if (Info.IsPackAttr())
523 Encoding |= PackAttrMask;
524
525 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
526
527 return Encoding;
528 }
529
530 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
531 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
532 AlignPackInfo::Mode M =
533 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
534 int PackNumber = (Encoding & PackNumMask) >> 4;
535
536 if (Encoding & PackAttrMask)
537 return AlignPackInfo(M, PackNumber, IsXL);
538
539 return AlignPackInfo(M, IsXL);
540 }
541
542 bool IsPackAttr() const { return PackAttr; }
543
544 bool IsAlignAttr() const { return !PackAttr; }
545
546 Mode getAlignMode() const { return AlignMode; }
547
548 unsigned getPackNumber() const { return PackNumber; }
549
550 bool IsPackSet() const {
551 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
552 // attriute on a decl.
553 return PackNumber != UninitPackVal && PackNumber != 0;
554 }
555
556 bool IsXLStack() const { return XLStack; }
557
558 bool operator==(const AlignPackInfo &Info) const {
559 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
560 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
561 Info.XLStack);
562 }
563
564 bool operator!=(const AlignPackInfo &Info) const {
565 return !(*this == Info);
566 }
567
568 private:
569 /// \brief True if this is a pragma pack attribute,
570 /// not a pragma align attribute.
571 bool PackAttr;
572
573 /// \brief The alignment mode that is in effect.
574 Mode AlignMode;
575
576 /// \brief The pack number of the stack.
577 unsigned char PackNumber;
578
579 /// \brief True if it is a XL #pragma align/pack stack.
580 bool XLStack;
581
582 /// \brief Uninitialized pack value.
583 static constexpr unsigned char UninitPackVal = -1;
584
585 // Masks to encode and decode an AlignPackInfo.
586 static constexpr uint32_t IsXLMask{0x0000'0001};
587 static constexpr uint32_t AlignModeMask{0x0000'0006};
588 static constexpr uint32_t PackAttrMask{0x00000'0008};
589 static constexpr uint32_t PackNumMask{0x0000'01F0};
590 };
591
592 template<typename ValueType>
593 struct PragmaStack {
594 struct Slot {
595 llvm::StringRef StackSlotLabel;
596 ValueType Value;
597 SourceLocation PragmaLocation;
598 SourceLocation PragmaPushLocation;
599 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
600 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
601 : StackSlotLabel(StackSlotLabel), Value(Value),
602 PragmaLocation(PragmaLocation),
603 PragmaPushLocation(PragmaPushLocation) {}
604 };
605
606 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
607 llvm::StringRef StackSlotLabel, ValueType Value) {
608 if (Action == PSK_Reset) {
609 CurrentValue = DefaultValue;
610 CurrentPragmaLocation = PragmaLocation;
611 return;
612 }
613 if (Action & PSK_Push)
614 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
615 PragmaLocation);
616 else if (Action & PSK_Pop) {
617 if (!StackSlotLabel.empty()) {
618 // If we've got a label, try to find it and jump there.
619 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
620 return x.StackSlotLabel == StackSlotLabel;
621 });
622 // If we found the label so pop from there.
623 if (I != Stack.rend()) {
624 CurrentValue = I->Value;
625 CurrentPragmaLocation = I->PragmaLocation;
626 Stack.erase(std::prev(I.base()), Stack.end());
627 }
628 } else if (!Stack.empty()) {
629 // We do not have a label, just pop the last entry.
630 CurrentValue = Stack.back().Value;
631 CurrentPragmaLocation = Stack.back().PragmaLocation;
632 Stack.pop_back();
633 }
634 }
635 if (Action & PSK_Set) {
636 CurrentValue = Value;
637 CurrentPragmaLocation = PragmaLocation;
638 }
639 }
640
641 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
642 // method body to restore the stacks on exit, so it works like this:
643 //
644 // struct S {
645 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
646 // void Method {}
647 // #pragma <name>(pop, InternalPragmaSlot)
648 // };
649 //
650 // It works even with #pragma vtordisp, although MSVC doesn't support
651 // #pragma vtordisp(push [, id], n)
652 // syntax.
653 //
654 // Push / pop a named sentinel slot.
655 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
656 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 657, __extension__ __PRETTY_FUNCTION__
))
657 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 657, __extension__ __PRETTY_FUNCTION__
))
;
658 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
659 }
660
661 // Constructors.
662 explicit PragmaStack(const ValueType &Default)
663 : DefaultValue(Default), CurrentValue(Default) {}
664
665 bool hasValue() const { return CurrentValue != DefaultValue; }
666
667 SmallVector<Slot, 2> Stack;
668 ValueType DefaultValue; // Value used for PSK_Reset action.
669 ValueType CurrentValue;
670 SourceLocation CurrentPragmaLocation;
671 };
672 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
673 // we shouldn't do so if they're in a module).
674
675 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
676 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
677 ///
678 /// 0: Suppress all vtordisps
679 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
680 /// structors
681 /// 2: Always insert vtordisps to support RTTI on partially constructed
682 /// objects
683 PragmaStack<MSVtorDispMode> VtorDispStack;
684 PragmaStack<AlignPackInfo> AlignPackStack;
685 // The current #pragma align/pack values and locations at each #include.
686 struct AlignPackIncludeState {
687 AlignPackInfo CurrentValue;
688 SourceLocation CurrentPragmaLocation;
689 bool HasNonDefaultValue, ShouldWarnOnInclude;
690 };
691 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
692 // Segment #pragmas.
693 PragmaStack<StringLiteral *> DataSegStack;
694 PragmaStack<StringLiteral *> BSSSegStack;
695 PragmaStack<StringLiteral *> ConstSegStack;
696 PragmaStack<StringLiteral *> CodeSegStack;
697
698 // #pragma strict_gs_check.
699 PragmaStack<bool> StrictGuardStackCheckStack;
700
701 // This stack tracks the current state of Sema.CurFPFeatures.
702 PragmaStack<FPOptionsOverride> FpPragmaStack;
703 FPOptionsOverride CurFPFeatureOverrides() {
704 FPOptionsOverride result;
705 if (!FpPragmaStack.hasValue()) {
706 result = FPOptionsOverride();
707 } else {
708 result = FpPragmaStack.CurrentValue;
709 }
710 return result;
711 }
712
713 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
714 // Actions should be performed only if we enter / exit a C++ method body.
715 class PragmaStackSentinelRAII {
716 public:
717 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
718 ~PragmaStackSentinelRAII();
719
720 private:
721 Sema &S;
722 StringRef SlotLabel;
723 bool ShouldAct;
724 };
725
726 /// A mapping that describes the nullability we've seen in each header file.
727 FileNullabilityMap NullabilityMap;
728
729 /// Last section used with #pragma init_seg.
730 StringLiteral *CurInitSeg;
731 SourceLocation CurInitSegLoc;
732
733 /// Sections used with #pragma alloc_text.
734 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
735
736 /// VisContext - Manages the stack for \#pragma GCC visibility.
737 void *VisContext; // Really a "PragmaVisStack*"
738
739 /// This an attribute introduced by \#pragma clang attribute.
740 struct PragmaAttributeEntry {
741 SourceLocation Loc;
742 ParsedAttr *Attribute;
743 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
744 bool IsUsed;
745 };
746
747 /// A push'd group of PragmaAttributeEntries.
748 struct PragmaAttributeGroup {
749 /// The location of the push attribute.
750 SourceLocation Loc;
751 /// The namespace of this push group.
752 const IdentifierInfo *Namespace;
753 SmallVector<PragmaAttributeEntry, 2> Entries;
754 };
755
756 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
757
758 /// The declaration that is currently receiving an attribute from the
759 /// #pragma attribute stack.
760 const Decl *PragmaAttributeCurrentTargetDecl;
761
762 /// This represents the last location of a "#pragma clang optimize off"
763 /// directive if such a directive has not been closed by an "on" yet. If
764 /// optimizations are currently "on", this is set to an invalid location.
765 SourceLocation OptimizeOffPragmaLocation;
766
767 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
768 /// whether the optimizations in the list passed to the pragma should be
769 /// turned off or on. This boolean is true by default because command line
770 /// options are honored when `#pragma optimize("", on)`.
771 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
772 bool MSPragmaOptimizeIsOn = true;
773
774 /// Set of no-builtin functions listed by \#pragma function.
775 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
776
777 /// Flag indicating if Sema is building a recovery call expression.
778 ///
779 /// This flag is used to avoid building recovery call expressions
780 /// if Sema is already doing so, which would cause infinite recursions.
781 bool IsBuildingRecoveryCallExpr;
782
783 /// Used to control the generation of ExprWithCleanups.
784 CleanupInfo Cleanup;
785
786 /// ExprCleanupObjects - This is the stack of objects requiring
787 /// cleanup that are created by the current full expression.
788 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
789
790 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
791 /// to a variable (constant) that may or may not be odr-used in this Expr, and
792 /// we won't know until all lvalue-to-rvalue and discarded value conversions
793 /// have been applied to all subexpressions of the enclosing full expression.
794 /// This is cleared at the end of each full expression.
795 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
796 llvm::SmallPtrSet<Expr *, 4>>;
797 MaybeODRUseExprSet MaybeODRUseExprs;
798
799 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
800
801 /// Stack containing information about each of the nested
802 /// function, block, and method scopes that are currently active.
803 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
804
805 /// The index of the first FunctionScope that corresponds to the current
806 /// context.
807 unsigned FunctionScopesStart = 0;
808
809 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
810 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
811 FunctionScopes.end());
812 }
813
814 /// Stack containing information needed when in C++2a an 'auto' is encountered
815 /// in a function declaration parameter type specifier in order to invent a
816 /// corresponding template parameter in the enclosing abbreviated function
817 /// template. This information is also present in LambdaScopeInfo, stored in
818 /// the FunctionScopes stack.
819 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
820
821 /// The index of the first InventedParameterInfo that refers to the current
822 /// context.
823 unsigned InventedParameterInfosStart = 0;
824
825 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
826 return llvm::ArrayRef(InventedParameterInfos.begin() +
827 InventedParameterInfosStart,
828 InventedParameterInfos.end());
829 }
830
831 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
832 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
833 ExtVectorDeclsType;
834
835 /// ExtVectorDecls - This is a list all the extended vector types. This allows
836 /// us to associate a raw vector type with one of the ext_vector type names.
837 /// This is only necessary for issuing pretty diagnostics.
838 ExtVectorDeclsType ExtVectorDecls;
839
840 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
841 std::unique_ptr<CXXFieldCollector> FieldCollector;
842
843 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
844
845 /// Set containing all declared private fields that are not used.
846 NamedDeclSetType UnusedPrivateFields;
847
848 /// Set containing all typedefs that are likely unused.
849 llvm::SmallSetVector<const TypedefNameDecl *, 4>
850 UnusedLocalTypedefNameCandidates;
851
852 /// Delete-expressions to be analyzed at the end of translation unit
853 ///
854 /// This list contains class members, and locations of delete-expressions
855 /// that could not be proven as to whether they mismatch with new-expression
856 /// used in initializer of the field.
857 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
858 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
859 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
860
861 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
862
863 /// PureVirtualClassDiagSet - a set of class declarations which we have
864 /// emitted a list of pure virtual functions. Used to prevent emitting the
865 /// same list more than once.
866 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
867
868 /// ParsingInitForAutoVars - a set of declarations with auto types for which
869 /// we are currently parsing the initializer.
870 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
871
872 /// Look for a locally scoped extern "C" declaration by the given name.
873 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
874
875 typedef LazyVector<VarDecl *, ExternalSemaSource,
876 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
877 TentativeDefinitionsType;
878
879 /// All the tentative definitions encountered in the TU.
880 TentativeDefinitionsType TentativeDefinitions;
881
882 /// All the external declarations encoutered and used in the TU.
883 SmallVector<VarDecl *, 4> ExternalDeclarations;
884
885 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
886 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
887 UnusedFileScopedDeclsType;
888
889 /// The set of file scoped decls seen so far that have not been used
890 /// and must warn if not used. Only contains the first declaration.
891 UnusedFileScopedDeclsType UnusedFileScopedDecls;
892
893 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
894 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
895 DelegatingCtorDeclsType;
896
897 /// All the delegating constructors seen so far in the file, used for
898 /// cycle detection at the end of the TU.
899 DelegatingCtorDeclsType DelegatingCtorDecls;
900
901 /// All the overriding functions seen during a class definition
902 /// that had their exception spec checks delayed, plus the overridden
903 /// function.
904 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
905 DelayedOverridingExceptionSpecChecks;
906
907 /// All the function redeclarations seen during a class definition that had
908 /// their exception spec checks delayed, plus the prior declaration they
909 /// should be checked against. Except during error recovery, the new decl
910 /// should always be a friend declaration, as that's the only valid way to
911 /// redeclare a special member before its class is complete.
912 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
913 DelayedEquivalentExceptionSpecChecks;
914
915 typedef llvm::MapVector<const FunctionDecl *,
916 std::unique_ptr<LateParsedTemplate>>
917 LateParsedTemplateMapT;
918 LateParsedTemplateMapT LateParsedTemplateMap;
919
920 /// Callback to the parser to parse templated functions when needed.
921 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
922 typedef void LateTemplateParserCleanupCB(void *P);
923 LateTemplateParserCB *LateTemplateParser;
924 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
925 void *OpaqueParser;
926
927 void SetLateTemplateParser(LateTemplateParserCB *LTP,
928 LateTemplateParserCleanupCB *LTPCleanup,
929 void *P) {
930 LateTemplateParser = LTP;
931 LateTemplateParserCleanup = LTPCleanup;
932 OpaqueParser = P;
933 }
934
935 class DelayedDiagnostics;
936
937 class DelayedDiagnosticsState {
938 sema::DelayedDiagnosticPool *SavedPool;
939 friend class Sema::DelayedDiagnostics;
940 };
941 typedef DelayedDiagnosticsState ParsingDeclState;
942 typedef DelayedDiagnosticsState ProcessingContextState;
943
944 /// A class which encapsulates the logic for delaying diagnostics
945 /// during parsing and other processing.
946 class DelayedDiagnostics {
947 /// The current pool of diagnostics into which delayed
948 /// diagnostics should go.
949 sema::DelayedDiagnosticPool *CurPool;
950
951 public:
952 DelayedDiagnostics() : CurPool(nullptr) {}
953
954 /// Adds a delayed diagnostic.
955 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
956
957 /// Determines whether diagnostics should be delayed.
958 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
959
960 /// Returns the current delayed-diagnostics pool.
961 sema::DelayedDiagnosticPool *getCurrentPool() const {
962 return CurPool;
963 }
964
965 /// Enter a new scope. Access and deprecation diagnostics will be
966 /// collected in this pool.
967 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
968 DelayedDiagnosticsState state;
969 state.SavedPool = CurPool;
970 CurPool = &pool;
971 return state;
972 }
973
974 /// Leave a delayed-diagnostic state that was previously pushed.
975 /// Do not emit any of the diagnostics. This is performed as part
976 /// of the bookkeeping of popping a pool "properly".
977 void popWithoutEmitting(DelayedDiagnosticsState state) {
978 CurPool = state.SavedPool;
979 }
980
981 /// Enter a new scope where access and deprecation diagnostics are
982 /// not delayed.
983 DelayedDiagnosticsState pushUndelayed() {
984 DelayedDiagnosticsState state;
985 state.SavedPool = CurPool;
986 CurPool = nullptr;
987 return state;
988 }
989
990 /// Undo a previous pushUndelayed().
991 void popUndelayed(DelayedDiagnosticsState state) {
992 assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail
("CurPool == nullptr", "clang/include/clang/Sema/Sema.h", 992
, __extension__ __PRETTY_FUNCTION__))
;
993 CurPool = state.SavedPool;
994 }
995 } DelayedDiagnostics;
996
997 /// A RAII object to temporarily push a declaration context.
998 class ContextRAII {
999 private:
1000 Sema &S;
1001 DeclContext *SavedContext;
1002 ProcessingContextState SavedContextState;
1003 QualType SavedCXXThisTypeOverride;
1004 unsigned SavedFunctionScopesStart;
1005 unsigned SavedInventedParameterInfosStart;
1006
1007 public:
1008 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1009 : S(S), SavedContext(S.CurContext),
1010 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1011 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1012 SavedFunctionScopesStart(S.FunctionScopesStart),
1013 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1014 {
1015 assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context"
) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "clang/include/clang/Sema/Sema.h", 1015, __extension__ __PRETTY_FUNCTION__
))
;
1016 S.CurContext = ContextToPush;
1017 if (NewThisContext)
1018 S.CXXThisTypeOverride = QualType();
1019 // Any saved FunctionScopes do not refer to this context.
1020 S.FunctionScopesStart = S.FunctionScopes.size();
1021 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1022 }
1023
1024 void pop() {
1025 if (!SavedContext) return;
1026 S.CurContext = SavedContext;
1027 S.DelayedDiagnostics.popUndelayed(SavedContextState);
1028 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1029 S.FunctionScopesStart = SavedFunctionScopesStart;
1030 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1031 SavedContext = nullptr;
1032 }
1033
1034 ~ContextRAII() {
1035 pop();
1036 }
1037 };
1038
1039 /// Whether the AST is currently being rebuilt to correct immediate
1040 /// invocations. Immediate invocation candidates and references to consteval
1041 /// functions aren't tracked when this is set.
1042 bool RebuildingImmediateInvocation = false;
1043
1044 /// Used to change context to isConstantEvaluated without pushing a heavy
1045 /// ExpressionEvaluationContextRecord object.
1046 bool isConstantEvaluatedOverride;
1047
1048 bool isConstantEvaluated() const {
1049 return ExprEvalContexts.back().isConstantEvaluated() ||
1050 isConstantEvaluatedOverride;
1051 }
1052
1053 /// RAII object to handle the state changes required to synthesize
1054 /// a function body.
1055 class SynthesizedFunctionScope {
1056 Sema &S;
1057 Sema::ContextRAII SavedContext;
1058 bool PushedCodeSynthesisContext = false;
1059
1060 public:
1061 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1062 : S(S), SavedContext(S, DC) {
1063 S.PushFunctionScope();
1064 S.PushExpressionEvaluationContext(
1065 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1066 if (auto *FD = dyn_cast<FunctionDecl>(DC))
1067 FD->setWillHaveBody(true);
1068 else
1069 assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void
(0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "clang/include/clang/Sema/Sema.h"
, 1069, __extension__ __PRETTY_FUNCTION__))
;
1070 }
1071
1072 void addContextNote(SourceLocation UseLoc) {
1073 assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void
(0) : __assert_fail ("!PushedCodeSynthesisContext", "clang/include/clang/Sema/Sema.h"
, 1073, __extension__ __PRETTY_FUNCTION__))
;
1074
1075 Sema::CodeSynthesisContext Ctx;
1076 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1077 Ctx.PointOfInstantiation = UseLoc;
1078 Ctx.Entity = cast<Decl>(S.CurContext);
1079 S.pushCodeSynthesisContext(Ctx);
1080
1081 PushedCodeSynthesisContext = true;
1082 }
1083
1084 ~SynthesizedFunctionScope() {
1085 if (PushedCodeSynthesisContext)
1086 S.popCodeSynthesisContext();
1087 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1088 FD->setWillHaveBody(false);
1089 S.PopExpressionEvaluationContext();
1090 S.PopFunctionScopeInfo();
1091 }
1092 };
1093
1094 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1095 /// declared. Rare. May alias another identifier, declared or undeclared.
1096 ///
1097 /// For aliases, the target identifier is used as a key for eventual
1098 /// processing when the target is declared. For the single-identifier form,
1099 /// the sole identifier is used as the key. Each entry is a `SetVector`
1100 /// (ordered by parse order) of aliases (identified by the alias name) in case
1101 /// of multiple aliases to the same undeclared identifier.
1102 llvm::MapVector<
1103 IdentifierInfo *,
1104 llvm::SetVector<
1105 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
1106 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1107 WeakUndeclaredIdentifiers;
1108
1109 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1110 /// \#pragma redefine_extname before declared. Used in Solaris system headers
1111 /// to define functions that occur in multiple standards to call the version
1112 /// in the currently selected standard.
1113 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1114
1115
1116 /// Load weak undeclared identifiers from the external source.
1117 void LoadExternalWeakUndeclaredIdentifiers();
1118
1119 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1120 /// \#pragma weak during processing of other Decls.
1121 /// I couldn't figure out a clean way to generate these in-line, so
1122 /// we store them here and handle separately -- which is a hack.
1123 /// It would be best to refactor this.
1124 SmallVector<Decl*,2> WeakTopLevelDecl;
1125
1126 IdentifierResolver IdResolver;
1127
1128 /// Translation Unit Scope - useful to Objective-C actions that need
1129 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1130 /// For example, user-defined classes, built-in "id" type, etc.
1131 Scope *TUScope;
1132
1133 /// The C++ "std" namespace, where the standard library resides.
1134 LazyDeclPtr StdNamespace;
1135
1136 /// The C++ "std::bad_alloc" class, which is defined by the C++
1137 /// standard library.
1138 LazyDeclPtr StdBadAlloc;
1139
1140 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1141 /// standard library.
1142 LazyDeclPtr StdAlignValT;
1143
1144 /// The C++ "std::initializer_list" template, which is defined in
1145 /// \<initializer_list>.
1146 ClassTemplateDecl *StdInitializerList;
1147
1148 /// The C++ "std::coroutine_traits" template, which is defined in
1149 /// \<coroutine_traits>
1150 ClassTemplateDecl *StdCoroutineTraitsCache;
1151
1152 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1153 RecordDecl *CXXTypeInfoDecl;
1154
1155 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1156 RecordDecl *MSVCGuidDecl;
1157
1158 /// The C++ "std::source_location::__impl" struct, defined in
1159 /// \<source_location>.
1160 RecordDecl *StdSourceLocationImplDecl;
1161
1162 /// Caches identifiers/selectors for NSFoundation APIs.
1163 std::unique_ptr<NSAPI> NSAPIObj;
1164
1165 /// The declaration of the Objective-C NSNumber class.
1166 ObjCInterfaceDecl *NSNumberDecl;
1167
1168 /// The declaration of the Objective-C NSValue class.
1169 ObjCInterfaceDecl *NSValueDecl;
1170
1171 /// Pointer to NSNumber type (NSNumber *).
1172 QualType NSNumberPointer;
1173
1174 /// Pointer to NSValue type (NSValue *).
1175 QualType NSValuePointer;
1176
1177 /// The Objective-C NSNumber methods used to create NSNumber literals.
1178 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1179
1180 /// The declaration of the Objective-C NSString class.
1181 ObjCInterfaceDecl *NSStringDecl;
1182
1183 /// Pointer to NSString type (NSString *).
1184 QualType NSStringPointer;
1185
1186 /// The declaration of the stringWithUTF8String: method.
1187 ObjCMethodDecl *StringWithUTF8StringMethod;
1188
1189 /// The declaration of the valueWithBytes:objCType: method.
1190 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1191
1192 /// The declaration of the Objective-C NSArray class.
1193 ObjCInterfaceDecl *NSArrayDecl;
1194
1195 /// The declaration of the arrayWithObjects:count: method.
1196 ObjCMethodDecl *ArrayWithObjectsMethod;
1197
1198 /// The declaration of the Objective-C NSDictionary class.
1199 ObjCInterfaceDecl *NSDictionaryDecl;
1200
1201 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1202 ObjCMethodDecl *DictionaryWithObjectsMethod;
1203
1204 /// id<NSCopying> type.
1205 QualType QIDNSCopying;
1206
1207 /// will hold 'respondsToSelector:'
1208 Selector RespondsToSelectorSel;
1209
1210 /// A flag to remember whether the implicit forms of operator new and delete
1211 /// have been declared.
1212 bool GlobalNewDeleteDeclared;
1213
1214 /// Describes how the expressions currently being parsed are
1215 /// evaluated at run-time, if at all.
1216 enum class ExpressionEvaluationContext {
1217 /// The current expression and its subexpressions occur within an
1218 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1219 /// \c sizeof, where the type of the expression may be significant but
1220 /// no code will be generated to evaluate the value of the expression at
1221 /// run time.
1222 Unevaluated,
1223
1224 /// The current expression occurs within a braced-init-list within
1225 /// an unevaluated operand. This is mostly like a regular unevaluated
1226 /// context, except that we still instantiate constexpr functions that are
1227 /// referenced here so that we can perform narrowing checks correctly.
1228 UnevaluatedList,
1229
1230 /// The current expression occurs within a discarded statement.
1231 /// This behaves largely similarly to an unevaluated operand in preventing
1232 /// definitions from being required, but not in other ways.
1233 DiscardedStatement,
1234
1235 /// The current expression occurs within an unevaluated
1236 /// operand that unconditionally permits abstract references to
1237 /// fields, such as a SIZE operator in MS-style inline assembly.
1238 UnevaluatedAbstract,
1239
1240 /// The current context is "potentially evaluated" in C++11 terms,
1241 /// but the expression is evaluated at compile-time (like the values of
1242 /// cases in a switch statement).
1243 ConstantEvaluated,
1244
1245 /// In addition of being constant evaluated, the current expression
1246 /// occurs in an immediate function context - either a consteval function
1247 /// or a consteval if function.
1248 ImmediateFunctionContext,
1249
1250 /// The current expression is potentially evaluated at run time,
1251 /// which means that code may be generated to evaluate the value of the
1252 /// expression at run time.
1253 PotentiallyEvaluated,
1254
1255 /// The current expression is potentially evaluated, but any
1256 /// declarations referenced inside that expression are only used if
1257 /// in fact the current expression is used.
1258 ///
1259 /// This value is used when parsing default function arguments, for which
1260 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1261 /// through varargs) but do not want to mark declarations as "referenced"
1262 /// until the default argument is used.
1263 PotentiallyEvaluatedIfUsed
1264 };
1265
1266 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1267
1268 /// Data structure used to record current or nested
1269 /// expression evaluation contexts.
1270 struct ExpressionEvaluationContextRecord {
1271 /// The expression evaluation context.
1272 ExpressionEvaluationContext Context;
1273
1274 /// Whether the enclosing context needed a cleanup.
1275 CleanupInfo ParentCleanup;
1276
1277 /// The number of active cleanup objects when we entered
1278 /// this expression evaluation context.
1279 unsigned NumCleanupObjects;
1280
1281 /// The number of typos encountered during this expression evaluation
1282 /// context (i.e. the number of TypoExprs created).
1283 unsigned NumTypos;
1284
1285 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1286
1287 /// The lambdas that are present within this context, if it
1288 /// is indeed an unevaluated context.
1289 SmallVector<LambdaExpr *, 2> Lambdas;
1290
1291 /// The declaration that provides context for lambda expressions
1292 /// and block literals if the normal declaration context does not
1293 /// suffice, e.g., in a default function argument.
1294 Decl *ManglingContextDecl;
1295
1296 /// If we are processing a decltype type, a set of call expressions
1297 /// for which we have deferred checking the completeness of the return type.
1298 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1299
1300 /// If we are processing a decltype type, a set of temporary binding
1301 /// expressions for which we have deferred checking the destructor.
1302 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1303
1304 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1305
1306 /// Expressions appearing as the LHS of a volatile assignment in this
1307 /// context. We produce a warning for these when popping the context if
1308 /// they are not discarded-value expressions nor unevaluated operands.
1309 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1310
1311 /// Set of candidates for starting an immediate invocation.
1312 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1313
1314 /// Set of DeclRefExprs referencing a consteval function when used in a
1315 /// context not already known to be immediately invoked.
1316 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1317
1318 /// \brief Describes whether we are in an expression constext which we have
1319 /// to handle differently.
1320 enum ExpressionKind {
1321 EK_Decltype, EK_TemplateArgument, EK_Other
1322 } ExprContext;
1323
1324 // A context can be nested in both a discarded statement context and
1325 // an immediate function context, so they need to be tracked independently.
1326 bool InDiscardedStatement;
1327 bool InImmediateFunctionContext;
1328
1329 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
1330
1331 // When evaluating immediate functions in the initializer of a default
1332 // argument or default member initializer, this is the declaration whose
1333 // default initializer is being evaluated and the location of the call
1334 // or constructor definition.
1335 struct InitializationContext {
1336 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
1337 DeclContext *Context)
1338 : Loc(Loc), Decl(Decl), Context(Context) {
1339 assert(Decl && Context && "invalid initialization context")(static_cast <bool> (Decl && Context &&
"invalid initialization context") ? void (0) : __assert_fail
("Decl && Context && \"invalid initialization context\""
, "clang/include/clang/Sema/Sema.h", 1339, __extension__ __PRETTY_FUNCTION__
))
;
1340 }
1341
1342 SourceLocation Loc;
1343 ValueDecl *Decl = nullptr;
1344 DeclContext *Context = nullptr;
1345 };
1346 std::optional<InitializationContext> DelayedDefaultInitializationContext;
1347
1348 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1349 unsigned NumCleanupObjects,
1350 CleanupInfo ParentCleanup,
1351 Decl *ManglingContextDecl,
1352 ExpressionKind ExprContext)
1353 : Context(Context), ParentCleanup(ParentCleanup),
1354 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1355 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
1356 InDiscardedStatement(false), InImmediateFunctionContext(false) {}
1357
1358 bool isUnevaluated() const {
1359 return Context == ExpressionEvaluationContext::Unevaluated ||
1360 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1361 Context == ExpressionEvaluationContext::UnevaluatedList;
1362 }
1363
1364 bool isConstantEvaluated() const {
1365 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
1366 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1367 }
1368
1369 bool isImmediateFunctionContext() const {
1370 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
1371 (Context == ExpressionEvaluationContext::DiscardedStatement &&
1372 InImmediateFunctionContext) ||
1373 // C++2b [expr.const]p14:
1374 // An expression or conversion is in an immediate function
1375 // context if it is potentially evaluated and either:
1376 // * its innermost enclosing non-block scope is a function
1377 // parameter scope of an immediate function, or
1378 // * its enclosing statement is enclosed by the compound-
1379 // statement of a consteval if statement.
1380 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
1381 InImmediateFunctionContext);
1382 }
1383
1384 bool isDiscardedStatementContext() const {
1385 return Context == ExpressionEvaluationContext::DiscardedStatement ||
1386 (Context ==
1387 ExpressionEvaluationContext::ImmediateFunctionContext &&
1388 InDiscardedStatement);
1389 }
1390 };
1391
1392 /// A stack of expression evaluation contexts.
1393 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1394
1395 /// Emit a warning for all pending noderef expressions that we recorded.
1396 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1397
1398 /// Compute the mangling number context for a lambda expression or
1399 /// block literal. Also return the extra mangling decl if any.
1400 ///
1401 /// \param DC - The DeclContext containing the lambda expression or
1402 /// block literal.
1403 std::tuple<MangleNumberingContext *, Decl *>
1404 getCurrentMangleNumberContext(const DeclContext *DC);
1405
1406
1407 /// SpecialMemberOverloadResult - The overloading result for a special member
1408 /// function.
1409 ///
1410 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1411 /// integer are used to determine whether overload resolution succeeded.
1412 class SpecialMemberOverloadResult {
1413 public:
1414 enum Kind {
1415 NoMemberOrDeleted,
1416 Ambiguous,
1417 Success
1418 };
1419
1420 private:
1421 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1422
1423 public:
1424 SpecialMemberOverloadResult() {}
1425 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1426 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1427
1428 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1429 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1430
1431 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1432 void setKind(Kind K) { Pair.setInt(K); }
1433 };
1434
1435 class SpecialMemberOverloadResultEntry
1436 : public llvm::FastFoldingSetNode,
1437 public SpecialMemberOverloadResult {
1438 public:
1439 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1440 : FastFoldingSetNode(ID)
1441 {}
1442 };
1443
1444 /// A cache of special member function overload resolution results
1445 /// for C++ records.
1446 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1447
1448 /// A cache of the flags available in enumerations with the flag_bits
1449 /// attribute.
1450 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1451
1452 /// The kind of translation unit we are processing.
1453 ///
1454 /// When we're processing a complete translation unit, Sema will perform
1455 /// end-of-translation-unit semantic tasks (such as creating
1456 /// initializers for tentative definitions in C) once parsing has
1457 /// completed. Modules and precompiled headers perform different kinds of
1458 /// checks.
1459 const TranslationUnitKind TUKind;
1460
1461 llvm::BumpPtrAllocator BumpAlloc;
1462
1463 /// The number of SFINAE diagnostics that have been trapped.
1464 unsigned NumSFINAEErrors;
1465
1466 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1467 UnparsedDefaultArgInstantiationsMap;
1468
1469 /// A mapping from parameters with unparsed default arguments to the
1470 /// set of instantiations of each parameter.
1471 ///
1472 /// This mapping is a temporary data structure used when parsing
1473 /// nested class templates or nested classes of class templates,
1474 /// where we might end up instantiating an inner class before the
1475 /// default arguments of its methods have been parsed.
1476 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1477
1478 // Contains the locations of the beginning of unparsed default
1479 // argument locations.
1480 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1481
1482 /// UndefinedInternals - all the used, undefined objects which require a
1483 /// definition in this translation unit.
1484 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1485
1486 /// Determine if VD, which must be a variable or function, is an external
1487 /// symbol that nonetheless can't be referenced from outside this translation
1488 /// unit because its type has no linkage and it's not extern "C".
1489 bool isExternalWithNoLinkageType(ValueDecl *VD) const;
1490
1491 /// Obtain a sorted list of functions that are undefined but ODR-used.
1492 void getUndefinedButUsed(
1493 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1494
1495 /// Retrieves list of suspicious delete-expressions that will be checked at
1496 /// the end of translation unit.
1497 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1498 getMismatchingDeleteExpressions() const;
1499
1500 class GlobalMethodPool {
1501 public:
1502 using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1503 using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1504 iterator begin() { return Methods.begin(); }
1505 iterator end() { return Methods.end(); }
1506 iterator find(Selector Sel) { return Methods.find(Sel); }
1507 std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1508 return Methods.insert(Val);
1509 }
1510 int count(Selector Sel) const { return Methods.count(Sel); }
1511 bool empty() const { return Methods.empty(); }
1512
1513 private:
1514 llvm::DenseMap<Selector, Lists> Methods;
1515 };
1516
1517 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1518 /// We need to maintain a list, since selectors can have differing signatures
1519 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1520 /// of selectors are "overloaded").
1521 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1522 /// methods inside categories with a particular selector.
1523 GlobalMethodPool MethodPool;
1524
1525 /// Method selectors used in a \@selector expression. Used for implementation
1526 /// of -Wselector.
1527 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1528
1529 /// List of SourceLocations where 'self' is implicitly retained inside a
1530 /// block.
1531 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1532 ImplicitlyRetainedSelfLocs;
1533
1534 /// Kinds of C++ special members.
1535 enum CXXSpecialMember {
1536 CXXDefaultConstructor,
1537 CXXCopyConstructor,
1538 CXXMoveConstructor,
1539 CXXCopyAssignment,
1540 CXXMoveAssignment,
1541 CXXDestructor,
1542 CXXInvalid
1543 };
1544
1545 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1546 SpecialMemberDecl;
1547
1548 /// The C++ special members which we are currently in the process of
1549 /// declaring. If this process recursively triggers the declaration of the
1550 /// same special member, we should act as if it is not yet declared.
1551 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1552
1553 /// Kinds of defaulted comparison operator functions.
1554 enum class DefaultedComparisonKind : unsigned char {
1555 /// This is not a defaultable comparison operator.
1556 None,
1557 /// This is an operator== that should be implemented as a series of
1558 /// subobject comparisons.
1559 Equal,
1560 /// This is an operator<=> that should be implemented as a series of
1561 /// subobject comparisons.
1562 ThreeWay,
1563 /// This is an operator!= that should be implemented as a rewrite in terms
1564 /// of a == comparison.
1565 NotEqual,
1566 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1567 /// terms of a <=> comparison.
1568 Relational,
1569 };
1570
1571 /// The function definitions which were renamed as part of typo-correction
1572 /// to match their respective declarations. We want to keep track of them
1573 /// to ensure that we don't emit a "redefinition" error if we encounter a
1574 /// correctly named definition after the renamed definition.
1575 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1576
1577 /// Stack of types that correspond to the parameter entities that are
1578 /// currently being copy-initialized. Can be empty.
1579 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1580
1581 void ReadMethodPool(Selector Sel);
1582 void updateOutOfDateSelector(Selector Sel);
1583
1584 /// Private Helper predicate to check for 'self'.
1585 bool isSelfExpr(Expr *RExpr);
1586 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1587
1588 /// Cause the active diagnostic on the DiagosticsEngine to be
1589 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1590 /// should not be used elsewhere.
1591 void EmitCurrentDiagnostic(unsigned DiagID);
1592
1593 /// Records and restores the CurFPFeatures state on entry/exit of compound
1594 /// statements.
1595 class FPFeaturesStateRAII {
1596 public:
1597 FPFeaturesStateRAII(Sema &S);
1598 ~FPFeaturesStateRAII();
1599 FPOptionsOverride getOverrides() { return OldOverrides; }
1600
1601 private:
1602 Sema& S;
1603 FPOptions OldFPFeaturesState;
1604 FPOptionsOverride OldOverrides;
1605 LangOptions::FPEvalMethodKind OldEvalMethod;
1606 SourceLocation OldFPPragmaLocation;
1607 };
1608
1609 void addImplicitTypedef(StringRef Name, QualType T);
1610
1611 bool WarnedStackExhausted = false;
1612
1613 /// Increment when we find a reference; decrement when we find an ignored
1614 /// assignment. Ultimately the value is 0 if every reference is an ignored
1615 /// assignment.
1616 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1617
1618 /// Indicate RISC-V vector builtin functions enabled or not.
1619 bool DeclareRISCVVBuiltins = false;
1620
1621private:
1622 std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager;
1623
1624 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1625
1626 bool WarnedDarwinSDKInfoMissing = false;
1627
1628public:
1629 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1630 TranslationUnitKind TUKind = TU_Complete,
1631 CodeCompleteConsumer *CompletionConsumer = nullptr);
1632 ~Sema();
1633
1634 /// Perform initialization that occurs after the parser has been
1635 /// initialized but before it parses anything.
1636 void Initialize();
1637
1638 /// This virtual key function only exists to limit the emission of debug info
1639 /// describing the Sema class. GCC and Clang only emit debug info for a class
1640 /// with a vtable when the vtable is emitted. Sema is final and not
1641 /// polymorphic, but the debug info size savings are so significant that it is
1642 /// worth adding a vtable just to take advantage of this optimization.
1643 virtual void anchor();
1644
1645 const LangOptions &getLangOpts() const { return LangOpts; }
1646 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1647 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
1648
1649 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1650 SourceManager &getSourceManager() const { return SourceMgr; }
1651 Preprocessor &getPreprocessor() const { return PP; }
1652 ASTContext &getASTContext() const { return Context; }
1653 ASTConsumer &getASTConsumer() const { return Consumer; }
1654 ASTMutationListener *getASTMutationListener() const;
1655 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
1656
1657 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1658 StringRef Platform);
1659 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
1660
1661 ///Registers an external source. If an external source already exists,
1662 /// creates a multiplex external source and appends to it.
1663 ///
1664 ///\param[in] E - A non-null external sema source.
1665 ///
1666 void addExternalSource(ExternalSemaSource *E);
1667
1668 void PrintStats() const;
1669
1670 /// Warn that the stack is nearly exhausted.
1671 void warnStackExhausted(SourceLocation Loc);
1672
1673 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1674 /// guaranteed). Produces a warning if we're low on stack space and allocates
1675 /// more in that case. Use this in code that may recurse deeply (for example,
1676 /// in template instantiation) to avoid stack overflow.
1677 void runWithSufficientStackSpace(SourceLocation Loc,
1678 llvm::function_ref<void()> Fn);
1679
1680 /// Helper class that creates diagnostics with optional
1681 /// template instantiation stacks.
1682 ///
1683 /// This class provides a wrapper around the basic DiagnosticBuilder
1684 /// class that emits diagnostics. ImmediateDiagBuilder is
1685 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1686 /// does) and, if the diagnostic comes from inside a template
1687 /// instantiation, printing the template instantiation stack as
1688 /// well.
1689 class ImmediateDiagBuilder : public DiagnosticBuilder {
1690 Sema &SemaRef;
1691 unsigned DiagID;
1692
1693 public:
1694 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1695 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1696 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1697 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1698
1699 // This is a cunning lie. DiagnosticBuilder actually performs move
1700 // construction in its copy constructor (but due to varied uses, it's not
1701 // possible to conveniently express this as actual move construction). So
1702 // the default copy ctor here is fine, because the base class disables the
1703 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1704 // in that case anwyay.
1705 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1706
1707 ~ImmediateDiagBuilder() {
1708 // If we aren't active, there is nothing to do.
1709 if (!isActive()) return;
1710
1711 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1712 // builder itself so it won't emit the diagnostic in its own destructor.
1713 //
1714 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1715 // do its own needless checks to see if the diagnostic needs to be
1716 // emitted. However, because we take care to ensure that the builder
1717 // objects never escape, a sufficiently smart compiler will be able to
1718 // eliminate that code.
1719 Clear();
1720
1721 // Dispatch to Sema to emit the diagnostic.
1722 SemaRef.EmitCurrentDiagnostic(DiagID);
1723 }
1724
1725 /// Teach operator<< to produce an object of the correct type.
1726 template <typename T>
1727 friend const ImmediateDiagBuilder &
1728 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1729 const DiagnosticBuilder &BaseDiag = Diag;
1730 BaseDiag << Value;
1731 return Diag;
1732 }
1733
1734 // It is necessary to limit this to rvalue reference to avoid calling this
1735 // function with a bitfield lvalue argument since non-const reference to
1736 // bitfield is not allowed.
1737 template <typename T,
1738 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1739 const ImmediateDiagBuilder &operator<<(T &&V) const {
1740 const DiagnosticBuilder &BaseDiag = *this;
1741 BaseDiag << std::move(V);
1742 return *this;
1743 }
1744 };
1745
1746 /// A generic diagnostic builder for errors which may or may not be deferred.
1747 ///
1748 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1749 /// which are not allowed to appear inside __device__ functions and are
1750 /// allowed to appear in __host__ __device__ functions only if the host+device
1751 /// function is never codegen'ed.
1752 ///
1753 /// To handle this, we use the notion of "deferred diagnostics", where we
1754 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1755 ///
1756 /// This class lets you emit either a regular diagnostic, a deferred
1757 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1758 /// its constructor, thus simplifying the process of creating these "maybe
1759 /// deferred" diagnostics.
1760 class SemaDiagnosticBuilder {
1761 public:
1762 enum Kind {
1763 /// Emit no diagnostics.
1764 K_Nop,
1765 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1766 K_Immediate,
1767 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1768 /// emit a call stack showing how this function can be reached by an a
1769 /// priori known-emitted function.
1770 K_ImmediateWithCallStack,
1771 /// Create a deferred diagnostic, which is emitted only if the function
1772 /// it's attached to is codegen'ed. Also emit a call stack as with
1773 /// K_ImmediateWithCallStack.
1774 K_Deferred
1775 };
1776
1777 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1778 FunctionDecl *Fn, Sema &S);
1779 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1780 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1781 ~SemaDiagnosticBuilder();
1782
1783 bool isImmediate() const { return ImmediateDiag.has_value(); }
1784
1785 /// Convertible to bool: True if we immediately emitted an error, false if
1786 /// we didn't emit an error or we created a deferred error.
1787 ///
1788 /// Example usage:
1789 ///
1790 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1791 /// return ExprError();
1792 ///
1793 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1794 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1795 operator bool() const { return isImmediate(); }
1796
1797 template <typename T>
1798 friend const SemaDiagnosticBuilder &
1799 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1800 if (Diag.ImmediateDiag)
1801 *Diag.ImmediateDiag << Value;
1802 else if (Diag.PartialDiagId)
1803 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1804 << Value;
1805 return Diag;
1806 }
1807
1808 // It is necessary to limit this to rvalue reference to avoid calling this
1809 // function with a bitfield lvalue argument since non-const reference to
1810 // bitfield is not allowed.
1811 template <typename T,
1812 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1813 const SemaDiagnosticBuilder &operator<<(T &&V) const {
1814 if (ImmediateDiag)
1815 *ImmediateDiag << std::move(V);
1816 else if (PartialDiagId)
1817 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1818 return *this;
1819 }
1820
1821 friend const SemaDiagnosticBuilder &
1822 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1823 if (Diag.ImmediateDiag)
1824 PD.Emit(*Diag.ImmediateDiag);
1825 else if (Diag.PartialDiagId)
1826 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1827 return Diag;
1828 }
1829
1830 void AddFixItHint(const FixItHint &Hint) const {
1831 if (ImmediateDiag)
1832 ImmediateDiag->AddFixItHint(Hint);
1833 else if (PartialDiagId)
1834 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1835 }
1836
1837 friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1838 return ExprError();
1839 }
1840 friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1841 return StmtError();
1842 }
1843 operator ExprResult() const { return ExprError(); }
1844 operator StmtResult() const { return StmtError(); }
1845 operator TypeResult() const { return TypeError(); }
1846 operator DeclResult() const { return DeclResult(true); }
1847 operator MemInitResult() const { return MemInitResult(true); }
1848
1849 private:
1850 Sema &S;
1851 SourceLocation Loc;
1852 unsigned DiagID;
1853 FunctionDecl *Fn;
1854 bool ShowCallStack;
1855
1856 // Invariant: At most one of these Optionals has a value.
1857 // FIXME: Switch these to a Variant once that exists.
1858 std::optional<ImmediateDiagBuilder> ImmediateDiag;
1859 std::optional<unsigned> PartialDiagId;
1860 };
1861
1862 /// Is the last error level diagnostic immediate. This is used to determined
1863 /// whether the next info diagnostic should be immediate.
1864 bool IsLastErrorImmediate = true;
1865
1866 /// Emit a diagnostic.
1867 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1868 bool DeferHint = false);
1869
1870 /// Emit a partial diagnostic.
1871 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1872 bool DeferHint = false);
1873
1874 /// Build a partial diagnostic.
1875 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1876
1877 /// Whether deferrable diagnostics should be deferred.
1878 bool DeferDiags = false;
1879
1880 /// RAII class to control scope of DeferDiags.
1881 class DeferDiagsRAII {
1882 Sema &S;
1883 bool SavedDeferDiags = false;
1884
1885 public:
1886 DeferDiagsRAII(Sema &S, bool DeferDiags)
1887 : S(S), SavedDeferDiags(S.DeferDiags) {
1888 S.DeferDiags = DeferDiags;
1889 }
1890 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1891 };
1892
1893 /// Whether uncompilable error has occurred. This includes error happens
1894 /// in deferred diagnostics.
1895 bool hasUncompilableErrorOccurred() const;
1896
1897 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1898
1899 /// Get a string to suggest for zero-initialization of a type.
1900 std::string
1901 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1902 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1903
1904 /// Calls \c Lexer::getLocForEndOfToken()
1905 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1906
1907 /// Retrieve the module loader associated with the preprocessor.
1908 ModuleLoader &getModuleLoader() const;
1909
1910 /// Invent a new identifier for parameters of abbreviated templates.
1911 IdentifierInfo *
1912 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1913 unsigned Index);
1914
1915 void emitAndClearUnusedLocalTypedefWarnings();
1916
1917 private:
1918 /// Function or variable declarations to be checked for whether the deferred
1919 /// diagnostics should be emitted.
1920 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1921
1922 public:
1923 // Emit all deferred diagnostics.
1924 void emitDeferredDiags();
1925
1926 enum TUFragmentKind {
1927 /// The global module fragment, between 'module;' and a module-declaration.
1928 Global,
1929 /// A normal translation unit fragment. For a non-module unit, this is the
1930 /// entire translation unit. Otherwise, it runs from the module-declaration
1931 /// to the private-module-fragment (if any) or the end of the TU (if not).
1932 Normal,
1933 /// The private module fragment, between 'module :private;' and the end of
1934 /// the translation unit.
1935 Private
1936 };
1937
1938 void ActOnStartOfTranslationUnit();
1939 void ActOnEndOfTranslationUnit();
1940 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1941
1942 void CheckDelegatingCtorCycles();
1943
1944 Scope *getScopeForContext(DeclContext *Ctx);
1945
1946 void PushFunctionScope();
1947 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1948 sema::LambdaScopeInfo *PushLambdaScope();
1949
1950 /// This is used to inform Sema what the current TemplateParameterDepth
1951 /// is during Parsing. Currently it is used to pass on the depth
1952 /// when parsing generic lambda 'auto' parameters.
1953 void RecordParsingTemplateParameterDepth(unsigned Depth);
1954
1955 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1956 RecordDecl *RD, CapturedRegionKind K,
1957 unsigned OpenMPCaptureLevel = 0);
1958
1959 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1960 /// time after they've been popped.
1961 class PoppedFunctionScopeDeleter {
1962 Sema *Self;
1963
1964 public:
1965 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1966 void operator()(sema::FunctionScopeInfo *Scope) const;
1967 };
1968
1969 using PoppedFunctionScopePtr =
1970 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1971
1972 PoppedFunctionScopePtr
1973 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1974 const Decl *D = nullptr,
1975 QualType BlockType = QualType());
1976
1977 sema::FunctionScopeInfo *getCurFunction() const {
1978 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
13
'?' condition is false
14
Returning pointer, which participates in a condition later
1979 }
1980
1981 sema::FunctionScopeInfo *getEnclosingFunction() const;
1982
1983 void setFunctionHasBranchIntoScope();
1984 void setFunctionHasBranchProtectedScope();
1985 void setFunctionHasIndirectGoto();
1986 void setFunctionHasMustTail();
1987
1988 void PushCompoundScope(bool IsStmtExpr);
1989 void PopCompoundScope();
1990
1991 sema::CompoundScopeInfo &getCurCompoundScope() const;
1992
1993 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1994
1995 /// Retrieve the current block, if any.
1996 sema::BlockScopeInfo *getCurBlock();
1997
1998 /// Get the innermost lambda enclosing the current location, if any. This
1999 /// looks through intervening non-lambda scopes such as local functions and
2000 /// blocks.
2001 sema::LambdaScopeInfo *getEnclosingLambda() const;
2002
2003 /// Retrieve the current lambda scope info, if any.
2004 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
2005 /// lambda scope info ignoring all inner capturing scopes that are not
2006 /// lambda scopes.
2007 sema::LambdaScopeInfo *
2008 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
2009
2010 /// Retrieve the current generic lambda info, if any.
2011 sema::LambdaScopeInfo *getCurGenericLambda();
2012
2013 /// Retrieve the current captured region, if any.
2014 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
2015
2016 /// Retrieve the current function, if any, that should be analyzed for
2017 /// potential availability violations.
2018 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2019
2020 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
2021 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
2022
2023 /// Called before parsing a function declarator belonging to a function
2024 /// declaration.
2025 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
2026 unsigned TemplateParameterDepth);
2027
2028 /// Called after parsing a function declarator belonging to a function
2029 /// declaration.
2030 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
2031
2032 void ActOnComment(SourceRange Comment);
2033
2034 //===--------------------------------------------------------------------===//
2035 // Type Analysis / Processing: SemaType.cpp.
2036 //
2037
2038 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
2039 const DeclSpec *DS = nullptr);
2040 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2041 const DeclSpec *DS = nullptr);
2042 QualType BuildPointerType(QualType T,
2043 SourceLocation Loc, DeclarationName Entity);
2044 QualType BuildReferenceType(QualType T, bool LValueRef,
2045 SourceLocation Loc, DeclarationName Entity);
2046 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2047 Expr *ArraySize, unsigned Quals,
2048 SourceRange Brackets, DeclarationName Entity);
2049 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2050 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2051 SourceLocation AttrLoc);
2052 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2053 SourceLocation AttrLoc);
2054
2055 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2056 SourceLocation AttrLoc);
2057
2058 /// Same as above, but constructs the AddressSpace index if not provided.
2059 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
2060 SourceLocation AttrLoc);
2061
2062 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
2063
2064 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
2065
2066 /// Build a function type.
2067 ///
2068 /// This routine checks the function type according to C++ rules and
2069 /// under the assumption that the result type and parameter types have
2070 /// just been instantiated from a template. It therefore duplicates
2071 /// some of the behavior of GetTypeForDeclarator, but in a much
2072 /// simpler form that is only suitable for this narrow use case.
2073 ///
2074 /// \param T The return type of the function.
2075 ///
2076 /// \param ParamTypes The parameter types of the function. This array
2077 /// will be modified to account for adjustments to the types of the
2078 /// function parameters.
2079 ///
2080 /// \param Loc The location of the entity whose type involves this
2081 /// function type or, if there is no such entity, the location of the
2082 /// type that will have function type.
2083 ///
2084 /// \param Entity The name of the entity that involves the function
2085 /// type, if known.
2086 ///
2087 /// \param EPI Extra information about the function type. Usually this will
2088 /// be taken from an existing function with the same prototype.
2089 ///
2090 /// \returns A suitable function type, if there are no errors. The
2091 /// unqualified type will always be a FunctionProtoType.
2092 /// Otherwise, returns a NULL type.
2093 QualType BuildFunctionType(QualType T,
2094 MutableArrayRef<QualType> ParamTypes,
2095 SourceLocation Loc, DeclarationName Entity,
2096 const FunctionProtoType::ExtProtoInfo &EPI);
2097
2098 QualType BuildMemberPointerType(QualType T, QualType Class,
2099 SourceLocation Loc,
2100 DeclarationName Entity);
2101 QualType BuildBlockPointerType(QualType T,
2102 SourceLocation Loc, DeclarationName Entity);
2103 QualType BuildParenType(QualType T);
2104 QualType BuildAtomicType(QualType T, SourceLocation Loc);
2105 QualType BuildReadPipeType(QualType T,
2106 SourceLocation Loc);
2107 QualType BuildWritePipeType(QualType T,
2108 SourceLocation Loc);
2109 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2110
2111 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
2112 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
2113
2114 /// Package the given type and TSI into a ParsedType.
2115 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
2116 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
2117 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
2118 static QualType GetTypeFromParser(ParsedType Ty,
2119 TypeSourceInfo **TInfo = nullptr);
2120 CanThrowResult canThrow(const Stmt *E);
2121 /// Determine whether the callee of a particular function call can throw.
2122 /// E, D and Loc are all optional.
2123 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2124 SourceLocation Loc = SourceLocation());
2125 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
2126 const FunctionProtoType *FPT);
2127 void UpdateExceptionSpec(FunctionDecl *FD,
2128 const FunctionProtoType::ExceptionSpecInfo &ESI);
2129 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
2130 bool CheckDistantExceptionSpec(QualType T);
2131 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
2132 bool CheckEquivalentExceptionSpec(
2133 const FunctionProtoType *Old, SourceLocation OldLoc,
2134 const FunctionProtoType *New, SourceLocation NewLoc);
2135 bool CheckEquivalentExceptionSpec(
2136 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2137 const FunctionProtoType *Old, SourceLocation OldLoc,
2138 const FunctionProtoType *New, SourceLocation NewLoc);
2139 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2140 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2141 const PartialDiagnostic &NestedDiagID,
2142 const PartialDiagnostic &NoteID,
2143 const PartialDiagnostic &NoThrowDiagID,
2144 const FunctionProtoType *Superset,
2145 SourceLocation SuperLoc,
2146 const FunctionProtoType *Subset,
2147 SourceLocation SubLoc);
2148 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2149 const PartialDiagnostic &NoteID,
2150 const FunctionProtoType *Target,
2151 SourceLocation TargetLoc,
2152 const FunctionProtoType *Source,
2153 SourceLocation SourceLoc);
2154
2155 TypeResult ActOnTypeName(Scope *S, Declarator &D);
2156
2157 /// The parser has parsed the context-sensitive type 'instancetype'
2158 /// in an Objective-C message declaration. Return the appropriate type.
2159 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2160
2161 /// Abstract class used to diagnose incomplete types.
2162 struct TypeDiagnoser {
2163 TypeDiagnoser() {}
2164
2165 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2166 virtual ~TypeDiagnoser() {}
2167 };
2168
2169 static int getPrintable(int I) { return I; }
2170 static unsigned getPrintable(unsigned I) { return I; }
2171 static bool getPrintable(bool B) { return B; }
2172 static const char * getPrintable(const char *S) { return S; }
2173 static StringRef getPrintable(StringRef S) { return S; }
2174 static const std::string &getPrintable(const std::string &S) { return S; }
2175 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2176 return II;
2177 }
2178 static DeclarationName getPrintable(DeclarationName N) { return N; }
2179 static QualType getPrintable(QualType T) { return T; }
2180 static SourceRange getPrintable(SourceRange R) { return R; }
2181 static SourceRange getPrintable(SourceLocation L) { return L; }
2182 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2183 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2184
2185 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2186 protected:
2187 unsigned DiagID;
2188 std::tuple<const Ts &...> Args;
2189
2190 template <std::size_t... Is>
2191 void emit(const SemaDiagnosticBuilder &DB,
2192 std::index_sequence<Is...>) const {
2193 // Apply all tuple elements to the builder in order.
2194 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2195 (void)Dummy;
2196 }
2197
2198 public:
2199 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2200 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2201 assert(DiagID != 0 && "no diagnostic for type diagnoser")(static_cast <bool> (DiagID != 0 && "no diagnostic for type diagnoser"
) ? void (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "clang/include/clang/Sema/Sema.h", 2201, __extension__ __PRETTY_FUNCTION__
))
;
2202 }
2203
2204 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2205 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2206 emit(DB, std::index_sequence_for<Ts...>());
2207 DB << T;
2208 }
2209 };
2210
2211 /// Do a check to make sure \p Name looks like a legal argument for the
2212 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2213 /// is invalid for the given declaration.
2214 ///
2215 /// \p AL is used to provide caret diagnostics in case of a malformed name.
2216 ///
2217 /// \returns true if the name is a valid swift name for \p D, false otherwise.
2218 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2219 const ParsedAttr &AL, bool IsAsync);
2220
2221 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2222 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2223 /// For example, a diagnostic with no other parameters would generally have
2224 /// the form "...%select{incomplete|sizeless}0 type %1...".
2225 template <typename... Ts>
2226 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2227 public:
2228 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2229 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2230
2231 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2232 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2233 this->emit(DB, std::index_sequence_for<Ts...>());
2234 DB << T->isSizelessType() << T;
2235 }
2236 };
2237
2238 enum class CompleteTypeKind {
2239 /// Apply the normal rules for complete types. In particular,
2240 /// treat all sizeless types as incomplete.
2241 Normal,
2242
2243 /// Relax the normal rules for complete types so that they include
2244 /// sizeless built-in types.
2245 AcceptSizeless,
2246
2247 // FIXME: Eventually we should flip the default to Normal and opt in
2248 // to AcceptSizeless rather than opt out of it.
2249 Default = AcceptSizeless
2250 };
2251
2252 enum class AcceptableKind { Visible, Reachable };
2253
2254private:
2255 /// Methods for marking which expressions involve dereferencing a pointer
2256 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2257 /// they are parsed, meaning that a noderef pointer may not be accessed. For
2258 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2259 /// `*p`, but need to check that `address of` is called on it. This requires
2260 /// keeping a container of all pending expressions and checking if the address
2261 /// of them are eventually taken.
2262 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2263 void CheckAddressOfNoDeref(const Expr *E);
2264 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2265
2266 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2267 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2268
2269 struct ModuleScope {
2270 SourceLocation BeginLoc;
2271 clang::Module *Module = nullptr;
2272 bool ModuleInterface = false;
2273 VisibleModuleSet OuterVisibleModules;
2274 };
2275 /// The modules we're currently parsing.
2276 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2277
2278 /// For an interface unit, this is the implicitly imported interface unit.
2279 clang::Module *ThePrimaryInterface = nullptr;
2280
2281 /// The explicit global module fragment of the current translation unit.
2282 /// The explicit Global Module Fragment, as specified in C++
2283 /// [module.global.frag].
2284 clang::Module *TheGlobalModuleFragment = nullptr;
2285
2286 /// The implicit global module fragments of the current translation unit.
2287 /// We would only create at most two implicit global module fragments to
2288 /// avoid performance penalties when there are many language linkage
2289 /// exports.
2290 ///
2291 /// The contents in the implicit global module fragment can't be discarded
2292 /// no matter if it is exported or not.
2293 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
2294 clang::Module *TheExportedImplicitGlobalModuleFragment = nullptr;
2295
2296 /// Namespace definitions that we will export when they finish.
2297 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2298
2299 /// In a C++ standard module, inline declarations require a definition to be
2300 /// present at the end of a definition domain. This set holds the decls to
2301 /// be checked at the end of the TU.
2302 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
2303
2304 /// Helper function to judge if we are in module purview.
2305 /// Return false if we are not in a module.
2306 bool isCurrentModulePurview() const {
2307 return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2308 }
2309
2310 /// Enter the scope of the explicit global module fragment.
2311 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
2312 /// Leave the scope of the explicit global module fragment.
2313 void PopGlobalModuleFragment();
2314
2315 /// Enter the scope of an implicit global module fragment.
2316 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc,
2317 bool IsExported);
2318 /// Leave the scope of an implicit global module fragment.
2319 void PopImplicitGlobalModuleFragment();
2320
2321 VisibleModuleSet VisibleModules;
2322
2323 /// Cache for module units which is usable for current module.
2324 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2325
2326 bool isUsableModule(const Module *M);
2327
2328 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
2329
2330public:
2331 /// Get the module unit whose scope we are currently within.
2332 Module *getCurrentModule() const {
2333 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2334 }
2335
2336 /// Is the module scope we are an interface?
2337 bool currentModuleIsInterface() const {
2338 return ModuleScopes.empty() ? false : ModuleScopes.back().ModuleInterface;
2339 }
2340
2341 /// Is the module scope we are in a C++ Header Unit?
2342 bool currentModuleIsHeaderUnit() const {
2343 return ModuleScopes.empty() ? false
2344 : ModuleScopes.back().Module->isHeaderUnit();
2345 }
2346
2347 /// Get the module owning an entity.
2348 Module *getOwningModule(const Decl *Entity) {
2349 return Entity->getOwningModule();
2350 }
2351
2352 // Determine whether the module M belongs to the current TU.
2353 bool isModuleUnitOfCurrentTU(const Module *M) const;
2354
2355 /// Make a merged definition of an existing hidden definition \p ND
2356 /// visible at the specified location.
2357 void makeMergedDefinitionVisible(NamedDecl *ND);
2358
2359 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2360
2361 // When loading a non-modular PCH files, this is used to restore module
2362 // visibility.
2363 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2364 VisibleModules.setVisible(Mod, ImportLoc);
2365 }
2366
2367 /// Determine whether a declaration is visible to name lookup.
2368 bool isVisible(const NamedDecl *D) {
2369 return D->isUnconditionallyVisible() ||
2370 isAcceptableSlow(D, AcceptableKind::Visible);
2371 }
2372
2373 /// Determine whether a declaration is reachable.
2374 bool isReachable(const NamedDecl *D) {
2375 // All visible declarations are reachable.
2376 return D->isUnconditionallyVisible() ||
2377 isAcceptableSlow(D, AcceptableKind::Reachable);
2378 }
2379
2380 /// Determine whether a declaration is acceptable (visible/reachable).
2381 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
2382 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
2383 }
2384
2385 /// Determine whether any declaration of an entity is visible.
2386 bool
2387 hasVisibleDeclaration(const NamedDecl *D,
2388 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2389 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2390 }
2391
2392 bool hasVisibleDeclarationSlow(const NamedDecl *D,
2393 llvm::SmallVectorImpl<Module *> *Modules);
2394 /// Determine whether any declaration of an entity is reachable.
2395 bool
2396 hasReachableDeclaration(const NamedDecl *D,
2397 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2398 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
2399 }
2400 bool hasReachableDeclarationSlow(
2401 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2402
2403 bool hasVisibleMergedDefinition(NamedDecl *Def);
2404 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
2405
2406 /// Determine if \p D and \p Suggested have a structurally compatible
2407 /// layout as described in C11 6.2.7/1.
2408 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2409
2410 /// Determine if \p D has a visible definition. If not, suggest a declaration
2411 /// that should be made visible to expose the definition.
2412 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2413 bool OnlyNeedComplete = false);
2414 bool hasVisibleDefinition(const NamedDecl *D) {
2415 NamedDecl *Hidden;
2416 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2417 }
2418
2419 /// Determine if \p D has a reachable definition. If not, suggest a
2420 /// declaration that should be made reachable to expose the definition.
2421 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
2422 bool OnlyNeedComplete = false);
2423 bool hasReachableDefinition(NamedDecl *D) {
2424 NamedDecl *Hidden;
2425 return hasReachableDefinition(D, &Hidden);
2426 }
2427
2428 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
2429 AcceptableKind Kind,
2430 bool OnlyNeedComplete = false);
2431 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
2432 NamedDecl *Hidden;
2433 return hasAcceptableDefinition(D, &Hidden, Kind);
2434 }
2435
2436 /// Determine if the template parameter \p D has a visible default argument.
2437 bool
2438 hasVisibleDefaultArgument(const NamedDecl *D,
2439 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2440 /// Determine if the template parameter \p D has a reachable default argument.
2441 bool hasReachableDefaultArgument(
2442 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2443 /// Determine if the template parameter \p D has a reachable default argument.
2444 bool hasAcceptableDefaultArgument(const NamedDecl *D,
2445 llvm::SmallVectorImpl<Module *> *Modules,
2446 Sema::AcceptableKind Kind);
2447
2448 /// Determine if there is a visible declaration of \p D that is an explicit
2449 /// specialization declaration for a specialization of a template. (For a
2450 /// member specialization, use hasVisibleMemberSpecialization.)
2451 bool hasVisibleExplicitSpecialization(
2452 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2453 /// Determine if there is a reachable declaration of \p D that is an explicit
2454 /// specialization declaration for a specialization of a template. (For a
2455 /// member specialization, use hasReachableMemberSpecialization.)
2456 bool hasReachableExplicitSpecialization(
2457 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2458
2459 /// Determine if there is a visible declaration of \p D that is a member
2460 /// specialization declaration (as opposed to an instantiated declaration).
2461 bool hasVisibleMemberSpecialization(
2462 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2463 /// Determine if there is a reachable declaration of \p D that is a member
2464 /// specialization declaration (as opposed to an instantiated declaration).
2465 bool hasReachableMemberSpecialization(
2466 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2467
2468 /// Determine if \p A and \p B are equivalent internal linkage declarations
2469 /// from different modules, and thus an ambiguity error can be downgraded to
2470 /// an extension warning.
2471 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2472 const NamedDecl *B);
2473 void diagnoseEquivalentInternalLinkageDeclarations(
2474 SourceLocation Loc, const NamedDecl *D,
2475 ArrayRef<const NamedDecl *> Equiv);
2476
2477 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2478
2479 // Check whether the size of array element of type \p EltTy is a multiple of
2480 // its alignment and return false if it isn't.
2481 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
2482
2483 bool isCompleteType(SourceLocation Loc, QualType T,
2484 CompleteTypeKind Kind = CompleteTypeKind::Default) {
2485 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2486 }
2487 bool RequireCompleteType(SourceLocation Loc, QualType T,
2488 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2489 bool RequireCompleteType(SourceLocation Loc, QualType T,
2490 CompleteTypeKind Kind, unsigned DiagID);
2491
2492 bool RequireCompleteType(SourceLocation Loc, QualType T,
2493 TypeDiagnoser &Diagnoser) {
2494 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2495 }
2496 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2497 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2498 }
2499
2500 template <typename... Ts>
2501 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2502 const Ts &...Args) {
2503 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2504 return RequireCompleteType(Loc, T, Diagnoser);
2505 }
2506
2507 template <typename... Ts>
2508 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2509 const Ts &... Args) {
2510 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2511 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2512 }
2513
2514 /// Get the type of expression E, triggering instantiation to complete the
2515 /// type if necessary -- that is, if the expression refers to a templated
2516 /// static data member of incomplete array type.
2517 ///
2518 /// May still return an incomplete type if instantiation was not possible or
2519 /// if the type is incomplete for a different reason. Use
2520 /// RequireCompleteExprType instead if a diagnostic is expected for an
2521 /// incomplete expression type.
2522 QualType getCompletedType(Expr *E);
2523
2524 void completeExprArrayBound(Expr *E);
2525 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2526 TypeDiagnoser &Diagnoser);
2527 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2528
2529 template <typename... Ts>
2530 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2531 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2532 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2533 }
2534
2535 template <typename... Ts>
2536 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2537 const Ts &... Args) {
2538 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2539 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2540 }
2541
2542 bool RequireLiteralType(SourceLocation Loc, QualType T,
2543 TypeDiagnoser &Diagnoser);
2544 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2545
2546 template <typename... Ts>
2547 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2548 const Ts &...Args) {
2549 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2550 return RequireLiteralType(Loc, T, Diagnoser);
2551 }
2552
2553 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2554 const CXXScopeSpec &SS, QualType T,
2555 TagDecl *OwnedTagDecl = nullptr);
2556
2557 // Returns the underlying type of a decltype with the given expression.
2558 QualType getDecltypeForExpr(Expr *E);
2559
2560 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
2561 /// If AsUnevaluated is false, E is treated as though it were an evaluated
2562 /// context, such as when building a type for decltype(auto).
2563 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2564
2565 using UTTKind = UnaryTransformType::UTTKind;
2566 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
2567 SourceLocation Loc);
2568 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
2569 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
2570 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
2571 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
2572 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
2573 SourceLocation Loc);
2574 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
2575 SourceLocation Loc);
2576 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
2577 SourceLocation Loc);
2578 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
2579 SourceLocation Loc);
2580 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
2581 SourceLocation Loc);
2582
2583 //===--------------------------------------------------------------------===//
2584 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2585 //
2586
2587 struct SkipBodyInfo {
2588 SkipBodyInfo()
2589 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2590 New(nullptr) {}
2591 bool ShouldSkip;
2592 bool CheckSameAsPrevious;
2593 NamedDecl *Previous;
2594 NamedDecl *New;
2595 };
2596
2597 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2598
2599 void DiagnoseUseOfUnimplementedSelectors();
2600
2601 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2602
2603 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2604 Scope *S, CXXScopeSpec *SS = nullptr,
2605 bool isClassName = false, bool HasTrailingDot = false,
2606 ParsedType ObjectType = nullptr,
2607 bool IsCtorOrDtorName = false,
2608 bool WantNontrivialTypeSourceInfo = false,
2609 bool IsClassTemplateDeductionContext = true,
2610 ImplicitTypenameContext AllowImplicitTypename =
2611 ImplicitTypenameContext::No,
2612 IdentifierInfo **CorrectedII = nullptr);
2613 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2614 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2615 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2616 SourceLocation IILoc,
2617 Scope *S,
2618 CXXScopeSpec *SS,
2619 ParsedType &SuggestedType,
2620 bool IsTemplateName = false);
2621
2622 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2623 /// type name has failed in a dependent context. In these situations, we
2624 /// automatically form a DependentTypeName that will retry lookup in a related
2625 /// scope during instantiation.
2626 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2627 SourceLocation NameLoc,
2628 bool IsTemplateTypeArg);
2629
2630 /// Describes the result of the name lookup and resolution performed
2631 /// by \c ClassifyName().
2632 enum NameClassificationKind {
2633 /// This name is not a type or template in this context, but might be
2634 /// something else.
2635 NC_Unknown,
2636 /// Classification failed; an error has been produced.
2637 NC_Error,
2638 /// The name has been typo-corrected to a keyword.
2639 NC_Keyword,
2640 /// The name was classified as a type.
2641 NC_Type,
2642 /// The name was classified as a specific non-type, non-template
2643 /// declaration. ActOnNameClassifiedAsNonType should be called to
2644 /// convert the declaration to an expression.
2645 NC_NonType,
2646 /// The name was classified as an ADL-only function name.
2647 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2648 /// result to an expression.
2649 NC_UndeclaredNonType,
2650 /// The name denotes a member of a dependent type that could not be
2651 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2652 /// convert the result to an expression.
2653 NC_DependentNonType,
2654 /// The name was classified as an overload set, and an expression
2655 /// representing that overload set has been formed.
2656 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2657 /// expression referencing the overload set.
2658 NC_OverloadSet,
2659 /// The name was classified as a template whose specializations are types.
2660 NC_TypeTemplate,
2661 /// The name was classified as a variable template name.
2662 NC_VarTemplate,
2663 /// The name was classified as a function template name.
2664 NC_FunctionTemplate,
2665 /// The name was classified as an ADL-only function template name.
2666 NC_UndeclaredTemplate,
2667 /// The name was classified as a concept name.
2668 NC_Concept,
2669 };
2670
2671 class NameClassification {
2672 NameClassificationKind Kind;
2673 union {
2674 ExprResult Expr;
2675 NamedDecl *NonTypeDecl;
2676 TemplateName Template;
2677 ParsedType Type;
2678 };
2679
2680 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2681
2682 public:
2683 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2684
2685 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2686
2687 static NameClassification Error() {
2688 return NameClassification(NC_Error);
2689 }
2690
2691 static NameClassification Unknown() {
2692 return NameClassification(NC_Unknown);
2693 }
2694
2695 static NameClassification OverloadSet(ExprResult E) {
2696 NameClassification Result(NC_OverloadSet);
2697 Result.Expr = E;
2698 return Result;
2699 }
2700
2701 static NameClassification NonType(NamedDecl *D) {
2702 NameClassification Result(NC_NonType);
2703 Result.NonTypeDecl = D;
2704 return Result;
2705 }
2706
2707 static NameClassification UndeclaredNonType() {
2708 return NameClassification(NC_UndeclaredNonType);
2709 }
2710
2711 static NameClassification DependentNonType() {
2712 return NameClassification(NC_DependentNonType);
2713 }
2714
2715 static NameClassification TypeTemplate(TemplateName Name) {
2716 NameClassification Result(NC_TypeTemplate);
2717 Result.Template = Name;
2718 return Result;
2719 }
2720
2721 static NameClassification VarTemplate(TemplateName Name) {
2722 NameClassification Result(NC_VarTemplate);
2723 Result.Template = Name;
2724 return Result;
2725 }
2726
2727 static NameClassification FunctionTemplate(TemplateName Name) {
2728 NameClassification Result(NC_FunctionTemplate);
2729 Result.Template = Name;
2730 return Result;
2731 }
2732
2733 static NameClassification Concept(TemplateName Name) {
2734 NameClassification Result(NC_Concept);
2735 Result.Template = Name;
2736 return Result;
2737 }
2738
2739 static NameClassification UndeclaredTemplate(TemplateName Name) {
2740 NameClassification Result(NC_UndeclaredTemplate);
2741 Result.Template = Name;
2742 return Result;
2743 }
2744
2745 NameClassificationKind getKind() const { return Kind; }
2746
2747 ExprResult getExpression() const {
2748 assert(Kind == NC_OverloadSet)(static_cast <bool> (Kind == NC_OverloadSet) ? void (0)
: __assert_fail ("Kind == NC_OverloadSet", "clang/include/clang/Sema/Sema.h"
, 2748, __extension__ __PRETTY_FUNCTION__))
;
2749 return Expr;
2750 }
2751
2752 ParsedType getType() const {
2753 assert(Kind == NC_Type)(static_cast <bool> (Kind == NC_Type) ? void (0) : __assert_fail
("Kind == NC_Type", "clang/include/clang/Sema/Sema.h", 2753,
__extension__ __PRETTY_FUNCTION__))
;
2754 return Type;
2755 }
2756
2757 NamedDecl *getNonTypeDecl() const {
2758 assert(Kind == NC_NonType)(static_cast <bool> (Kind == NC_NonType) ? void (0) : __assert_fail
("Kind == NC_NonType", "clang/include/clang/Sema/Sema.h", 2758
, __extension__ __PRETTY_FUNCTION__))
;
2759 return NonTypeDecl;
2760 }
2761
2762 TemplateName getTemplateName() const {
2763 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2765, __extension__ __PRETTY_FUNCTION__
))
2764 Kind == NC_VarTemplate || Kind == NC_Concept ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2765, __extension__ __PRETTY_FUNCTION__
))
2765 Kind == NC_UndeclaredTemplate)(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2765, __extension__ __PRETTY_FUNCTION__
))
;
2766 return Template;
2767 }
2768
2769 TemplateNameKind getTemplateNameKind() const {
2770 switch (Kind) {
2771 case NC_TypeTemplate:
2772 return TNK_Type_template;
2773 case NC_FunctionTemplate:
2774 return TNK_Function_template;
2775 case NC_VarTemplate:
2776 return TNK_Var_template;
2777 case NC_Concept:
2778 return TNK_Concept_template;
2779 case NC_UndeclaredTemplate:
2780 return TNK_Undeclared_template;
2781 default:
2782 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "clang/include/clang/Sema/Sema.h", 2782)
;
2783 }
2784 }
2785 };
2786
2787 /// Perform name lookup on the given name, classifying it based on
2788 /// the results of name lookup and the following token.
2789 ///
2790 /// This routine is used by the parser to resolve identifiers and help direct
2791 /// parsing. When the identifier cannot be found, this routine will attempt
2792 /// to correct the typo and classify based on the resulting name.
2793 ///
2794 /// \param S The scope in which we're performing name lookup.
2795 ///
2796 /// \param SS The nested-name-specifier that precedes the name.
2797 ///
2798 /// \param Name The identifier. If typo correction finds an alternative name,
2799 /// this pointer parameter will be updated accordingly.
2800 ///
2801 /// \param NameLoc The location of the identifier.
2802 ///
2803 /// \param NextToken The token following the identifier. Used to help
2804 /// disambiguate the name.
2805 ///
2806 /// \param CCC The correction callback, if typo correction is desired.
2807 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2808 IdentifierInfo *&Name, SourceLocation NameLoc,
2809 const Token &NextToken,
2810 CorrectionCandidateCallback *CCC = nullptr);
2811
2812 /// Act on the result of classifying a name as an undeclared (ADL-only)
2813 /// non-type declaration.
2814 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2815 SourceLocation NameLoc);
2816 /// Act on the result of classifying a name as an undeclared member of a
2817 /// dependent base class.
2818 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2819 IdentifierInfo *Name,
2820 SourceLocation NameLoc,
2821 bool IsAddressOfOperand);
2822 /// Act on the result of classifying a name as a specific non-type
2823 /// declaration.
2824 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2825 NamedDecl *Found,
2826 SourceLocation NameLoc,
2827 const Token &NextToken);
2828 /// Act on the result of classifying a name as an overload set.
2829 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2830
2831 /// Describes the detailed kind of a template name. Used in diagnostics.
2832 enum class TemplateNameKindForDiagnostics {
2833 ClassTemplate,
2834 FunctionTemplate,
2835 VarTemplate,
2836 AliasTemplate,
2837 TemplateTemplateParam,
2838 Concept,
2839 DependentTemplate
2840 };
2841 TemplateNameKindForDiagnostics
2842 getTemplateNameKindForDiagnostics(TemplateName Name);
2843
2844 /// Determine whether it's plausible that E was intended to be a
2845 /// template-name.
2846 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2847 if (!getLangOpts().CPlusPlus || E.isInvalid())
2848 return false;
2849 Dependent = false;
2850 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2851 return !DRE->hasExplicitTemplateArgs();
2852 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2853 return !ME->hasExplicitTemplateArgs();
2854 Dependent = true;
2855 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2856 return !DSDRE->hasExplicitTemplateArgs();
2857 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2858 return !DSME->hasExplicitTemplateArgs();
2859 // Any additional cases recognized here should also be handled by
2860 // diagnoseExprIntendedAsTemplateName.
2861 return false;
2862 }
2863 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2864 SourceLocation Less,
2865 SourceLocation Greater);
2866
2867 void warnOnReservedIdentifier(const NamedDecl *D);
2868
2869 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2870
2871 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2872 MultiTemplateParamsArg TemplateParameterLists);
2873 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2874 QualType &T, SourceLocation Loc,
2875 unsigned FailedFoldDiagID);
2876 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2877 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2878 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2879 DeclarationName Name, SourceLocation Loc,
2880 bool IsTemplateId);
2881 void
2882 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2883 SourceLocation FallbackLoc,
2884 SourceLocation ConstQualLoc = SourceLocation(),
2885 SourceLocation VolatileQualLoc = SourceLocation(),
2886 SourceLocation RestrictQualLoc = SourceLocation(),
2887 SourceLocation AtomicQualLoc = SourceLocation(),
2888 SourceLocation UnalignedQualLoc = SourceLocation());
2889
2890 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2891 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2892 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2893 const LookupResult &R);
2894 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2895 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2896 const LookupResult &R);
2897 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2898 const LookupResult &R);
2899 void CheckShadow(Scope *S, VarDecl *D);
2900
2901 /// Warn if 'E', which is an expression that is about to be modified, refers
2902 /// to a shadowing declaration.
2903 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2904
2905 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2906
2907private:
2908 /// Map of current shadowing declarations to shadowed declarations. Warn if
2909 /// it looks like the user is trying to modify the shadowing declaration.
2910 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2911
2912public:
2913 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2914 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2915 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2916 TypedefNameDecl *NewTD);
2917 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2918 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2919 TypeSourceInfo *TInfo,
2920 LookupResult &Previous);
2921 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2922 LookupResult &Previous, bool &Redeclaration);
2923 NamedDecl *ActOnVariableDeclarator(
2924 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
2925 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
2926 bool &AddToScope, ArrayRef<BindingDecl *> Bindings = std::nullopt);
2927 NamedDecl *
2928 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2929 MultiTemplateParamsArg TemplateParamLists);
2930 // Returns true if the variable declaration is a redeclaration
2931 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2932 void CheckVariableDeclarationType(VarDecl *NewVD);
2933 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2934 Expr *Init);
2935 void CheckCompleteVariableDeclaration(VarDecl *VD);
2936 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2937 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2938
2939 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2940 TypeSourceInfo *TInfo,
2941 LookupResult &Previous,
2942 MultiTemplateParamsArg TemplateParamLists,
2943 bool &AddToScope);
2944 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2945
2946 enum class CheckConstexprKind {
2947 /// Diagnose issues that are non-constant or that are extensions.
2948 Diagnose,
2949 /// Identify whether this function satisfies the formal rules for constexpr
2950 /// functions in the current lanugage mode (with no extensions).
2951 CheckValid
2952 };
2953
2954 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2955 CheckConstexprKind Kind);
2956
2957 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2958 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2959 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2960 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2961 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2962 // Returns true if the function declaration is a redeclaration
2963 bool CheckFunctionDeclaration(Scope *S,
2964 FunctionDecl *NewFD, LookupResult &Previous,
2965 bool IsMemberSpecialization, bool DeclIsDefn);
2966 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2967 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2968 QualType NewT, QualType OldT);
2969 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2970 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2971 void CheckHLSLEntryPoint(FunctionDecl *FD);
2972 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2973 bool IsDefinition);
2974 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2975 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2976 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2977 SourceLocation Loc,
2978 QualType T);
2979 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2980 SourceLocation NameLoc, IdentifierInfo *Name,
2981 QualType T, TypeSourceInfo *TSInfo,
2982 StorageClass SC);
2983 void ActOnParamDefaultArgument(Decl *param,
2984 SourceLocation EqualLoc,
2985 Expr *defarg);
2986 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2987 SourceLocation ArgLoc);
2988 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2989 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2990 SourceLocation EqualLoc);
2991 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2992 SourceLocation EqualLoc);
2993
2994 // Contexts where using non-trivial C union types can be disallowed. This is
2995 // passed to err_non_trivial_c_union_in_invalid_context.
2996 enum NonTrivialCUnionContext {
2997 // Function parameter.
2998 NTCUC_FunctionParam,
2999 // Function return.
3000 NTCUC_FunctionReturn,
3001 // Default-initialized object.
3002 NTCUC_DefaultInitializedObject,
3003 // Variable with automatic storage duration.
3004 NTCUC_AutoVar,
3005 // Initializer expression that might copy from another object.
3006 NTCUC_CopyInit,
3007 // Assignment.
3008 NTCUC_Assignment,
3009 // Compound literal.
3010 NTCUC_CompoundLiteral,
3011 // Block capture.
3012 NTCUC_BlockCapture,
3013 // lvalue-to-rvalue conversion of volatile type.
3014 NTCUC_LValueToRValueVolatile,
3015 };
3016
3017 /// Emit diagnostics if the initializer or any of its explicit or
3018 /// implicitly-generated subexpressions require copying or
3019 /// default-initializing a type that is or contains a C union type that is
3020 /// non-trivial to copy or default-initialize.
3021 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
3022
3023 // These flags are passed to checkNonTrivialCUnion.
3024 enum NonTrivialCUnionKind {
3025 NTCUK_Init = 0x1,
3026 NTCUK_Destruct = 0x2,
3027 NTCUK_Copy = 0x4,
3028 };
3029
3030 /// Emit diagnostics if a non-trivial C union type or a struct that contains
3031 /// a non-trivial C union is used in an invalid context.
3032 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
3033 NonTrivialCUnionContext UseContext,
3034 unsigned NonTrivialKind);
3035
3036 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3037 void ActOnUninitializedDecl(Decl *dcl);
3038 void ActOnInitializerError(Decl *Dcl);
3039
3040 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
3041 void ActOnCXXForRangeDecl(Decl *D);
3042 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
3043 IdentifierInfo *Ident,
3044 ParsedAttributes &Attrs);
3045 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
3046 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
3047 void CheckStaticLocalForDllExport(VarDecl *VD);
3048 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
3049 void FinalizeDeclaration(Decl *D);
3050 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3051 ArrayRef<Decl *> Group);
3052 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
3053
3054 /// Should be called on all declarations that might have attached
3055 /// documentation comments.
3056 void ActOnDocumentableDecl(Decl *D);
3057 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
3058
3059 enum class FnBodyKind {
3060 /// C++ [dcl.fct.def.general]p1
3061 /// function-body:
3062 /// ctor-initializer[opt] compound-statement
3063 /// function-try-block
3064 Other,
3065 /// = default ;
3066 Default,
3067 /// = delete ;
3068 Delete
3069 };
3070
3071 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3072 SourceLocation LocAfterDecls);
3073 void CheckForFunctionRedefinition(
3074 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3075 SkipBodyInfo *SkipBody = nullptr);
3076 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
3077 MultiTemplateParamsArg TemplateParamLists,
3078 SkipBodyInfo *SkipBody = nullptr,
3079 FnBodyKind BodyKind = FnBodyKind::Other);
3080 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
3081 SkipBodyInfo *SkipBody = nullptr,
3082 FnBodyKind BodyKind = FnBodyKind::Other);
3083 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
3084 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
3085 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
3086 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
3087 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
3088 bool isObjCMethodDecl(Decl *D) {
3089 return D && isa<ObjCMethodDecl>(D);
3090 }
3091
3092 /// Determine whether we can delay parsing the body of a function or
3093 /// function template until it is used, assuming we don't care about emitting
3094 /// code for that function.
3095 ///
3096 /// This will be \c false if we may need the body of the function in the
3097 /// middle of parsing an expression (where it's impractical to switch to
3098 /// parsing a different function), for instance, if it's constexpr in C++11
3099 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3100 bool canDelayFunctionBody(const Declarator &D);
3101
3102 /// Determine whether we can skip parsing the body of a function
3103 /// definition, assuming we don't care about analyzing its body or emitting
3104 /// code for that function.
3105 ///
3106 /// This will be \c false only if we may need the body of the function in
3107 /// order to parse the rest of the program (for instance, if it is
3108 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3109 bool canSkipFunctionBody(Decl *D);
3110
3111 /// Determine whether \param D is function like (function or function
3112 /// template) for parsing.
3113 bool isDeclaratorFunctionLike(Declarator &D);
3114
3115 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
3116 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
3117 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3118 Decl *ActOnSkippedFunctionBody(Decl *Decl);
3119 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
3120
3121 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3122 /// attribute for which parsing is delayed.
3123 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
3124
3125 /// Diagnose any unused parameters in the given sequence of
3126 /// ParmVarDecl pointers.
3127 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
3128
3129 /// Diagnose whether the size of parameters or return value of a
3130 /// function or obj-c method definition is pass-by-value and larger than a
3131 /// specified threshold.
3132 void
3133 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
3134 QualType ReturnTy, NamedDecl *D);
3135
3136 void DiagnoseInvalidJumps(Stmt *Body);
3137 Decl *ActOnFileScopeAsmDecl(Expr *expr,
3138 SourceLocation AsmLoc,
3139 SourceLocation RParenLoc);
3140
3141 Decl *ActOnTopLevelStmtDecl(Stmt *Statement);
3142
3143 /// Handle a C++11 empty-declaration and attribute-declaration.
3144 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
3145 SourceLocation SemiLoc);
3146
3147 enum class ModuleDeclKind {
3148 Interface, ///< 'export module X;'
3149 Implementation, ///< 'module X;'
3150 PartitionInterface, ///< 'export module X:Y;'
3151 PartitionImplementation, ///< 'module X:Y;'
3152 };
3153
3154 /// An enumeration to represent the transition of states in parsing module
3155 /// fragments and imports. If we are not parsing a C++20 TU, or we find
3156 /// an error in state transition, the state is set to NotACXX20Module.
3157 enum class ModuleImportState {
3158 FirstDecl, ///< Parsing the first decl in a TU.
3159 GlobalFragment, ///< after 'module;' but before 'module X;'
3160 ImportAllowed, ///< after 'module X;' but before any non-import decl.
3161 ImportFinished, ///< after any non-import decl.
3162 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
3163 ///< non-import decl.
3164 PrivateFragmentImportFinished, ///< after 'module :private;' but a
3165 ///< non-import decl has already been seen.
3166 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3167 };
3168
3169private:
3170 /// The parser has begun a translation unit to be compiled as a C++20
3171 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3172 void HandleStartOfHeaderUnit();
3173
3174public:
3175 /// The parser has processed a module-declaration that begins the definition
3176 /// of a module interface or implementation.
3177 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
3178 SourceLocation ModuleLoc, ModuleDeclKind MDK,
3179 ModuleIdPath Path, ModuleIdPath Partition,
3180 ModuleImportState &ImportState);
3181
3182 /// The parser has processed a global-module-fragment declaration that begins
3183 /// the definition of the global module fragment of the current module unit.
3184 /// \param ModuleLoc The location of the 'module' keyword.
3185 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
3186
3187 /// The parser has processed a private-module-fragment declaration that begins
3188 /// the definition of the private module fragment of the current module unit.
3189 /// \param ModuleLoc The location of the 'module' keyword.
3190 /// \param PrivateLoc The location of the 'private' keyword.
3191 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
3192 SourceLocation PrivateLoc);
3193
3194 /// The parser has processed a module import declaration.
3195 ///
3196 /// \param StartLoc The location of the first token in the declaration. This
3197 /// could be the location of an '@', 'export', or 'import'.
3198 /// \param ExportLoc The location of the 'export' keyword, if any.
3199 /// \param ImportLoc The location of the 'import' keyword.
3200 /// \param Path The module toplevel name as an access path.
3201 /// \param IsPartition If the name is for a partition.
3202 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3203 SourceLocation ExportLoc,
3204 SourceLocation ImportLoc, ModuleIdPath Path,
3205 bool IsPartition = false);
3206 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3207 SourceLocation ExportLoc,
3208 SourceLocation ImportLoc, Module *M,
3209 ModuleIdPath Path = {});
3210
3211 /// The parser has processed a module import translated from a
3212 /// #include or similar preprocessing directive.
3213 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3214 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3215
3216 /// The parsed has entered a submodule.
3217 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3218 /// The parser has left a submodule.
3219 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3220
3221 /// Create an implicit import of the given module at the given
3222 /// source location, for error recovery, if possible.
3223 ///
3224 /// This routine is typically used when an entity found by name lookup
3225 /// is actually hidden within a module that we know about but the user
3226 /// has forgotten to import.
3227 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3228 Module *Mod);
3229
3230 /// Kinds of missing import. Note, the values of these enumerators correspond
3231 /// to %select values in diagnostics.
3232 enum class MissingImportKind {
3233 Declaration,
3234 Definition,
3235 DefaultArgument,
3236 ExplicitSpecialization,
3237 PartialSpecialization
3238 };
3239
3240 /// Diagnose that the specified declaration needs to be visible but
3241 /// isn't, and suggest a module import that would resolve the problem.
3242 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
3243 MissingImportKind MIK, bool Recover = true);
3244 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
3245 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3246 MissingImportKind MIK, bool Recover);
3247
3248 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
3249 SourceLocation LBraceLoc);
3250 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
3251 SourceLocation RBraceLoc);
3252
3253 /// We've found a use of a templated declaration that would trigger an
3254 /// implicit instantiation. Check that any relevant explicit specializations
3255 /// and partial specializations are visible/reachable, and diagnose if not.
3256 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
3257 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
3258
3259 /// Retrieve a suitable printing policy for diagnostics.
3260 PrintingPolicy getPrintingPolicy() const {
3261 return getPrintingPolicy(Context, PP);
3262 }
3263
3264 /// Retrieve a suitable printing policy for diagnostics.
3265 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3266 const Preprocessor &PP);
3267
3268 /// Scope actions.
3269 void ActOnPopScope(SourceLocation Loc, Scope *S);
3270 void ActOnTranslationUnitScope(Scope *S);
3271
3272 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3273 const ParsedAttributesView &DeclAttrs,
3274 RecordDecl *&AnonRecord);
3275 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3276 const ParsedAttributesView &DeclAttrs,
3277 MultiTemplateParamsArg TemplateParams,
3278 bool IsExplicitInstantiation,
3279 RecordDecl *&AnonRecord);
3280
3281 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3282 AccessSpecifier AS,
3283 RecordDecl *Record,
3284 const PrintingPolicy &Policy);
3285
3286 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3287 RecordDecl *Record);
3288
3289 /// Common ways to introduce type names without a tag for use in diagnostics.
3290 /// Keep in sync with err_tag_reference_non_tag.
3291 enum NonTagKind {
3292 NTK_NonStruct,
3293 NTK_NonClass,
3294 NTK_NonUnion,
3295 NTK_NonEnum,
3296 NTK_Typedef,
3297 NTK_TypeAlias,
3298 NTK_Template,
3299 NTK_TypeAliasTemplate,
3300 NTK_TemplateTemplateArgument,
3301 };
3302
3303 /// Given a non-tag type declaration, returns an enum useful for indicating
3304 /// what kind of non-tag type this is.
3305 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
3306
3307 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
3308 TagTypeKind NewTag, bool isDefinition,
3309 SourceLocation NewTagLoc,
3310 const IdentifierInfo *Name);
3311
3312 enum TagUseKind {
3313 TUK_Reference, // Reference to a tag: 'struct foo *X;'
3314 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3315 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3316 TUK_Friend // Friend declaration: 'friend struct foo;'
3317 };
3318
3319 enum OffsetOfKind {
3320 // Not parsing a type within __builtin_offsetof.
3321 OOK_Outside,
3322 // Parsing a type within __builtin_offsetof.
3323 OOK_Builtin,
3324 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
3325 // To improve our diagnostic message.
3326 OOK_Macro,
3327 };
3328
3329 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3330 SourceLocation KWLoc, CXXScopeSpec &SS,
3331 IdentifierInfo *Name, SourceLocation NameLoc,
3332 const ParsedAttributesView &Attr, AccessSpecifier AS,
3333 SourceLocation ModulePrivateLoc,
3334 MultiTemplateParamsArg TemplateParameterLists,
3335 bool &OwnedDecl, bool &IsDependent,
3336 SourceLocation ScopedEnumKWLoc,
3337 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3338 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3339 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
3340
3341 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
3342 unsigned TagSpec, SourceLocation TagLoc,
3343 CXXScopeSpec &SS, IdentifierInfo *Name,
3344 SourceLocation NameLoc,
3345 const ParsedAttributesView &Attr,
3346 MultiTemplateParamsArg TempParamLists);
3347
3348 TypeResult ActOnDependentTag(Scope *S,
3349 unsigned TagSpec,
3350 TagUseKind TUK,
3351 const CXXScopeSpec &SS,
3352 IdentifierInfo *Name,
3353 SourceLocation TagLoc,
3354 SourceLocation NameLoc);
3355
3356 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3357 IdentifierInfo *ClassName,
3358 SmallVectorImpl<Decl *> &Decls);
3359 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3360 Declarator &D, Expr *BitfieldWidth);
3361
3362 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3363 Declarator &D, Expr *BitfieldWidth,
3364 InClassInitStyle InitStyle,
3365 AccessSpecifier AS);
3366 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3367 SourceLocation DeclStart, Declarator &D,
3368 Expr *BitfieldWidth,
3369 InClassInitStyle InitStyle,
3370 AccessSpecifier AS,
3371 const ParsedAttr &MSPropertyAttr);
3372
3373 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3374 TypeSourceInfo *TInfo,
3375 RecordDecl *Record, SourceLocation Loc,
3376 bool Mutable, Expr *BitfieldWidth,
3377 InClassInitStyle InitStyle,
3378 SourceLocation TSSL,
3379 AccessSpecifier AS, NamedDecl *PrevDecl,
3380 Declarator *D = nullptr);
3381
3382 bool CheckNontrivialField(FieldDecl *FD);
3383 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3384
3385 enum TrivialABIHandling {
3386 /// The triviality of a method unaffected by "trivial_abi".
3387 TAH_IgnoreTrivialABI,
3388
3389 /// The triviality of a method affected by "trivial_abi".
3390 TAH_ConsiderTrivialABI
3391 };
3392
3393 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3394 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3395 bool Diagnose = false);
3396
3397 /// For a defaulted function, the kind of defaulted function that it is.
3398 class DefaultedFunctionKind {
3399 CXXSpecialMember SpecialMember : 8;
3400 DefaultedComparisonKind Comparison : 8;
3401
3402 public:
3403 DefaultedFunctionKind()
3404 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3405 }
3406 DefaultedFunctionKind(CXXSpecialMember CSM)
3407 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3408 DefaultedFunctionKind(DefaultedComparisonKind Comp)
3409 : SpecialMember(CXXInvalid), Comparison(Comp) {}
3410
3411 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3412 bool isComparison() const {
3413 return Comparison != DefaultedComparisonKind::None;
3414 }
3415
3416 explicit operator bool() const {
3417 return isSpecialMember() || isComparison();
3418 }
3419
3420 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3421 DefaultedComparisonKind asComparison() const { return Comparison; }
3422
3423 /// Get the index of this function kind for use in diagnostics.
3424 unsigned getDiagnosticIndex() const {
3425 static_assert(CXXInvalid > CXXDestructor,
3426 "invalid should have highest index");
3427 static_assert((unsigned)DefaultedComparisonKind::None == 0,
3428 "none should be equal to zero");
3429 return SpecialMember + (unsigned)Comparison;
3430 }
3431 };
3432
3433 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3434
3435 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3436 return getDefaultedFunctionKind(MD).asSpecialMember();
3437 }
3438 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3439 return getDefaultedFunctionKind(FD).asComparison();
3440 }
3441
3442 void ActOnLastBitfield(SourceLocation DeclStart,
3443 SmallVectorImpl<Decl *> &AllIvarDecls);
3444 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3445 Declarator &D, Expr *BitfieldWidth,
3446 tok::ObjCKeywordKind visibility);
3447
3448 // This is used for both record definitions and ObjC interface declarations.
3449 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3450 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3451 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3452
3453 /// ActOnTagStartDefinition - Invoked when we have entered the
3454 /// scope of a tag's definition (e.g., for an enumeration, class,
3455 /// struct, or union).
3456 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3457
3458 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3459 /// Differently from C++, actually parse the body and reject / error out
3460 /// in case of a structural mismatch.
3461 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3462
3463 /// Check ODR hashes for C/ObjC when merging types from modules.
3464 /// Differently from C++, actually parse the body and reject in case
3465 /// of a mismatch.
3466 template <typename T,
3467 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
3468 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
3469 if (Duplicate->getODRHash() != Previous->getODRHash())
3470 return false;
3471
3472 // Make the previous decl visible.
3473 makeMergedDefinitionVisible(Previous);
3474 return true;
3475 }
3476
3477 typedef void *SkippedDefinitionContext;
3478
3479 /// Invoked when we enter a tag definition that we're skipping.
3480 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3481
3482 void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl);
3483
3484 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3485 /// C++ record definition's base-specifiers clause and are starting its
3486 /// member declarations.
3487 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3488 SourceLocation FinalLoc,
3489 bool IsFinalSpelledSealed,
3490 bool IsAbstract,
3491 SourceLocation LBraceLoc);
3492
3493 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3494 /// the definition of a tag (enumeration, class, struct, or union).
3495 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3496 SourceRange BraceRange);
3497
3498 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3499
3500 void ActOnObjCContainerFinishDefinition();
3501
3502 /// Invoked when we must temporarily exit the objective-c container
3503 /// scope for parsing/looking-up C constructs.
3504 ///
3505 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3506 void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx);
3507 void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx);
3508
3509 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3510 /// error parsing the definition of a tag.
3511 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3512
3513 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3514 EnumConstantDecl *LastEnumConst,
3515 SourceLocation IdLoc,
3516 IdentifierInfo *Id,
3517 Expr *val);
3518 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3519 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3520 QualType EnumUnderlyingTy, bool IsFixed,
3521 const EnumDecl *Prev);
3522
3523 /// Determine whether the body of an anonymous enumeration should be skipped.
3524 /// \param II The name of the first enumerator.
3525 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3526 SourceLocation IILoc);
3527
3528 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3529 SourceLocation IdLoc, IdentifierInfo *Id,
3530 const ParsedAttributesView &Attrs,
3531 SourceLocation EqualLoc, Expr *Val);
3532 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3533 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3534 const ParsedAttributesView &Attr);
3535
3536 /// Set the current declaration context until it gets popped.
3537 void PushDeclContext(Scope *S, DeclContext *DC);
3538 void PopDeclContext();
3539
3540 /// EnterDeclaratorContext - Used when we must lookup names in the context
3541 /// of a declarator's nested name specifier.
3542 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3543 void ExitDeclaratorContext(Scope *S);
3544
3545 /// Enter a template parameter scope, after it's been associated with a particular
3546 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3547 /// in the correct order.
3548 void EnterTemplatedContext(Scope *S, DeclContext *DC);
3549
3550 /// Push the parameters of D, which must be a function, into scope.
3551 void ActOnReenterFunctionContext(Scope* S, Decl* D);
3552 void ActOnExitFunctionContext();
3553
3554 /// If \p AllowLambda is true, treat lambda as function.
3555 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
3556
3557 /// Returns a pointer to the innermost enclosing function, or nullptr if the
3558 /// current context is not inside a function. If \p AllowLambda is true,
3559 /// this can return the call operator of an enclosing lambda, otherwise
3560 /// lambdas are skipped when looking for an enclosing function.
3561 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
3562
3563 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3564 /// the method decl for the method being parsed. If we're currently
3565 /// in a 'block', this returns the containing context.
3566 ObjCMethodDecl *getCurMethodDecl();
3567
3568 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3569 /// or C function we're in, otherwise return null. If we're currently
3570 /// in a 'block', this returns the containing context.
3571 NamedDecl *getCurFunctionOrMethodDecl() const;
3572
3573 /// Add this decl to the scope shadowed decl chains.
3574 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3575
3576 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3577 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3578 /// true if 'D' belongs to the given declaration context.
3579 ///
3580 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3581 /// enclosing namespace set of the context, rather than contained
3582 /// directly within it.
3583 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3584 bool AllowInlineNamespace = false) const;
3585
3586 /// Finds the scope corresponding to the given decl context, if it
3587 /// happens to be an enclosing scope. Otherwise return NULL.
3588 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3589
3590 /// Subroutines of ActOnDeclarator().
3591 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3592 TypeSourceInfo *TInfo);
3593 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3594
3595 /// Describes the kind of merge to perform for availability
3596 /// attributes (including "deprecated", "unavailable", and "availability").
3597 enum AvailabilityMergeKind {
3598 /// Don't merge availability attributes at all.
3599 AMK_None,
3600 /// Merge availability attributes for a redeclaration, which requires
3601 /// an exact match.
3602 AMK_Redeclaration,
3603 /// Merge availability attributes for an override, which requires
3604 /// an exact match or a weakening of constraints.
3605 AMK_Override,
3606 /// Merge availability attributes for an implementation of
3607 /// a protocol requirement.
3608 AMK_ProtocolImplementation,
3609 /// Merge availability attributes for an implementation of
3610 /// an optional protocol requirement.
3611 AMK_OptionalProtocolImplementation
3612 };
3613
3614 /// Describes the kind of priority given to an availability attribute.
3615 ///
3616 /// The sum of priorities deteremines the final priority of the attribute.
3617 /// The final priority determines how the attribute will be merged.
3618 /// An attribute with a lower priority will always remove higher priority
3619 /// attributes for the specified platform when it is being applied. An
3620 /// attribute with a higher priority will not be applied if the declaration
3621 /// already has an availability attribute with a lower priority for the
3622 /// specified platform. The final prirority values are not expected to match
3623 /// the values in this enumeration, but instead should be treated as a plain
3624 /// integer value. This enumeration just names the priority weights that are
3625 /// used to calculate that final vaue.
3626 enum AvailabilityPriority : int {
3627 /// The availability attribute was specified explicitly next to the
3628 /// declaration.
3629 AP_Explicit = 0,
3630
3631 /// The availability attribute was applied using '#pragma clang attribute'.
3632 AP_PragmaClangAttribute = 1,
3633
3634 /// The availability attribute for a specific platform was inferred from
3635 /// an availability attribute for another platform.
3636 AP_InferredFromOtherPlatform = 2
3637 };
3638
3639 /// Attribute merging methods. Return true if a new attribute was added.
3640 AvailabilityAttr *
3641 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3642 IdentifierInfo *Platform, bool Implicit,
3643 VersionTuple Introduced, VersionTuple Deprecated,
3644 VersionTuple Obsoleted, bool IsUnavailable,
3645 StringRef Message, bool IsStrict, StringRef Replacement,
3646 AvailabilityMergeKind AMK, int Priority);
3647 TypeVisibilityAttr *
3648 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3649 TypeVisibilityAttr::VisibilityType Vis);
3650 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3651 VisibilityAttr::VisibilityType Vis);
3652 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3653 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3654 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3655 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3656 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3657 const AttributeCommonInfo &CI,
3658 bool BestCase,
3659 MSInheritanceModel Model);
3660 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3661 StringRef NewUserDiagnostic);
3662 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3663 IdentifierInfo *Format, int FormatIdx,
3664 int FirstArg);
3665 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3666 StringRef Name);
3667 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3668 StringRef Name);
3669 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3670 const AttributeCommonInfo &CI,
3671 const IdentifierInfo *Ident);
3672 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3673 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3674 StringRef Name);
3675 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3676 const AttributeCommonInfo &CI);
3677 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3678 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3679 const InternalLinkageAttr &AL);
3680 WebAssemblyImportNameAttr *mergeImportNameAttr(
3681 Decl *D, const WebAssemblyImportNameAttr &AL);
3682 WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3683 Decl *D, const WebAssemblyImportModuleAttr &AL);
3684 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3685 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3686 const EnforceTCBLeafAttr &AL);
3687 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3688 HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3689 const AttributeCommonInfo &AL,
3690 int X, int Y, int Z);
3691 HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
3692 HLSLShaderAttr::ShaderType ShaderType);
3693
3694 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3695 AvailabilityMergeKind AMK = AMK_Redeclaration);
3696 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3697 LookupResult &OldDecls);
3698 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3699 bool MergeTypeWithOld, bool NewDeclIsDefn);
3700 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3701 Scope *S, bool MergeTypeWithOld);
3702 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3703 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3704 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3705 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3706 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3707 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3708 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3709
3710 // AssignmentAction - This is used by all the assignment diagnostic functions
3711 // to represent what is actually causing the operation
3712 enum AssignmentAction {
3713 AA_Assigning,
3714 AA_Passing,
3715 AA_Returning,
3716 AA_Converting,
3717 AA_Initializing,
3718 AA_Sending,
3719 AA_Casting,
3720 AA_Passing_CFAudited
3721 };
3722
3723 /// C++ Overloading.
3724 enum OverloadKind {
3725 /// This is a legitimate overload: the existing declarations are
3726 /// functions or function templates with different signatures.
3727 Ovl_Overload,
3728
3729 /// This is not an overload because the signature exactly matches
3730 /// an existing declaration.
3731 Ovl_Match,
3732
3733 /// This is not an overload because the lookup results contain a
3734 /// non-function.
3735 Ovl_NonFunction
3736 };
3737 OverloadKind CheckOverload(Scope *S,
3738 FunctionDecl *New,
3739 const LookupResult &OldDecls,
3740 NamedDecl *&OldDecl,
3741 bool UseMemberUsingDeclRules);
3742 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
3743 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true,
3744 bool ConsiderRequiresClauses = true);
3745
3746 // Calculates whether the expression Constraint depends on an enclosing
3747 // template, for the purposes of [temp.friend] p9.
3748 // TemplateDepth is the 'depth' of the friend function, which is used to
3749 // compare whether a declaration reference is referring to a containing
3750 // template, or just the current friend function. A 'lower' TemplateDepth in
3751 // the AST refers to a 'containing' template. As the constraint is
3752 // uninstantiated, this is relative to the 'top' of the TU.
3753 bool
3754 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
3755 unsigned TemplateDepth,
3756 const Expr *Constraint);
3757
3758 // Calculates whether the friend function depends on an enclosing template for
3759 // the purposes of [temp.friend] p9.
3760 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
3761
3762 // Calculates whether two constraint expressions are equal irrespective of a
3763 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
3764 // 'New', which are the "source" of the constraint, since this is necessary
3765 // for figuring out the relative 'depth' of the constraint. The depth of the
3766 // 'primary template' and the 'instantiated from' templates aren't necessarily
3767 // the same, such as a case when one is a 'friend' defined in a class.
3768 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
3769 const Expr *OldConstr,
3770 const NamedDecl *New,
3771 const Expr *NewConstr);
3772
3773 enum class AllowedExplicit {
3774 /// Allow no explicit functions to be used.
3775 None,
3776 /// Allow explicit conversion functions but not explicit constructors.
3777 Conversions,
3778 /// Allow both explicit conversion functions and explicit constructors.
3779 All
3780 };
3781
3782 ImplicitConversionSequence
3783 TryImplicitConversion(Expr *From, QualType ToType,
3784 bool SuppressUserConversions,
3785 AllowedExplicit AllowExplicit,
3786 bool InOverloadResolution,
3787 bool CStyle,
3788 bool AllowObjCWritebackConversion);
3789
3790 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3791 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3792 bool IsComplexPromotion(QualType FromType, QualType ToType);
3793 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3794 bool InOverloadResolution,
3795 QualType& ConvertedType, bool &IncompatibleObjC);
3796 bool isObjCPointerConversion(QualType FromType, QualType ToType,
3797 QualType& ConvertedType, bool &IncompatibleObjC);
3798 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3799 QualType &ConvertedType);
3800 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3801 QualType& ConvertedType);
3802 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3803 const FunctionProtoType *NewType,
3804 unsigned *ArgPos = nullptr,
3805 bool Reversed = false);
3806 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3807 QualType FromType, QualType ToType);
3808
3809 void maybeExtendBlockObject(ExprResult &E);
3810 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3811 bool CheckPointerConversion(Expr *From, QualType ToType,
3812 CastKind &Kind,
3813 CXXCastPath& BasePath,
3814 bool IgnoreBaseAccess,
3815 bool Diagnose = true);
3816 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3817 bool InOverloadResolution,
3818 QualType &ConvertedType);
3819 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3820 CastKind &Kind,
3821 CXXCastPath &BasePath,
3822