Bug Summary

File:clang/include/clang/AST/ExprCXX.h
Warning:line 4695, 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 -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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/include -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-01-24-223304-31662-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/clang/lib/Sema/SemaCoroutine.cpp

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

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