Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include/clang/AST/ExprCXX.h
Warning:line 4710, 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/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/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-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -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/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -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-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema/SemaCoroutine.cpp

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

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