Bug Summary

File:clang/include/clang/AST/ExprCXX.h
Warning:line 4693, 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-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -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-14~++20220116100644+5f782d25a742/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.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-14~++20220116100644+5f782d25a742/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/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-14/lib/clang/14.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-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -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-01-16-232930-107970-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/lib/Sema/SemaCoroutine.cpp

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

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