[lld][WebAssembly] Add `--table-base` setting
[llvm-project.git] / clang / lib / Sema / SemaExpr.cpp
blobf9badf4ede847f9f99a1deb7aa0cc4fd80dbd2ee
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
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 expressions.
11 //===----------------------------------------------------------------------===//
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/OperationKinds.h"
28 #include "clang/AST/ParentMapContext.h"
29 #include "clang/AST/RecursiveASTVisitor.h"
30 #include "clang/AST/Type.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/DiagnosticSema.h"
34 #include "clang/Basic/PartialDiagnostic.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Lex/LiteralSupport.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Sema/AnalysisBasedWarnings.h"
41 #include "clang/Sema/DeclSpec.h"
42 #include "clang/Sema/DelayedDiagnostic.h"
43 #include "clang/Sema/Designator.h"
44 #include "clang/Sema/EnterExpressionEvaluationContext.h"
45 #include "clang/Sema/Initialization.h"
46 #include "clang/Sema/Lookup.h"
47 #include "clang/Sema/Overload.h"
48 #include "clang/Sema/ParsedTemplate.h"
49 #include "clang/Sema/Scope.h"
50 #include "clang/Sema/ScopeInfo.h"
51 #include "clang/Sema/SemaFixItUtils.h"
52 #include "clang/Sema/SemaInternal.h"
53 #include "clang/Sema/Template.h"
54 #include "llvm/ADT/STLExtras.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/ConvertUTF.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/TypeSize.h"
60 #include <optional>
62 using namespace clang;
63 using namespace sema;
65 /// Determine whether the use of this declaration is valid, without
66 /// emitting diagnostics.
67 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
68 // See if this is an auto-typed variable whose initializer we are parsing.
69 if (ParsingInitForAutoVars.count(D))
70 return false;
72 // See if this is a deleted function.
73 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74 if (FD->isDeleted())
75 return false;
77 // If the function has a deduced return type, and we can't deduce it,
78 // then we can't use it either.
79 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
80 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
81 return false;
83 // See if this is an aligned allocation/deallocation function that is
84 // unavailable.
85 if (TreatUnavailableAsInvalid &&
86 isUnavailableAlignedAllocationFunction(*FD))
87 return false;
90 // See if this function is unavailable.
91 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
92 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
93 return false;
95 if (isa<UnresolvedUsingIfExistsDecl>(D))
96 return false;
98 return true;
101 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
102 // Warn if this is used but marked unused.
103 if (const auto *A = D->getAttr<UnusedAttr>()) {
104 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
105 // should diagnose them.
106 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
107 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
108 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
109 if (DC && !DC->hasAttr<UnusedAttr>())
110 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
115 /// Emit a note explaining that this function is deleted.
116 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
117 assert(Decl && Decl->isDeleted());
119 if (Decl->isDefaulted()) {
120 // If the method was explicitly defaulted, point at that declaration.
121 if (!Decl->isImplicit())
122 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
124 // Try to diagnose why this special member function was implicitly
125 // deleted. This might fail, if that reason no longer applies.
126 DiagnoseDeletedDefaultedFunction(Decl);
127 return;
130 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
131 if (Ctor && Ctor->isInheritingConstructor())
132 return NoteDeletedInheritingConstructor(Ctor);
134 Diag(Decl->getLocation(), diag::note_availability_specified_here)
135 << Decl << 1;
138 /// Determine whether a FunctionDecl was ever declared with an
139 /// explicit storage class.
140 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
141 for (auto *I : D->redecls()) {
142 if (I->getStorageClass() != SC_None)
143 return true;
145 return false;
148 /// Check whether we're in an extern inline function and referring to a
149 /// variable or function with internal linkage (C11 6.7.4p3).
151 /// This is only a warning because we used to silently accept this code, but
152 /// in many cases it will not behave correctly. This is not enabled in C++ mode
153 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
154 /// and so while there may still be user mistakes, most of the time we can't
155 /// prove that there are errors.
156 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
157 const NamedDecl *D,
158 SourceLocation Loc) {
159 // This is disabled under C++; there are too many ways for this to fire in
160 // contexts where the warning is a false positive, or where it is technically
161 // correct but benign.
162 if (S.getLangOpts().CPlusPlus)
163 return;
165 // Check if this is an inlined function or method.
166 FunctionDecl *Current = S.getCurFunctionDecl();
167 if (!Current)
168 return;
169 if (!Current->isInlined())
170 return;
171 if (!Current->isExternallyVisible())
172 return;
174 // Check if the decl has internal linkage.
175 if (D->getFormalLinkage() != InternalLinkage)
176 return;
178 // Downgrade from ExtWarn to Extension if
179 // (1) the supposedly external inline function is in the main file,
180 // and probably won't be included anywhere else.
181 // (2) the thing we're referencing is a pure function.
182 // (3) the thing we're referencing is another inline function.
183 // This last can give us false negatives, but it's better than warning on
184 // wrappers for simple C library functions.
185 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
186 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
187 if (!DowngradeWarning && UsedFn)
188 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
190 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
191 : diag::ext_internal_in_extern_inline)
192 << /*IsVar=*/!UsedFn << D;
194 S.MaybeSuggestAddingStaticToDecl(Current);
196 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
197 << D;
200 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
201 const FunctionDecl *First = Cur->getFirstDecl();
203 // Suggest "static" on the function, if possible.
204 if (!hasAnyExplicitStorageClass(First)) {
205 SourceLocation DeclBegin = First->getSourceRange().getBegin();
206 Diag(DeclBegin, diag::note_convert_inline_to_static)
207 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
211 /// Determine whether the use of this declaration is valid, and
212 /// emit any corresponding diagnostics.
214 /// This routine diagnoses various problems with referencing
215 /// declarations that can occur when using a declaration. For example,
216 /// it might warn if a deprecated or unavailable declaration is being
217 /// used, or produce an error (and return true) if a C++0x deleted
218 /// function is being used.
220 /// \returns true if there was an error (this declaration cannot be
221 /// referenced), false otherwise.
223 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
224 const ObjCInterfaceDecl *UnknownObjCClass,
225 bool ObjCPropertyAccess,
226 bool AvoidPartialAvailabilityChecks,
227 ObjCInterfaceDecl *ClassReceiver,
228 bool SkipTrailingRequiresClause) {
229 SourceLocation Loc = Locs.front();
230 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
231 // If there were any diagnostics suppressed by template argument deduction,
232 // emit them now.
233 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
234 if (Pos != SuppressedDiagnostics.end()) {
235 for (const PartialDiagnosticAt &Suppressed : Pos->second)
236 Diag(Suppressed.first, Suppressed.second);
238 // Clear out the list of suppressed diagnostics, so that we don't emit
239 // them again for this specialization. However, we don't obsolete this
240 // entry from the table, because we want to avoid ever emitting these
241 // diagnostics again.
242 Pos->second.clear();
245 // C++ [basic.start.main]p3:
246 // The function 'main' shall not be used within a program.
247 if (cast<FunctionDecl>(D)->isMain())
248 Diag(Loc, diag::ext_main_used);
250 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
253 // See if this is an auto-typed variable whose initializer we are parsing.
254 if (ParsingInitForAutoVars.count(D)) {
255 if (isa<BindingDecl>(D)) {
256 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
257 << D->getDeclName();
258 } else {
259 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
260 << D->getDeclName() << cast<VarDecl>(D)->getType();
262 return true;
265 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
266 // See if this is a deleted function.
267 if (FD->isDeleted()) {
268 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
269 if (Ctor && Ctor->isInheritingConstructor())
270 Diag(Loc, diag::err_deleted_inherited_ctor_use)
271 << Ctor->getParent()
272 << Ctor->getInheritedConstructor().getConstructor()->getParent();
273 else
274 Diag(Loc, diag::err_deleted_function_use);
275 NoteDeletedFunction(FD);
276 return true;
279 // [expr.prim.id]p4
280 // A program that refers explicitly or implicitly to a function with a
281 // trailing requires-clause whose constraint-expression is not satisfied,
282 // other than to declare it, is ill-formed. [...]
284 // See if this is a function with constraints that need to be satisfied.
285 // Check this before deducing the return type, as it might instantiate the
286 // definition.
287 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
288 ConstraintSatisfaction Satisfaction;
289 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
290 /*ForOverloadResolution*/ true))
291 // A diagnostic will have already been generated (non-constant
292 // constraint expression, for example)
293 return true;
294 if (!Satisfaction.IsSatisfied) {
295 Diag(Loc,
296 diag::err_reference_to_function_with_unsatisfied_constraints)
297 << D;
298 DiagnoseUnsatisfiedConstraint(Satisfaction);
299 return true;
303 // If the function has a deduced return type, and we can't deduce it,
304 // then we can't use it either.
305 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
306 DeduceReturnType(FD, Loc))
307 return true;
309 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
310 return true;
314 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
315 // Lambdas are only default-constructible or assignable in C++2a onwards.
316 if (MD->getParent()->isLambda() &&
317 ((isa<CXXConstructorDecl>(MD) &&
318 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
319 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
320 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
321 << !isa<CXXConstructorDecl>(MD);
325 auto getReferencedObjCProp = [](const NamedDecl *D) ->
326 const ObjCPropertyDecl * {
327 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
328 return MD->findPropertyDecl();
329 return nullptr;
331 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
332 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
333 return true;
334 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
335 return true;
338 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
339 // Only the variables omp_in and omp_out are allowed in the combiner.
340 // Only the variables omp_priv and omp_orig are allowed in the
341 // initializer-clause.
342 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
343 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
344 isa<VarDecl>(D)) {
345 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
346 << getCurFunction()->HasOMPDeclareReductionCombiner;
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
351 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
352 // List-items in map clauses on this construct may only refer to the declared
353 // variable var and entities that could be referenced by a procedure defined
354 // at the same location.
355 // [OpenMP 5.2] Also allow iterator declared variables.
356 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
357 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
358 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
359 << getOpenMPDeclareMapperVarName();
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
364 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
365 Diag(Loc, diag::err_use_of_empty_using_if_exists);
366 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
367 return true;
370 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
371 AvoidPartialAvailabilityChecks, ClassReceiver);
373 DiagnoseUnusedOfDecl(*this, D, Loc);
375 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
377 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
378 if (getLangOpts().getFPEvalMethod() !=
379 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
380 PP.getLastFPEvalPragmaLocation().isValid() &&
381 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
382 Diag(D->getLocation(),
383 diag::err_type_available_only_in_default_eval_method)
384 << D->getName();
387 if (auto *VD = dyn_cast<ValueDecl>(D))
388 checkTypeSupport(VD->getType(), Loc, VD);
390 if (LangOpts.SYCLIsDevice ||
391 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
392 if (!Context.getTargetInfo().isTLSSupported())
393 if (const auto *VD = dyn_cast<VarDecl>(D))
394 if (VD->getTLSKind() != VarDecl::TLS_None)
395 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
398 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
399 !isUnevaluatedContext()) {
400 // C++ [expr.prim.req.nested] p3
401 // A local parameter shall only appear as an unevaluated operand
402 // (Clause 8) within the constraint-expression.
403 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
404 << D;
405 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
406 return true;
409 return false;
412 /// DiagnoseSentinelCalls - This routine checks whether a call or
413 /// message-send is to a declaration with the sentinel attribute, and
414 /// if so, it checks that the requirements of the sentinel are
415 /// satisfied.
416 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
417 ArrayRef<Expr *> Args) {
418 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
419 if (!attr)
420 return;
422 // The number of formal parameters of the declaration.
423 unsigned numFormalParams;
425 // The kind of declaration. This is also an index into a %select in
426 // the diagnostic.
427 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
429 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
430 numFormalParams = MD->param_size();
431 calleeType = CT_Method;
432 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
433 numFormalParams = FD->param_size();
434 calleeType = CT_Function;
435 } else if (isa<VarDecl>(D)) {
436 QualType type = cast<ValueDecl>(D)->getType();
437 const FunctionType *fn = nullptr;
438 if (const PointerType *ptr = type->getAs<PointerType>()) {
439 fn = ptr->getPointeeType()->getAs<FunctionType>();
440 if (!fn) return;
441 calleeType = CT_Function;
442 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
443 fn = ptr->getPointeeType()->castAs<FunctionType>();
444 calleeType = CT_Block;
445 } else {
446 return;
449 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
450 numFormalParams = proto->getNumParams();
451 } else {
452 numFormalParams = 0;
454 } else {
455 return;
458 // "nullPos" is the number of formal parameters at the end which
459 // effectively count as part of the variadic arguments. This is
460 // useful if you would prefer to not have *any* formal parameters,
461 // but the language forces you to have at least one.
462 unsigned nullPos = attr->getNullPos();
463 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
464 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
466 // The number of arguments which should follow the sentinel.
467 unsigned numArgsAfterSentinel = attr->getSentinel();
469 // If there aren't enough arguments for all the formal parameters,
470 // the sentinel, and the args after the sentinel, complain.
471 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
472 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
473 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
474 return;
477 // Otherwise, find the sentinel expression.
478 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
479 if (!sentinelExpr) return;
480 if (sentinelExpr->isValueDependent()) return;
481 if (Context.isSentinelNullExpr(sentinelExpr)) return;
483 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
484 // or 'NULL' if those are actually defined in the context. Only use
485 // 'nil' for ObjC methods, where it's much more likely that the
486 // variadic arguments form a list of object pointers.
487 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
488 std::string NullValue;
489 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
490 NullValue = "nil";
491 else if (getLangOpts().CPlusPlus11)
492 NullValue = "nullptr";
493 else if (PP.isMacroDefined("NULL"))
494 NullValue = "NULL";
495 else
496 NullValue = "(void*) 0";
498 if (MissingNilLoc.isInvalid())
499 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
500 else
501 Diag(MissingNilLoc, diag::warn_missing_sentinel)
502 << int(calleeType)
503 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
504 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
507 SourceRange Sema::getExprRange(Expr *E) const {
508 return E ? E->getSourceRange() : SourceRange();
511 //===----------------------------------------------------------------------===//
512 // Standard Promotions and Conversions
513 //===----------------------------------------------------------------------===//
515 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
516 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
517 // Handle any placeholder expressions which made it here.
518 if (E->hasPlaceholderType()) {
519 ExprResult result = CheckPlaceholderExpr(E);
520 if (result.isInvalid()) return ExprError();
521 E = result.get();
524 QualType Ty = E->getType();
525 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
527 if (Ty->isFunctionType()) {
528 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
529 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
530 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
531 return ExprError();
533 E = ImpCastExprToType(E, Context.getPointerType(Ty),
534 CK_FunctionToPointerDecay).get();
535 } else if (Ty->isArrayType()) {
536 // In C90 mode, arrays only promote to pointers if the array expression is
537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538 // type 'array of type' is converted to an expression that has type 'pointer
539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
540 // that has type 'array of type' ...". The relevant change is "an lvalue"
541 // (C90) to "an expression" (C99).
543 // C++ 4.2p1:
544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545 // T" can be converted to an rvalue of type "pointer to T".
547 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
548 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
549 CK_ArrayToPointerDecay);
550 if (Res.isInvalid())
551 return ExprError();
552 E = Res.get();
555 return E;
558 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
559 // Check to see if we are dereferencing a null pointer. If so,
560 // and if not volatile-qualified, this is undefined behavior that the
561 // optimizer will delete, so warn about it. People sometimes try to use this
562 // to get a deterministic trap and are surprised by clang's behavior. This
563 // only handles the pattern "*null", which is a very syntactic check.
564 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
565 if (UO && UO->getOpcode() == UO_Deref &&
566 UO->getSubExpr()->getType()->isPointerType()) {
567 const LangAS AS =
568 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
569 if ((!isTargetAddressSpace(AS) ||
570 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
571 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
572 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
573 !UO->getType().isVolatileQualified()) {
574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575 S.PDiag(diag::warn_indirection_through_null)
576 << UO->getSubExpr()->getSourceRange());
577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578 S.PDiag(diag::note_indirection_through_null));
583 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
584 SourceLocation AssignLoc,
585 const Expr* RHS) {
586 const ObjCIvarDecl *IV = OIRE->getDecl();
587 if (!IV)
588 return;
590 DeclarationName MemberName = IV->getDeclName();
591 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
592 if (!Member || !Member->isStr("isa"))
593 return;
595 const Expr *Base = OIRE->getBase();
596 QualType BaseType = Base->getType();
597 if (OIRE->isArrow())
598 BaseType = BaseType->getPointeeType();
599 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
600 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
601 ObjCInterfaceDecl *ClassDeclared = nullptr;
602 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
603 if (!ClassDeclared->getSuperClass()
604 && (*ClassDeclared->ivar_begin()) == IV) {
605 if (RHS) {
606 NamedDecl *ObjectSetClass =
607 S.LookupSingleName(S.TUScope,
608 &S.Context.Idents.get("object_setClass"),
609 SourceLocation(), S.LookupOrdinaryName);
610 if (ObjectSetClass) {
611 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
612 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
613 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
614 "object_setClass(")
615 << FixItHint::CreateReplacement(
616 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
617 << FixItHint::CreateInsertion(RHSLocEnd, ")");
619 else
620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
621 } else {
622 NamedDecl *ObjectGetClass =
623 S.LookupSingleName(S.TUScope,
624 &S.Context.Idents.get("object_getClass"),
625 SourceLocation(), S.LookupOrdinaryName);
626 if (ObjectGetClass)
627 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
628 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
629 "object_getClass(")
630 << FixItHint::CreateReplacement(
631 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
632 else
633 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
635 S.Diag(IV->getLocation(), diag::note_ivar_decl);
640 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
641 // Handle any placeholder expressions which made it here.
642 if (E->hasPlaceholderType()) {
643 ExprResult result = CheckPlaceholderExpr(E);
644 if (result.isInvalid()) return ExprError();
645 E = result.get();
648 // C++ [conv.lval]p1:
649 // A glvalue of a non-function, non-array type T can be
650 // converted to a prvalue.
651 if (!E->isGLValue()) return E;
653 QualType T = E->getType();
654 assert(!T.isNull() && "r-value conversion on typeless expression?");
656 // lvalue-to-rvalue conversion cannot be applied to function or array types.
657 if (T->isFunctionType() || T->isArrayType())
658 return E;
660 // We don't want to throw lvalue-to-rvalue casts on top of
661 // expressions of certain types in C++.
662 if (getLangOpts().CPlusPlus &&
663 (E->getType() == Context.OverloadTy ||
664 T->isDependentType() ||
665 T->isRecordType()))
666 return E;
668 // The C standard is actually really unclear on this point, and
669 // DR106 tells us what the result should be but not why. It's
670 // generally best to say that void types just doesn't undergo
671 // lvalue-to-rvalue at all. Note that expressions of unqualified
672 // 'void' type are never l-values, but qualified void can be.
673 if (T->isVoidType())
674 return E;
676 // OpenCL usually rejects direct accesses to values of 'half' type.
677 if (getLangOpts().OpenCL &&
678 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
679 T->isHalfType()) {
680 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
681 << 0 << T;
682 return ExprError();
685 CheckForNullPointerDereference(*this, E);
686 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
687 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
688 &Context.Idents.get("object_getClass"),
689 SourceLocation(), LookupOrdinaryName);
690 if (ObjectGetClass)
691 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
692 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
693 << FixItHint::CreateReplacement(
694 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
695 else
696 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
698 else if (const ObjCIvarRefExpr *OIRE =
699 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
700 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
702 // C++ [conv.lval]p1:
703 // [...] If T is a non-class type, the type of the prvalue is the
704 // cv-unqualified version of T. Otherwise, the type of the
705 // rvalue is T.
707 // C99 6.3.2.1p2:
708 // If the lvalue has qualified type, the value has the unqualified
709 // version of the type of the lvalue; otherwise, the value has the
710 // type of the lvalue.
711 if (T.hasQualifiers())
712 T = T.getUnqualifiedType();
714 // Under the MS ABI, lock down the inheritance model now.
715 if (T->isMemberPointerType() &&
716 Context.getTargetInfo().getCXXABI().isMicrosoft())
717 (void)isCompleteType(E->getExprLoc(), T);
719 ExprResult Res = CheckLValueToRValueConversionOperand(E);
720 if (Res.isInvalid())
721 return Res;
722 E = Res.get();
724 // Loading a __weak object implicitly retains the value, so we need a cleanup to
725 // balance that.
726 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
727 Cleanup.setExprNeedsCleanups(true);
729 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
730 Cleanup.setExprNeedsCleanups(true);
732 // C++ [conv.lval]p3:
733 // If T is cv std::nullptr_t, the result is a null pointer constant.
734 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
735 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
736 CurFPFeatureOverrides());
738 // C11 6.3.2.1p2:
739 // ... if the lvalue has atomic type, the value has the non-atomic version
740 // of the type of the lvalue ...
741 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
742 T = Atomic->getValueType().getUnqualifiedType();
743 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
744 nullptr, VK_PRValue, FPOptionsOverride());
747 return Res;
750 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
751 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
752 if (Res.isInvalid())
753 return ExprError();
754 Res = DefaultLvalueConversion(Res.get());
755 if (Res.isInvalid())
756 return ExprError();
757 return Res;
760 /// CallExprUnaryConversions - a special case of an unary conversion
761 /// performed on a function designator of a call expression.
762 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
763 QualType Ty = E->getType();
764 ExprResult Res = E;
765 // Only do implicit cast for a function type, but not for a pointer
766 // to function type.
767 if (Ty->isFunctionType()) {
768 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
769 CK_FunctionToPointerDecay);
770 if (Res.isInvalid())
771 return ExprError();
773 Res = DefaultLvalueConversion(Res.get());
774 if (Res.isInvalid())
775 return ExprError();
776 return Res.get();
779 /// UsualUnaryConversions - Performs various conversions that are common to most
780 /// operators (C99 6.3). The conversions of array and function types are
781 /// sometimes suppressed. For example, the array->pointer conversion doesn't
782 /// apply if the array is an argument to the sizeof or address (&) operators.
783 /// In these instances, this routine should *not* be called.
784 ExprResult Sema::UsualUnaryConversions(Expr *E) {
785 // First, convert to an r-value.
786 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
787 if (Res.isInvalid())
788 return ExprError();
789 E = Res.get();
791 QualType Ty = E->getType();
792 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
794 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
795 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
796 (getLangOpts().getFPEvalMethod() !=
797 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
798 PP.getLastFPEvalPragmaLocation().isValid())) {
799 switch (EvalMethod) {
800 default:
801 llvm_unreachable("Unrecognized float evaluation method");
802 break;
803 case LangOptions::FEM_UnsetOnCommandLine:
804 llvm_unreachable("Float evaluation method should be set by now");
805 break;
806 case LangOptions::FEM_Double:
807 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
808 // Widen the expression to double.
809 return Ty->isComplexType()
810 ? ImpCastExprToType(E,
811 Context.getComplexType(Context.DoubleTy),
812 CK_FloatingComplexCast)
813 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
814 break;
815 case LangOptions::FEM_Extended:
816 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
817 // Widen the expression to long double.
818 return Ty->isComplexType()
819 ? ImpCastExprToType(
820 E, Context.getComplexType(Context.LongDoubleTy),
821 CK_FloatingComplexCast)
822 : ImpCastExprToType(E, Context.LongDoubleTy,
823 CK_FloatingCast);
824 break;
828 // Half FP have to be promoted to float unless it is natively supported
829 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
830 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
832 // Try to perform integral promotions if the object has a theoretically
833 // promotable type.
834 if (Ty->isIntegralOrUnscopedEnumerationType()) {
835 // C99 6.3.1.1p2:
837 // The following may be used in an expression wherever an int or
838 // unsigned int may be used:
839 // - an object or expression with an integer type whose integer
840 // conversion rank is less than or equal to the rank of int
841 // and unsigned int.
842 // - A bit-field of type _Bool, int, signed int, or unsigned int.
844 // If an int can represent all values of the original type, the
845 // value is converted to an int; otherwise, it is converted to an
846 // unsigned int. These are called the integer promotions. All
847 // other types are unchanged by the integer promotions.
849 QualType PTy = Context.isPromotableBitField(E);
850 if (!PTy.isNull()) {
851 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
852 return E;
854 if (Context.isPromotableIntegerType(Ty)) {
855 QualType PT = Context.getPromotedIntegerType(Ty);
856 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
857 return E;
860 return E;
863 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
864 /// do not have a prototype. Arguments that have type float or __fp16
865 /// are promoted to double. All other argument types are converted by
866 /// UsualUnaryConversions().
867 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
868 QualType Ty = E->getType();
869 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
871 ExprResult Res = UsualUnaryConversions(E);
872 if (Res.isInvalid())
873 return ExprError();
874 E = Res.get();
876 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
877 // promote to double.
878 // Note that default argument promotion applies only to float (and
879 // half/fp16); it does not apply to _Float16.
880 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
881 if (BTy && (BTy->getKind() == BuiltinType::Half ||
882 BTy->getKind() == BuiltinType::Float)) {
883 if (getLangOpts().OpenCL &&
884 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
885 if (BTy->getKind() == BuiltinType::Half) {
886 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
888 } else {
889 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
892 if (BTy &&
893 getLangOpts().getExtendIntArgs() ==
894 LangOptions::ExtendArgsKind::ExtendTo64 &&
895 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
896 Context.getTypeSizeInChars(BTy) <
897 Context.getTypeSizeInChars(Context.LongLongTy)) {
898 E = (Ty->isUnsignedIntegerType())
899 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
900 .get()
901 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
902 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
903 "Unexpected typesize for LongLongTy");
906 // C++ performs lvalue-to-rvalue conversion as a default argument
907 // promotion, even on class types, but note:
908 // C++11 [conv.lval]p2:
909 // When an lvalue-to-rvalue conversion occurs in an unevaluated
910 // operand or a subexpression thereof the value contained in the
911 // referenced object is not accessed. Otherwise, if the glvalue
912 // has a class type, the conversion copy-initializes a temporary
913 // of type T from the glvalue and the result of the conversion
914 // is a prvalue for the temporary.
915 // FIXME: add some way to gate this entire thing for correctness in
916 // potentially potentially evaluated contexts.
917 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
918 ExprResult Temp = PerformCopyInitialization(
919 InitializedEntity::InitializeTemporary(E->getType()),
920 E->getExprLoc(), E);
921 if (Temp.isInvalid())
922 return ExprError();
923 E = Temp.get();
926 return E;
929 /// Determine the degree of POD-ness for an expression.
930 /// Incomplete types are considered POD, since this check can be performed
931 /// when we're in an unevaluated context.
932 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
933 if (Ty->isIncompleteType()) {
934 // C++11 [expr.call]p7:
935 // After these conversions, if the argument does not have arithmetic,
936 // enumeration, pointer, pointer to member, or class type, the program
937 // is ill-formed.
939 // Since we've already performed array-to-pointer and function-to-pointer
940 // decay, the only such type in C++ is cv void. This also handles
941 // initializer lists as variadic arguments.
942 if (Ty->isVoidType())
943 return VAK_Invalid;
945 if (Ty->isObjCObjectType())
946 return VAK_Invalid;
947 return VAK_Valid;
950 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
951 return VAK_Invalid;
953 if (Context.getTargetInfo().getTriple().isWasm() &&
954 Ty.isWebAssemblyReferenceType()) {
955 return VAK_Invalid;
958 if (Ty.isCXX98PODType(Context))
959 return VAK_Valid;
961 // C++11 [expr.call]p7:
962 // Passing a potentially-evaluated argument of class type (Clause 9)
963 // having a non-trivial copy constructor, a non-trivial move constructor,
964 // or a non-trivial destructor, with no corresponding parameter,
965 // is conditionally-supported with implementation-defined semantics.
966 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
967 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
968 if (!Record->hasNonTrivialCopyConstructor() &&
969 !Record->hasNonTrivialMoveConstructor() &&
970 !Record->hasNonTrivialDestructor())
971 return VAK_ValidInCXX11;
973 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
974 return VAK_Valid;
976 if (Ty->isObjCObjectType())
977 return VAK_Invalid;
979 if (getLangOpts().MSVCCompat)
980 return VAK_MSVCUndefined;
982 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
983 // permitted to reject them. We should consider doing so.
984 return VAK_Undefined;
987 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
988 // Don't allow one to pass an Objective-C interface to a vararg.
989 const QualType &Ty = E->getType();
990 VarArgKind VAK = isValidVarArgType(Ty);
992 // Complain about passing non-POD types through varargs.
993 switch (VAK) {
994 case VAK_ValidInCXX11:
995 DiagRuntimeBehavior(
996 E->getBeginLoc(), nullptr,
997 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
998 [[fallthrough]];
999 case VAK_Valid:
1000 if (Ty->isRecordType()) {
1001 // This is unlikely to be what the user intended. If the class has a
1002 // 'c_str' member function, the user probably meant to call that.
1003 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1004 PDiag(diag::warn_pass_class_arg_to_vararg)
1005 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1007 break;
1009 case VAK_Undefined:
1010 case VAK_MSVCUndefined:
1011 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1012 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1013 << getLangOpts().CPlusPlus11 << Ty << CT);
1014 break;
1016 case VAK_Invalid:
1017 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1018 Diag(E->getBeginLoc(),
1019 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1020 << Ty << CT;
1021 else if (Ty->isObjCObjectType())
1022 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1023 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1024 << Ty << CT);
1025 else
1026 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1027 << isa<InitListExpr>(E) << Ty << CT;
1028 break;
1032 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1033 /// will create a trap if the resulting type is not a POD type.
1034 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1035 FunctionDecl *FDecl) {
1036 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1037 // Strip the unbridged-cast placeholder expression off, if applicable.
1038 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1039 (CT == VariadicMethod ||
1040 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1041 E = stripARCUnbridgedCast(E);
1043 // Otherwise, do normal placeholder checking.
1044 } else {
1045 ExprResult ExprRes = CheckPlaceholderExpr(E);
1046 if (ExprRes.isInvalid())
1047 return ExprError();
1048 E = ExprRes.get();
1052 ExprResult ExprRes = DefaultArgumentPromotion(E);
1053 if (ExprRes.isInvalid())
1054 return ExprError();
1056 // Copy blocks to the heap.
1057 if (ExprRes.get()->getType()->isBlockPointerType())
1058 maybeExtendBlockObject(ExprRes);
1060 E = ExprRes.get();
1062 // Diagnostics regarding non-POD argument types are
1063 // emitted along with format string checking in Sema::CheckFunctionCall().
1064 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1065 // Turn this into a trap.
1066 CXXScopeSpec SS;
1067 SourceLocation TemplateKWLoc;
1068 UnqualifiedId Name;
1069 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1070 E->getBeginLoc());
1071 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1072 /*HasTrailingLParen=*/true,
1073 /*IsAddressOfOperand=*/false);
1074 if (TrapFn.isInvalid())
1075 return ExprError();
1077 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1078 std::nullopt, E->getEndLoc());
1079 if (Call.isInvalid())
1080 return ExprError();
1082 ExprResult Comma =
1083 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1084 if (Comma.isInvalid())
1085 return ExprError();
1086 return Comma.get();
1089 if (!getLangOpts().CPlusPlus &&
1090 RequireCompleteType(E->getExprLoc(), E->getType(),
1091 diag::err_call_incomplete_argument))
1092 return ExprError();
1094 return E;
1097 /// Converts an integer to complex float type. Helper function of
1098 /// UsualArithmeticConversions()
1100 /// \return false if the integer expression is an integer type and is
1101 /// successfully converted to the complex type.
1102 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1103 ExprResult &ComplexExpr,
1104 QualType IntTy,
1105 QualType ComplexTy,
1106 bool SkipCast) {
1107 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1108 if (SkipCast) return false;
1109 if (IntTy->isIntegerType()) {
1110 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1111 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1112 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1113 CK_FloatingRealToComplex);
1114 } else {
1115 assert(IntTy->isComplexIntegerType());
1116 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1117 CK_IntegralComplexToFloatingComplex);
1119 return false;
1122 // This handles complex/complex, complex/float, or float/complex.
1123 // When both operands are complex, the shorter operand is converted to the
1124 // type of the longer, and that is the type of the result. This corresponds
1125 // to what is done when combining two real floating-point operands.
1126 // The fun begins when size promotion occur across type domains.
1127 // From H&S 6.3.4: When one operand is complex and the other is a real
1128 // floating-point type, the less precise type is converted, within it's
1129 // real or complex domain, to the precision of the other type. For example,
1130 // when combining a "long double" with a "double _Complex", the
1131 // "double _Complex" is promoted to "long double _Complex".
1132 static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1133 QualType ShorterType,
1134 QualType LongerType,
1135 bool PromotePrecision) {
1136 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1137 QualType Result =
1138 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1140 if (PromotePrecision) {
1141 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1142 Shorter =
1143 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1144 } else {
1145 if (LongerIsComplex)
1146 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1147 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1150 return Result;
1153 /// Handle arithmetic conversion with complex types. Helper function of
1154 /// UsualArithmeticConversions()
1155 static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1156 ExprResult &RHS, QualType LHSType,
1157 QualType RHSType, bool IsCompAssign) {
1158 // if we have an integer operand, the result is the complex type.
1159 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1160 /*SkipCast=*/false))
1161 return LHSType;
1162 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1163 /*SkipCast=*/IsCompAssign))
1164 return RHSType;
1166 // Compute the rank of the two types, regardless of whether they are complex.
1167 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1168 if (Order < 0)
1169 // Promote the precision of the LHS if not an assignment.
1170 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1171 /*PromotePrecision=*/!IsCompAssign);
1172 // Promote the precision of the RHS unless it is already the same as the LHS.
1173 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1174 /*PromotePrecision=*/Order > 0);
1177 /// Handle arithmetic conversion from integer to float. Helper function
1178 /// of UsualArithmeticConversions()
1179 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1180 ExprResult &IntExpr,
1181 QualType FloatTy, QualType IntTy,
1182 bool ConvertFloat, bool ConvertInt) {
1183 if (IntTy->isIntegerType()) {
1184 if (ConvertInt)
1185 // Convert intExpr to the lhs floating point type.
1186 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1187 CK_IntegralToFloating);
1188 return FloatTy;
1191 // Convert both sides to the appropriate complex float.
1192 assert(IntTy->isComplexIntegerType());
1193 QualType result = S.Context.getComplexType(FloatTy);
1195 // _Complex int -> _Complex float
1196 if (ConvertInt)
1197 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1198 CK_IntegralComplexToFloatingComplex);
1200 // float -> _Complex float
1201 if (ConvertFloat)
1202 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1203 CK_FloatingRealToComplex);
1205 return result;
1208 /// Handle arithmethic conversion with floating point types. Helper
1209 /// function of UsualArithmeticConversions()
1210 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1211 ExprResult &RHS, QualType LHSType,
1212 QualType RHSType, bool IsCompAssign) {
1213 bool LHSFloat = LHSType->isRealFloatingType();
1214 bool RHSFloat = RHSType->isRealFloatingType();
1216 // N1169 4.1.4: If one of the operands has a floating type and the other
1217 // operand has a fixed-point type, the fixed-point operand
1218 // is converted to the floating type [...]
1219 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1220 if (LHSFloat)
1221 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1222 else if (!IsCompAssign)
1223 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1224 return LHSFloat ? LHSType : RHSType;
1227 // If we have two real floating types, convert the smaller operand
1228 // to the bigger result.
1229 if (LHSFloat && RHSFloat) {
1230 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1231 if (order > 0) {
1232 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1233 return LHSType;
1236 assert(order < 0 && "illegal float comparison");
1237 if (!IsCompAssign)
1238 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1239 return RHSType;
1242 if (LHSFloat) {
1243 // Half FP has to be promoted to float unless it is natively supported
1244 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1245 LHSType = S.Context.FloatTy;
1247 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1248 /*ConvertFloat=*/!IsCompAssign,
1249 /*ConvertInt=*/ true);
1251 assert(RHSFloat);
1252 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1253 /*ConvertFloat=*/ true,
1254 /*ConvertInt=*/!IsCompAssign);
1257 /// Diagnose attempts to convert between __float128, __ibm128 and
1258 /// long double if there is no support for such conversion.
1259 /// Helper function of UsualArithmeticConversions().
1260 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1261 QualType RHSType) {
1262 // No issue if either is not a floating point type.
1263 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1264 return false;
1266 // No issue if both have the same 128-bit float semantics.
1267 auto *LHSComplex = LHSType->getAs<ComplexType>();
1268 auto *RHSComplex = RHSType->getAs<ComplexType>();
1270 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1271 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1273 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1274 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1276 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1277 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1278 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1279 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1280 return false;
1282 return true;
1285 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1287 namespace {
1288 /// These helper callbacks are placed in an anonymous namespace to
1289 /// permit their use as function template parameters.
1290 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1291 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1294 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1295 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1296 CK_IntegralComplexCast);
1300 /// Handle integer arithmetic conversions. Helper function of
1301 /// UsualArithmeticConversions()
1302 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1303 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1304 ExprResult &RHS, QualType LHSType,
1305 QualType RHSType, bool IsCompAssign) {
1306 // The rules for this case are in C99 6.3.1.8
1307 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1308 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1309 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1310 if (LHSSigned == RHSSigned) {
1311 // Same signedness; use the higher-ranked type
1312 if (order >= 0) {
1313 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1314 return LHSType;
1315 } else if (!IsCompAssign)
1316 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1317 return RHSType;
1318 } else if (order != (LHSSigned ? 1 : -1)) {
1319 // The unsigned type has greater than or equal rank to the
1320 // signed type, so use the unsigned type
1321 if (RHSSigned) {
1322 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1323 return LHSType;
1324 } else if (!IsCompAssign)
1325 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1326 return RHSType;
1327 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1328 // The two types are different widths; if we are here, that
1329 // means the signed type is larger than the unsigned type, so
1330 // use the signed type.
1331 if (LHSSigned) {
1332 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1333 return LHSType;
1334 } else if (!IsCompAssign)
1335 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1336 return RHSType;
1337 } else {
1338 // The signed type is higher-ranked than the unsigned type,
1339 // but isn't actually any bigger (like unsigned int and long
1340 // on most 32-bit systems). Use the unsigned type corresponding
1341 // to the signed type.
1342 QualType result =
1343 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1344 RHS = (*doRHSCast)(S, RHS.get(), result);
1345 if (!IsCompAssign)
1346 LHS = (*doLHSCast)(S, LHS.get(), result);
1347 return result;
1351 /// Handle conversions with GCC complex int extension. Helper function
1352 /// of UsualArithmeticConversions()
1353 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1354 ExprResult &RHS, QualType LHSType,
1355 QualType RHSType,
1356 bool IsCompAssign) {
1357 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1358 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1360 if (LHSComplexInt && RHSComplexInt) {
1361 QualType LHSEltType = LHSComplexInt->getElementType();
1362 QualType RHSEltType = RHSComplexInt->getElementType();
1363 QualType ScalarType =
1364 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1365 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1367 return S.Context.getComplexType(ScalarType);
1370 if (LHSComplexInt) {
1371 QualType LHSEltType = LHSComplexInt->getElementType();
1372 QualType ScalarType =
1373 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1374 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1375 QualType ComplexType = S.Context.getComplexType(ScalarType);
1376 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1377 CK_IntegralRealToComplex);
1379 return ComplexType;
1382 assert(RHSComplexInt);
1384 QualType RHSEltType = RHSComplexInt->getElementType();
1385 QualType ScalarType =
1386 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1387 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1388 QualType ComplexType = S.Context.getComplexType(ScalarType);
1390 if (!IsCompAssign)
1391 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1392 CK_IntegralRealToComplex);
1393 return ComplexType;
1396 /// Return the rank of a given fixed point or integer type. The value itself
1397 /// doesn't matter, but the values must be increasing with proper increasing
1398 /// rank as described in N1169 4.1.1.
1399 static unsigned GetFixedPointRank(QualType Ty) {
1400 const auto *BTy = Ty->getAs<BuiltinType>();
1401 assert(BTy && "Expected a builtin type.");
1403 switch (BTy->getKind()) {
1404 case BuiltinType::ShortFract:
1405 case BuiltinType::UShortFract:
1406 case BuiltinType::SatShortFract:
1407 case BuiltinType::SatUShortFract:
1408 return 1;
1409 case BuiltinType::Fract:
1410 case BuiltinType::UFract:
1411 case BuiltinType::SatFract:
1412 case BuiltinType::SatUFract:
1413 return 2;
1414 case BuiltinType::LongFract:
1415 case BuiltinType::ULongFract:
1416 case BuiltinType::SatLongFract:
1417 case BuiltinType::SatULongFract:
1418 return 3;
1419 case BuiltinType::ShortAccum:
1420 case BuiltinType::UShortAccum:
1421 case BuiltinType::SatShortAccum:
1422 case BuiltinType::SatUShortAccum:
1423 return 4;
1424 case BuiltinType::Accum:
1425 case BuiltinType::UAccum:
1426 case BuiltinType::SatAccum:
1427 case BuiltinType::SatUAccum:
1428 return 5;
1429 case BuiltinType::LongAccum:
1430 case BuiltinType::ULongAccum:
1431 case BuiltinType::SatLongAccum:
1432 case BuiltinType::SatULongAccum:
1433 return 6;
1434 default:
1435 if (BTy->isInteger())
1436 return 0;
1437 llvm_unreachable("Unexpected fixed point or integer type");
1441 /// handleFixedPointConversion - Fixed point operations between fixed
1442 /// point types and integers or other fixed point types do not fall under
1443 /// usual arithmetic conversion since these conversions could result in loss
1444 /// of precsision (N1169 4.1.4). These operations should be calculated with
1445 /// the full precision of their result type (N1169 4.1.6.2.1).
1446 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1447 QualType RHSTy) {
1448 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1449 "Expected at least one of the operands to be a fixed point type");
1450 assert((LHSTy->isFixedPointOrIntegerType() ||
1451 RHSTy->isFixedPointOrIntegerType()) &&
1452 "Special fixed point arithmetic operation conversions are only "
1453 "applied to ints or other fixed point types");
1455 // If one operand has signed fixed-point type and the other operand has
1456 // unsigned fixed-point type, then the unsigned fixed-point operand is
1457 // converted to its corresponding signed fixed-point type and the resulting
1458 // type is the type of the converted operand.
1459 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1460 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1461 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1462 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1464 // The result type is the type with the highest rank, whereby a fixed-point
1465 // conversion rank is always greater than an integer conversion rank; if the
1466 // type of either of the operands is a saturating fixedpoint type, the result
1467 // type shall be the saturating fixed-point type corresponding to the type
1468 // with the highest rank; the resulting value is converted (taking into
1469 // account rounding and overflow) to the precision of the resulting type.
1470 // Same ranks between signed and unsigned types are resolved earlier, so both
1471 // types are either signed or both unsigned at this point.
1472 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1473 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1475 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1477 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1478 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1480 return ResultTy;
1483 /// Check that the usual arithmetic conversions can be performed on this pair of
1484 /// expressions that might be of enumeration type.
1485 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1486 SourceLocation Loc,
1487 Sema::ArithConvKind ACK) {
1488 // C++2a [expr.arith.conv]p1:
1489 // If one operand is of enumeration type and the other operand is of a
1490 // different enumeration type or a floating-point type, this behavior is
1491 // deprecated ([depr.arith.conv.enum]).
1493 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1494 // Eventually we will presumably reject these cases (in C++23 onwards?).
1495 QualType L = LHS->getType(), R = RHS->getType();
1496 bool LEnum = L->isUnscopedEnumerationType(),
1497 REnum = R->isUnscopedEnumerationType();
1498 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1499 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1500 (REnum && L->isFloatingType())) {
1501 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1502 ? diag::warn_arith_conv_enum_float_cxx20
1503 : diag::warn_arith_conv_enum_float)
1504 << LHS->getSourceRange() << RHS->getSourceRange()
1505 << (int)ACK << LEnum << L << R;
1506 } else if (!IsCompAssign && LEnum && REnum &&
1507 !S.Context.hasSameUnqualifiedType(L, R)) {
1508 unsigned DiagID;
1509 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1510 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1511 // If either enumeration type is unnamed, it's less likely that the
1512 // user cares about this, but this situation is still deprecated in
1513 // C++2a. Use a different warning group.
1514 DiagID = S.getLangOpts().CPlusPlus20
1515 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1516 : diag::warn_arith_conv_mixed_anon_enum_types;
1517 } else if (ACK == Sema::ACK_Conditional) {
1518 // Conditional expressions are separated out because they have
1519 // historically had a different warning flag.
1520 DiagID = S.getLangOpts().CPlusPlus20
1521 ? diag::warn_conditional_mixed_enum_types_cxx20
1522 : diag::warn_conditional_mixed_enum_types;
1523 } else if (ACK == Sema::ACK_Comparison) {
1524 // Comparison expressions are separated out because they have
1525 // historically had a different warning flag.
1526 DiagID = S.getLangOpts().CPlusPlus20
1527 ? diag::warn_comparison_mixed_enum_types_cxx20
1528 : diag::warn_comparison_mixed_enum_types;
1529 } else {
1530 DiagID = S.getLangOpts().CPlusPlus20
1531 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1532 : diag::warn_arith_conv_mixed_enum_types;
1534 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1535 << (int)ACK << L << R;
1539 /// UsualArithmeticConversions - Performs various conversions that are common to
1540 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1541 /// routine returns the first non-arithmetic type found. The client is
1542 /// responsible for emitting appropriate error diagnostics.
1543 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1544 SourceLocation Loc,
1545 ArithConvKind ACK) {
1546 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1548 if (ACK != ACK_CompAssign) {
1549 LHS = UsualUnaryConversions(LHS.get());
1550 if (LHS.isInvalid())
1551 return QualType();
1554 RHS = UsualUnaryConversions(RHS.get());
1555 if (RHS.isInvalid())
1556 return QualType();
1558 // For conversion purposes, we ignore any qualifiers.
1559 // For example, "const float" and "float" are equivalent.
1560 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1561 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1563 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1564 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1565 LHSType = AtomicLHS->getValueType();
1567 // If both types are identical, no conversion is needed.
1568 if (Context.hasSameType(LHSType, RHSType))
1569 return Context.getCommonSugaredType(LHSType, RHSType);
1571 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1572 // The caller can deal with this (e.g. pointer + int).
1573 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1574 return QualType();
1576 // Apply unary and bitfield promotions to the LHS's type.
1577 QualType LHSUnpromotedType = LHSType;
1578 if (Context.isPromotableIntegerType(LHSType))
1579 LHSType = Context.getPromotedIntegerType(LHSType);
1580 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1581 if (!LHSBitfieldPromoteTy.isNull())
1582 LHSType = LHSBitfieldPromoteTy;
1583 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1584 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1586 // If both types are identical, no conversion is needed.
1587 if (Context.hasSameType(LHSType, RHSType))
1588 return Context.getCommonSugaredType(LHSType, RHSType);
1590 // At this point, we have two different arithmetic types.
1592 // Diagnose attempts to convert between __ibm128, __float128 and long double
1593 // where such conversions currently can't be handled.
1594 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1595 return QualType();
1597 // Handle complex types first (C99 6.3.1.8p1).
1598 if (LHSType->isComplexType() || RHSType->isComplexType())
1599 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1600 ACK == ACK_CompAssign);
1602 // Now handle "real" floating types (i.e. float, double, long double).
1603 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1604 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1605 ACK == ACK_CompAssign);
1607 // Handle GCC complex int extension.
1608 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1609 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1610 ACK == ACK_CompAssign);
1612 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1613 return handleFixedPointConversion(*this, LHSType, RHSType);
1615 // Finally, we have two differing integer types.
1616 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1617 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1620 //===----------------------------------------------------------------------===//
1621 // Semantic Analysis for various Expression Types
1622 //===----------------------------------------------------------------------===//
1625 ExprResult Sema::ActOnGenericSelectionExpr(
1626 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1627 bool PredicateIsExpr, void *ControllingExprOrType,
1628 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1629 unsigned NumAssocs = ArgTypes.size();
1630 assert(NumAssocs == ArgExprs.size());
1632 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1633 for (unsigned i = 0; i < NumAssocs; ++i) {
1634 if (ArgTypes[i])
1635 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1636 else
1637 Types[i] = nullptr;
1640 // If we have a controlling type, we need to convert it from a parsed type
1641 // into a semantic type and then pass that along.
1642 if (!PredicateIsExpr) {
1643 TypeSourceInfo *ControllingType;
1644 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1645 &ControllingType);
1646 assert(ControllingType && "couldn't get the type out of the parser");
1647 ControllingExprOrType = ControllingType;
1650 ExprResult ER = CreateGenericSelectionExpr(
1651 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1652 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1653 delete [] Types;
1654 return ER;
1657 ExprResult Sema::CreateGenericSelectionExpr(
1658 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1659 bool PredicateIsExpr, void *ControllingExprOrType,
1660 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
1661 unsigned NumAssocs = Types.size();
1662 assert(NumAssocs == Exprs.size());
1663 assert(ControllingExprOrType &&
1664 "Must have either a controlling expression or a controlling type");
1666 Expr *ControllingExpr = nullptr;
1667 TypeSourceInfo *ControllingType = nullptr;
1668 if (PredicateIsExpr) {
1669 // Decay and strip qualifiers for the controlling expression type, and
1670 // handle placeholder type replacement. See committee discussion from WG14
1671 // DR423.
1672 EnterExpressionEvaluationContext Unevaluated(
1673 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1674 ExprResult R = DefaultFunctionArrayLvalueConversion(
1675 reinterpret_cast<Expr *>(ControllingExprOrType));
1676 if (R.isInvalid())
1677 return ExprError();
1678 ControllingExpr = R.get();
1679 } else {
1680 // The extension form uses the type directly rather than converting it.
1681 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1682 if (!ControllingType)
1683 return ExprError();
1686 bool TypeErrorFound = false,
1687 IsResultDependent = ControllingExpr
1688 ? ControllingExpr->isTypeDependent()
1689 : ControllingType->getType()->isDependentType(),
1690 ContainsUnexpandedParameterPack =
1691 ControllingExpr
1692 ? ControllingExpr->containsUnexpandedParameterPack()
1693 : ControllingType->getType()->containsUnexpandedParameterPack();
1695 // The controlling expression is an unevaluated operand, so side effects are
1696 // likely unintended.
1697 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1698 ControllingExpr->HasSideEffects(Context, false))
1699 Diag(ControllingExpr->getExprLoc(),
1700 diag::warn_side_effects_unevaluated_context);
1702 for (unsigned i = 0; i < NumAssocs; ++i) {
1703 if (Exprs[i]->containsUnexpandedParameterPack())
1704 ContainsUnexpandedParameterPack = true;
1706 if (Types[i]) {
1707 if (Types[i]->getType()->containsUnexpandedParameterPack())
1708 ContainsUnexpandedParameterPack = true;
1710 if (Types[i]->getType()->isDependentType()) {
1711 IsResultDependent = true;
1712 } else {
1713 // We relax the restriction on use of incomplete types and non-object
1714 // types with the type-based extension of _Generic. Allowing incomplete
1715 // objects means those can be used as "tags" for a type-safe way to map
1716 // to a value. Similarly, matching on function types rather than
1717 // function pointer types can be useful. However, the restriction on VM
1718 // types makes sense to retain as there are open questions about how
1719 // the selection can be made at compile time.
1721 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1722 // complete object type other than a variably modified type."
1723 unsigned D = 0;
1724 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1725 D = diag::err_assoc_type_incomplete;
1726 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1727 D = diag::err_assoc_type_nonobject;
1728 else if (Types[i]->getType()->isVariablyModifiedType())
1729 D = diag::err_assoc_type_variably_modified;
1730 else if (ControllingExpr) {
1731 // Because the controlling expression undergoes lvalue conversion,
1732 // array conversion, and function conversion, an association which is
1733 // of array type, function type, or is qualified can never be
1734 // reached. We will warn about this so users are less surprised by
1735 // the unreachable association. However, we don't have to handle
1736 // function types; that's not an object type, so it's handled above.
1738 // The logic is somewhat different for C++ because C++ has different
1739 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1740 // If T is a non-class type, the type of the prvalue is the cv-
1741 // unqualified version of T. Otherwise, the type of the prvalue is T.
1742 // The result of these rules is that all qualified types in an
1743 // association in C are unreachable, and in C++, only qualified non-
1744 // class types are unreachable.
1746 // NB: this does not apply when the first operand is a type rather
1747 // than an expression, because the type form does not undergo
1748 // conversion.
1749 unsigned Reason = 0;
1750 QualType QT = Types[i]->getType();
1751 if (QT->isArrayType())
1752 Reason = 1;
1753 else if (QT.hasQualifiers() &&
1754 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1755 Reason = 2;
1757 if (Reason)
1758 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1759 diag::warn_unreachable_association)
1760 << QT << (Reason - 1);
1763 if (D != 0) {
1764 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1765 << Types[i]->getTypeLoc().getSourceRange()
1766 << Types[i]->getType();
1767 TypeErrorFound = true;
1770 // C11 6.5.1.1p2 "No two generic associations in the same generic
1771 // selection shall specify compatible types."
1772 for (unsigned j = i+1; j < NumAssocs; ++j)
1773 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1774 Context.typesAreCompatible(Types[i]->getType(),
1775 Types[j]->getType())) {
1776 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1777 diag::err_assoc_compatible_types)
1778 << Types[j]->getTypeLoc().getSourceRange()
1779 << Types[j]->getType()
1780 << Types[i]->getType();
1781 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1782 diag::note_compat_assoc)
1783 << Types[i]->getTypeLoc().getSourceRange()
1784 << Types[i]->getType();
1785 TypeErrorFound = true;
1790 if (TypeErrorFound)
1791 return ExprError();
1793 // If we determined that the generic selection is result-dependent, don't
1794 // try to compute the result expression.
1795 if (IsResultDependent) {
1796 if (ControllingExpr)
1797 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1798 Types, Exprs, DefaultLoc, RParenLoc,
1799 ContainsUnexpandedParameterPack);
1800 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1801 Exprs, DefaultLoc, RParenLoc,
1802 ContainsUnexpandedParameterPack);
1805 SmallVector<unsigned, 1> CompatIndices;
1806 unsigned DefaultIndex = -1U;
1807 // Look at the canonical type of the controlling expression in case it was a
1808 // deduced type like __auto_type. However, when issuing diagnostics, use the
1809 // type the user wrote in source rather than the canonical one.
1810 for (unsigned i = 0; i < NumAssocs; ++i) {
1811 if (!Types[i])
1812 DefaultIndex = i;
1813 else if (ControllingExpr &&
1814 Context.typesAreCompatible(
1815 ControllingExpr->getType().getCanonicalType(),
1816 Types[i]->getType()))
1817 CompatIndices.push_back(i);
1818 else if (ControllingType &&
1819 Context.typesAreCompatible(
1820 ControllingType->getType().getCanonicalType(),
1821 Types[i]->getType()))
1822 CompatIndices.push_back(i);
1825 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1826 TypeSourceInfo *ControllingType) {
1827 // We strip parens here because the controlling expression is typically
1828 // parenthesized in macro definitions.
1829 if (ControllingExpr)
1830 ControllingExpr = ControllingExpr->IgnoreParens();
1832 SourceRange SR = ControllingExpr
1833 ? ControllingExpr->getSourceRange()
1834 : ControllingType->getTypeLoc().getSourceRange();
1835 QualType QT = ControllingExpr ? ControllingExpr->getType()
1836 : ControllingType->getType();
1838 return std::make_pair(SR, QT);
1841 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1842 // type compatible with at most one of the types named in its generic
1843 // association list."
1844 if (CompatIndices.size() > 1) {
1845 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1846 SourceRange SR = P.first;
1847 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1848 << SR << P.second << (unsigned)CompatIndices.size();
1849 for (unsigned I : CompatIndices) {
1850 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1851 diag::note_compat_assoc)
1852 << Types[I]->getTypeLoc().getSourceRange()
1853 << Types[I]->getType();
1855 return ExprError();
1858 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1859 // its controlling expression shall have type compatible with exactly one of
1860 // the types named in its generic association list."
1861 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1862 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1863 SourceRange SR = P.first;
1864 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1865 return ExprError();
1868 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1869 // type name that is compatible with the type of the controlling expression,
1870 // then the result expression of the generic selection is the expression
1871 // in that generic association. Otherwise, the result expression of the
1872 // generic selection is the expression in the default generic association."
1873 unsigned ResultIndex =
1874 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1876 if (ControllingExpr) {
1877 return GenericSelectionExpr::Create(
1878 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1879 ContainsUnexpandedParameterPack, ResultIndex);
1881 return GenericSelectionExpr::Create(
1882 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1883 ContainsUnexpandedParameterPack, ResultIndex);
1886 static PredefinedExpr::IdentKind getPredefinedExprKind(tok::TokenKind Kind) {
1887 switch (Kind) {
1888 default:
1889 llvm_unreachable("unexpected TokenKind");
1890 case tok::kw___func__:
1891 return PredefinedExpr::Func; // [C99 6.4.2.2]
1892 case tok::kw___FUNCTION__:
1893 return PredefinedExpr::Function;
1894 case tok::kw___FUNCDNAME__:
1895 return PredefinedExpr::FuncDName; // [MS]
1896 case tok::kw___FUNCSIG__:
1897 return PredefinedExpr::FuncSig; // [MS]
1898 case tok::kw_L__FUNCTION__:
1899 return PredefinedExpr::LFunction; // [MS]
1900 case tok::kw_L__FUNCSIG__:
1901 return PredefinedExpr::LFuncSig; // [MS]
1902 case tok::kw___PRETTY_FUNCTION__:
1903 return PredefinedExpr::PrettyFunction; // [GNU]
1907 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1908 /// location of the token and the offset of the ud-suffix within it.
1909 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1910 unsigned Offset) {
1911 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1912 S.getLangOpts());
1915 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1916 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1917 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1918 IdentifierInfo *UDSuffix,
1919 SourceLocation UDSuffixLoc,
1920 ArrayRef<Expr*> Args,
1921 SourceLocation LitEndLoc) {
1922 assert(Args.size() <= 2 && "too many arguments for literal operator");
1924 QualType ArgTy[2];
1925 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1926 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1927 if (ArgTy[ArgIdx]->isArrayType())
1928 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1931 DeclarationName OpName =
1932 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1933 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1934 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1936 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1937 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1938 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1939 /*AllowStringTemplatePack*/ false,
1940 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1941 return ExprError();
1943 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1946 ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
1947 // StringToks needs backing storage as it doesn't hold array elements itself
1948 std::vector<Token> ExpandedToks;
1949 if (getLangOpts().MicrosoftExt)
1950 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1952 StringLiteralParser Literal(StringToks, PP,
1953 StringLiteralEvalMethod::Unevaluated);
1954 if (Literal.hadError)
1955 return ExprError();
1957 SmallVector<SourceLocation, 4> StringTokLocs;
1958 for (const Token &Tok : StringToks)
1959 StringTokLocs.push_back(Tok.getLocation());
1961 StringLiteral *Lit = StringLiteral::Create(
1962 Context, Literal.GetString(), StringLiteral::Unevaluated, false, {},
1963 &StringTokLocs[0], StringTokLocs.size());
1965 if (!Literal.getUDSuffix().empty()) {
1966 SourceLocation UDSuffixLoc =
1967 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1968 Literal.getUDSuffixOffset());
1969 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1972 return Lit;
1975 std::vector<Token>
1976 Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
1977 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
1978 // local macros that expand to string literals that may be concatenated.
1979 // These macros are expanded here (in Sema), because StringLiteralParser
1980 // (in Lex) doesn't know the enclosing function (because it hasn't been
1981 // parsed yet).
1982 assert(getLangOpts().MicrosoftExt);
1984 // Note: Although function local macros are defined only inside functions,
1985 // we ensure a valid `CurrentDecl` even outside of a function. This allows
1986 // expansion of macros into empty string literals without additional checks.
1987 Decl *CurrentDecl = getCurLocalScopeDecl();
1988 if (!CurrentDecl)
1989 CurrentDecl = Context.getTranslationUnitDecl();
1991 std::vector<Token> ExpandedToks;
1992 ExpandedToks.reserve(Toks.size());
1993 for (const Token &Tok : Toks) {
1994 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
1995 assert(tok::isStringLiteral(Tok.getKind()));
1996 ExpandedToks.emplace_back(Tok);
1997 continue;
1999 if (isa<TranslationUnitDecl>(CurrentDecl))
2000 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2001 // Stringify predefined expression
2002 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2003 << Tok.getKind();
2004 SmallString<64> Str;
2005 llvm::raw_svector_ostream OS(Str);
2006 Token &Exp = ExpandedToks.emplace_back();
2007 Exp.startToken();
2008 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2009 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2010 OS << 'L';
2011 Exp.setKind(tok::wide_string_literal);
2012 } else {
2013 Exp.setKind(tok::string_literal);
2015 OS << '"'
2016 << Lexer::Stringify(PredefinedExpr::ComputeName(
2017 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2018 << '"';
2019 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2021 return ExpandedToks;
2024 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
2025 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
2026 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
2027 /// multiple tokens. However, the common case is that StringToks points to one
2028 /// string.
2030 ExprResult
2031 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2032 assert(!StringToks.empty() && "Must have at least one string!");
2034 // StringToks needs backing storage as it doesn't hold array elements itself
2035 std::vector<Token> ExpandedToks;
2036 if (getLangOpts().MicrosoftExt)
2037 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2039 StringLiteralParser Literal(StringToks, PP);
2040 if (Literal.hadError)
2041 return ExprError();
2043 SmallVector<SourceLocation, 4> StringTokLocs;
2044 for (const Token &Tok : StringToks)
2045 StringTokLocs.push_back(Tok.getLocation());
2047 QualType CharTy = Context.CharTy;
2048 StringLiteral::StringKind Kind = StringLiteral::Ordinary;
2049 if (Literal.isWide()) {
2050 CharTy = Context.getWideCharType();
2051 Kind = StringLiteral::Wide;
2052 } else if (Literal.isUTF8()) {
2053 if (getLangOpts().Char8)
2054 CharTy = Context.Char8Ty;
2055 Kind = StringLiteral::UTF8;
2056 } else if (Literal.isUTF16()) {
2057 CharTy = Context.Char16Ty;
2058 Kind = StringLiteral::UTF16;
2059 } else if (Literal.isUTF32()) {
2060 CharTy = Context.Char32Ty;
2061 Kind = StringLiteral::UTF32;
2062 } else if (Literal.isPascal()) {
2063 CharTy = Context.UnsignedCharTy;
2066 // Warn on initializing an array of char from a u8 string literal; this
2067 // becomes ill-formed in C++2a.
2068 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
2069 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
2070 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
2072 // Create removals for all 'u8' prefixes in the string literal(s). This
2073 // ensures C++2a compatibility (but may change the program behavior when
2074 // built by non-Clang compilers for which the execution character set is
2075 // not always UTF-8).
2076 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
2077 SourceLocation RemovalDiagLoc;
2078 for (const Token &Tok : StringToks) {
2079 if (Tok.getKind() == tok::utf8_string_literal) {
2080 if (RemovalDiagLoc.isInvalid())
2081 RemovalDiagLoc = Tok.getLocation();
2082 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
2083 Tok.getLocation(),
2084 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2085 getSourceManager(), getLangOpts())));
2088 Diag(RemovalDiagLoc, RemovalDiag);
2091 QualType StrTy =
2092 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2094 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2095 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2096 Kind, Literal.Pascal, StrTy,
2097 &StringTokLocs[0],
2098 StringTokLocs.size());
2099 if (Literal.getUDSuffix().empty())
2100 return Lit;
2102 // We're building a user-defined literal.
2103 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2104 SourceLocation UDSuffixLoc =
2105 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2106 Literal.getUDSuffixOffset());
2108 // Make sure we're allowed user-defined literals here.
2109 if (!UDLScope)
2110 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2112 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2113 // operator "" X (str, len)
2114 QualType SizeType = Context.getSizeType();
2116 DeclarationName OpName =
2117 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2118 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2119 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2121 QualType ArgTy[] = {
2122 Context.getArrayDecayedType(StrTy), SizeType
2125 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2126 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2127 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2128 /*AllowStringTemplatePack*/ true,
2129 /*DiagnoseMissing*/ true, Lit)) {
2131 case LOLR_Cooked: {
2132 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2133 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2134 StringTokLocs[0]);
2135 Expr *Args[] = { Lit, LenArg };
2137 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2140 case LOLR_Template: {
2141 TemplateArgumentListInfo ExplicitArgs;
2142 TemplateArgument Arg(Lit);
2143 TemplateArgumentLocInfo ArgInfo(Lit);
2144 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2145 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2146 StringTokLocs.back(), &ExplicitArgs);
2149 case LOLR_StringTemplatePack: {
2150 TemplateArgumentListInfo ExplicitArgs;
2152 unsigned CharBits = Context.getIntWidth(CharTy);
2153 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2154 llvm::APSInt Value(CharBits, CharIsUnsigned);
2156 TemplateArgument TypeArg(CharTy);
2157 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2158 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2160 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2161 Value = Lit->getCodeUnit(I);
2162 TemplateArgument Arg(Context, Value, CharTy);
2163 TemplateArgumentLocInfo ArgInfo;
2164 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2166 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2167 StringTokLocs.back(), &ExplicitArgs);
2169 case LOLR_Raw:
2170 case LOLR_ErrorNoDiagnostic:
2171 llvm_unreachable("unexpected literal operator lookup result");
2172 case LOLR_Error:
2173 return ExprError();
2175 llvm_unreachable("unexpected literal operator lookup result");
2178 DeclRefExpr *
2179 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2180 SourceLocation Loc,
2181 const CXXScopeSpec *SS) {
2182 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2183 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2186 DeclRefExpr *
2187 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2188 const DeclarationNameInfo &NameInfo,
2189 const CXXScopeSpec *SS, NamedDecl *FoundD,
2190 SourceLocation TemplateKWLoc,
2191 const TemplateArgumentListInfo *TemplateArgs) {
2192 NestedNameSpecifierLoc NNS =
2193 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2194 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2195 TemplateArgs);
2198 // CUDA/HIP: Check whether a captured reference variable is referencing a
2199 // host variable in a device or host device lambda.
2200 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2201 VarDecl *VD) {
2202 if (!S.getLangOpts().CUDA || !VD->hasInit())
2203 return false;
2204 assert(VD->getType()->isReferenceType());
2206 // Check whether the reference variable is referencing a host variable.
2207 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2208 if (!DRE)
2209 return false;
2210 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2211 if (!Referee || !Referee->hasGlobalStorage() ||
2212 Referee->hasAttr<CUDADeviceAttr>())
2213 return false;
2215 // Check whether the current function is a device or host device lambda.
2216 // Check whether the reference variable is a capture by getDeclContext()
2217 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2218 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2219 if (MD && MD->getParent()->isLambda() &&
2220 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2221 VD->getDeclContext() != MD)
2222 return true;
2224 return false;
2227 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2228 // A declaration named in an unevaluated operand never constitutes an odr-use.
2229 if (isUnevaluatedContext())
2230 return NOUR_Unevaluated;
2232 // C++2a [basic.def.odr]p4:
2233 // A variable x whose name appears as a potentially-evaluated expression e
2234 // is odr-used by e unless [...] x is a reference that is usable in
2235 // constant expressions.
2236 // CUDA/HIP:
2237 // If a reference variable referencing a host variable is captured in a
2238 // device or host device lambda, the value of the referee must be copied
2239 // to the capture and the reference variable must be treated as odr-use
2240 // since the value of the referee is not known at compile time and must
2241 // be loaded from the captured.
2242 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2243 if (VD->getType()->isReferenceType() &&
2244 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2245 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2246 VD->isUsableInConstantExpressions(Context))
2247 return NOUR_Constant;
2250 // All remaining non-variable cases constitute an odr-use. For variables, we
2251 // need to wait and see how the expression is used.
2252 return NOUR_None;
2255 /// BuildDeclRefExpr - Build an expression that references a
2256 /// declaration that does not require a closure capture.
2257 DeclRefExpr *
2258 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2259 const DeclarationNameInfo &NameInfo,
2260 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2261 SourceLocation TemplateKWLoc,
2262 const TemplateArgumentListInfo *TemplateArgs) {
2263 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2264 NeedToCaptureVariable(D, NameInfo.getLoc());
2266 DeclRefExpr *E = DeclRefExpr::Create(
2267 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2268 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2269 MarkDeclRefReferenced(E);
2271 // C++ [except.spec]p17:
2272 // An exception-specification is considered to be needed when:
2273 // - in an expression, the function is the unique lookup result or
2274 // the selected member of a set of overloaded functions.
2276 // We delay doing this until after we've built the function reference and
2277 // marked it as used so that:
2278 // a) if the function is defaulted, we get errors from defining it before /
2279 // instead of errors from computing its exception specification, and
2280 // b) if the function is a defaulted comparison, we can use the body we
2281 // build when defining it as input to the exception specification
2282 // computation rather than computing a new body.
2283 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2284 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2285 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2286 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2290 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2291 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2292 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2293 getCurFunction()->recordUseOfWeak(E);
2295 const auto *FD = dyn_cast<FieldDecl>(D);
2296 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2297 FD = IFD->getAnonField();
2298 if (FD) {
2299 UnusedPrivateFields.remove(FD);
2300 // Just in case we're building an illegal pointer-to-member.
2301 if (FD->isBitField())
2302 E->setObjectKind(OK_BitField);
2305 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2306 // designates a bit-field.
2307 if (const auto *BD = dyn_cast<BindingDecl>(D))
2308 if (const auto *BE = BD->getBinding())
2309 E->setObjectKind(BE->getObjectKind());
2311 return E;
2314 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2315 /// possibly a list of template arguments.
2317 /// If this produces template arguments, it is permitted to call
2318 /// DecomposeTemplateName.
2320 /// This actually loses a lot of source location information for
2321 /// non-standard name kinds; we should consider preserving that in
2322 /// some way.
2323 void
2324 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2325 TemplateArgumentListInfo &Buffer,
2326 DeclarationNameInfo &NameInfo,
2327 const TemplateArgumentListInfo *&TemplateArgs) {
2328 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2329 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2330 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2332 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2333 Id.TemplateId->NumArgs);
2334 translateTemplateArguments(TemplateArgsPtr, Buffer);
2336 TemplateName TName = Id.TemplateId->Template.get();
2337 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2338 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2339 TemplateArgs = &Buffer;
2340 } else {
2341 NameInfo = GetNameFromUnqualifiedId(Id);
2342 TemplateArgs = nullptr;
2346 static void emitEmptyLookupTypoDiagnostic(
2347 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2348 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2349 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2350 DeclContext *Ctx =
2351 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2352 if (!TC) {
2353 // Emit a special diagnostic for failed member lookups.
2354 // FIXME: computing the declaration context might fail here (?)
2355 if (Ctx)
2356 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2357 << SS.getRange();
2358 else
2359 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2360 return;
2363 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2364 bool DroppedSpecifier =
2365 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2366 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2367 ? diag::note_implicit_param_decl
2368 : diag::note_previous_decl;
2369 if (!Ctx)
2370 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2371 SemaRef.PDiag(NoteID));
2372 else
2373 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2374 << Typo << Ctx << DroppedSpecifier
2375 << SS.getRange(),
2376 SemaRef.PDiag(NoteID));
2379 /// Diagnose a lookup that found results in an enclosing class during error
2380 /// recovery. This usually indicates that the results were found in a dependent
2381 /// base class that could not be searched as part of a template definition.
2382 /// Always issues a diagnostic (though this may be only a warning in MS
2383 /// compatibility mode).
2385 /// Return \c true if the error is unrecoverable, or \c false if the caller
2386 /// should attempt to recover using these lookup results.
2387 bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2388 // During a default argument instantiation the CurContext points
2389 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2390 // function parameter list, hence add an explicit check.
2391 bool isDefaultArgument =
2392 !CodeSynthesisContexts.empty() &&
2393 CodeSynthesisContexts.back().Kind ==
2394 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2395 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2396 bool isInstance = CurMethod && CurMethod->isInstance() &&
2397 R.getNamingClass() == CurMethod->getParent() &&
2398 !isDefaultArgument;
2400 // There are two ways we can find a class-scope declaration during template
2401 // instantiation that we did not find in the template definition: if it is a
2402 // member of a dependent base class, or if it is declared after the point of
2403 // use in the same class. Distinguish these by comparing the class in which
2404 // the member was found to the naming class of the lookup.
2405 unsigned DiagID = diag::err_found_in_dependent_base;
2406 unsigned NoteID = diag::note_member_declared_at;
2407 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2408 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2409 : diag::err_found_later_in_class;
2410 } else if (getLangOpts().MSVCCompat) {
2411 DiagID = diag::ext_found_in_dependent_base;
2412 NoteID = diag::note_dependent_member_use;
2415 if (isInstance) {
2416 // Give a code modification hint to insert 'this->'.
2417 Diag(R.getNameLoc(), DiagID)
2418 << R.getLookupName()
2419 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2420 CheckCXXThisCapture(R.getNameLoc());
2421 } else {
2422 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2423 // they're not shadowed).
2424 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2427 for (const NamedDecl *D : R)
2428 Diag(D->getLocation(), NoteID);
2430 // Return true if we are inside a default argument instantiation
2431 // and the found name refers to an instance member function, otherwise
2432 // the caller will try to create an implicit member call and this is wrong
2433 // for default arguments.
2435 // FIXME: Is this special case necessary? We could allow the caller to
2436 // diagnose this.
2437 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2438 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2439 return true;
2442 // Tell the callee to try to recover.
2443 return false;
2446 /// Diagnose an empty lookup.
2448 /// \return false if new lookup candidates were found
2449 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2450 CorrectionCandidateCallback &CCC,
2451 TemplateArgumentListInfo *ExplicitTemplateArgs,
2452 ArrayRef<Expr *> Args, TypoExpr **Out) {
2453 DeclarationName Name = R.getLookupName();
2455 unsigned diagnostic = diag::err_undeclared_var_use;
2456 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2457 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2458 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2459 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2460 diagnostic = diag::err_undeclared_use;
2461 diagnostic_suggest = diag::err_undeclared_use_suggest;
2464 // If the original lookup was an unqualified lookup, fake an
2465 // unqualified lookup. This is useful when (for example) the
2466 // original lookup would not have found something because it was a
2467 // dependent name.
2468 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2469 while (DC) {
2470 if (isa<CXXRecordDecl>(DC)) {
2471 LookupQualifiedName(R, DC);
2473 if (!R.empty()) {
2474 // Don't give errors about ambiguities in this lookup.
2475 R.suppressDiagnostics();
2477 // If there's a best viable function among the results, only mention
2478 // that one in the notes.
2479 OverloadCandidateSet Candidates(R.getNameLoc(),
2480 OverloadCandidateSet::CSK_Normal);
2481 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2482 OverloadCandidateSet::iterator Best;
2483 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2484 OR_Success) {
2485 R.clear();
2486 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2487 R.resolveKind();
2490 return DiagnoseDependentMemberLookup(R);
2493 R.clear();
2496 DC = DC->getLookupParent();
2499 // We didn't find anything, so try to correct for a typo.
2500 TypoCorrection Corrected;
2501 if (S && Out) {
2502 SourceLocation TypoLoc = R.getNameLoc();
2503 assert(!ExplicitTemplateArgs &&
2504 "Diagnosing an empty lookup with explicit template args!");
2505 *Out = CorrectTypoDelayed(
2506 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2507 [=](const TypoCorrection &TC) {
2508 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2509 diagnostic, diagnostic_suggest);
2511 nullptr, CTK_ErrorRecovery);
2512 if (*Out)
2513 return true;
2514 } else if (S &&
2515 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2516 S, &SS, CCC, CTK_ErrorRecovery))) {
2517 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2518 bool DroppedSpecifier =
2519 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2520 R.setLookupName(Corrected.getCorrection());
2522 bool AcceptableWithRecovery = false;
2523 bool AcceptableWithoutRecovery = false;
2524 NamedDecl *ND = Corrected.getFoundDecl();
2525 if (ND) {
2526 if (Corrected.isOverloaded()) {
2527 OverloadCandidateSet OCS(R.getNameLoc(),
2528 OverloadCandidateSet::CSK_Normal);
2529 OverloadCandidateSet::iterator Best;
2530 for (NamedDecl *CD : Corrected) {
2531 if (FunctionTemplateDecl *FTD =
2532 dyn_cast<FunctionTemplateDecl>(CD))
2533 AddTemplateOverloadCandidate(
2534 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2535 Args, OCS);
2536 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2537 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2538 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2539 Args, OCS);
2541 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2542 case OR_Success:
2543 ND = Best->FoundDecl;
2544 Corrected.setCorrectionDecl(ND);
2545 break;
2546 default:
2547 // FIXME: Arbitrarily pick the first declaration for the note.
2548 Corrected.setCorrectionDecl(ND);
2549 break;
2552 R.addDecl(ND);
2553 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2554 CXXRecordDecl *Record = nullptr;
2555 if (Corrected.getCorrectionSpecifier()) {
2556 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2557 Record = Ty->getAsCXXRecordDecl();
2559 if (!Record)
2560 Record = cast<CXXRecordDecl>(
2561 ND->getDeclContext()->getRedeclContext());
2562 R.setNamingClass(Record);
2565 auto *UnderlyingND = ND->getUnderlyingDecl();
2566 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2567 isa<FunctionTemplateDecl>(UnderlyingND);
2568 // FIXME: If we ended up with a typo for a type name or
2569 // Objective-C class name, we're in trouble because the parser
2570 // is in the wrong place to recover. Suggest the typo
2571 // correction, but don't make it a fix-it since we're not going
2572 // to recover well anyway.
2573 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2574 getAsTypeTemplateDecl(UnderlyingND) ||
2575 isa<ObjCInterfaceDecl>(UnderlyingND);
2576 } else {
2577 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2578 // because we aren't able to recover.
2579 AcceptableWithoutRecovery = true;
2582 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2583 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2584 ? diag::note_implicit_param_decl
2585 : diag::note_previous_decl;
2586 if (SS.isEmpty())
2587 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2588 PDiag(NoteID), AcceptableWithRecovery);
2589 else
2590 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2591 << Name << computeDeclContext(SS, false)
2592 << DroppedSpecifier << SS.getRange(),
2593 PDiag(NoteID), AcceptableWithRecovery);
2595 // Tell the callee whether to try to recover.
2596 return !AcceptableWithRecovery;
2599 R.clear();
2601 // Emit a special diagnostic for failed member lookups.
2602 // FIXME: computing the declaration context might fail here (?)
2603 if (!SS.isEmpty()) {
2604 Diag(R.getNameLoc(), diag::err_no_member)
2605 << Name << computeDeclContext(SS, false)
2606 << SS.getRange();
2607 return true;
2610 // Give up, we can't recover.
2611 Diag(R.getNameLoc(), diagnostic) << Name;
2612 return true;
2615 /// In Microsoft mode, if we are inside a template class whose parent class has
2616 /// dependent base classes, and we can't resolve an unqualified identifier, then
2617 /// assume the identifier is a member of a dependent base class. We can only
2618 /// recover successfully in static methods, instance methods, and other contexts
2619 /// where 'this' is available. This doesn't precisely match MSVC's
2620 /// instantiation model, but it's close enough.
2621 static Expr *
2622 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2623 DeclarationNameInfo &NameInfo,
2624 SourceLocation TemplateKWLoc,
2625 const TemplateArgumentListInfo *TemplateArgs) {
2626 // Only try to recover from lookup into dependent bases in static methods or
2627 // contexts where 'this' is available.
2628 QualType ThisType = S.getCurrentThisType();
2629 const CXXRecordDecl *RD = nullptr;
2630 if (!ThisType.isNull())
2631 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2632 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2633 RD = MD->getParent();
2634 if (!RD || !RD->hasAnyDependentBases())
2635 return nullptr;
2637 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2638 // is available, suggest inserting 'this->' as a fixit.
2639 SourceLocation Loc = NameInfo.getLoc();
2640 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2641 DB << NameInfo.getName() << RD;
2643 if (!ThisType.isNull()) {
2644 DB << FixItHint::CreateInsertion(Loc, "this->");
2645 return CXXDependentScopeMemberExpr::Create(
2646 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2647 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2648 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2651 // Synthesize a fake NNS that points to the derived class. This will
2652 // perform name lookup during template instantiation.
2653 CXXScopeSpec SS;
2654 auto *NNS =
2655 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2656 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2657 return DependentScopeDeclRefExpr::Create(
2658 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2659 TemplateArgs);
2662 ExprResult
2663 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2664 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2665 bool HasTrailingLParen, bool IsAddressOfOperand,
2666 CorrectionCandidateCallback *CCC,
2667 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2668 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2669 "cannot be direct & operand and have a trailing lparen");
2670 if (SS.isInvalid())
2671 return ExprError();
2673 TemplateArgumentListInfo TemplateArgsBuffer;
2675 // Decompose the UnqualifiedId into the following data.
2676 DeclarationNameInfo NameInfo;
2677 const TemplateArgumentListInfo *TemplateArgs;
2678 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2680 DeclarationName Name = NameInfo.getName();
2681 IdentifierInfo *II = Name.getAsIdentifierInfo();
2682 SourceLocation NameLoc = NameInfo.getLoc();
2684 if (II && II->isEditorPlaceholder()) {
2685 // FIXME: When typed placeholders are supported we can create a typed
2686 // placeholder expression node.
2687 return ExprError();
2690 // C++ [temp.dep.expr]p3:
2691 // An id-expression is type-dependent if it contains:
2692 // -- an identifier that was declared with a dependent type,
2693 // (note: handled after lookup)
2694 // -- a template-id that is dependent,
2695 // (note: handled in BuildTemplateIdExpr)
2696 // -- a conversion-function-id that specifies a dependent type,
2697 // -- a nested-name-specifier that contains a class-name that
2698 // names a dependent type.
2699 // Determine whether this is a member of an unknown specialization;
2700 // we need to handle these differently.
2701 bool DependentID = false;
2702 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2703 Name.getCXXNameType()->isDependentType()) {
2704 DependentID = true;
2705 } else if (SS.isSet()) {
2706 if (DeclContext *DC = computeDeclContext(SS, false)) {
2707 if (RequireCompleteDeclContext(SS, DC))
2708 return ExprError();
2709 } else {
2710 DependentID = true;
2714 if (DependentID)
2715 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2716 IsAddressOfOperand, TemplateArgs);
2718 // Perform the required lookup.
2719 LookupResult R(*this, NameInfo,
2720 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2721 ? LookupObjCImplicitSelfParam
2722 : LookupOrdinaryName);
2723 if (TemplateKWLoc.isValid() || TemplateArgs) {
2724 // Lookup the template name again to correctly establish the context in
2725 // which it was found. This is really unfortunate as we already did the
2726 // lookup to determine that it was a template name in the first place. If
2727 // this becomes a performance hit, we can work harder to preserve those
2728 // results until we get here but it's likely not worth it.
2729 bool MemberOfUnknownSpecialization;
2730 AssumedTemplateKind AssumedTemplate;
2731 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2732 MemberOfUnknownSpecialization, TemplateKWLoc,
2733 &AssumedTemplate))
2734 return ExprError();
2736 if (MemberOfUnknownSpecialization ||
2737 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2738 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2739 IsAddressOfOperand, TemplateArgs);
2740 } else {
2741 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2742 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2744 // If the result might be in a dependent base class, this is a dependent
2745 // id-expression.
2746 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2747 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2748 IsAddressOfOperand, TemplateArgs);
2750 // If this reference is in an Objective-C method, then we need to do
2751 // some special Objective-C lookup, too.
2752 if (IvarLookupFollowUp) {
2753 ExprResult E(LookupInObjCMethod(R, S, II, true));
2754 if (E.isInvalid())
2755 return ExprError();
2757 if (Expr *Ex = E.getAs<Expr>())
2758 return Ex;
2762 if (R.isAmbiguous())
2763 return ExprError();
2765 // This could be an implicitly declared function reference if the language
2766 // mode allows it as a feature.
2767 if (R.empty() && HasTrailingLParen && II &&
2768 getLangOpts().implicitFunctionsAllowed()) {
2769 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2770 if (D) R.addDecl(D);
2773 // Determine whether this name might be a candidate for
2774 // argument-dependent lookup.
2775 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2777 if (R.empty() && !ADL) {
2778 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2779 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2780 TemplateKWLoc, TemplateArgs))
2781 return E;
2784 // Don't diagnose an empty lookup for inline assembly.
2785 if (IsInlineAsmIdentifier)
2786 return ExprError();
2788 // If this name wasn't predeclared and if this is not a function
2789 // call, diagnose the problem.
2790 TypoExpr *TE = nullptr;
2791 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2792 : nullptr);
2793 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2794 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2795 "Typo correction callback misconfigured");
2796 if (CCC) {
2797 // Make sure the callback knows what the typo being diagnosed is.
2798 CCC->setTypoName(II);
2799 if (SS.isValid())
2800 CCC->setTypoNNS(SS.getScopeRep());
2802 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2803 // a template name, but we happen to have always already looked up the name
2804 // before we get here if it must be a template name.
2805 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2806 std::nullopt, &TE)) {
2807 if (TE && KeywordReplacement) {
2808 auto &State = getTypoExprState(TE);
2809 auto BestTC = State.Consumer->getNextCorrection();
2810 if (BestTC.isKeyword()) {
2811 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2812 if (State.DiagHandler)
2813 State.DiagHandler(BestTC);
2814 KeywordReplacement->startToken();
2815 KeywordReplacement->setKind(II->getTokenID());
2816 KeywordReplacement->setIdentifierInfo(II);
2817 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2818 // Clean up the state associated with the TypoExpr, since it has
2819 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2820 clearDelayedTypo(TE);
2821 // Signal that a correction to a keyword was performed by returning a
2822 // valid-but-null ExprResult.
2823 return (Expr*)nullptr;
2825 State.Consumer->resetCorrectionStream();
2827 return TE ? TE : ExprError();
2830 assert(!R.empty() &&
2831 "DiagnoseEmptyLookup returned false but added no results");
2833 // If we found an Objective-C instance variable, let
2834 // LookupInObjCMethod build the appropriate expression to
2835 // reference the ivar.
2836 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2837 R.clear();
2838 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2839 // In a hopelessly buggy code, Objective-C instance variable
2840 // lookup fails and no expression will be built to reference it.
2841 if (!E.isInvalid() && !E.get())
2842 return ExprError();
2843 return E;
2847 // This is guaranteed from this point on.
2848 assert(!R.empty() || ADL);
2850 // Check whether this might be a C++ implicit instance member access.
2851 // C++ [class.mfct.non-static]p3:
2852 // When an id-expression that is not part of a class member access
2853 // syntax and not used to form a pointer to member is used in the
2854 // body of a non-static member function of class X, if name lookup
2855 // resolves the name in the id-expression to a non-static non-type
2856 // member of some class C, the id-expression is transformed into a
2857 // class member access expression using (*this) as the
2858 // postfix-expression to the left of the . operator.
2860 // But we don't actually need to do this for '&' operands if R
2861 // resolved to a function or overloaded function set, because the
2862 // expression is ill-formed if it actually works out to be a
2863 // non-static member function:
2865 // C++ [expr.ref]p4:
2866 // Otherwise, if E1.E2 refers to a non-static member function. . .
2867 // [t]he expression can be used only as the left-hand operand of a
2868 // member function call.
2870 // There are other safeguards against such uses, but it's important
2871 // to get this right here so that we don't end up making a
2872 // spuriously dependent expression if we're inside a dependent
2873 // instance method.
2874 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2875 bool MightBeImplicitMember;
2876 if (!IsAddressOfOperand)
2877 MightBeImplicitMember = true;
2878 else if (!SS.isEmpty())
2879 MightBeImplicitMember = false;
2880 else if (R.isOverloadedResult())
2881 MightBeImplicitMember = false;
2882 else if (R.isUnresolvableResult())
2883 MightBeImplicitMember = true;
2884 else
2885 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2886 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2887 isa<MSPropertyDecl>(R.getFoundDecl());
2889 if (MightBeImplicitMember)
2890 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2891 R, TemplateArgs, S);
2894 if (TemplateArgs || TemplateKWLoc.isValid()) {
2896 // In C++1y, if this is a variable template id, then check it
2897 // in BuildTemplateIdExpr().
2898 // The single lookup result must be a variable template declaration.
2899 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2900 Id.TemplateId->Kind == TNK_Var_template) {
2901 assert(R.getAsSingle<VarTemplateDecl>() &&
2902 "There should only be one declaration found.");
2905 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2908 return BuildDeclarationNameExpr(SS, R, ADL);
2911 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2912 /// declaration name, generally during template instantiation.
2913 /// There's a large number of things which don't need to be done along
2914 /// this path.
2915 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2916 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2917 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2918 if (NameInfo.getName().isDependentName())
2919 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2920 NameInfo, /*TemplateArgs=*/nullptr);
2922 DeclContext *DC = computeDeclContext(SS, false);
2923 if (!DC)
2924 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2925 NameInfo, /*TemplateArgs=*/nullptr);
2927 if (RequireCompleteDeclContext(SS, DC))
2928 return ExprError();
2930 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2931 LookupQualifiedName(R, DC);
2933 if (R.isAmbiguous())
2934 return ExprError();
2936 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2937 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2938 NameInfo, /*TemplateArgs=*/nullptr);
2940 if (R.empty()) {
2941 // Don't diagnose problems with invalid record decl, the secondary no_member
2942 // diagnostic during template instantiation is likely bogus, e.g. if a class
2943 // is invalid because it's derived from an invalid base class, then missing
2944 // members were likely supposed to be inherited.
2945 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2946 if (CD->isInvalidDecl())
2947 return ExprError();
2948 Diag(NameInfo.getLoc(), diag::err_no_member)
2949 << NameInfo.getName() << DC << SS.getRange();
2950 return ExprError();
2953 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2954 // Diagnose a missing typename if this resolved unambiguously to a type in
2955 // a dependent context. If we can recover with a type, downgrade this to
2956 // a warning in Microsoft compatibility mode.
2957 unsigned DiagID = diag::err_typename_missing;
2958 if (RecoveryTSI && getLangOpts().MSVCCompat)
2959 DiagID = diag::ext_typename_missing;
2960 SourceLocation Loc = SS.getBeginLoc();
2961 auto D = Diag(Loc, DiagID);
2962 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2963 << SourceRange(Loc, NameInfo.getEndLoc());
2965 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2966 // context.
2967 if (!RecoveryTSI)
2968 return ExprError();
2970 // Only issue the fixit if we're prepared to recover.
2971 D << FixItHint::CreateInsertion(Loc, "typename ");
2973 // Recover by pretending this was an elaborated type.
2974 QualType Ty = Context.getTypeDeclType(TD);
2975 TypeLocBuilder TLB;
2976 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2978 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2979 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2980 QTL.setElaboratedKeywordLoc(SourceLocation());
2981 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2983 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2985 return ExprEmpty();
2988 // Defend against this resolving to an implicit member access. We usually
2989 // won't get here if this might be a legitimate a class member (we end up in
2990 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2991 // a pointer-to-member or in an unevaluated context in C++11.
2992 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2993 return BuildPossibleImplicitMemberExpr(SS,
2994 /*TemplateKWLoc=*/SourceLocation(),
2995 R, /*TemplateArgs=*/nullptr, S);
2997 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
3000 /// The parser has read a name in, and Sema has detected that we're currently
3001 /// inside an ObjC method. Perform some additional checks and determine if we
3002 /// should form a reference to an ivar.
3004 /// Ideally, most of this would be done by lookup, but there's
3005 /// actually quite a lot of extra work involved.
3006 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
3007 IdentifierInfo *II) {
3008 SourceLocation Loc = Lookup.getNameLoc();
3009 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3011 // Check for error condition which is already reported.
3012 if (!CurMethod)
3013 return DeclResult(true);
3015 // There are two cases to handle here. 1) scoped lookup could have failed,
3016 // in which case we should look for an ivar. 2) scoped lookup could have
3017 // found a decl, but that decl is outside the current instance method (i.e.
3018 // a global variable). In these two cases, we do a lookup for an ivar with
3019 // this name, if the lookup sucedes, we replace it our current decl.
3021 // If we're in a class method, we don't normally want to look for
3022 // ivars. But if we don't find anything else, and there's an
3023 // ivar, that's an error.
3024 bool IsClassMethod = CurMethod->isClassMethod();
3026 bool LookForIvars;
3027 if (Lookup.empty())
3028 LookForIvars = true;
3029 else if (IsClassMethod)
3030 LookForIvars = false;
3031 else
3032 LookForIvars = (Lookup.isSingleResult() &&
3033 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
3034 ObjCInterfaceDecl *IFace = nullptr;
3035 if (LookForIvars) {
3036 IFace = CurMethod->getClassInterface();
3037 ObjCInterfaceDecl *ClassDeclared;
3038 ObjCIvarDecl *IV = nullptr;
3039 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
3040 // Diagnose using an ivar in a class method.
3041 if (IsClassMethod) {
3042 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3043 return DeclResult(true);
3046 // Diagnose the use of an ivar outside of the declaring class.
3047 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
3048 !declaresSameEntity(ClassDeclared, IFace) &&
3049 !getLangOpts().DebuggerSupport)
3050 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
3052 // Success.
3053 return IV;
3055 } else if (CurMethod->isInstanceMethod()) {
3056 // We should warn if a local variable hides an ivar.
3057 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
3058 ObjCInterfaceDecl *ClassDeclared;
3059 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
3060 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
3061 declaresSameEntity(IFace, ClassDeclared))
3062 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
3065 } else if (Lookup.isSingleResult() &&
3066 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
3067 // If accessing a stand-alone ivar in a class method, this is an error.
3068 if (const ObjCIvarDecl *IV =
3069 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
3070 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3071 return DeclResult(true);
3075 // Didn't encounter an error, didn't find an ivar.
3076 return DeclResult(false);
3079 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
3080 ObjCIvarDecl *IV) {
3081 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3082 assert(CurMethod && CurMethod->isInstanceMethod() &&
3083 "should not reference ivar from this context");
3085 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
3086 assert(IFace && "should not reference ivar from this context");
3088 // If we're referencing an invalid decl, just return this as a silent
3089 // error node. The error diagnostic was already emitted on the decl.
3090 if (IV->isInvalidDecl())
3091 return ExprError();
3093 // Check if referencing a field with __attribute__((deprecated)).
3094 if (DiagnoseUseOfDecl(IV, Loc))
3095 return ExprError();
3097 // FIXME: This should use a new expr for a direct reference, don't
3098 // turn this into Self->ivar, just return a BareIVarExpr or something.
3099 IdentifierInfo &II = Context.Idents.get("self");
3100 UnqualifiedId SelfName;
3101 SelfName.setImplicitSelfParam(&II);
3102 CXXScopeSpec SelfScopeSpec;
3103 SourceLocation TemplateKWLoc;
3104 ExprResult SelfExpr =
3105 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
3106 /*HasTrailingLParen=*/false,
3107 /*IsAddressOfOperand=*/false);
3108 if (SelfExpr.isInvalid())
3109 return ExprError();
3111 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
3112 if (SelfExpr.isInvalid())
3113 return ExprError();
3115 MarkAnyDeclReferenced(Loc, IV, true);
3117 ObjCMethodFamily MF = CurMethod->getMethodFamily();
3118 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
3119 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
3120 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
3122 ObjCIvarRefExpr *Result = new (Context)
3123 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
3124 IV->getLocation(), SelfExpr.get(), true, true);
3126 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3127 if (!isUnevaluatedContext() &&
3128 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
3129 getCurFunction()->recordUseOfWeak(Result);
3131 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
3132 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
3133 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
3135 return Result;
3138 /// The parser has read a name in, and Sema has detected that we're currently
3139 /// inside an ObjC method. Perform some additional checks and determine if we
3140 /// should form a reference to an ivar. If so, build an expression referencing
3141 /// that ivar.
3142 ExprResult
3143 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
3144 IdentifierInfo *II, bool AllowBuiltinCreation) {
3145 // FIXME: Integrate this lookup step into LookupParsedName.
3146 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
3147 if (Ivar.isInvalid())
3148 return ExprError();
3149 if (Ivar.isUsable())
3150 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
3151 cast<ObjCIvarDecl>(Ivar.get()));
3153 if (Lookup.empty() && II && AllowBuiltinCreation)
3154 LookupBuiltin(Lookup);
3156 // Sentinel value saying that we didn't do anything special.
3157 return ExprResult(false);
3160 /// Cast a base object to a member's actual type.
3162 /// There are two relevant checks:
3164 /// C++ [class.access.base]p7:
3166 /// If a class member access operator [...] is used to access a non-static
3167 /// data member or non-static member function, the reference is ill-formed if
3168 /// the left operand [...] cannot be implicitly converted to a pointer to the
3169 /// naming class of the right operand.
3171 /// C++ [expr.ref]p7:
3173 /// If E2 is a non-static data member or a non-static member function, the
3174 /// program is ill-formed if the class of which E2 is directly a member is an
3175 /// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3177 /// Note that the latter check does not consider access; the access of the
3178 /// "real" base class is checked as appropriate when checking the access of the
3179 /// member name.
3180 ExprResult
3181 Sema::PerformObjectMemberConversion(Expr *From,
3182 NestedNameSpecifier *Qualifier,
3183 NamedDecl *FoundDecl,
3184 NamedDecl *Member) {
3185 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3186 if (!RD)
3187 return From;
3189 QualType DestRecordType;
3190 QualType DestType;
3191 QualType FromRecordType;
3192 QualType FromType = From->getType();
3193 bool PointerConversions = false;
3194 if (isa<FieldDecl>(Member)) {
3195 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3196 auto FromPtrType = FromType->getAs<PointerType>();
3197 DestRecordType = Context.getAddrSpaceQualType(
3198 DestRecordType, FromPtrType
3199 ? FromType->getPointeeType().getAddressSpace()
3200 : FromType.getAddressSpace());
3202 if (FromPtrType) {
3203 DestType = Context.getPointerType(DestRecordType);
3204 FromRecordType = FromPtrType->getPointeeType();
3205 PointerConversions = true;
3206 } else {
3207 DestType = DestRecordType;
3208 FromRecordType = FromType;
3210 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3211 if (Method->isStatic())
3212 return From;
3214 DestType = Method->getThisType();
3215 DestRecordType = DestType->getPointeeType();
3217 if (FromType->getAs<PointerType>()) {
3218 FromRecordType = FromType->getPointeeType();
3219 PointerConversions = true;
3220 } else {
3221 FromRecordType = FromType;
3222 DestType = DestRecordType;
3225 LangAS FromAS = FromRecordType.getAddressSpace();
3226 LangAS DestAS = DestRecordType.getAddressSpace();
3227 if (FromAS != DestAS) {
3228 QualType FromRecordTypeWithoutAS =
3229 Context.removeAddrSpaceQualType(FromRecordType);
3230 QualType FromTypeWithDestAS =
3231 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3232 if (PointerConversions)
3233 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3234 From = ImpCastExprToType(From, FromTypeWithDestAS,
3235 CK_AddressSpaceConversion, From->getValueKind())
3236 .get();
3238 } else {
3239 // No conversion necessary.
3240 return From;
3243 if (DestType->isDependentType() || FromType->isDependentType())
3244 return From;
3246 // If the unqualified types are the same, no conversion is necessary.
3247 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3248 return From;
3250 SourceRange FromRange = From->getSourceRange();
3251 SourceLocation FromLoc = FromRange.getBegin();
3253 ExprValueKind VK = From->getValueKind();
3255 // C++ [class.member.lookup]p8:
3256 // [...] Ambiguities can often be resolved by qualifying a name with its
3257 // class name.
3259 // If the member was a qualified name and the qualified referred to a
3260 // specific base subobject type, we'll cast to that intermediate type
3261 // first and then to the object in which the member is declared. That allows
3262 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3264 // class Base { public: int x; };
3265 // class Derived1 : public Base { };
3266 // class Derived2 : public Base { };
3267 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3269 // void VeryDerived::f() {
3270 // x = 17; // error: ambiguous base subobjects
3271 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3272 // }
3273 if (Qualifier && Qualifier->getAsType()) {
3274 QualType QType = QualType(Qualifier->getAsType(), 0);
3275 assert(QType->isRecordType() && "lookup done with non-record type");
3277 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3279 // In C++98, the qualifier type doesn't actually have to be a base
3280 // type of the object type, in which case we just ignore it.
3281 // Otherwise build the appropriate casts.
3282 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3283 CXXCastPath BasePath;
3284 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3285 FromLoc, FromRange, &BasePath))
3286 return ExprError();
3288 if (PointerConversions)
3289 QType = Context.getPointerType(QType);
3290 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3291 VK, &BasePath).get();
3293 FromType = QType;
3294 FromRecordType = QRecordType;
3296 // If the qualifier type was the same as the destination type,
3297 // we're done.
3298 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3299 return From;
3303 CXXCastPath BasePath;
3304 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3305 FromLoc, FromRange, &BasePath,
3306 /*IgnoreAccess=*/true))
3307 return ExprError();
3309 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3310 VK, &BasePath);
3313 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3314 const LookupResult &R,
3315 bool HasTrailingLParen) {
3316 // Only when used directly as the postfix-expression of a call.
3317 if (!HasTrailingLParen)
3318 return false;
3320 // Never if a scope specifier was provided.
3321 if (SS.isSet())
3322 return false;
3324 // Only in C++ or ObjC++.
3325 if (!getLangOpts().CPlusPlus)
3326 return false;
3328 // Turn off ADL when we find certain kinds of declarations during
3329 // normal lookup:
3330 for (const NamedDecl *D : R) {
3331 // C++0x [basic.lookup.argdep]p3:
3332 // -- a declaration of a class member
3333 // Since using decls preserve this property, we check this on the
3334 // original decl.
3335 if (D->isCXXClassMember())
3336 return false;
3338 // C++0x [basic.lookup.argdep]p3:
3339 // -- a block-scope function declaration that is not a
3340 // using-declaration
3341 // NOTE: we also trigger this for function templates (in fact, we
3342 // don't check the decl type at all, since all other decl types
3343 // turn off ADL anyway).
3344 if (isa<UsingShadowDecl>(D))
3345 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3346 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3347 return false;
3349 // C++0x [basic.lookup.argdep]p3:
3350 // -- a declaration that is neither a function or a function
3351 // template
3352 // And also for builtin functions.
3353 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3354 // But also builtin functions.
3355 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3356 return false;
3357 } else if (!isa<FunctionTemplateDecl>(D))
3358 return false;
3361 return true;
3365 /// Diagnoses obvious problems with the use of the given declaration
3366 /// as an expression. This is only actually called for lookups that
3367 /// were not overloaded, and it doesn't promise that the declaration
3368 /// will in fact be used.
3369 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3370 bool AcceptInvalid) {
3371 if (D->isInvalidDecl() && !AcceptInvalid)
3372 return true;
3374 if (isa<TypedefNameDecl>(D)) {
3375 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3376 return true;
3379 if (isa<ObjCInterfaceDecl>(D)) {
3380 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3381 return true;
3384 if (isa<NamespaceDecl>(D)) {
3385 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3386 return true;
3389 return false;
3392 // Certain multiversion types should be treated as overloaded even when there is
3393 // only one result.
3394 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3395 assert(R.isSingleResult() && "Expected only a single result");
3396 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3397 return FD &&
3398 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3401 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3402 LookupResult &R, bool NeedsADL,
3403 bool AcceptInvalidDecl) {
3404 // If this is a single, fully-resolved result and we don't need ADL,
3405 // just build an ordinary singleton decl ref.
3406 if (!NeedsADL && R.isSingleResult() &&
3407 !R.getAsSingle<FunctionTemplateDecl>() &&
3408 !ShouldLookupResultBeMultiVersionOverload(R))
3409 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3410 R.getRepresentativeDecl(), nullptr,
3411 AcceptInvalidDecl);
3413 // We only need to check the declaration if there's exactly one
3414 // result, because in the overloaded case the results can only be
3415 // functions and function templates.
3416 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3417 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3418 AcceptInvalidDecl))
3419 return ExprError();
3421 // Otherwise, just build an unresolved lookup expression. Suppress
3422 // any lookup-related diagnostics; we'll hash these out later, when
3423 // we've picked a target.
3424 R.suppressDiagnostics();
3426 UnresolvedLookupExpr *ULE
3427 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3428 SS.getWithLocInContext(Context),
3429 R.getLookupNameInfo(),
3430 NeedsADL, R.isOverloadedResult(),
3431 R.begin(), R.end());
3433 return ULE;
3436 static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
3437 SourceLocation loc,
3438 ValueDecl *var);
3440 /// Complete semantic analysis for a reference to the given declaration.
3441 ExprResult Sema::BuildDeclarationNameExpr(
3442 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3443 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3444 bool AcceptInvalidDecl) {
3445 assert(D && "Cannot refer to a NULL declaration");
3446 assert(!isa<FunctionTemplateDecl>(D) &&
3447 "Cannot refer unambiguously to a function template");
3449 SourceLocation Loc = NameInfo.getLoc();
3450 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3451 // Recovery from invalid cases (e.g. D is an invalid Decl).
3452 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3453 // diagnostics, as invalid decls use int as a fallback type.
3454 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3457 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3458 // Specifically diagnose references to class templates that are missing
3459 // a template argument list.
3460 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3461 return ExprError();
3464 // Make sure that we're referring to a value.
3465 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3466 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3467 Diag(D->getLocation(), diag::note_declared_at);
3468 return ExprError();
3471 // Check whether this declaration can be used. Note that we suppress
3472 // this check when we're going to perform argument-dependent lookup
3473 // on this function name, because this might not be the function
3474 // that overload resolution actually selects.
3475 if (DiagnoseUseOfDecl(D, Loc))
3476 return ExprError();
3478 auto *VD = cast<ValueDecl>(D);
3480 // Only create DeclRefExpr's for valid Decl's.
3481 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3482 return ExprError();
3484 // Handle members of anonymous structs and unions. If we got here,
3485 // and the reference is to a class member indirect field, then this
3486 // must be the subject of a pointer-to-member expression.
3487 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3488 IndirectField && !IndirectField->isCXXClassMember())
3489 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3490 IndirectField);
3492 QualType type = VD->getType();
3493 if (type.isNull())
3494 return ExprError();
3495 ExprValueKind valueKind = VK_PRValue;
3497 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3498 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3499 // is expanded by some outer '...' in the context of the use.
3500 type = type.getNonPackExpansionType();
3502 switch (D->getKind()) {
3503 // Ignore all the non-ValueDecl kinds.
3504 #define ABSTRACT_DECL(kind)
3505 #define VALUE(type, base)
3506 #define DECL(type, base) case Decl::type:
3507 #include "clang/AST/DeclNodes.inc"
3508 llvm_unreachable("invalid value decl kind");
3510 // These shouldn't make it here.
3511 case Decl::ObjCAtDefsField:
3512 llvm_unreachable("forming non-member reference to ivar?");
3514 // Enum constants are always r-values and never references.
3515 // Unresolved using declarations are dependent.
3516 case Decl::EnumConstant:
3517 case Decl::UnresolvedUsingValue:
3518 case Decl::OMPDeclareReduction:
3519 case Decl::OMPDeclareMapper:
3520 valueKind = VK_PRValue;
3521 break;
3523 // Fields and indirect fields that got here must be for
3524 // pointer-to-member expressions; we just call them l-values for
3525 // internal consistency, because this subexpression doesn't really
3526 // exist in the high-level semantics.
3527 case Decl::Field:
3528 case Decl::IndirectField:
3529 case Decl::ObjCIvar:
3530 assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3532 // These can't have reference type in well-formed programs, but
3533 // for internal consistency we do this anyway.
3534 type = type.getNonReferenceType();
3535 valueKind = VK_LValue;
3536 break;
3538 // Non-type template parameters are either l-values or r-values
3539 // depending on the type.
3540 case Decl::NonTypeTemplateParm: {
3541 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3542 type = reftype->getPointeeType();
3543 valueKind = VK_LValue; // even if the parameter is an r-value reference
3544 break;
3547 // [expr.prim.id.unqual]p2:
3548 // If the entity is a template parameter object for a template
3549 // parameter of type T, the type of the expression is const T.
3550 // [...] The expression is an lvalue if the entity is a [...] template
3551 // parameter object.
3552 if (type->isRecordType()) {
3553 type = type.getUnqualifiedType().withConst();
3554 valueKind = VK_LValue;
3555 break;
3558 // For non-references, we need to strip qualifiers just in case
3559 // the template parameter was declared as 'const int' or whatever.
3560 valueKind = VK_PRValue;
3561 type = type.getUnqualifiedType();
3562 break;
3565 case Decl::Var:
3566 case Decl::VarTemplateSpecialization:
3567 case Decl::VarTemplatePartialSpecialization:
3568 case Decl::Decomposition:
3569 case Decl::OMPCapturedExpr:
3570 // In C, "extern void blah;" is valid and is an r-value.
3571 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3572 type->isVoidType()) {
3573 valueKind = VK_PRValue;
3574 break;
3576 [[fallthrough]];
3578 case Decl::ImplicitParam:
3579 case Decl::ParmVar: {
3580 // These are always l-values.
3581 valueKind = VK_LValue;
3582 type = type.getNonReferenceType();
3584 // FIXME: Does the addition of const really only apply in
3585 // potentially-evaluated contexts? Since the variable isn't actually
3586 // captured in an unevaluated context, it seems that the answer is no.
3587 if (!isUnevaluatedContext()) {
3588 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3589 if (!CapturedType.isNull())
3590 type = CapturedType;
3593 break;
3596 case Decl::Binding:
3597 // These are always lvalues.
3598 valueKind = VK_LValue;
3599 type = type.getNonReferenceType();
3600 break;
3602 case Decl::Function: {
3603 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3604 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3605 type = Context.BuiltinFnTy;
3606 valueKind = VK_PRValue;
3607 break;
3611 const FunctionType *fty = type->castAs<FunctionType>();
3613 // If we're referring to a function with an __unknown_anytype
3614 // result type, make the entire expression __unknown_anytype.
3615 if (fty->getReturnType() == Context.UnknownAnyTy) {
3616 type = Context.UnknownAnyTy;
3617 valueKind = VK_PRValue;
3618 break;
3621 // Functions are l-values in C++.
3622 if (getLangOpts().CPlusPlus) {
3623 valueKind = VK_LValue;
3624 break;
3627 // C99 DR 316 says that, if a function type comes from a
3628 // function definition (without a prototype), that type is only
3629 // used for checking compatibility. Therefore, when referencing
3630 // the function, we pretend that we don't have the full function
3631 // type.
3632 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3633 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3634 fty->getExtInfo());
3636 // Functions are r-values in C.
3637 valueKind = VK_PRValue;
3638 break;
3641 case Decl::CXXDeductionGuide:
3642 llvm_unreachable("building reference to deduction guide");
3644 case Decl::MSProperty:
3645 case Decl::MSGuid:
3646 case Decl::TemplateParamObject:
3647 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3648 // capture in OpenMP, or duplicated between host and device?
3649 valueKind = VK_LValue;
3650 break;
3652 case Decl::UnnamedGlobalConstant:
3653 valueKind = VK_LValue;
3654 break;
3656 case Decl::CXXMethod:
3657 // If we're referring to a method with an __unknown_anytype
3658 // result type, make the entire expression __unknown_anytype.
3659 // This should only be possible with a type written directly.
3660 if (const FunctionProtoType *proto =
3661 dyn_cast<FunctionProtoType>(VD->getType()))
3662 if (proto->getReturnType() == Context.UnknownAnyTy) {
3663 type = Context.UnknownAnyTy;
3664 valueKind = VK_PRValue;
3665 break;
3668 // C++ methods are l-values if static, r-values if non-static.
3669 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3670 valueKind = VK_LValue;
3671 break;
3673 [[fallthrough]];
3675 case Decl::CXXConversion:
3676 case Decl::CXXDestructor:
3677 case Decl::CXXConstructor:
3678 valueKind = VK_PRValue;
3679 break;
3682 auto *E =
3683 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3684 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3685 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3686 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3687 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3688 // diagnostics).
3689 if (VD->isInvalidDecl() && E)
3690 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3691 return E;
3694 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3695 SmallString<32> &Target) {
3696 Target.resize(CharByteWidth * (Source.size() + 1));
3697 char *ResultPtr = &Target[0];
3698 const llvm::UTF8 *ErrorPtr;
3699 bool success =
3700 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3701 (void)success;
3702 assert(success);
3703 Target.resize(ResultPtr - &Target[0]);
3706 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3707 PredefinedExpr::IdentKind IK) {
3708 Decl *currentDecl = getCurLocalScopeDecl();
3709 if (!currentDecl) {
3710 Diag(Loc, diag::ext_predef_outside_function);
3711 currentDecl = Context.getTranslationUnitDecl();
3714 QualType ResTy;
3715 StringLiteral *SL = nullptr;
3716 if (cast<DeclContext>(currentDecl)->isDependentContext())
3717 ResTy = Context.DependentTy;
3718 else {
3719 // Pre-defined identifiers are of type char[x], where x is the length of
3720 // the string.
3721 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3722 unsigned Length = Str.length();
3724 llvm::APInt LengthI(32, Length + 1);
3725 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3726 ResTy =
3727 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3728 SmallString<32> RawChars;
3729 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3730 Str, RawChars);
3731 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3732 ArrayType::Normal,
3733 /*IndexTypeQuals*/ 0);
3734 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3735 /*Pascal*/ false, ResTy, Loc);
3736 } else {
3737 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3738 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3739 ArrayType::Normal,
3740 /*IndexTypeQuals*/ 0);
3741 SL = StringLiteral::Create(Context, Str, StringLiteral::Ordinary,
3742 /*Pascal*/ false, ResTy, Loc);
3746 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3747 SL);
3750 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3751 SourceLocation LParen,
3752 SourceLocation RParen,
3753 TypeSourceInfo *TSI) {
3754 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3757 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3758 SourceLocation LParen,
3759 SourceLocation RParen,
3760 ParsedType ParsedTy) {
3761 TypeSourceInfo *TSI = nullptr;
3762 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3764 if (Ty.isNull())
3765 return ExprError();
3766 if (!TSI)
3767 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3769 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3772 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3773 return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind));
3776 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3777 SmallString<16> CharBuffer;
3778 bool Invalid = false;
3779 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3780 if (Invalid)
3781 return ExprError();
3783 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3784 PP, Tok.getKind());
3785 if (Literal.hadError())
3786 return ExprError();
3788 QualType Ty;
3789 if (Literal.isWide())
3790 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3791 else if (Literal.isUTF8() && getLangOpts().C23)
3792 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3793 else if (Literal.isUTF8() && getLangOpts().Char8)
3794 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3795 else if (Literal.isUTF16())
3796 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3797 else if (Literal.isUTF32())
3798 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3799 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3800 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3801 else
3802 Ty = Context.CharTy; // 'x' -> char in C++;
3803 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3805 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3806 if (Literal.isWide())
3807 Kind = CharacterLiteral::Wide;
3808 else if (Literal.isUTF16())
3809 Kind = CharacterLiteral::UTF16;
3810 else if (Literal.isUTF32())
3811 Kind = CharacterLiteral::UTF32;
3812 else if (Literal.isUTF8())
3813 Kind = CharacterLiteral::UTF8;
3815 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3816 Tok.getLocation());
3818 if (Literal.getUDSuffix().empty())
3819 return Lit;
3821 // We're building a user-defined literal.
3822 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3823 SourceLocation UDSuffixLoc =
3824 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3826 // Make sure we're allowed user-defined literals here.
3827 if (!UDLScope)
3828 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3830 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3831 // operator "" X (ch)
3832 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3833 Lit, Tok.getLocation());
3836 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3837 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3838 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3839 Context.IntTy, Loc);
3842 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3843 QualType Ty, SourceLocation Loc) {
3844 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3846 using llvm::APFloat;
3847 APFloat Val(Format);
3849 APFloat::opStatus result = Literal.GetFloatValue(Val);
3851 // Overflow is always an error, but underflow is only an error if
3852 // we underflowed to zero (APFloat reports denormals as underflow).
3853 if ((result & APFloat::opOverflow) ||
3854 ((result & APFloat::opUnderflow) && Val.isZero())) {
3855 unsigned diagnostic;
3856 SmallString<20> buffer;
3857 if (result & APFloat::opOverflow) {
3858 diagnostic = diag::warn_float_overflow;
3859 APFloat::getLargest(Format).toString(buffer);
3860 } else {
3861 diagnostic = diag::warn_float_underflow;
3862 APFloat::getSmallest(Format).toString(buffer);
3865 S.Diag(Loc, diagnostic)
3866 << Ty
3867 << StringRef(buffer.data(), buffer.size());
3870 bool isExact = (result == APFloat::opOK);
3871 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3874 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3875 assert(E && "Invalid expression");
3877 if (E->isValueDependent())
3878 return false;
3880 QualType QT = E->getType();
3881 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3882 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3883 return true;
3886 llvm::APSInt ValueAPS;
3887 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3889 if (R.isInvalid())
3890 return true;
3892 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3893 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3894 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3895 << toString(ValueAPS, 10) << ValueIsPositive;
3896 return true;
3899 return false;
3902 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3903 // Fast path for a single digit (which is quite common). A single digit
3904 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3905 if (Tok.getLength() == 1) {
3906 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3907 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3910 SmallString<128> SpellingBuffer;
3911 // NumericLiteralParser wants to overread by one character. Add padding to
3912 // the buffer in case the token is copied to the buffer. If getSpelling()
3913 // returns a StringRef to the memory buffer, it should have a null char at
3914 // the EOF, so it is also safe.
3915 SpellingBuffer.resize(Tok.getLength() + 1);
3917 // Get the spelling of the token, which eliminates trigraphs, etc.
3918 bool Invalid = false;
3919 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3920 if (Invalid)
3921 return ExprError();
3923 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3924 PP.getSourceManager(), PP.getLangOpts(),
3925 PP.getTargetInfo(), PP.getDiagnostics());
3926 if (Literal.hadError)
3927 return ExprError();
3929 if (Literal.hasUDSuffix()) {
3930 // We're building a user-defined literal.
3931 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3932 SourceLocation UDSuffixLoc =
3933 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3935 // Make sure we're allowed user-defined literals here.
3936 if (!UDLScope)
3937 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3939 QualType CookedTy;
3940 if (Literal.isFloatingLiteral()) {
3941 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3942 // long double, the literal is treated as a call of the form
3943 // operator "" X (f L)
3944 CookedTy = Context.LongDoubleTy;
3945 } else {
3946 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3947 // unsigned long long, the literal is treated as a call of the form
3948 // operator "" X (n ULL)
3949 CookedTy = Context.UnsignedLongLongTy;
3952 DeclarationName OpName =
3953 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3954 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3955 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3957 SourceLocation TokLoc = Tok.getLocation();
3959 // Perform literal operator lookup to determine if we're building a raw
3960 // literal or a cooked one.
3961 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3962 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3963 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3964 /*AllowStringTemplatePack*/ false,
3965 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3966 case LOLR_ErrorNoDiagnostic:
3967 // Lookup failure for imaginary constants isn't fatal, there's still the
3968 // GNU extension producing _Complex types.
3969 break;
3970 case LOLR_Error:
3971 return ExprError();
3972 case LOLR_Cooked: {
3973 Expr *Lit;
3974 if (Literal.isFloatingLiteral()) {
3975 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3976 } else {
3977 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3978 if (Literal.GetIntegerValue(ResultVal))
3979 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3980 << /* Unsigned */ 1;
3981 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3982 Tok.getLocation());
3984 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3987 case LOLR_Raw: {
3988 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3989 // literal is treated as a call of the form
3990 // operator "" X ("n")
3991 unsigned Length = Literal.getUDSuffixOffset();
3992 QualType StrTy = Context.getConstantArrayType(
3993 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3994 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3995 Expr *Lit =
3996 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3997 StringLiteral::Ordinary,
3998 /*Pascal*/ false, StrTy, &TokLoc, 1);
3999 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4002 case LOLR_Template: {
4003 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
4004 // template), L is treated as a call fo the form
4005 // operator "" X <'c1', 'c2', ... 'ck'>()
4006 // where n is the source character sequence c1 c2 ... ck.
4007 TemplateArgumentListInfo ExplicitArgs;
4008 unsigned CharBits = Context.getIntWidth(Context.CharTy);
4009 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4010 llvm::APSInt Value(CharBits, CharIsUnsigned);
4011 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4012 Value = TokSpelling[I];
4013 TemplateArgument Arg(Context, Value, Context.CharTy);
4014 TemplateArgumentLocInfo ArgInfo;
4015 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
4017 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
4018 &ExplicitArgs);
4020 case LOLR_StringTemplatePack:
4021 llvm_unreachable("unexpected literal operator lookup result");
4025 Expr *Res;
4027 if (Literal.isFixedPointLiteral()) {
4028 QualType Ty;
4030 if (Literal.isAccum) {
4031 if (Literal.isHalf) {
4032 Ty = Context.ShortAccumTy;
4033 } else if (Literal.isLong) {
4034 Ty = Context.LongAccumTy;
4035 } else {
4036 Ty = Context.AccumTy;
4038 } else if (Literal.isFract) {
4039 if (Literal.isHalf) {
4040 Ty = Context.ShortFractTy;
4041 } else if (Literal.isLong) {
4042 Ty = Context.LongFractTy;
4043 } else {
4044 Ty = Context.FractTy;
4048 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
4050 bool isSigned = !Literal.isUnsigned;
4051 unsigned scale = Context.getFixedPointScale(Ty);
4052 unsigned bit_width = Context.getTypeInfo(Ty).Width;
4054 llvm::APInt Val(bit_width, 0, isSigned);
4055 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
4056 bool ValIsZero = Val.isZero() && !Overflowed;
4058 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4059 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4060 // Clause 6.4.4 - The value of a constant shall be in the range of
4061 // representable values for its type, with exception for constants of a
4062 // fract type with a value of exactly 1; such a constant shall denote
4063 // the maximal value for the type.
4064 --Val;
4065 else if (Val.ugt(MaxVal) || Overflowed)
4066 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4068 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
4069 Tok.getLocation(), scale);
4070 } else if (Literal.isFloatingLiteral()) {
4071 QualType Ty;
4072 if (Literal.isHalf){
4073 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4074 Ty = Context.HalfTy;
4075 else {
4076 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4077 return ExprError();
4079 } else if (Literal.isFloat)
4080 Ty = Context.FloatTy;
4081 else if (Literal.isLong)
4082 Ty = Context.LongDoubleTy;
4083 else if (Literal.isFloat16)
4084 Ty = Context.Float16Ty;
4085 else if (Literal.isFloat128)
4086 Ty = Context.Float128Ty;
4087 else
4088 Ty = Context.DoubleTy;
4090 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4092 if (Ty == Context.DoubleTy) {
4093 if (getLangOpts().SinglePrecisionConstants) {
4094 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4095 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4097 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4098 "cl_khr_fp64", getLangOpts())) {
4099 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4100 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4101 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4102 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4105 } else if (!Literal.isIntegerLiteral()) {
4106 return ExprError();
4107 } else {
4108 QualType Ty;
4110 // 'z/uz' literals are a C++23 feature.
4111 if (Literal.isSizeT)
4112 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4113 ? getLangOpts().CPlusPlus23
4114 ? diag::warn_cxx20_compat_size_t_suffix
4115 : diag::ext_cxx23_size_t_suffix
4116 : diag::err_cxx23_size_t_suffix);
4118 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4119 // but we do not currently support the suffix in C++ mode because it's not
4120 // entirely clear whether WG21 will prefer this suffix to return a library
4121 // type such as std::bit_int instead of returning a _BitInt.
4122 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
4123 PP.Diag(Tok.getLocation(), getLangOpts().C23
4124 ? diag::warn_c23_compat_bitint_suffix
4125 : diag::ext_c23_bitint_suffix);
4127 // Get the value in the widest-possible width. What is "widest" depends on
4128 // whether the literal is a bit-precise integer or not. For a bit-precise
4129 // integer type, try to scan the source to determine how many bits are
4130 // needed to represent the value. This may seem a bit expensive, but trying
4131 // to get the integer value from an overly-wide APInt is *extremely*
4132 // expensive, so the naive approach of assuming
4133 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4134 unsigned BitsNeeded =
4135 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
4136 Literal.getLiteralDigits(), Literal.getRadix())
4137 : Context.getTargetInfo().getIntMaxTWidth();
4138 llvm::APInt ResultVal(BitsNeeded, 0);
4140 if (Literal.GetIntegerValue(ResultVal)) {
4141 // If this value didn't fit into uintmax_t, error and force to ull.
4142 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4143 << /* Unsigned */ 1;
4144 Ty = Context.UnsignedLongLongTy;
4145 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4146 "long long is not intmax_t?");
4147 } else {
4148 // If this value fits into a ULL, try to figure out what else it fits into
4149 // according to the rules of C99 6.4.4.1p5.
4151 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4152 // be an unsigned int.
4153 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4155 // Check from smallest to largest, picking the smallest type we can.
4156 unsigned Width = 0;
4158 // Microsoft specific integer suffixes are explicitly sized.
4159 if (Literal.MicrosoftInteger) {
4160 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4161 Width = 8;
4162 Ty = Context.CharTy;
4163 } else {
4164 Width = Literal.MicrosoftInteger;
4165 Ty = Context.getIntTypeForBitwidth(Width,
4166 /*Signed=*/!Literal.isUnsigned);
4170 // Bit-precise integer literals are automagically-sized based on the
4171 // width required by the literal.
4172 if (Literal.isBitInt) {
4173 // The signed version has one more bit for the sign value. There are no
4174 // zero-width bit-precise integers, even if the literal value is 0.
4175 Width = std::max(ResultVal.getActiveBits(), 1u) +
4176 (Literal.isUnsigned ? 0u : 1u);
4178 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4179 // and reset the type to the largest supported width.
4180 unsigned int MaxBitIntWidth =
4181 Context.getTargetInfo().getMaxBitIntWidth();
4182 if (Width > MaxBitIntWidth) {
4183 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4184 << Literal.isUnsigned;
4185 Width = MaxBitIntWidth;
4188 // Reset the result value to the smaller APInt and select the correct
4189 // type to be used. Note, we zext even for signed values because the
4190 // literal itself is always an unsigned value (a preceeding - is a
4191 // unary operator, not part of the literal).
4192 ResultVal = ResultVal.zextOrTrunc(Width);
4193 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4196 // Check C++23 size_t literals.
4197 if (Literal.isSizeT) {
4198 assert(!Literal.MicrosoftInteger &&
4199 "size_t literals can't be Microsoft literals");
4200 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4201 Context.getTargetInfo().getSizeType());
4203 // Does it fit in size_t?
4204 if (ResultVal.isIntN(SizeTSize)) {
4205 // Does it fit in ssize_t?
4206 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4207 Ty = Context.getSignedSizeType();
4208 else if (AllowUnsigned)
4209 Ty = Context.getSizeType();
4210 Width = SizeTSize;
4214 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4215 !Literal.isSizeT) {
4216 // Are int/unsigned possibilities?
4217 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4219 // Does it fit in a unsigned int?
4220 if (ResultVal.isIntN(IntSize)) {
4221 // Does it fit in a signed int?
4222 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4223 Ty = Context.IntTy;
4224 else if (AllowUnsigned)
4225 Ty = Context.UnsignedIntTy;
4226 Width = IntSize;
4230 // Are long/unsigned long possibilities?
4231 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4232 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4234 // Does it fit in a unsigned long?
4235 if (ResultVal.isIntN(LongSize)) {
4236 // Does it fit in a signed long?
4237 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4238 Ty = Context.LongTy;
4239 else if (AllowUnsigned)
4240 Ty = Context.UnsignedLongTy;
4241 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4242 // is compatible.
4243 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4244 const unsigned LongLongSize =
4245 Context.getTargetInfo().getLongLongWidth();
4246 Diag(Tok.getLocation(),
4247 getLangOpts().CPlusPlus
4248 ? Literal.isLong
4249 ? diag::warn_old_implicitly_unsigned_long_cxx
4250 : /*C++98 UB*/ diag::
4251 ext_old_implicitly_unsigned_long_cxx
4252 : diag::warn_old_implicitly_unsigned_long)
4253 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4254 : /*will be ill-formed*/ 1);
4255 Ty = Context.UnsignedLongTy;
4257 Width = LongSize;
4261 // Check long long if needed.
4262 if (Ty.isNull() && !Literal.isSizeT) {
4263 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4265 // Does it fit in a unsigned long long?
4266 if (ResultVal.isIntN(LongLongSize)) {
4267 // Does it fit in a signed long long?
4268 // To be compatible with MSVC, hex integer literals ending with the
4269 // LL or i64 suffix are always signed in Microsoft mode.
4270 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4271 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4272 Ty = Context.LongLongTy;
4273 else if (AllowUnsigned)
4274 Ty = Context.UnsignedLongLongTy;
4275 Width = LongLongSize;
4277 // 'long long' is a C99 or C++11 feature, whether the literal
4278 // explicitly specified 'long long' or we needed the extra width.
4279 if (getLangOpts().CPlusPlus)
4280 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4281 ? diag::warn_cxx98_compat_longlong
4282 : diag::ext_cxx11_longlong);
4283 else if (!getLangOpts().C99)
4284 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4288 // If we still couldn't decide a type, we either have 'size_t' literal
4289 // that is out of range, or a decimal literal that does not fit in a
4290 // signed long long and has no U suffix.
4291 if (Ty.isNull()) {
4292 if (Literal.isSizeT)
4293 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4294 << Literal.isUnsigned;
4295 else
4296 Diag(Tok.getLocation(),
4297 diag::ext_integer_literal_too_large_for_signed);
4298 Ty = Context.UnsignedLongLongTy;
4299 Width = Context.getTargetInfo().getLongLongWidth();
4302 if (ResultVal.getBitWidth() != Width)
4303 ResultVal = ResultVal.trunc(Width);
4305 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4308 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4309 if (Literal.isImaginary) {
4310 Res = new (Context) ImaginaryLiteral(Res,
4311 Context.getComplexType(Res->getType()));
4313 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4315 return Res;
4318 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4319 assert(E && "ActOnParenExpr() missing expr");
4320 QualType ExprTy = E->getType();
4321 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4322 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4323 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4324 return new (Context) ParenExpr(L, R, E);
4327 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4328 SourceLocation Loc,
4329 SourceRange ArgRange) {
4330 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4331 // scalar or vector data type argument..."
4332 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4333 // type (C99 6.2.5p18) or void.
4334 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4335 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4336 << T << ArgRange;
4337 return true;
4340 assert((T->isVoidType() || !T->isIncompleteType()) &&
4341 "Scalar types should always be complete");
4342 return false;
4345 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4346 SourceLocation Loc,
4347 SourceRange ArgRange,
4348 UnaryExprOrTypeTrait TraitKind) {
4349 // Invalid types must be hard errors for SFINAE in C++.
4350 if (S.LangOpts.CPlusPlus)
4351 return true;
4353 // C99 6.5.3.4p1:
4354 if (T->isFunctionType() &&
4355 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4356 TraitKind == UETT_PreferredAlignOf)) {
4357 // sizeof(function)/alignof(function) is allowed as an extension.
4358 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4359 << getTraitSpelling(TraitKind) << ArgRange;
4360 return false;
4363 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4364 // this is an error (OpenCL v1.1 s6.3.k)
4365 if (T->isVoidType()) {
4366 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4367 : diag::ext_sizeof_alignof_void_type;
4368 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4369 return false;
4372 return true;
4375 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4376 SourceLocation Loc,
4377 SourceRange ArgRange,
4378 UnaryExprOrTypeTrait TraitKind) {
4379 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4380 // runtime doesn't allow it.
4381 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4382 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4383 << T << (TraitKind == UETT_SizeOf)
4384 << ArgRange;
4385 return true;
4388 return false;
4391 /// Check whether E is a pointer from a decayed array type (the decayed
4392 /// pointer type is equal to T) and emit a warning if it is.
4393 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4394 const Expr *E) {
4395 // Don't warn if the operation changed the type.
4396 if (T != E->getType())
4397 return;
4399 // Now look for array decays.
4400 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4401 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4402 return;
4404 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4405 << ICE->getType()
4406 << ICE->getSubExpr()->getType();
4409 /// Check the constraints on expression operands to unary type expression
4410 /// and type traits.
4412 /// Completes any types necessary and validates the constraints on the operand
4413 /// expression. The logic mostly mirrors the type-based overload, but may modify
4414 /// the expression as it completes the type for that expression through template
4415 /// instantiation, etc.
4416 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4417 UnaryExprOrTypeTrait ExprKind) {
4418 QualType ExprTy = E->getType();
4419 assert(!ExprTy->isReferenceType());
4421 bool IsUnevaluatedOperand =
4422 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4423 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4424 if (IsUnevaluatedOperand) {
4425 ExprResult Result = CheckUnevaluatedOperand(E);
4426 if (Result.isInvalid())
4427 return true;
4428 E = Result.get();
4431 // The operand for sizeof and alignof is in an unevaluated expression context,
4432 // so side effects could result in unintended consequences.
4433 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4434 // used to build SFINAE gadgets.
4435 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4436 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4437 !E->isInstantiationDependent() &&
4438 !E->getType()->isVariableArrayType() &&
4439 E->HasSideEffects(Context, false))
4440 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4442 if (ExprKind == UETT_VecStep)
4443 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4444 E->getSourceRange());
4446 // Explicitly list some types as extensions.
4447 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4448 E->getSourceRange(), ExprKind))
4449 return false;
4451 // WebAssembly tables are always illegal operands to unary expressions and
4452 // type traits.
4453 if (Context.getTargetInfo().getTriple().isWasm() &&
4454 E->getType()->isWebAssemblyTableType()) {
4455 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4456 << getTraitSpelling(ExprKind);
4457 return true;
4460 // 'alignof' applied to an expression only requires the base element type of
4461 // the expression to be complete. 'sizeof' requires the expression's type to
4462 // be complete (and will attempt to complete it if it's an array of unknown
4463 // bound).
4464 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4465 if (RequireCompleteSizedType(
4466 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4467 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4468 getTraitSpelling(ExprKind), E->getSourceRange()))
4469 return true;
4470 } else {
4471 if (RequireCompleteSizedExprType(
4472 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4473 getTraitSpelling(ExprKind), E->getSourceRange()))
4474 return true;
4477 // Completing the expression's type may have changed it.
4478 ExprTy = E->getType();
4479 assert(!ExprTy->isReferenceType());
4481 if (ExprTy->isFunctionType()) {
4482 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4483 << getTraitSpelling(ExprKind) << E->getSourceRange();
4484 return true;
4487 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4488 E->getSourceRange(), ExprKind))
4489 return true;
4491 if (ExprKind == UETT_SizeOf) {
4492 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4493 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4494 QualType OType = PVD->getOriginalType();
4495 QualType Type = PVD->getType();
4496 if (Type->isPointerType() && OType->isArrayType()) {
4497 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4498 << Type << OType;
4499 Diag(PVD->getLocation(), diag::note_declared_at);
4504 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4505 // decays into a pointer and returns an unintended result. This is most
4506 // likely a typo for "sizeof(array) op x".
4507 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4508 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4509 BO->getLHS());
4510 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4511 BO->getRHS());
4515 return false;
4518 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4519 // Cannot know anything else if the expression is dependent.
4520 if (E->isTypeDependent())
4521 return false;
4523 if (E->getObjectKind() == OK_BitField) {
4524 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4525 << 1 << E->getSourceRange();
4526 return true;
4529 ValueDecl *D = nullptr;
4530 Expr *Inner = E->IgnoreParens();
4531 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4532 D = DRE->getDecl();
4533 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4534 D = ME->getMemberDecl();
4537 // If it's a field, require the containing struct to have a
4538 // complete definition so that we can compute the layout.
4540 // This can happen in C++11 onwards, either by naming the member
4541 // in a way that is not transformed into a member access expression
4542 // (in an unevaluated operand, for instance), or by naming the member
4543 // in a trailing-return-type.
4545 // For the record, since __alignof__ on expressions is a GCC
4546 // extension, GCC seems to permit this but always gives the
4547 // nonsensical answer 0.
4549 // We don't really need the layout here --- we could instead just
4550 // directly check for all the appropriate alignment-lowing
4551 // attributes --- but that would require duplicating a lot of
4552 // logic that just isn't worth duplicating for such a marginal
4553 // use-case.
4554 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4555 // Fast path this check, since we at least know the record has a
4556 // definition if we can find a member of it.
4557 if (!FD->getParent()->isCompleteDefinition()) {
4558 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4559 << E->getSourceRange();
4560 return true;
4563 // Otherwise, if it's a field, and the field doesn't have
4564 // reference type, then it must have a complete type (or be a
4565 // flexible array member, which we explicitly want to
4566 // white-list anyway), which makes the following checks trivial.
4567 if (!FD->getType()->isReferenceType())
4568 return false;
4571 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4574 bool Sema::CheckVecStepExpr(Expr *E) {
4575 E = E->IgnoreParens();
4577 // Cannot know anything else if the expression is dependent.
4578 if (E->isTypeDependent())
4579 return false;
4581 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4584 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4585 CapturingScopeInfo *CSI) {
4586 assert(T->isVariablyModifiedType());
4587 assert(CSI != nullptr);
4589 // We're going to walk down into the type and look for VLA expressions.
4590 do {
4591 const Type *Ty = T.getTypePtr();
4592 switch (Ty->getTypeClass()) {
4593 #define TYPE(Class, Base)
4594 #define ABSTRACT_TYPE(Class, Base)
4595 #define NON_CANONICAL_TYPE(Class, Base)
4596 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4597 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4598 #include "clang/AST/TypeNodes.inc"
4599 T = QualType();
4600 break;
4601 // These types are never variably-modified.
4602 case Type::Builtin:
4603 case Type::Complex:
4604 case Type::Vector:
4605 case Type::ExtVector:
4606 case Type::ConstantMatrix:
4607 case Type::Record:
4608 case Type::Enum:
4609 case Type::TemplateSpecialization:
4610 case Type::ObjCObject:
4611 case Type::ObjCInterface:
4612 case Type::ObjCObjectPointer:
4613 case Type::ObjCTypeParam:
4614 case Type::Pipe:
4615 case Type::BitInt:
4616 llvm_unreachable("type class is never variably-modified!");
4617 case Type::Elaborated:
4618 T = cast<ElaboratedType>(Ty)->getNamedType();
4619 break;
4620 case Type::Adjusted:
4621 T = cast<AdjustedType>(Ty)->getOriginalType();
4622 break;
4623 case Type::Decayed:
4624 T = cast<DecayedType>(Ty)->getPointeeType();
4625 break;
4626 case Type::Pointer:
4627 T = cast<PointerType>(Ty)->getPointeeType();
4628 break;
4629 case Type::BlockPointer:
4630 T = cast<BlockPointerType>(Ty)->getPointeeType();
4631 break;
4632 case Type::LValueReference:
4633 case Type::RValueReference:
4634 T = cast<ReferenceType>(Ty)->getPointeeType();
4635 break;
4636 case Type::MemberPointer:
4637 T = cast<MemberPointerType>(Ty)->getPointeeType();
4638 break;
4639 case Type::ConstantArray:
4640 case Type::IncompleteArray:
4641 // Losing element qualification here is fine.
4642 T = cast<ArrayType>(Ty)->getElementType();
4643 break;
4644 case Type::VariableArray: {
4645 // Losing element qualification here is fine.
4646 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4648 // Unknown size indication requires no size computation.
4649 // Otherwise, evaluate and record it.
4650 auto Size = VAT->getSizeExpr();
4651 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4652 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4653 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4655 T = VAT->getElementType();
4656 break;
4658 case Type::FunctionProto:
4659 case Type::FunctionNoProto:
4660 T = cast<FunctionType>(Ty)->getReturnType();
4661 break;
4662 case Type::Paren:
4663 case Type::TypeOf:
4664 case Type::UnaryTransform:
4665 case Type::Attributed:
4666 case Type::BTFTagAttributed:
4667 case Type::SubstTemplateTypeParm:
4668 case Type::MacroQualified:
4669 // Keep walking after single level desugaring.
4670 T = T.getSingleStepDesugaredType(Context);
4671 break;
4672 case Type::Typedef:
4673 T = cast<TypedefType>(Ty)->desugar();
4674 break;
4675 case Type::Decltype:
4676 T = cast<DecltypeType>(Ty)->desugar();
4677 break;
4678 case Type::Using:
4679 T = cast<UsingType>(Ty)->desugar();
4680 break;
4681 case Type::Auto:
4682 case Type::DeducedTemplateSpecialization:
4683 T = cast<DeducedType>(Ty)->getDeducedType();
4684 break;
4685 case Type::TypeOfExpr:
4686 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4687 break;
4688 case Type::Atomic:
4689 T = cast<AtomicType>(Ty)->getValueType();
4690 break;
4692 } while (!T.isNull() && T->isVariablyModifiedType());
4695 /// Check the constraints on operands to unary expression and type
4696 /// traits.
4698 /// This will complete any types necessary, and validate the various constraints
4699 /// on those operands.
4701 /// The UsualUnaryConversions() function is *not* called by this routine.
4702 /// C99 6.3.2.1p[2-4] all state:
4703 /// Except when it is the operand of the sizeof operator ...
4705 /// C++ [expr.sizeof]p4
4706 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4707 /// standard conversions are not applied to the operand of sizeof.
4709 /// This policy is followed for all of the unary trait expressions.
4710 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4711 SourceLocation OpLoc,
4712 SourceRange ExprRange,
4713 UnaryExprOrTypeTrait ExprKind,
4714 StringRef KWName) {
4715 if (ExprType->isDependentType())
4716 return false;
4718 // C++ [expr.sizeof]p2:
4719 // When applied to a reference or a reference type, the result
4720 // is the size of the referenced type.
4721 // C++11 [expr.alignof]p3:
4722 // When alignof is applied to a reference type, the result
4723 // shall be the alignment of the referenced type.
4724 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4725 ExprType = Ref->getPointeeType();
4727 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4728 // When alignof or _Alignof is applied to an array type, the result
4729 // is the alignment of the element type.
4730 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4731 ExprKind == UETT_OpenMPRequiredSimdAlign)
4732 ExprType = Context.getBaseElementType(ExprType);
4734 if (ExprKind == UETT_VecStep)
4735 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4737 // Explicitly list some types as extensions.
4738 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4739 ExprKind))
4740 return false;
4742 if (RequireCompleteSizedType(
4743 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4744 KWName, ExprRange))
4745 return true;
4747 if (ExprType->isFunctionType()) {
4748 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4749 return true;
4752 // WebAssembly tables are always illegal operands to unary expressions and
4753 // type traits.
4754 if (Context.getTargetInfo().getTriple().isWasm() &&
4755 ExprType->isWebAssemblyTableType()) {
4756 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4757 << getTraitSpelling(ExprKind);
4758 return true;
4761 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4762 ExprKind))
4763 return true;
4765 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4766 if (auto *TT = ExprType->getAs<TypedefType>()) {
4767 for (auto I = FunctionScopes.rbegin(),
4768 E = std::prev(FunctionScopes.rend());
4769 I != E; ++I) {
4770 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4771 if (CSI == nullptr)
4772 break;
4773 DeclContext *DC = nullptr;
4774 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4775 DC = LSI->CallOperator;
4776 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4777 DC = CRSI->TheCapturedDecl;
4778 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4779 DC = BSI->TheDecl;
4780 if (DC) {
4781 if (DC->containsDecl(TT->getDecl()))
4782 break;
4783 captureVariablyModifiedType(Context, ExprType, CSI);
4789 return false;
4792 /// Build a sizeof or alignof expression given a type operand.
4793 ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4794 SourceLocation OpLoc,
4795 UnaryExprOrTypeTrait ExprKind,
4796 SourceRange R) {
4797 if (!TInfo)
4798 return ExprError();
4800 QualType T = TInfo->getType();
4802 if (!T->isDependentType() &&
4803 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4804 getTraitSpelling(ExprKind)))
4805 return ExprError();
4807 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4808 // properly deal with VLAs in nested calls of sizeof and typeof.
4809 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4810 TInfo->getType()->isVariablyModifiedType())
4811 TInfo = TransformToPotentiallyEvaluated(TInfo);
4813 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4814 return new (Context) UnaryExprOrTypeTraitExpr(
4815 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4818 /// Build a sizeof or alignof expression given an expression
4819 /// operand.
4820 ExprResult
4821 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4822 UnaryExprOrTypeTrait ExprKind) {
4823 ExprResult PE = CheckPlaceholderExpr(E);
4824 if (PE.isInvalid())
4825 return ExprError();
4827 E = PE.get();
4829 // Verify that the operand is valid.
4830 bool isInvalid = false;
4831 if (E->isTypeDependent()) {
4832 // Delay type-checking for type-dependent expressions.
4833 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4834 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4835 } else if (ExprKind == UETT_VecStep) {
4836 isInvalid = CheckVecStepExpr(E);
4837 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4838 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4839 isInvalid = true;
4840 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4841 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4842 isInvalid = true;
4843 } else {
4844 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4847 if (isInvalid)
4848 return ExprError();
4850 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4851 PE = TransformToPotentiallyEvaluated(E);
4852 if (PE.isInvalid()) return ExprError();
4853 E = PE.get();
4856 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4857 return new (Context) UnaryExprOrTypeTraitExpr(
4858 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4861 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4862 /// expr and the same for @c alignof and @c __alignof
4863 /// Note that the ArgRange is invalid if isType is false.
4864 ExprResult
4865 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4866 UnaryExprOrTypeTrait ExprKind, bool IsType,
4867 void *TyOrEx, SourceRange ArgRange) {
4868 // If error parsing type, ignore.
4869 if (!TyOrEx) return ExprError();
4871 if (IsType) {
4872 TypeSourceInfo *TInfo;
4873 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4874 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4877 Expr *ArgEx = (Expr *)TyOrEx;
4878 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4879 return Result;
4882 bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4883 SourceLocation OpLoc, SourceRange R) {
4884 if (!TInfo)
4885 return true;
4886 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4887 UETT_AlignOf, KWName);
4890 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
4891 /// _Alignas(type-name) .
4892 /// [dcl.align] An alignment-specifier of the form
4893 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
4895 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
4896 /// _Alignas(_Alignof(type-name)).
4897 bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4898 SourceLocation OpLoc, SourceRange R) {
4899 TypeSourceInfo *TInfo;
4900 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(Ty.getAsOpaquePtr()),
4901 &TInfo);
4902 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4905 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4906 bool IsReal) {
4907 if (V.get()->isTypeDependent())
4908 return S.Context.DependentTy;
4910 // _Real and _Imag are only l-values for normal l-values.
4911 if (V.get()->getObjectKind() != OK_Ordinary) {
4912 V = S.DefaultLvalueConversion(V.get());
4913 if (V.isInvalid())
4914 return QualType();
4917 // These operators return the element type of a complex type.
4918 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4919 return CT->getElementType();
4921 // Otherwise they pass through real integer and floating point types here.
4922 if (V.get()->getType()->isArithmeticType())
4923 return V.get()->getType();
4925 // Test for placeholders.
4926 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4927 if (PR.isInvalid()) return QualType();
4928 if (PR.get() != V.get()) {
4929 V = PR;
4930 return CheckRealImagOperand(S, V, Loc, IsReal);
4933 // Reject anything else.
4934 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4935 << (IsReal ? "__real" : "__imag");
4936 return QualType();
4941 ExprResult
4942 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4943 tok::TokenKind Kind, Expr *Input) {
4944 UnaryOperatorKind Opc;
4945 switch (Kind) {
4946 default: llvm_unreachable("Unknown unary op!");
4947 case tok::plusplus: Opc = UO_PostInc; break;
4948 case tok::minusminus: Opc = UO_PostDec; break;
4951 // Since this might is a postfix expression, get rid of ParenListExprs.
4952 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4953 if (Result.isInvalid()) return ExprError();
4954 Input = Result.get();
4956 return BuildUnaryOp(S, OpLoc, Opc, Input);
4959 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4961 /// \return true on error
4962 static bool checkArithmeticOnObjCPointer(Sema &S,
4963 SourceLocation opLoc,
4964 Expr *op) {
4965 assert(op->getType()->isObjCObjectPointerType());
4966 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4967 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4968 return false;
4970 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4971 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4972 << op->getSourceRange();
4973 return true;
4976 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4977 auto *BaseNoParens = Base->IgnoreParens();
4978 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4979 return MSProp->getPropertyDecl()->getType()->isArrayType();
4980 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4983 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4984 // Typically this is DependentTy, but can sometimes be more precise.
4986 // There are cases when we could determine a non-dependent type:
4987 // - LHS and RHS may have non-dependent types despite being type-dependent
4988 // (e.g. unbounded array static members of the current instantiation)
4989 // - one may be a dependent-sized array with known element type
4990 // - one may be a dependent-typed valid index (enum in current instantiation)
4992 // We *always* return a dependent type, in such cases it is DependentTy.
4993 // This avoids creating type-dependent expressions with non-dependent types.
4994 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4995 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4996 const ASTContext &Ctx) {
4997 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4998 QualType LTy = LHS->getType(), RTy = RHS->getType();
4999 QualType Result = Ctx.DependentTy;
5000 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5001 if (const PointerType *PT = LTy->getAs<PointerType>())
5002 Result = PT->getPointeeType();
5003 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5004 Result = AT->getElementType();
5005 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5006 if (const PointerType *PT = RTy->getAs<PointerType>())
5007 Result = PT->getPointeeType();
5008 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5009 Result = AT->getElementType();
5011 // Ensure we return a dependent type.
5012 return Result->isDependentType() ? Result : Ctx.DependentTy;
5015 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
5017 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5018 SourceLocation lbLoc,
5019 MultiExprArg ArgExprs,
5020 SourceLocation rbLoc) {
5022 if (base && !base->getType().isNull() &&
5023 base->hasPlaceholderType(BuiltinType::OMPArraySection))
5024 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
5025 SourceLocation(), /*Length*/ nullptr,
5026 /*Stride=*/nullptr, rbLoc);
5028 // Since this might be a postfix expression, get rid of ParenListExprs.
5029 if (isa<ParenListExpr>(base)) {
5030 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
5031 if (result.isInvalid())
5032 return ExprError();
5033 base = result.get();
5036 // Check if base and idx form a MatrixSubscriptExpr.
5038 // Helper to check for comma expressions, which are not allowed as indices for
5039 // matrix subscript expressions.
5040 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
5041 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
5042 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5043 << SourceRange(base->getBeginLoc(), rbLoc);
5044 return true;
5046 return false;
5048 // The matrix subscript operator ([][])is considered a single operator.
5049 // Separating the index expressions by parenthesis is not allowed.
5050 if (base && !base->getType().isNull() &&
5051 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5052 !isa<MatrixSubscriptExpr>(base)) {
5053 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5054 << SourceRange(base->getBeginLoc(), rbLoc);
5055 return ExprError();
5057 // If the base is a MatrixSubscriptExpr, try to create a new
5058 // MatrixSubscriptExpr.
5059 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5060 if (matSubscriptE) {
5061 assert(ArgExprs.size() == 1);
5062 if (CheckAndReportCommaError(ArgExprs.front()))
5063 return ExprError();
5065 assert(matSubscriptE->isIncomplete() &&
5066 "base has to be an incomplete matrix subscript");
5067 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5068 matSubscriptE->getRowIdx(),
5069 ArgExprs.front(), rbLoc);
5071 if (base->getType()->isWebAssemblyTableType()) {
5072 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5073 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5074 return ExprError();
5077 // Handle any non-overload placeholder types in the base and index
5078 // expressions. We can't handle overloads here because the other
5079 // operand might be an overloadable type, in which case the overload
5080 // resolution for the operator overload should get the first crack
5081 // at the overload.
5082 bool IsMSPropertySubscript = false;
5083 if (base->getType()->isNonOverloadPlaceholderType()) {
5084 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5085 if (!IsMSPropertySubscript) {
5086 ExprResult result = CheckPlaceholderExpr(base);
5087 if (result.isInvalid())
5088 return ExprError();
5089 base = result.get();
5093 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5094 if (base->getType()->isMatrixType()) {
5095 assert(ArgExprs.size() == 1);
5096 if (CheckAndReportCommaError(ArgExprs.front()))
5097 return ExprError();
5099 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5100 rbLoc);
5103 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5104 Expr *idx = ArgExprs[0];
5105 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5106 (isa<CXXOperatorCallExpr>(idx) &&
5107 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5108 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5109 << SourceRange(base->getBeginLoc(), rbLoc);
5113 if (ArgExprs.size() == 1 &&
5114 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5115 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5116 if (result.isInvalid())
5117 return ExprError();
5118 ArgExprs[0] = result.get();
5119 } else {
5120 if (checkArgsForPlaceholders(*this, ArgExprs))
5121 return ExprError();
5124 // Build an unanalyzed expression if either operand is type-dependent.
5125 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5126 (base->isTypeDependent() ||
5127 Expr::hasAnyTypeDependentArguments(ArgExprs)) &&
5128 !isa<PackExpansionExpr>(ArgExprs[0])) {
5129 return new (Context) ArraySubscriptExpr(
5130 base, ArgExprs.front(),
5131 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5132 VK_LValue, OK_Ordinary, rbLoc);
5135 // MSDN, property (C++)
5136 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5137 // This attribute can also be used in the declaration of an empty array in a
5138 // class or structure definition. For example:
5139 // __declspec(property(get=GetX, put=PutX)) int x[];
5140 // The above statement indicates that x[] can be used with one or more array
5141 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5142 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5143 if (IsMSPropertySubscript) {
5144 assert(ArgExprs.size() == 1);
5145 // Build MS property subscript expression if base is MS property reference
5146 // or MS property subscript.
5147 return new (Context)
5148 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5149 VK_LValue, OK_Ordinary, rbLoc);
5152 // Use C++ overloaded-operator rules if either operand has record
5153 // type. The spec says to do this if either type is *overloadable*,
5154 // but enum types can't declare subscript operators or conversion
5155 // operators, so there's nothing interesting for overload resolution
5156 // to do if there aren't any record types involved.
5158 // ObjC pointers have their own subscripting logic that is not tied
5159 // to overload resolution and so should not take this path.
5160 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5161 ((base->getType()->isRecordType() ||
5162 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5163 ArgExprs[0]->getType()->isRecordType())))) {
5164 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5167 ExprResult Res =
5168 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5170 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5171 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5173 return Res;
5176 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5177 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
5178 InitializationKind Kind =
5179 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
5180 InitializationSequence InitSeq(*this, Entity, Kind, E);
5181 return InitSeq.Perform(*this, Entity, Kind, E);
5184 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5185 Expr *ColumnIdx,
5186 SourceLocation RBLoc) {
5187 ExprResult BaseR = CheckPlaceholderExpr(Base);
5188 if (BaseR.isInvalid())
5189 return BaseR;
5190 Base = BaseR.get();
5192 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5193 if (RowR.isInvalid())
5194 return RowR;
5195 RowIdx = RowR.get();
5197 if (!ColumnIdx)
5198 return new (Context) MatrixSubscriptExpr(
5199 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5201 // Build an unanalyzed expression if any of the operands is type-dependent.
5202 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5203 ColumnIdx->isTypeDependent())
5204 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5205 Context.DependentTy, RBLoc);
5207 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5208 if (ColumnR.isInvalid())
5209 return ColumnR;
5210 ColumnIdx = ColumnR.get();
5212 // Check that IndexExpr is an integer expression. If it is a constant
5213 // expression, check that it is less than Dim (= the number of elements in the
5214 // corresponding dimension).
5215 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5216 bool IsColumnIdx) -> Expr * {
5217 if (!IndexExpr->getType()->isIntegerType() &&
5218 !IndexExpr->isTypeDependent()) {
5219 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5220 << IsColumnIdx;
5221 return nullptr;
5224 if (std::optional<llvm::APSInt> Idx =
5225 IndexExpr->getIntegerConstantExpr(Context)) {
5226 if ((*Idx < 0 || *Idx >= Dim)) {
5227 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5228 << IsColumnIdx << Dim;
5229 return nullptr;
5233 ExprResult ConvExpr =
5234 tryConvertExprToType(IndexExpr, Context.getSizeType());
5235 assert(!ConvExpr.isInvalid() &&
5236 "should be able to convert any integer type to size type");
5237 return ConvExpr.get();
5240 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5241 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5242 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5243 if (!RowIdx || !ColumnIdx)
5244 return ExprError();
5246 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5247 MTy->getElementType(), RBLoc);
5250 void Sema::CheckAddressOfNoDeref(const Expr *E) {
5251 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5252 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5254 // For expressions like `&(*s).b`, the base is recorded and what should be
5255 // checked.
5256 const MemberExpr *Member = nullptr;
5257 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5258 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5260 LastRecord.PossibleDerefs.erase(StrippedExpr);
5263 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5264 if (isUnevaluatedContext())
5265 return;
5267 QualType ResultTy = E->getType();
5268 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5270 // Bail if the element is an array since it is not memory access.
5271 if (isa<ArrayType>(ResultTy))
5272 return;
5274 if (ResultTy->hasAttr(attr::NoDeref)) {
5275 LastRecord.PossibleDerefs.insert(E);
5276 return;
5279 // Check if the base type is a pointer to a member access of a struct
5280 // marked with noderef.
5281 const Expr *Base = E->getBase();
5282 QualType BaseTy = Base->getType();
5283 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5284 // Not a pointer access
5285 return;
5287 const MemberExpr *Member = nullptr;
5288 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5289 Member->isArrow())
5290 Base = Member->getBase();
5292 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5293 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5294 LastRecord.PossibleDerefs.insert(E);
5298 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5299 Expr *LowerBound,
5300 SourceLocation ColonLocFirst,
5301 SourceLocation ColonLocSecond,
5302 Expr *Length, Expr *Stride,
5303 SourceLocation RBLoc) {
5304 if (Base->hasPlaceholderType() &&
5305 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5306 ExprResult Result = CheckPlaceholderExpr(Base);
5307 if (Result.isInvalid())
5308 return ExprError();
5309 Base = Result.get();
5311 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5312 ExprResult Result = CheckPlaceholderExpr(LowerBound);
5313 if (Result.isInvalid())
5314 return ExprError();
5315 Result = DefaultLvalueConversion(Result.get());
5316 if (Result.isInvalid())
5317 return ExprError();
5318 LowerBound = Result.get();
5320 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5321 ExprResult Result = CheckPlaceholderExpr(Length);
5322 if (Result.isInvalid())
5323 return ExprError();
5324 Result = DefaultLvalueConversion(Result.get());
5325 if (Result.isInvalid())
5326 return ExprError();
5327 Length = Result.get();
5329 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5330 ExprResult Result = CheckPlaceholderExpr(Stride);
5331 if (Result.isInvalid())
5332 return ExprError();
5333 Result = DefaultLvalueConversion(Result.get());
5334 if (Result.isInvalid())
5335 return ExprError();
5336 Stride = Result.get();
5339 // Build an unanalyzed expression if either operand is type-dependent.
5340 if (Base->isTypeDependent() ||
5341 (LowerBound &&
5342 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5343 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5344 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5345 return new (Context) OMPArraySectionExpr(
5346 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5347 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5350 // Perform default conversions.
5351 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5352 QualType ResultTy;
5353 if (OriginalTy->isAnyPointerType()) {
5354 ResultTy = OriginalTy->getPointeeType();
5355 } else if (OriginalTy->isArrayType()) {
5356 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5357 } else {
5358 return ExprError(
5359 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5360 << Base->getSourceRange());
5362 // C99 6.5.2.1p1
5363 if (LowerBound) {
5364 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5365 LowerBound);
5366 if (Res.isInvalid())
5367 return ExprError(Diag(LowerBound->getExprLoc(),
5368 diag::err_omp_typecheck_section_not_integer)
5369 << 0 << LowerBound->getSourceRange());
5370 LowerBound = Res.get();
5372 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5373 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5374 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5375 << 0 << LowerBound->getSourceRange();
5377 if (Length) {
5378 auto Res =
5379 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5380 if (Res.isInvalid())
5381 return ExprError(Diag(Length->getExprLoc(),
5382 diag::err_omp_typecheck_section_not_integer)
5383 << 1 << Length->getSourceRange());
5384 Length = Res.get();
5386 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5387 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5388 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5389 << 1 << Length->getSourceRange();
5391 if (Stride) {
5392 ExprResult Res =
5393 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5394 if (Res.isInvalid())
5395 return ExprError(Diag(Stride->getExprLoc(),
5396 diag::err_omp_typecheck_section_not_integer)
5397 << 1 << Stride->getSourceRange());
5398 Stride = Res.get();
5400 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5401 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5402 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5403 << 1 << Stride->getSourceRange();
5406 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5407 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5408 // type. Note that functions are not objects, and that (in C99 parlance)
5409 // incomplete types are not object types.
5410 if (ResultTy->isFunctionType()) {
5411 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5412 << ResultTy << Base->getSourceRange();
5413 return ExprError();
5416 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5417 diag::err_omp_section_incomplete_type, Base))
5418 return ExprError();
5420 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5421 Expr::EvalResult Result;
5422 if (LowerBound->EvaluateAsInt(Result, Context)) {
5423 // OpenMP 5.0, [2.1.5 Array Sections]
5424 // The array section must be a subset of the original array.
5425 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5426 if (LowerBoundValue.isNegative()) {
5427 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5428 << LowerBound->getSourceRange();
5429 return ExprError();
5434 if (Length) {
5435 Expr::EvalResult Result;
5436 if (Length->EvaluateAsInt(Result, Context)) {
5437 // OpenMP 5.0, [2.1.5 Array Sections]
5438 // The length must evaluate to non-negative integers.
5439 llvm::APSInt LengthValue = Result.Val.getInt();
5440 if (LengthValue.isNegative()) {
5441 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5442 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5443 << Length->getSourceRange();
5444 return ExprError();
5447 } else if (ColonLocFirst.isValid() &&
5448 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5449 !OriginalTy->isVariableArrayType()))) {
5450 // OpenMP 5.0, [2.1.5 Array Sections]
5451 // When the size of the array dimension is not known, the length must be
5452 // specified explicitly.
5453 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5454 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5455 return ExprError();
5458 if (Stride) {
5459 Expr::EvalResult Result;
5460 if (Stride->EvaluateAsInt(Result, Context)) {
5461 // OpenMP 5.0, [2.1.5 Array Sections]
5462 // The stride must evaluate to a positive integer.
5463 llvm::APSInt StrideValue = Result.Val.getInt();
5464 if (!StrideValue.isStrictlyPositive()) {
5465 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5466 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5467 << Stride->getSourceRange();
5468 return ExprError();
5473 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5474 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5475 if (Result.isInvalid())
5476 return ExprError();
5477 Base = Result.get();
5479 return new (Context) OMPArraySectionExpr(
5480 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5481 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5484 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5485 SourceLocation RParenLoc,
5486 ArrayRef<Expr *> Dims,
5487 ArrayRef<SourceRange> Brackets) {
5488 if (Base->hasPlaceholderType()) {
5489 ExprResult Result = CheckPlaceholderExpr(Base);
5490 if (Result.isInvalid())
5491 return ExprError();
5492 Result = DefaultLvalueConversion(Result.get());
5493 if (Result.isInvalid())
5494 return ExprError();
5495 Base = Result.get();
5497 QualType BaseTy = Base->getType();
5498 // Delay analysis of the types/expressions if instantiation/specialization is
5499 // required.
5500 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5501 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5502 LParenLoc, RParenLoc, Dims, Brackets);
5503 if (!BaseTy->isPointerType() ||
5504 (!Base->isTypeDependent() &&
5505 BaseTy->getPointeeType()->isIncompleteType()))
5506 return ExprError(Diag(Base->getExprLoc(),
5507 diag::err_omp_non_pointer_type_array_shaping_base)
5508 << Base->getSourceRange());
5510 SmallVector<Expr *, 4> NewDims;
5511 bool ErrorFound = false;
5512 for (Expr *Dim : Dims) {
5513 if (Dim->hasPlaceholderType()) {
5514 ExprResult Result = CheckPlaceholderExpr(Dim);
5515 if (Result.isInvalid()) {
5516 ErrorFound = true;
5517 continue;
5519 Result = DefaultLvalueConversion(Result.get());
5520 if (Result.isInvalid()) {
5521 ErrorFound = true;
5522 continue;
5524 Dim = Result.get();
5526 if (!Dim->isTypeDependent()) {
5527 ExprResult Result =
5528 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5529 if (Result.isInvalid()) {
5530 ErrorFound = true;
5531 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5532 << Dim->getSourceRange();
5533 continue;
5535 Dim = Result.get();
5536 Expr::EvalResult EvResult;
5537 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5538 // OpenMP 5.0, [2.1.4 Array Shaping]
5539 // Each si is an integral type expression that must evaluate to a
5540 // positive integer.
5541 llvm::APSInt Value = EvResult.Val.getInt();
5542 if (!Value.isStrictlyPositive()) {
5543 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5544 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5545 << Dim->getSourceRange();
5546 ErrorFound = true;
5547 continue;
5551 NewDims.push_back(Dim);
5553 if (ErrorFound)
5554 return ExprError();
5555 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5556 LParenLoc, RParenLoc, NewDims, Brackets);
5559 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5560 SourceLocation LLoc, SourceLocation RLoc,
5561 ArrayRef<OMPIteratorData> Data) {
5562 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5563 bool IsCorrect = true;
5564 for (const OMPIteratorData &D : Data) {
5565 TypeSourceInfo *TInfo = nullptr;
5566 SourceLocation StartLoc;
5567 QualType DeclTy;
5568 if (!D.Type.getAsOpaquePtr()) {
5569 // OpenMP 5.0, 2.1.6 Iterators
5570 // In an iterator-specifier, if the iterator-type is not specified then
5571 // the type of that iterator is of int type.
5572 DeclTy = Context.IntTy;
5573 StartLoc = D.DeclIdentLoc;
5574 } else {
5575 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5576 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5579 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5580 DeclTy->containsUnexpandedParameterPack() ||
5581 DeclTy->isInstantiationDependentType();
5582 if (!IsDeclTyDependent) {
5583 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5584 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5585 // The iterator-type must be an integral or pointer type.
5586 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5587 << DeclTy;
5588 IsCorrect = false;
5589 continue;
5591 if (DeclTy.isConstant(Context)) {
5592 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5593 // The iterator-type must not be const qualified.
5594 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5595 << DeclTy;
5596 IsCorrect = false;
5597 continue;
5601 // Iterator declaration.
5602 assert(D.DeclIdent && "Identifier expected.");
5603 // Always try to create iterator declarator to avoid extra error messages
5604 // about unknown declarations use.
5605 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5606 D.DeclIdent, DeclTy, TInfo, SC_None);
5607 VD->setImplicit();
5608 if (S) {
5609 // Check for conflicting previous declaration.
5610 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5611 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5612 ForVisibleRedeclaration);
5613 Previous.suppressDiagnostics();
5614 LookupName(Previous, S);
5616 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5617 /*AllowInlineNamespace=*/false);
5618 if (!Previous.empty()) {
5619 NamedDecl *Old = Previous.getRepresentativeDecl();
5620 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5621 Diag(Old->getLocation(), diag::note_previous_definition);
5622 } else {
5623 PushOnScopeChains(VD, S);
5625 } else {
5626 CurContext->addDecl(VD);
5629 /// Act on the iterator variable declaration.
5630 ActOnOpenMPIteratorVarDecl(VD);
5632 Expr *Begin = D.Range.Begin;
5633 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5634 ExprResult BeginRes =
5635 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5636 Begin = BeginRes.get();
5638 Expr *End = D.Range.End;
5639 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5640 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5641 End = EndRes.get();
5643 Expr *Step = D.Range.Step;
5644 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5645 if (!Step->getType()->isIntegralType(Context)) {
5646 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5647 << Step << Step->getSourceRange();
5648 IsCorrect = false;
5649 continue;
5651 std::optional<llvm::APSInt> Result =
5652 Step->getIntegerConstantExpr(Context);
5653 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5654 // If the step expression of a range-specification equals zero, the
5655 // behavior is unspecified.
5656 if (Result && Result->isZero()) {
5657 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5658 << Step << Step->getSourceRange();
5659 IsCorrect = false;
5660 continue;
5663 if (!Begin || !End || !IsCorrect) {
5664 IsCorrect = false;
5665 continue;
5667 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5668 IDElem.IteratorDecl = VD;
5669 IDElem.AssignmentLoc = D.AssignLoc;
5670 IDElem.Range.Begin = Begin;
5671 IDElem.Range.End = End;
5672 IDElem.Range.Step = Step;
5673 IDElem.ColonLoc = D.ColonLoc;
5674 IDElem.SecondColonLoc = D.SecColonLoc;
5676 if (!IsCorrect) {
5677 // Invalidate all created iterator declarations if error is found.
5678 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5679 if (Decl *ID = D.IteratorDecl)
5680 ID->setInvalidDecl();
5682 return ExprError();
5684 SmallVector<OMPIteratorHelperData, 4> Helpers;
5685 if (!CurContext->isDependentContext()) {
5686 // Build number of ityeration for each iteration range.
5687 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5688 // ((Begini-Stepi-1-Endi) / -Stepi);
5689 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5690 // (Endi - Begini)
5691 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5692 D.Range.Begin);
5693 if(!Res.isUsable()) {
5694 IsCorrect = false;
5695 continue;
5697 ExprResult St, St1;
5698 if (D.Range.Step) {
5699 St = D.Range.Step;
5700 // (Endi - Begini) + Stepi
5701 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5702 if (!Res.isUsable()) {
5703 IsCorrect = false;
5704 continue;
5706 // (Endi - Begini) + Stepi - 1
5707 Res =
5708 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5709 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5710 if (!Res.isUsable()) {
5711 IsCorrect = false;
5712 continue;
5714 // ((Endi - Begini) + Stepi - 1) / Stepi
5715 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5716 if (!Res.isUsable()) {
5717 IsCorrect = false;
5718 continue;
5720 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5721 // (Begini - Endi)
5722 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5723 D.Range.Begin, D.Range.End);
5724 if (!Res1.isUsable()) {
5725 IsCorrect = false;
5726 continue;
5728 // (Begini - Endi) - Stepi
5729 Res1 =
5730 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5731 if (!Res1.isUsable()) {
5732 IsCorrect = false;
5733 continue;
5735 // (Begini - Endi) - Stepi - 1
5736 Res1 =
5737 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5738 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5739 if (!Res1.isUsable()) {
5740 IsCorrect = false;
5741 continue;
5743 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5744 Res1 =
5745 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5746 if (!Res1.isUsable()) {
5747 IsCorrect = false;
5748 continue;
5750 // Stepi > 0.
5751 ExprResult CmpRes =
5752 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5753 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5754 if (!CmpRes.isUsable()) {
5755 IsCorrect = false;
5756 continue;
5758 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5759 Res.get(), Res1.get());
5760 if (!Res.isUsable()) {
5761 IsCorrect = false;
5762 continue;
5765 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5766 if (!Res.isUsable()) {
5767 IsCorrect = false;
5768 continue;
5771 // Build counter update.
5772 // Build counter.
5773 auto *CounterVD =
5774 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5775 D.IteratorDecl->getBeginLoc(), nullptr,
5776 Res.get()->getType(), nullptr, SC_None);
5777 CounterVD->setImplicit();
5778 ExprResult RefRes =
5779 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5780 D.IteratorDecl->getBeginLoc());
5781 // Build counter update.
5782 // I = Begini + counter * Stepi;
5783 ExprResult UpdateRes;
5784 if (D.Range.Step) {
5785 UpdateRes = CreateBuiltinBinOp(
5786 D.AssignmentLoc, BO_Mul,
5787 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5788 } else {
5789 UpdateRes = DefaultLvalueConversion(RefRes.get());
5791 if (!UpdateRes.isUsable()) {
5792 IsCorrect = false;
5793 continue;
5795 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5796 UpdateRes.get());
5797 if (!UpdateRes.isUsable()) {
5798 IsCorrect = false;
5799 continue;
5801 ExprResult VDRes =
5802 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5803 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5804 D.IteratorDecl->getBeginLoc());
5805 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5806 UpdateRes.get());
5807 if (!UpdateRes.isUsable()) {
5808 IsCorrect = false;
5809 continue;
5811 UpdateRes =
5812 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5813 if (!UpdateRes.isUsable()) {
5814 IsCorrect = false;
5815 continue;
5817 ExprResult CounterUpdateRes =
5818 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5819 if (!CounterUpdateRes.isUsable()) {
5820 IsCorrect = false;
5821 continue;
5823 CounterUpdateRes =
5824 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5825 if (!CounterUpdateRes.isUsable()) {
5826 IsCorrect = false;
5827 continue;
5829 OMPIteratorHelperData &HD = Helpers.emplace_back();
5830 HD.CounterVD = CounterVD;
5831 HD.Upper = Res.get();
5832 HD.Update = UpdateRes.get();
5833 HD.CounterUpdate = CounterUpdateRes.get();
5835 } else {
5836 Helpers.assign(ID.size(), {});
5838 if (!IsCorrect) {
5839 // Invalidate all created iterator declarations if error is found.
5840 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5841 if (Decl *ID = D.IteratorDecl)
5842 ID->setInvalidDecl();
5844 return ExprError();
5846 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5847 LLoc, RLoc, ID, Helpers);
5850 ExprResult
5851 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5852 Expr *Idx, SourceLocation RLoc) {
5853 Expr *LHSExp = Base;
5854 Expr *RHSExp = Idx;
5856 ExprValueKind VK = VK_LValue;
5857 ExprObjectKind OK = OK_Ordinary;
5859 // Per C++ core issue 1213, the result is an xvalue if either operand is
5860 // a non-lvalue array, and an lvalue otherwise.
5861 if (getLangOpts().CPlusPlus11) {
5862 for (auto *Op : {LHSExp, RHSExp}) {
5863 Op = Op->IgnoreImplicit();
5864 if (Op->getType()->isArrayType() && !Op->isLValue())
5865 VK = VK_XValue;
5869 // Perform default conversions.
5870 if (!LHSExp->getType()->getAs<VectorType>()) {
5871 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5872 if (Result.isInvalid())
5873 return ExprError();
5874 LHSExp = Result.get();
5876 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5877 if (Result.isInvalid())
5878 return ExprError();
5879 RHSExp = Result.get();
5881 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5883 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5884 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5885 // in the subscript position. As a result, we need to derive the array base
5886 // and index from the expression types.
5887 Expr *BaseExpr, *IndexExpr;
5888 QualType ResultType;
5889 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5890 BaseExpr = LHSExp;
5891 IndexExpr = RHSExp;
5892 ResultType =
5893 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5894 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5895 BaseExpr = LHSExp;
5896 IndexExpr = RHSExp;
5897 ResultType = PTy->getPointeeType();
5898 } else if (const ObjCObjectPointerType *PTy =
5899 LHSTy->getAs<ObjCObjectPointerType>()) {
5900 BaseExpr = LHSExp;
5901 IndexExpr = RHSExp;
5903 // Use custom logic if this should be the pseudo-object subscript
5904 // expression.
5905 if (!LangOpts.isSubscriptPointerArithmetic())
5906 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5907 nullptr);
5909 ResultType = PTy->getPointeeType();
5910 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5911 // Handle the uncommon case of "123[Ptr]".
5912 BaseExpr = RHSExp;
5913 IndexExpr = LHSExp;
5914 ResultType = PTy->getPointeeType();
5915 } else if (const ObjCObjectPointerType *PTy =
5916 RHSTy->getAs<ObjCObjectPointerType>()) {
5917 // Handle the uncommon case of "123[Ptr]".
5918 BaseExpr = RHSExp;
5919 IndexExpr = LHSExp;
5920 ResultType = PTy->getPointeeType();
5921 if (!LangOpts.isSubscriptPointerArithmetic()) {
5922 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5923 << ResultType << BaseExpr->getSourceRange();
5924 return ExprError();
5926 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5927 BaseExpr = LHSExp; // vectors: V[123]
5928 IndexExpr = RHSExp;
5929 // We apply C++ DR1213 to vector subscripting too.
5930 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5931 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5932 if (Materialized.isInvalid())
5933 return ExprError();
5934 LHSExp = Materialized.get();
5936 VK = LHSExp->getValueKind();
5937 if (VK != VK_PRValue)
5938 OK = OK_VectorComponent;
5940 ResultType = VTy->getElementType();
5941 QualType BaseType = BaseExpr->getType();
5942 Qualifiers BaseQuals = BaseType.getQualifiers();
5943 Qualifiers MemberQuals = ResultType.getQualifiers();
5944 Qualifiers Combined = BaseQuals + MemberQuals;
5945 if (Combined != MemberQuals)
5946 ResultType = Context.getQualifiedType(ResultType, Combined);
5947 } else if (LHSTy->isBuiltinType() &&
5948 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5949 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5950 if (BTy->isSVEBool())
5951 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5952 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5954 BaseExpr = LHSExp;
5955 IndexExpr = RHSExp;
5956 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5957 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5958 if (Materialized.isInvalid())
5959 return ExprError();
5960 LHSExp = Materialized.get();
5962 VK = LHSExp->getValueKind();
5963 if (VK != VK_PRValue)
5964 OK = OK_VectorComponent;
5966 ResultType = BTy->getSveEltType(Context);
5968 QualType BaseType = BaseExpr->getType();
5969 Qualifiers BaseQuals = BaseType.getQualifiers();
5970 Qualifiers MemberQuals = ResultType.getQualifiers();
5971 Qualifiers Combined = BaseQuals + MemberQuals;
5972 if (Combined != MemberQuals)
5973 ResultType = Context.getQualifiedType(ResultType, Combined);
5974 } else if (LHSTy->isArrayType()) {
5975 // If we see an array that wasn't promoted by
5976 // DefaultFunctionArrayLvalueConversion, it must be an array that
5977 // wasn't promoted because of the C90 rule that doesn't
5978 // allow promoting non-lvalue arrays. Warn, then
5979 // force the promotion here.
5980 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5981 << LHSExp->getSourceRange();
5982 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5983 CK_ArrayToPointerDecay).get();
5984 LHSTy = LHSExp->getType();
5986 BaseExpr = LHSExp;
5987 IndexExpr = RHSExp;
5988 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5989 } else if (RHSTy->isArrayType()) {
5990 // Same as previous, except for 123[f().a] case
5991 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5992 << RHSExp->getSourceRange();
5993 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5994 CK_ArrayToPointerDecay).get();
5995 RHSTy = RHSExp->getType();
5997 BaseExpr = RHSExp;
5998 IndexExpr = LHSExp;
5999 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
6000 } else {
6001 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
6002 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
6004 // C99 6.5.2.1p1
6005 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
6006 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
6007 << IndexExpr->getSourceRange());
6009 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
6010 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
6011 && !IndexExpr->isTypeDependent())
6012 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
6014 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
6015 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
6016 // type. Note that Functions are not objects, and that (in C99 parlance)
6017 // incomplete types are not object types.
6018 if (ResultType->isFunctionType()) {
6019 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
6020 << ResultType << BaseExpr->getSourceRange();
6021 return ExprError();
6024 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
6025 // GNU extension: subscripting on pointer to void
6026 Diag(LLoc, diag::ext_gnu_subscript_void_type)
6027 << BaseExpr->getSourceRange();
6029 // C forbids expressions of unqualified void type from being l-values.
6030 // See IsCForbiddenLValueType.
6031 if (!ResultType.hasQualifiers())
6032 VK = VK_PRValue;
6033 } else if (!ResultType->isDependentType() &&
6034 !ResultType.isWebAssemblyReferenceType() &&
6035 RequireCompleteSizedType(
6036 LLoc, ResultType,
6037 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
6038 return ExprError();
6040 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
6041 !ResultType.isCForbiddenLValueType());
6043 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
6044 FunctionScopes.size() > 1) {
6045 if (auto *TT =
6046 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
6047 for (auto I = FunctionScopes.rbegin(),
6048 E = std::prev(FunctionScopes.rend());
6049 I != E; ++I) {
6050 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
6051 if (CSI == nullptr)
6052 break;
6053 DeclContext *DC = nullptr;
6054 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
6055 DC = LSI->CallOperator;
6056 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
6057 DC = CRSI->TheCapturedDecl;
6058 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
6059 DC = BSI->TheDecl;
6060 if (DC) {
6061 if (DC->containsDecl(TT->getDecl()))
6062 break;
6063 captureVariablyModifiedType(
6064 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
6070 return new (Context)
6071 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
6074 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6075 ParmVarDecl *Param, Expr *RewrittenInit,
6076 bool SkipImmediateInvocations) {
6077 if (Param->hasUnparsedDefaultArg()) {
6078 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
6079 // If we've already cleared out the location for the default argument,
6080 // that means we're parsing it right now.
6081 if (!UnparsedDefaultArgLocs.count(Param)) {
6082 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
6083 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
6084 Param->setInvalidDecl();
6085 return true;
6088 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
6089 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
6090 Diag(UnparsedDefaultArgLocs[Param],
6091 diag::note_default_argument_declared_here);
6092 return true;
6095 if (Param->hasUninstantiatedDefaultArg()) {
6096 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
6097 if (InstantiateDefaultArgument(CallLoc, FD, Param))
6098 return true;
6101 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
6102 assert(Init && "default argument but no initializer?");
6104 // If the default expression creates temporaries, we need to
6105 // push them to the current stack of expression temporaries so they'll
6106 // be properly destroyed.
6107 // FIXME: We should really be rebuilding the default argument with new
6108 // bound temporaries; see the comment in PR5810.
6109 // We don't need to do that with block decls, though, because
6110 // blocks in default argument expression can never capture anything.
6111 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
6112 // Set the "needs cleanups" bit regardless of whether there are
6113 // any explicit objects.
6114 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
6115 // Append all the objects to the cleanup list. Right now, this
6116 // should always be a no-op, because blocks in default argument
6117 // expressions should never be able to capture anything.
6118 assert(!InitWithCleanup->getNumObjects() &&
6119 "default argument expression has capturing blocks?");
6121 // C++ [expr.const]p15.1:
6122 // An expression or conversion is in an immediate function context if it is
6123 // potentially evaluated and [...] its innermost enclosing non-block scope
6124 // is a function parameter scope of an immediate function.
6125 EnterExpressionEvaluationContext EvalContext(
6126 *this,
6127 FD->isImmediateFunction()
6128 ? ExpressionEvaluationContext::ImmediateFunctionContext
6129 : ExpressionEvaluationContext::PotentiallyEvaluated,
6130 Param);
6131 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6132 SkipImmediateInvocations;
6133 runWithSufficientStackSpace(CallLoc, [&] {
6134 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
6136 return false;
6139 struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
6140 const ASTContext &Context;
6141 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
6143 bool HasImmediateCalls = false;
6144 bool shouldVisitImplicitCode() const { return true; }
6146 bool VisitCallExpr(CallExpr *E) {
6147 if (const FunctionDecl *FD = E->getDirectCallee())
6148 HasImmediateCalls |= FD->isImmediateFunction();
6149 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
6152 // SourceLocExpr are not immediate invocations
6153 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
6154 // need to be rebuilt so that they refer to the correct SourceLocation and
6155 // DeclContext.
6156 bool VisitSourceLocExpr(SourceLocExpr *E) {
6157 HasImmediateCalls = true;
6158 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
6161 // A nested lambda might have parameters with immediate invocations
6162 // in their default arguments.
6163 // The compound statement is not visited (as it does not constitute a
6164 // subexpression).
6165 // FIXME: We should consider visiting and transforming captures
6166 // with init expressions.
6167 bool VisitLambdaExpr(LambdaExpr *E) {
6168 return VisitCXXMethodDecl(E->getCallOperator());
6171 // Blocks don't support default parameters, and, as for lambdas,
6172 // we don't consider their body a subexpression.
6173 bool VisitBlockDecl(BlockDecl *B) { return false; }
6175 bool VisitCompoundStmt(CompoundStmt *B) { return false; }
6177 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
6178 return TraverseStmt(E->getExpr());
6181 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
6182 return TraverseStmt(E->getExpr());
6186 struct EnsureImmediateInvocationInDefaultArgs
6187 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
6188 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
6189 : TreeTransform(SemaRef) {}
6191 // Lambda can only have immediate invocations in the default
6192 // args of their parameters, which is transformed upon calling the closure.
6193 // The body is not a subexpression, so we have nothing to do.
6194 // FIXME: Immediate calls in capture initializers should be transformed.
6195 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
6196 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
6198 // Make sure we don't rebuild the this pointer as it would
6199 // cause it to incorrectly point it to the outermost class
6200 // in the case of nested struct initialization.
6201 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
6204 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
6205 FunctionDecl *FD, ParmVarDecl *Param,
6206 Expr *Init) {
6207 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
6209 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6211 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6212 InitializationContext =
6213 OutermostDeclarationWithDelayedImmediateInvocations();
6214 if (!InitializationContext.has_value())
6215 InitializationContext.emplace(CallLoc, Param, CurContext);
6217 if (!Init && !Param->hasUnparsedDefaultArg()) {
6218 // Mark that we are replacing a default argument first.
6219 // If we are instantiating a template we won't have to
6220 // retransform immediate calls.
6221 // C++ [expr.const]p15.1:
6222 // An expression or conversion is in an immediate function context if it
6223 // is potentially evaluated and [...] its innermost enclosing non-block
6224 // scope is a function parameter scope of an immediate function.
6225 EnterExpressionEvaluationContext EvalContext(
6226 *this,
6227 FD->isImmediateFunction()
6228 ? ExpressionEvaluationContext::ImmediateFunctionContext
6229 : ExpressionEvaluationContext::PotentiallyEvaluated,
6230 Param);
6232 if (Param->hasUninstantiatedDefaultArg()) {
6233 if (InstantiateDefaultArgument(CallLoc, FD, Param))
6234 return ExprError();
6236 // CWG2631
6237 // An immediate invocation that is not evaluated where it appears is
6238 // evaluated and checked for whether it is a constant expression at the
6239 // point where the enclosing initializer is used in a function call.
6240 ImmediateCallVisitor V(getASTContext());
6241 if (!NestedDefaultChecking)
6242 V.TraverseDecl(Param);
6243 if (V.HasImmediateCalls) {
6244 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
6245 CallLoc, Param, CurContext};
6246 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6247 ExprResult Res;
6248 runWithSufficientStackSpace(CallLoc, [&] {
6249 Res = Immediate.TransformInitializer(Param->getInit(),
6250 /*NotCopy=*/false);
6252 if (Res.isInvalid())
6253 return ExprError();
6254 Res = ConvertParamDefaultArgument(Param, Res.get(),
6255 Res.get()->getBeginLoc());
6256 if (Res.isInvalid())
6257 return ExprError();
6258 Init = Res.get();
6262 if (CheckCXXDefaultArgExpr(
6263 CallLoc, FD, Param, Init,
6264 /*SkipImmediateInvocations=*/NestedDefaultChecking))
6265 return ExprError();
6267 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
6268 Init, InitializationContext->Context);
6271 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
6272 assert(Field->hasInClassInitializer());
6274 // If we might have already tried and failed to instantiate, don't try again.
6275 if (Field->isInvalidDecl())
6276 return ExprError();
6278 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6280 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
6282 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6283 InitializationContext =
6284 OutermostDeclarationWithDelayedImmediateInvocations();
6285 if (!InitializationContext.has_value())
6286 InitializationContext.emplace(Loc, Field, CurContext);
6288 Expr *Init = nullptr;
6290 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6292 EnterExpressionEvaluationContext EvalContext(
6293 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
6295 if (!Field->getInClassInitializer()) {
6296 // Maybe we haven't instantiated the in-class initializer. Go check the
6297 // pattern FieldDecl to see if it has one.
6298 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
6299 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
6300 DeclContext::lookup_result Lookup =
6301 ClassPattern->lookup(Field->getDeclName());
6303 FieldDecl *Pattern = nullptr;
6304 for (auto *L : Lookup) {
6305 if ((Pattern = dyn_cast<FieldDecl>(L)))
6306 break;
6308 assert(Pattern && "We must have set the Pattern!");
6309 if (!Pattern->hasInClassInitializer() ||
6310 InstantiateInClassInitializer(Loc, Field, Pattern,
6311 getTemplateInstantiationArgs(Field))) {
6312 Field->setInvalidDecl();
6313 return ExprError();
6318 // CWG2631
6319 // An immediate invocation that is not evaluated where it appears is
6320 // evaluated and checked for whether it is a constant expression at the
6321 // point where the enclosing initializer is used in a [...] a constructor
6322 // definition, or an aggregate initialization.
6323 ImmediateCallVisitor V(getASTContext());
6324 if (!NestedDefaultChecking)
6325 V.TraverseDecl(Field);
6326 if (V.HasImmediateCalls) {
6327 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
6328 CurContext};
6329 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6330 NestedDefaultChecking;
6332 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6333 ExprResult Res;
6334 runWithSufficientStackSpace(Loc, [&] {
6335 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
6336 /*CXXDirectInit=*/false);
6338 if (!Res.isInvalid())
6339 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
6340 if (Res.isInvalid()) {
6341 Field->setInvalidDecl();
6342 return ExprError();
6344 Init = Res.get();
6347 if (Field->getInClassInitializer()) {
6348 Expr *E = Init ? Init : Field->getInClassInitializer();
6349 if (!NestedDefaultChecking)
6350 runWithSufficientStackSpace(Loc, [&] {
6351 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
6353 // C++11 [class.base.init]p7:
6354 // The initialization of each base and member constitutes a
6355 // full-expression.
6356 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
6357 if (Res.isInvalid()) {
6358 Field->setInvalidDecl();
6359 return ExprError();
6361 Init = Res.get();
6363 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
6364 Field, InitializationContext->Context,
6365 Init);
6368 // DR1351:
6369 // If the brace-or-equal-initializer of a non-static data member
6370 // invokes a defaulted default constructor of its class or of an
6371 // enclosing class in a potentially evaluated subexpression, the
6372 // program is ill-formed.
6374 // This resolution is unworkable: the exception specification of the
6375 // default constructor can be needed in an unevaluated context, in
6376 // particular, in the operand of a noexcept-expression, and we can be
6377 // unable to compute an exception specification for an enclosed class.
6379 // Any attempt to resolve the exception specification of a defaulted default
6380 // constructor before the initializer is lexically complete will ultimately
6381 // come here at which point we can diagnose it.
6382 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6383 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
6384 << OutermostClass << Field;
6385 Diag(Field->getEndLoc(),
6386 diag::note_default_member_initializer_not_yet_parsed);
6387 // Recover by marking the field invalid, unless we're in a SFINAE context.
6388 if (!isSFINAEContext())
6389 Field->setInvalidDecl();
6390 return ExprError();
6393 Sema::VariadicCallType
6394 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
6395 Expr *Fn) {
6396 if (Proto && Proto->isVariadic()) {
6397 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6398 return VariadicConstructor;
6399 else if (Fn && Fn->getType()->isBlockPointerType())
6400 return VariadicBlock;
6401 else if (FDecl) {
6402 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6403 if (Method->isInstance())
6404 return VariadicMethod;
6405 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6406 return VariadicMethod;
6407 return VariadicFunction;
6409 return VariadicDoesNotApply;
6412 namespace {
6413 class FunctionCallCCC final : public FunctionCallFilterCCC {
6414 public:
6415 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6416 unsigned NumArgs, MemberExpr *ME)
6417 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6418 FunctionName(FuncName) {}
6420 bool ValidateCandidate(const TypoCorrection &candidate) override {
6421 if (!candidate.getCorrectionSpecifier() ||
6422 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6423 return false;
6426 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6429 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6430 return std::make_unique<FunctionCallCCC>(*this);
6433 private:
6434 const IdentifierInfo *const FunctionName;
6438 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6439 FunctionDecl *FDecl,
6440 ArrayRef<Expr *> Args) {
6441 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6442 DeclarationName FuncName = FDecl->getDeclName();
6443 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6445 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6446 if (TypoCorrection Corrected = S.CorrectTypo(
6447 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
6448 S.getScopeForContext(S.CurContext), nullptr, CCC,
6449 Sema::CTK_ErrorRecovery)) {
6450 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6451 if (Corrected.isOverloaded()) {
6452 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6453 OverloadCandidateSet::iterator Best;
6454 for (NamedDecl *CD : Corrected) {
6455 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6456 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
6457 OCS);
6459 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6460 case OR_Success:
6461 ND = Best->FoundDecl;
6462 Corrected.setCorrectionDecl(ND);
6463 break;
6464 default:
6465 break;
6468 ND = ND->getUnderlyingDecl();
6469 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
6470 return Corrected;
6473 return TypoCorrection();
6476 /// ConvertArgumentsForCall - Converts the arguments specified in
6477 /// Args/NumArgs to the parameter types of the function FDecl with
6478 /// function prototype Proto. Call is the call expression itself, and
6479 /// Fn is the function expression. For a C++ member function, this
6480 /// routine does not attempt to convert the object argument. Returns
6481 /// true if the call is ill-formed.
6482 bool
6483 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6484 FunctionDecl *FDecl,
6485 const FunctionProtoType *Proto,
6486 ArrayRef<Expr *> Args,
6487 SourceLocation RParenLoc,
6488 bool IsExecConfig) {
6489 // Bail out early if calling a builtin with custom typechecking.
6490 if (FDecl)
6491 if (unsigned ID = FDecl->getBuiltinID())
6492 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6493 return false;
6495 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6496 // assignment, to the types of the corresponding parameter, ...
6497 unsigned NumParams = Proto->getNumParams();
6498 bool Invalid = false;
6499 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6500 unsigned FnKind = Fn->getType()->isBlockPointerType()
6501 ? 1 /* block */
6502 : (IsExecConfig ? 3 /* kernel function (exec config) */
6503 : 0 /* function */);
6505 // If too few arguments are available (and we don't have default
6506 // arguments for the remaining parameters), don't make the call.
6507 if (Args.size() < NumParams) {
6508 if (Args.size() < MinArgs) {
6509 TypoCorrection TC;
6510 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6511 unsigned diag_id =
6512 MinArgs == NumParams && !Proto->isVariadic()
6513 ? diag::err_typecheck_call_too_few_args_suggest
6514 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6515 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6516 << static_cast<unsigned>(Args.size())
6517 << TC.getCorrectionRange());
6518 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6519 Diag(RParenLoc,
6520 MinArgs == NumParams && !Proto->isVariadic()
6521 ? diag::err_typecheck_call_too_few_args_one
6522 : diag::err_typecheck_call_too_few_args_at_least_one)
6523 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6524 else
6525 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6526 ? diag::err_typecheck_call_too_few_args
6527 : diag::err_typecheck_call_too_few_args_at_least)
6528 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6529 << Fn->getSourceRange();
6531 // Emit the location of the prototype.
6532 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6533 Diag(FDecl->getLocation(), diag::note_callee_decl)
6534 << FDecl << FDecl->getParametersSourceRange();
6536 return true;
6538 // We reserve space for the default arguments when we create
6539 // the call expression, before calling ConvertArgumentsForCall.
6540 assert((Call->getNumArgs() == NumParams) &&
6541 "We should have reserved space for the default arguments before!");
6544 // If too many are passed and not variadic, error on the extras and drop
6545 // them.
6546 if (Args.size() > NumParams) {
6547 if (!Proto->isVariadic()) {
6548 TypoCorrection TC;
6549 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6550 unsigned diag_id =
6551 MinArgs == NumParams && !Proto->isVariadic()
6552 ? diag::err_typecheck_call_too_many_args_suggest
6553 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6554 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6555 << static_cast<unsigned>(Args.size())
6556 << TC.getCorrectionRange());
6557 } else if (NumParams == 1 && FDecl &&
6558 FDecl->getParamDecl(0)->getDeclName())
6559 Diag(Args[NumParams]->getBeginLoc(),
6560 MinArgs == NumParams
6561 ? diag::err_typecheck_call_too_many_args_one
6562 : diag::err_typecheck_call_too_many_args_at_most_one)
6563 << FnKind << FDecl->getParamDecl(0)
6564 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6565 << SourceRange(Args[NumParams]->getBeginLoc(),
6566 Args.back()->getEndLoc());
6567 else
6568 Diag(Args[NumParams]->getBeginLoc(),
6569 MinArgs == NumParams
6570 ? diag::err_typecheck_call_too_many_args
6571 : diag::err_typecheck_call_too_many_args_at_most)
6572 << FnKind << NumParams << static_cast<unsigned>(Args.size())
6573 << Fn->getSourceRange()
6574 << SourceRange(Args[NumParams]->getBeginLoc(),
6575 Args.back()->getEndLoc());
6577 // Emit the location of the prototype.
6578 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6579 Diag(FDecl->getLocation(), diag::note_callee_decl)
6580 << FDecl << FDecl->getParametersSourceRange();
6582 // This deletes the extra arguments.
6583 Call->shrinkNumArgs(NumParams);
6584 return true;
6587 SmallVector<Expr *, 8> AllArgs;
6588 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6590 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6591 AllArgs, CallType);
6592 if (Invalid)
6593 return true;
6594 unsigned TotalNumArgs = AllArgs.size();
6595 for (unsigned i = 0; i < TotalNumArgs; ++i)
6596 Call->setArg(i, AllArgs[i]);
6598 Call->computeDependence();
6599 return false;
6602 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6603 const FunctionProtoType *Proto,
6604 unsigned FirstParam, ArrayRef<Expr *> Args,
6605 SmallVectorImpl<Expr *> &AllArgs,
6606 VariadicCallType CallType, bool AllowExplicit,
6607 bool IsListInitialization) {
6608 unsigned NumParams = Proto->getNumParams();
6609 bool Invalid = false;
6610 size_t ArgIx = 0;
6611 // Continue to check argument types (even if we have too few/many args).
6612 for (unsigned i = FirstParam; i < NumParams; i++) {
6613 QualType ProtoArgType = Proto->getParamType(i);
6615 Expr *Arg;
6616 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6617 if (ArgIx < Args.size()) {
6618 Arg = Args[ArgIx++];
6620 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6621 diag::err_call_incomplete_argument, Arg))
6622 return true;
6624 // Strip the unbridged-cast placeholder expression off, if applicable.
6625 bool CFAudited = false;
6626 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6627 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6628 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6629 Arg = stripARCUnbridgedCast(Arg);
6630 else if (getLangOpts().ObjCAutoRefCount &&
6631 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6632 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6633 CFAudited = true;
6635 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6636 ProtoArgType->isBlockPointerType())
6637 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6638 BE->getBlockDecl()->setDoesNotEscape();
6640 InitializedEntity Entity =
6641 Param ? InitializedEntity::InitializeParameter(Context, Param,
6642 ProtoArgType)
6643 : InitializedEntity::InitializeParameter(
6644 Context, ProtoArgType, Proto->isParamConsumed(i));
6646 // Remember that parameter belongs to a CF audited API.
6647 if (CFAudited)
6648 Entity.setParameterCFAudited();
6650 ExprResult ArgE = PerformCopyInitialization(
6651 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6652 if (ArgE.isInvalid())
6653 return true;
6655 Arg = ArgE.getAs<Expr>();
6656 } else {
6657 assert(Param && "can't use default arguments without a known callee");
6659 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6660 if (ArgExpr.isInvalid())
6661 return true;
6663 Arg = ArgExpr.getAs<Expr>();
6666 // Check for array bounds violations for each argument to the call. This
6667 // check only triggers warnings when the argument isn't a more complex Expr
6668 // with its own checking, such as a BinaryOperator.
6669 CheckArrayAccess(Arg);
6671 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6672 CheckStaticArrayArgument(CallLoc, Param, Arg);
6674 AllArgs.push_back(Arg);
6677 // If this is a variadic call, handle args passed through "...".
6678 if (CallType != VariadicDoesNotApply) {
6679 // Assume that extern "C" functions with variadic arguments that
6680 // return __unknown_anytype aren't *really* variadic.
6681 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6682 FDecl->isExternC()) {
6683 for (Expr *A : Args.slice(ArgIx)) {
6684 QualType paramType; // ignored
6685 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6686 Invalid |= arg.isInvalid();
6687 AllArgs.push_back(arg.get());
6690 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6691 } else {
6692 for (Expr *A : Args.slice(ArgIx)) {
6693 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6694 Invalid |= Arg.isInvalid();
6695 AllArgs.push_back(Arg.get());
6699 // Check for array bounds violations.
6700 for (Expr *A : Args.slice(ArgIx))
6701 CheckArrayAccess(A);
6703 return Invalid;
6706 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6707 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6708 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6709 TL = DTL.getOriginalLoc();
6710 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6711 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6712 << ATL.getLocalSourceRange();
6715 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6716 /// array parameter, check that it is non-null, and that if it is formed by
6717 /// array-to-pointer decay, the underlying array is sufficiently large.
6719 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6720 /// array type derivation, then for each call to the function, the value of the
6721 /// corresponding actual argument shall provide access to the first element of
6722 /// an array with at least as many elements as specified by the size expression.
6723 void
6724 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6725 ParmVarDecl *Param,
6726 const Expr *ArgExpr) {
6727 // Static array parameters are not supported in C++.
6728 if (!Param || getLangOpts().CPlusPlus)
6729 return;
6731 QualType OrigTy = Param->getOriginalType();
6733 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6734 if (!AT || AT->getSizeModifier() != ArrayType::Static)
6735 return;
6737 if (ArgExpr->isNullPointerConstant(Context,
6738 Expr::NPC_NeverValueDependent)) {
6739 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6740 DiagnoseCalleeStaticArrayParam(*this, Param);
6741 return;
6744 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6745 if (!CAT)
6746 return;
6748 const ConstantArrayType *ArgCAT =
6749 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6750 if (!ArgCAT)
6751 return;
6753 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6754 ArgCAT->getElementType())) {
6755 if (ArgCAT->getSize().ult(CAT->getSize())) {
6756 Diag(CallLoc, diag::warn_static_array_too_small)
6757 << ArgExpr->getSourceRange()
6758 << (unsigned)ArgCAT->getSize().getZExtValue()
6759 << (unsigned)CAT->getSize().getZExtValue() << 0;
6760 DiagnoseCalleeStaticArrayParam(*this, Param);
6762 return;
6765 std::optional<CharUnits> ArgSize =
6766 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6767 std::optional<CharUnits> ParmSize =
6768 getASTContext().getTypeSizeInCharsIfKnown(CAT);
6769 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6770 Diag(CallLoc, diag::warn_static_array_too_small)
6771 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6772 << (unsigned)ParmSize->getQuantity() << 1;
6773 DiagnoseCalleeStaticArrayParam(*this, Param);
6777 /// Given a function expression of unknown-any type, try to rebuild it
6778 /// to have a function type.
6779 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6781 /// Is the given type a placeholder that we need to lower out
6782 /// immediately during argument processing?
6783 static bool isPlaceholderToRemoveAsArg(QualType type) {
6784 // Placeholders are never sugared.
6785 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6786 if (!placeholder) return false;
6788 switch (placeholder->getKind()) {
6789 // Ignore all the non-placeholder types.
6790 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6791 case BuiltinType::Id:
6792 #include "clang/Basic/OpenCLImageTypes.def"
6793 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6794 case BuiltinType::Id:
6795 #include "clang/Basic/OpenCLExtensionTypes.def"
6796 // In practice we'll never use this, since all SVE types are sugared
6797 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6798 #define SVE_TYPE(Name, Id, SingletonId) \
6799 case BuiltinType::Id:
6800 #include "clang/Basic/AArch64SVEACLETypes.def"
6801 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6802 case BuiltinType::Id:
6803 #include "clang/Basic/PPCTypes.def"
6804 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6805 #include "clang/Basic/RISCVVTypes.def"
6806 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6807 #include "clang/Basic/WebAssemblyReferenceTypes.def"
6808 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6809 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6810 #include "clang/AST/BuiltinTypes.def"
6811 return false;
6813 // We cannot lower out overload sets; they might validly be resolved
6814 // by the call machinery.
6815 case BuiltinType::Overload:
6816 return false;
6818 // Unbridged casts in ARC can be handled in some call positions and
6819 // should be left in place.
6820 case BuiltinType::ARCUnbridgedCast:
6821 return false;
6823 // Pseudo-objects should be converted as soon as possible.
6824 case BuiltinType::PseudoObject:
6825 return true;
6827 // The debugger mode could theoretically but currently does not try
6828 // to resolve unknown-typed arguments based on known parameter types.
6829 case BuiltinType::UnknownAny:
6830 return true;
6832 // These are always invalid as call arguments and should be reported.
6833 case BuiltinType::BoundMember:
6834 case BuiltinType::BuiltinFn:
6835 case BuiltinType::IncompleteMatrixIdx:
6836 case BuiltinType::OMPArraySection:
6837 case BuiltinType::OMPArrayShaping:
6838 case BuiltinType::OMPIterator:
6839 return true;
6842 llvm_unreachable("bad builtin type kind");
6845 /// Check an argument list for placeholders that we won't try to
6846 /// handle later.
6847 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6848 // Apply this processing to all the arguments at once instead of
6849 // dying at the first failure.
6850 bool hasInvalid = false;
6851 for (size_t i = 0, e = args.size(); i != e; i++) {
6852 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6853 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6854 if (result.isInvalid()) hasInvalid = true;
6855 else args[i] = result.get();
6858 return hasInvalid;
6861 /// If a builtin function has a pointer argument with no explicit address
6862 /// space, then it should be able to accept a pointer to any address
6863 /// space as input. In order to do this, we need to replace the
6864 /// standard builtin declaration with one that uses the same address space
6865 /// as the call.
6867 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6868 /// it does not contain any pointer arguments without
6869 /// an address space qualifer. Otherwise the rewritten
6870 /// FunctionDecl is returned.
6871 /// TODO: Handle pointer return types.
6872 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6873 FunctionDecl *FDecl,
6874 MultiExprArg ArgExprs) {
6876 QualType DeclType = FDecl->getType();
6877 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6879 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6880 ArgExprs.size() < FT->getNumParams())
6881 return nullptr;
6883 bool NeedsNewDecl = false;
6884 unsigned i = 0;
6885 SmallVector<QualType, 8> OverloadParams;
6887 for (QualType ParamType : FT->param_types()) {
6889 // Convert array arguments to pointer to simplify type lookup.
6890 ExprResult ArgRes =
6891 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6892 if (ArgRes.isInvalid())
6893 return nullptr;
6894 Expr *Arg = ArgRes.get();
6895 QualType ArgType = Arg->getType();
6896 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6897 !ArgType->isPointerType() ||
6898 !ArgType->getPointeeType().hasAddressSpace() ||
6899 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6900 OverloadParams.push_back(ParamType);
6901 continue;
6904 QualType PointeeType = ParamType->getPointeeType();
6905 if (PointeeType.hasAddressSpace())
6906 continue;
6908 NeedsNewDecl = true;
6909 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6911 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6912 OverloadParams.push_back(Context.getPointerType(PointeeType));
6915 if (!NeedsNewDecl)
6916 return nullptr;
6918 FunctionProtoType::ExtProtoInfo EPI;
6919 EPI.Variadic = FT->isVariadic();
6920 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6921 OverloadParams, EPI);
6922 DeclContext *Parent = FDecl->getParent();
6923 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6924 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6925 FDecl->getIdentifier(), OverloadTy,
6926 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6927 false,
6928 /*hasPrototype=*/true);
6929 SmallVector<ParmVarDecl*, 16> Params;
6930 FT = cast<FunctionProtoType>(OverloadTy);
6931 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6932 QualType ParamType = FT->getParamType(i);
6933 ParmVarDecl *Parm =
6934 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6935 SourceLocation(), nullptr, ParamType,
6936 /*TInfo=*/nullptr, SC_None, nullptr);
6937 Parm->setScopeInfo(0, i);
6938 Params.push_back(Parm);
6940 OverloadDecl->setParams(Params);
6941 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6942 return OverloadDecl;
6945 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6946 FunctionDecl *Callee,
6947 MultiExprArg ArgExprs) {
6948 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6949 // similar attributes) really don't like it when functions are called with an
6950 // invalid number of args.
6951 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6952 /*PartialOverloading=*/false) &&
6953 !Callee->isVariadic())
6954 return;
6955 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6956 return;
6958 if (const EnableIfAttr *Attr =
6959 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6960 S.Diag(Fn->getBeginLoc(),
6961 isa<CXXMethodDecl>(Callee)
6962 ? diag::err_ovl_no_viable_member_function_in_call
6963 : diag::err_ovl_no_viable_function_in_call)
6964 << Callee << Callee->getSourceRange();
6965 S.Diag(Callee->getLocation(),
6966 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6967 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6968 return;
6972 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6973 const UnresolvedMemberExpr *const UME, Sema &S) {
6975 const auto GetFunctionLevelDCIfCXXClass =
6976 [](Sema &S) -> const CXXRecordDecl * {
6977 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6978 if (!DC || !DC->getParent())
6979 return nullptr;
6981 // If the call to some member function was made from within a member
6982 // function body 'M' return return 'M's parent.
6983 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6984 return MD->getParent()->getCanonicalDecl();
6985 // else the call was made from within a default member initializer of a
6986 // class, so return the class.
6987 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6988 return RD->getCanonicalDecl();
6989 return nullptr;
6991 // If our DeclContext is neither a member function nor a class (in the
6992 // case of a lambda in a default member initializer), we can't have an
6993 // enclosing 'this'.
6995 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6996 if (!CurParentClass)
6997 return false;
6999 // The naming class for implicit member functions call is the class in which
7000 // name lookup starts.
7001 const CXXRecordDecl *const NamingClass =
7002 UME->getNamingClass()->getCanonicalDecl();
7003 assert(NamingClass && "Must have naming class even for implicit access");
7005 // If the unresolved member functions were found in a 'naming class' that is
7006 // related (either the same or derived from) to the class that contains the
7007 // member function that itself contained the implicit member access.
7009 return CurParentClass == NamingClass ||
7010 CurParentClass->isDerivedFrom(NamingClass);
7013 static void
7014 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7015 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
7017 if (!UME)
7018 return;
7020 LambdaScopeInfo *const CurLSI = S.getCurLambda();
7021 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
7022 // already been captured, or if this is an implicit member function call (if
7023 // it isn't, an attempt to capture 'this' should already have been made).
7024 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
7025 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
7026 return;
7028 // Check if the naming class in which the unresolved members were found is
7029 // related (same as or is a base of) to the enclosing class.
7031 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
7032 return;
7035 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
7036 // If the enclosing function is not dependent, then this lambda is
7037 // capture ready, so if we can capture this, do so.
7038 if (!EnclosingFunctionCtx->isDependentContext()) {
7039 // If the current lambda and all enclosing lambdas can capture 'this' -
7040 // then go ahead and capture 'this' (since our unresolved overload set
7041 // contains at least one non-static member function).
7042 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
7043 S.CheckCXXThisCapture(CallLoc);
7044 } else if (S.CurContext->isDependentContext()) {
7045 // ... since this is an implicit member reference, that might potentially
7046 // involve a 'this' capture, mark 'this' for potential capture in
7047 // enclosing lambdas.
7048 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
7049 CurLSI->addPotentialThisCapture(CallLoc);
7053 // Once a call is fully resolved, warn for unqualified calls to specific
7054 // C++ standard functions, like move and forward.
7055 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
7056 const CallExpr *Call) {
7057 // We are only checking unary move and forward so exit early here.
7058 if (Call->getNumArgs() != 1)
7059 return;
7061 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
7062 if (!E || isa<UnresolvedLookupExpr>(E))
7063 return;
7064 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
7065 if (!DRE || !DRE->getLocation().isValid())
7066 return;
7068 if (DRE->getQualifier())
7069 return;
7071 const FunctionDecl *FD = Call->getDirectCallee();
7072 if (!FD)
7073 return;
7075 // Only warn for some functions deemed more frequent or problematic.
7076 unsigned BuiltinID = FD->getBuiltinID();
7077 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
7078 return;
7080 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
7081 << FD->getQualifiedNameAsString()
7082 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
7085 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
7086 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7087 Expr *ExecConfig) {
7088 ExprResult Call =
7089 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7090 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
7091 if (Call.isInvalid())
7092 return Call;
7094 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
7095 // language modes.
7096 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
7097 ULE && ULE->hasExplicitTemplateArgs() &&
7098 ULE->decls_begin() == ULE->decls_end()) {
7099 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
7100 ? diag::warn_cxx17_compat_adl_only_template_id
7101 : diag::ext_adl_only_template_id)
7102 << ULE->getName();
7105 if (LangOpts.OpenMP)
7106 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
7107 ExecConfig);
7108 if (LangOpts.CPlusPlus) {
7109 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
7110 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
7112 return Call;
7115 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7116 /// This provides the location of the left/right parens and a list of comma
7117 /// locations.
7118 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
7119 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7120 Expr *ExecConfig, bool IsExecConfig,
7121 bool AllowRecovery) {
7122 // Since this might be a postfix expression, get rid of ParenListExprs.
7123 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
7124 if (Result.isInvalid()) return ExprError();
7125 Fn = Result.get();
7127 if (checkArgsForPlaceholders(*this, ArgExprs))
7128 return ExprError();
7130 if (getLangOpts().CPlusPlus) {
7131 // If this is a pseudo-destructor expression, build the call immediately.
7132 if (isa<CXXPseudoDestructorExpr>(Fn)) {
7133 if (!ArgExprs.empty()) {
7134 // Pseudo-destructor calls should not have any arguments.
7135 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
7136 << FixItHint::CreateRemoval(
7137 SourceRange(ArgExprs.front()->getBeginLoc(),
7138 ArgExprs.back()->getEndLoc()));
7141 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
7142 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7144 if (Fn->getType() == Context.PseudoObjectTy) {
7145 ExprResult result = CheckPlaceholderExpr(Fn);
7146 if (result.isInvalid()) return ExprError();
7147 Fn = result.get();
7150 // Determine whether this is a dependent call inside a C++ template,
7151 // in which case we won't do any semantic analysis now.
7152 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
7153 if (ExecConfig) {
7154 return CUDAKernelCallExpr::Create(Context, Fn,
7155 cast<CallExpr>(ExecConfig), ArgExprs,
7156 Context.DependentTy, VK_PRValue,
7157 RParenLoc, CurFPFeatureOverrides());
7158 } else {
7160 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7161 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
7162 Fn->getBeginLoc());
7164 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7165 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7169 // Determine whether this is a call to an object (C++ [over.call.object]).
7170 if (Fn->getType()->isRecordType())
7171 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
7172 RParenLoc);
7174 if (Fn->getType() == Context.UnknownAnyTy) {
7175 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7176 if (result.isInvalid()) return ExprError();
7177 Fn = result.get();
7180 if (Fn->getType() == Context.BoundMemberTy) {
7181 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7182 RParenLoc, ExecConfig, IsExecConfig,
7183 AllowRecovery);
7187 // Check for overloaded calls. This can happen even in C due to extensions.
7188 if (Fn->getType() == Context.OverloadTy) {
7189 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
7191 // We aren't supposed to apply this logic if there's an '&' involved.
7192 if (!find.HasFormOfMemberPointer) {
7193 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
7194 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7195 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7196 OverloadExpr *ovl = find.Expression;
7197 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
7198 return BuildOverloadedCallExpr(
7199 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7200 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
7201 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7202 RParenLoc, ExecConfig, IsExecConfig,
7203 AllowRecovery);
7207 // If we're directly calling a function, get the appropriate declaration.
7208 if (Fn->getType() == Context.UnknownAnyTy) {
7209 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7210 if (result.isInvalid()) return ExprError();
7211 Fn = result.get();
7214 Expr *NakedFn = Fn->IgnoreParens();
7216 bool CallingNDeclIndirectly = false;
7217 NamedDecl *NDecl = nullptr;
7218 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
7219 if (UnOp->getOpcode() == UO_AddrOf) {
7220 CallingNDeclIndirectly = true;
7221 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7225 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
7226 NDecl = DRE->getDecl();
7228 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
7229 if (FDecl && FDecl->getBuiltinID()) {
7230 // Rewrite the function decl for this builtin by replacing parameters
7231 // with no explicit address space with the address space of the arguments
7232 // in ArgExprs.
7233 if ((FDecl =
7234 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
7235 NDecl = FDecl;
7236 Fn = DeclRefExpr::Create(
7237 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
7238 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
7239 nullptr, DRE->isNonOdrUse());
7242 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
7243 NDecl = ME->getMemberDecl();
7245 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
7246 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7247 FD, /*Complain=*/true, Fn->getBeginLoc()))
7248 return ExprError();
7250 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
7252 // If this expression is a call to a builtin function in HIP device
7253 // compilation, allow a pointer-type argument to default address space to be
7254 // passed as a pointer-type parameter to a non-default address space.
7255 // If Arg is declared in the default address space and Param is declared
7256 // in a non-default address space, perform an implicit address space cast to
7257 // the parameter type.
7258 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
7259 FD->getBuiltinID()) {
7260 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
7261 ParmVarDecl *Param = FD->getParamDecl(Idx);
7262 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7263 !ArgExprs[Idx]->getType()->isPointerType())
7264 continue;
7266 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7267 auto ArgTy = ArgExprs[Idx]->getType();
7268 auto ArgPtTy = ArgTy->getPointeeType();
7269 auto ArgAS = ArgPtTy.getAddressSpace();
7271 // Add address space cast if target address spaces are different
7272 bool NeedImplicitASC =
7273 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7274 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7275 // or from specific AS which has target AS matching that of Param.
7276 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
7277 if (!NeedImplicitASC)
7278 continue;
7280 // First, ensure that the Arg is an RValue.
7281 if (ArgExprs[Idx]->isGLValue()) {
7282 ArgExprs[Idx] = ImplicitCastExpr::Create(
7283 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
7284 nullptr, VK_PRValue, FPOptionsOverride());
7287 // Construct a new arg type with address space of Param
7288 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7289 ArgPtQuals.setAddressSpace(ParamAS);
7290 auto NewArgPtTy =
7291 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7292 auto NewArgTy =
7293 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7294 ArgTy.getQualifiers());
7296 // Finally perform an implicit address space cast
7297 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7298 CK_AddressSpaceConversion)
7299 .get();
7304 if (Context.isDependenceAllowed() &&
7305 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7306 assert(!getLangOpts().CPlusPlus);
7307 assert((Fn->containsErrors() ||
7308 llvm::any_of(ArgExprs,
7309 [](clang::Expr *E) { return E->containsErrors(); })) &&
7310 "should only occur in error-recovery path.");
7311 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7312 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7314 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7315 ExecConfig, IsExecConfig);
7318 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7319 // with the specified CallArgs
7320 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7321 MultiExprArg CallArgs) {
7322 StringRef Name = Context.BuiltinInfo.getName(Id);
7323 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7324 Sema::LookupOrdinaryName);
7325 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7327 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7328 assert(BuiltInDecl && "failed to find builtin declaration");
7330 ExprResult DeclRef =
7331 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7332 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7334 ExprResult Call =
7335 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7337 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7338 return Call.get();
7341 /// Parse a __builtin_astype expression.
7343 /// __builtin_astype( value, dst type )
7345 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7346 SourceLocation BuiltinLoc,
7347 SourceLocation RParenLoc) {
7348 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7349 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7352 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7353 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7354 SourceLocation BuiltinLoc,
7355 SourceLocation RParenLoc) {
7356 ExprValueKind VK = VK_PRValue;
7357 ExprObjectKind OK = OK_Ordinary;
7358 QualType SrcTy = E->getType();
7359 if (!SrcTy->isDependentType() &&
7360 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7361 return ExprError(
7362 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7363 << DestTy << SrcTy << E->getSourceRange());
7364 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7367 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7368 /// provided arguments.
7370 /// __builtin_convertvector( value, dst type )
7372 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7373 SourceLocation BuiltinLoc,
7374 SourceLocation RParenLoc) {
7375 TypeSourceInfo *TInfo;
7376 GetTypeFromParser(ParsedDestTy, &TInfo);
7377 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7380 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7381 /// i.e. an expression not of \p OverloadTy. The expression should
7382 /// unary-convert to an expression of function-pointer or
7383 /// block-pointer type.
7385 /// \param NDecl the declaration being called, if available
7386 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7387 SourceLocation LParenLoc,
7388 ArrayRef<Expr *> Args,
7389 SourceLocation RParenLoc, Expr *Config,
7390 bool IsExecConfig, ADLCallKind UsesADL) {
7391 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7392 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7394 // Functions with 'interrupt' attribute cannot be called directly.
7395 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
7396 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7397 return ExprError();
7400 // Interrupt handlers don't save off the VFP regs automatically on ARM,
7401 // so there's some risk when calling out to non-interrupt handler functions
7402 // that the callee might not preserve them. This is easy to diagnose here,
7403 // but can be very challenging to debug.
7404 // Likewise, X86 interrupt handlers may only call routines with attribute
7405 // no_caller_saved_registers since there is no efficient way to
7406 // save and restore the non-GPR state.
7407 if (auto *Caller = getCurFunctionDecl()) {
7408 if (Caller->hasAttr<ARMInterruptAttr>()) {
7409 bool VFP = Context.getTargetInfo().hasFeature("vfp");
7410 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
7411 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
7412 if (FDecl)
7413 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7416 if (Caller->hasAttr<AnyX86InterruptAttr>() &&
7417 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
7418 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
7419 if (FDecl)
7420 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7424 // Promote the function operand.
7425 // We special-case function promotion here because we only allow promoting
7426 // builtin functions to function pointers in the callee of a call.
7427 ExprResult Result;
7428 QualType ResultTy;
7429 if (BuiltinID &&
7430 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7431 // Extract the return type from the (builtin) function pointer type.
7432 // FIXME Several builtins still have setType in
7433 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7434 // Builtins.def to ensure they are correct before removing setType calls.
7435 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7436 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7437 ResultTy = FDecl->getCallResultType();
7438 } else {
7439 Result = CallExprUnaryConversions(Fn);
7440 ResultTy = Context.BoolTy;
7442 if (Result.isInvalid())
7443 return ExprError();
7444 Fn = Result.get();
7446 // Check for a valid function type, but only if it is not a builtin which
7447 // requires custom type checking. These will be handled by
7448 // CheckBuiltinFunctionCall below just after creation of the call expression.
7449 const FunctionType *FuncT = nullptr;
7450 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7451 retry:
7452 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7453 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7454 // have type pointer to function".
7455 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7456 if (!FuncT)
7457 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7458 << Fn->getType() << Fn->getSourceRange());
7459 } else if (const BlockPointerType *BPT =
7460 Fn->getType()->getAs<BlockPointerType>()) {
7461 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7462 } else {
7463 // Handle calls to expressions of unknown-any type.
7464 if (Fn->getType() == Context.UnknownAnyTy) {
7465 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7466 if (rewrite.isInvalid())
7467 return ExprError();
7468 Fn = rewrite.get();
7469 goto retry;
7472 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7473 << Fn->getType() << Fn->getSourceRange());
7477 // Get the number of parameters in the function prototype, if any.
7478 // We will allocate space for max(Args.size(), NumParams) arguments
7479 // in the call expression.
7480 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7481 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7483 CallExpr *TheCall;
7484 if (Config) {
7485 assert(UsesADL == ADLCallKind::NotADL &&
7486 "CUDAKernelCallExpr should not use ADL");
7487 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7488 Args, ResultTy, VK_PRValue, RParenLoc,
7489 CurFPFeatureOverrides(), NumParams);
7490 } else {
7491 TheCall =
7492 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7493 CurFPFeatureOverrides(), NumParams, UsesADL);
7496 if (!Context.isDependenceAllowed()) {
7497 // Forget about the nulled arguments since typo correction
7498 // do not handle them well.
7499 TheCall->shrinkNumArgs(Args.size());
7500 // C cannot always handle TypoExpr nodes in builtin calls and direct
7501 // function calls as their argument checking don't necessarily handle
7502 // dependent types properly, so make sure any TypoExprs have been
7503 // dealt with.
7504 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7505 if (!Result.isUsable()) return ExprError();
7506 CallExpr *TheOldCall = TheCall;
7507 TheCall = dyn_cast<CallExpr>(Result.get());
7508 bool CorrectedTypos = TheCall != TheOldCall;
7509 if (!TheCall) return Result;
7510 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7512 // A new call expression node was created if some typos were corrected.
7513 // However it may not have been constructed with enough storage. In this
7514 // case, rebuild the node with enough storage. The waste of space is
7515 // immaterial since this only happens when some typos were corrected.
7516 if (CorrectedTypos && Args.size() < NumParams) {
7517 if (Config)
7518 TheCall = CUDAKernelCallExpr::Create(
7519 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7520 RParenLoc, CurFPFeatureOverrides(), NumParams);
7521 else
7522 TheCall =
7523 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7524 CurFPFeatureOverrides(), NumParams, UsesADL);
7526 // We can now handle the nulled arguments for the default arguments.
7527 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7530 // Bail out early if calling a builtin with custom type checking.
7531 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7532 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7534 if (getLangOpts().CUDA) {
7535 if (Config) {
7536 // CUDA: Kernel calls must be to global functions
7537 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7538 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7539 << FDecl << Fn->getSourceRange());
7541 // CUDA: Kernel function must have 'void' return type
7542 if (!FuncT->getReturnType()->isVoidType() &&
7543 !FuncT->getReturnType()->getAs<AutoType>() &&
7544 !FuncT->getReturnType()->isInstantiationDependentType())
7545 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7546 << Fn->getType() << Fn->getSourceRange());
7547 } else {
7548 // CUDA: Calls to global functions must be configured
7549 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7550 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7551 << FDecl << Fn->getSourceRange());
7555 // Check for a valid return type
7556 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7557 FDecl))
7558 return ExprError();
7560 // We know the result type of the call, set it.
7561 TheCall->setType(FuncT->getCallResultType(Context));
7562 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7564 // WebAssembly tables can't be used as arguments.
7565 if (Context.getTargetInfo().getTriple().isWasm()) {
7566 for (const Expr *Arg : Args) {
7567 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7568 return ExprError(Diag(Arg->getExprLoc(),
7569 diag::err_wasm_table_as_function_parameter));
7574 if (Proto) {
7575 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7576 IsExecConfig))
7577 return ExprError();
7578 } else {
7579 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7581 if (FDecl) {
7582 // Check if we have too few/too many template arguments, based
7583 // on our knowledge of the function definition.
7584 const FunctionDecl *Def = nullptr;
7585 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7586 Proto = Def->getType()->getAs<FunctionProtoType>();
7587 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7588 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7589 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7592 // If the function we're calling isn't a function prototype, but we have
7593 // a function prototype from a prior declaratiom, use that prototype.
7594 if (!FDecl->hasPrototype())
7595 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7598 // If we still haven't found a prototype to use but there are arguments to
7599 // the call, diagnose this as calling a function without a prototype.
7600 // However, if we found a function declaration, check to see if
7601 // -Wdeprecated-non-prototype was disabled where the function was declared.
7602 // If so, we will silence the diagnostic here on the assumption that this
7603 // interface is intentional and the user knows what they're doing. We will
7604 // also silence the diagnostic if there is a function declaration but it
7605 // was implicitly defined (the user already gets diagnostics about the
7606 // creation of the implicit function declaration, so the additional warning
7607 // is not helpful).
7608 if (!Proto && !Args.empty() &&
7609 (!FDecl || (!FDecl->isImplicit() &&
7610 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7611 FDecl->getLocation()))))
7612 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7613 << (FDecl != nullptr) << FDecl;
7615 // Promote the arguments (C99 6.5.2.2p6).
7616 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7617 Expr *Arg = Args[i];
7619 if (Proto && i < Proto->getNumParams()) {
7620 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7621 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7622 ExprResult ArgE =
7623 PerformCopyInitialization(Entity, SourceLocation(), Arg);
7624 if (ArgE.isInvalid())
7625 return true;
7627 Arg = ArgE.getAs<Expr>();
7629 } else {
7630 ExprResult ArgE = DefaultArgumentPromotion(Arg);
7632 if (ArgE.isInvalid())
7633 return true;
7635 Arg = ArgE.getAs<Expr>();
7638 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7639 diag::err_call_incomplete_argument, Arg))
7640 return ExprError();
7642 TheCall->setArg(i, Arg);
7644 TheCall->computeDependence();
7647 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7648 if (!Method->isStatic())
7649 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7650 << Fn->getSourceRange());
7652 // Check for sentinels
7653 if (NDecl)
7654 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7656 // Warn for unions passing across security boundary (CMSE).
7657 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7658 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7659 if (const auto *RT =
7660 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7661 if (RT->getDecl()->isOrContainsUnion())
7662 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7663 << 0 << i;
7668 // Do special checking on direct calls to functions.
7669 if (FDecl) {
7670 if (CheckFunctionCall(FDecl, TheCall, Proto))
7671 return ExprError();
7673 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7675 if (BuiltinID)
7676 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7677 } else if (NDecl) {
7678 if (CheckPointerCall(NDecl, TheCall, Proto))
7679 return ExprError();
7680 } else {
7681 if (CheckOtherCall(TheCall, Proto))
7682 return ExprError();
7685 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7688 ExprResult
7689 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7690 SourceLocation RParenLoc, Expr *InitExpr) {
7691 assert(Ty && "ActOnCompoundLiteral(): missing type");
7692 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7694 TypeSourceInfo *TInfo;
7695 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7696 if (!TInfo)
7697 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7699 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7702 ExprResult
7703 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7704 SourceLocation RParenLoc, Expr *LiteralExpr) {
7705 QualType literalType = TInfo->getType();
7707 if (literalType->isArrayType()) {
7708 if (RequireCompleteSizedType(
7709 LParenLoc, Context.getBaseElementType(literalType),
7710 diag::err_array_incomplete_or_sizeless_type,
7711 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7712 return ExprError();
7713 if (literalType->isVariableArrayType()) {
7714 // C23 6.7.10p4: An entity of variable length array type shall not be
7715 // initialized except by an empty initializer.
7717 // The C extension warnings are issued from ParseBraceInitializer() and
7718 // do not need to be issued here. However, we continue to issue an error
7719 // in the case there are initializers or we are compiling C++. We allow
7720 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7721 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7722 // FIXME: should we allow this construct in C++ when it makes sense to do
7723 // so?
7724 std::optional<unsigned> NumInits;
7725 if (const auto *ILE = dyn_cast<InitListExpr>(LiteralExpr))
7726 NumInits = ILE->getNumInits();
7727 if ((LangOpts.CPlusPlus || NumInits.value_or(0)) &&
7728 !tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7729 diag::err_variable_object_no_init))
7730 return ExprError();
7732 } else if (!literalType->isDependentType() &&
7733 RequireCompleteType(LParenLoc, literalType,
7734 diag::err_typecheck_decl_incomplete_type,
7735 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7736 return ExprError();
7738 InitializedEntity Entity
7739 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7740 InitializationKind Kind
7741 = InitializationKind::CreateCStyleCast(LParenLoc,
7742 SourceRange(LParenLoc, RParenLoc),
7743 /*InitList=*/true);
7744 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7745 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7746 &literalType);
7747 if (Result.isInvalid())
7748 return ExprError();
7749 LiteralExpr = Result.get();
7751 bool isFileScope = !CurContext->isFunctionOrMethod();
7753 // In C, compound literals are l-values for some reason.
7754 // For GCC compatibility, in C++, file-scope array compound literals with
7755 // constant initializers are also l-values, and compound literals are
7756 // otherwise prvalues.
7758 // (GCC also treats C++ list-initialized file-scope array prvalues with
7759 // constant initializers as l-values, but that's non-conforming, so we don't
7760 // follow it there.)
7762 // FIXME: It would be better to handle the lvalue cases as materializing and
7763 // lifetime-extending a temporary object, but our materialized temporaries
7764 // representation only supports lifetime extension from a variable, not "out
7765 // of thin air".
7766 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7767 // is bound to the result of applying array-to-pointer decay to the compound
7768 // literal.
7769 // FIXME: GCC supports compound literals of reference type, which should
7770 // obviously have a value kind derived from the kind of reference involved.
7771 ExprValueKind VK =
7772 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7773 ? VK_PRValue
7774 : VK_LValue;
7776 if (isFileScope)
7777 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7778 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7779 Expr *Init = ILE->getInit(i);
7780 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7783 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7784 VK, LiteralExpr, isFileScope);
7785 if (isFileScope) {
7786 if (!LiteralExpr->isTypeDependent() &&
7787 !LiteralExpr->isValueDependent() &&
7788 !literalType->isDependentType()) // C99 6.5.2.5p3
7789 if (CheckForConstantInitializer(LiteralExpr, literalType))
7790 return ExprError();
7791 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7792 literalType.getAddressSpace() != LangAS::Default) {
7793 // Embedded-C extensions to C99 6.5.2.5:
7794 // "If the compound literal occurs inside the body of a function, the
7795 // type name shall not be qualified by an address-space qualifier."
7796 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7797 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7798 return ExprError();
7801 if (!isFileScope && !getLangOpts().CPlusPlus) {
7802 // Compound literals that have automatic storage duration are destroyed at
7803 // the end of the scope in C; in C++, they're just temporaries.
7805 // Emit diagnostics if it is or contains a C union type that is non-trivial
7806 // to destruct.
7807 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7808 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7809 NTCUC_CompoundLiteral, NTCUK_Destruct);
7811 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7812 if (literalType.isDestructedType()) {
7813 Cleanup.setExprNeedsCleanups(true);
7814 ExprCleanupObjects.push_back(E);
7815 getCurFunction()->setHasBranchProtectedScope();
7819 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7820 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7821 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7822 E->getInitializer()->getExprLoc());
7824 return MaybeBindToTemporary(E);
7827 ExprResult
7828 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7829 SourceLocation RBraceLoc) {
7830 // Only produce each kind of designated initialization diagnostic once.
7831 SourceLocation FirstDesignator;
7832 bool DiagnosedArrayDesignator = false;
7833 bool DiagnosedNestedDesignator = false;
7834 bool DiagnosedMixedDesignator = false;
7836 // Check that any designated initializers are syntactically valid in the
7837 // current language mode.
7838 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7839 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7840 if (FirstDesignator.isInvalid())
7841 FirstDesignator = DIE->getBeginLoc();
7843 if (!getLangOpts().CPlusPlus)
7844 break;
7846 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7847 DiagnosedNestedDesignator = true;
7848 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7849 << DIE->getDesignatorsSourceRange();
7852 for (auto &Desig : DIE->designators()) {
7853 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7854 DiagnosedArrayDesignator = true;
7855 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7856 << Desig.getSourceRange();
7860 if (!DiagnosedMixedDesignator &&
7861 !isa<DesignatedInitExpr>(InitArgList[0])) {
7862 DiagnosedMixedDesignator = true;
7863 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7864 << DIE->getSourceRange();
7865 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7866 << InitArgList[0]->getSourceRange();
7868 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7869 isa<DesignatedInitExpr>(InitArgList[0])) {
7870 DiagnosedMixedDesignator = true;
7871 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7872 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7873 << DIE->getSourceRange();
7874 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7875 << InitArgList[I]->getSourceRange();
7879 if (FirstDesignator.isValid()) {
7880 // Only diagnose designated initiaization as a C++20 extension if we didn't
7881 // already diagnose use of (non-C++20) C99 designator syntax.
7882 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7883 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7884 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7885 ? diag::warn_cxx17_compat_designated_init
7886 : diag::ext_cxx_designated_init);
7887 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7888 Diag(FirstDesignator, diag::ext_designated_init);
7892 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7895 ExprResult
7896 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7897 SourceLocation RBraceLoc) {
7898 // Semantic analysis for initializers is done by ActOnDeclarator() and
7899 // CheckInitializer() - it requires knowledge of the object being initialized.
7901 // Immediately handle non-overload placeholders. Overloads can be
7902 // resolved contextually, but everything else here can't.
7903 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7904 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7905 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7907 // Ignore failures; dropping the entire initializer list because
7908 // of one failure would be terrible for indexing/etc.
7909 if (result.isInvalid()) continue;
7911 InitArgList[I] = result.get();
7915 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7916 RBraceLoc);
7917 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7918 return E;
7921 /// Do an explicit extend of the given block pointer if we're in ARC.
7922 void Sema::maybeExtendBlockObject(ExprResult &E) {
7923 assert(E.get()->getType()->isBlockPointerType());
7924 assert(E.get()->isPRValue());
7926 // Only do this in an r-value context.
7927 if (!getLangOpts().ObjCAutoRefCount) return;
7929 E = ImplicitCastExpr::Create(
7930 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7931 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7932 Cleanup.setExprNeedsCleanups(true);
7935 /// Prepare a conversion of the given expression to an ObjC object
7936 /// pointer type.
7937 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7938 QualType type = E.get()->getType();
7939 if (type->isObjCObjectPointerType()) {
7940 return CK_BitCast;
7941 } else if (type->isBlockPointerType()) {
7942 maybeExtendBlockObject(E);
7943 return CK_BlockPointerToObjCPointerCast;
7944 } else {
7945 assert(type->isPointerType());
7946 return CK_CPointerToObjCPointerCast;
7950 /// Prepares for a scalar cast, performing all the necessary stages
7951 /// except the final cast and returning the kind required.
7952 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7953 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7954 // Also, callers should have filtered out the invalid cases with
7955 // pointers. Everything else should be possible.
7957 QualType SrcTy = Src.get()->getType();
7958 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7959 return CK_NoOp;
7961 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7962 case Type::STK_MemberPointer:
7963 llvm_unreachable("member pointer type in C");
7965 case Type::STK_CPointer:
7966 case Type::STK_BlockPointer:
7967 case Type::STK_ObjCObjectPointer:
7968 switch (DestTy->getScalarTypeKind()) {
7969 case Type::STK_CPointer: {
7970 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7971 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7972 if (SrcAS != DestAS)
7973 return CK_AddressSpaceConversion;
7974 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7975 return CK_NoOp;
7976 return CK_BitCast;
7978 case Type::STK_BlockPointer:
7979 return (SrcKind == Type::STK_BlockPointer
7980 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7981 case Type::STK_ObjCObjectPointer:
7982 if (SrcKind == Type::STK_ObjCObjectPointer)
7983 return CK_BitCast;
7984 if (SrcKind == Type::STK_CPointer)
7985 return CK_CPointerToObjCPointerCast;
7986 maybeExtendBlockObject(Src);
7987 return CK_BlockPointerToObjCPointerCast;
7988 case Type::STK_Bool:
7989 return CK_PointerToBoolean;
7990 case Type::STK_Integral:
7991 return CK_PointerToIntegral;
7992 case Type::STK_Floating:
7993 case Type::STK_FloatingComplex:
7994 case Type::STK_IntegralComplex:
7995 case Type::STK_MemberPointer:
7996 case Type::STK_FixedPoint:
7997 llvm_unreachable("illegal cast from pointer");
7999 llvm_unreachable("Should have returned before this");
8001 case Type::STK_FixedPoint:
8002 switch (DestTy->getScalarTypeKind()) {
8003 case Type::STK_FixedPoint:
8004 return CK_FixedPointCast;
8005 case Type::STK_Bool:
8006 return CK_FixedPointToBoolean;
8007 case Type::STK_Integral:
8008 return CK_FixedPointToIntegral;
8009 case Type::STK_Floating:
8010 return CK_FixedPointToFloating;
8011 case Type::STK_IntegralComplex:
8012 case Type::STK_FloatingComplex:
8013 Diag(Src.get()->getExprLoc(),
8014 diag::err_unimplemented_conversion_with_fixed_point_type)
8015 << DestTy;
8016 return CK_IntegralCast;
8017 case Type::STK_CPointer:
8018 case Type::STK_ObjCObjectPointer:
8019 case Type::STK_BlockPointer:
8020 case Type::STK_MemberPointer:
8021 llvm_unreachable("illegal cast to pointer type");
8023 llvm_unreachable("Should have returned before this");
8025 case Type::STK_Bool: // casting from bool is like casting from an integer
8026 case Type::STK_Integral:
8027 switch (DestTy->getScalarTypeKind()) {
8028 case Type::STK_CPointer:
8029 case Type::STK_ObjCObjectPointer:
8030 case Type::STK_BlockPointer:
8031 if (Src.get()->isNullPointerConstant(Context,
8032 Expr::NPC_ValueDependentIsNull))
8033 return CK_NullToPointer;
8034 return CK_IntegralToPointer;
8035 case Type::STK_Bool:
8036 return CK_IntegralToBoolean;
8037 case Type::STK_Integral:
8038 return CK_IntegralCast;
8039 case Type::STK_Floating:
8040 return CK_IntegralToFloating;
8041 case Type::STK_IntegralComplex:
8042 Src = ImpCastExprToType(Src.get(),
8043 DestTy->castAs<ComplexType>()->getElementType(),
8044 CK_IntegralCast);
8045 return CK_IntegralRealToComplex;
8046 case Type::STK_FloatingComplex:
8047 Src = ImpCastExprToType(Src.get(),
8048 DestTy->castAs<ComplexType>()->getElementType(),
8049 CK_IntegralToFloating);
8050 return CK_FloatingRealToComplex;
8051 case Type::STK_MemberPointer:
8052 llvm_unreachable("member pointer type in C");
8053 case Type::STK_FixedPoint:
8054 return CK_IntegralToFixedPoint;
8056 llvm_unreachable("Should have returned before this");
8058 case Type::STK_Floating:
8059 switch (DestTy->getScalarTypeKind()) {
8060 case Type::STK_Floating:
8061 return CK_FloatingCast;
8062 case Type::STK_Bool:
8063 return CK_FloatingToBoolean;
8064 case Type::STK_Integral:
8065 return CK_FloatingToIntegral;
8066 case Type::STK_FloatingComplex:
8067 Src = ImpCastExprToType(Src.get(),
8068 DestTy->castAs<ComplexType>()->getElementType(),
8069 CK_FloatingCast);
8070 return CK_FloatingRealToComplex;
8071 case Type::STK_IntegralComplex:
8072 Src = ImpCastExprToType(Src.get(),
8073 DestTy->castAs<ComplexType>()->getElementType(),
8074 CK_FloatingToIntegral);
8075 return CK_IntegralRealToComplex;
8076 case Type::STK_CPointer:
8077 case Type::STK_ObjCObjectPointer:
8078 case Type::STK_BlockPointer:
8079 llvm_unreachable("valid float->pointer cast?");
8080 case Type::STK_MemberPointer:
8081 llvm_unreachable("member pointer type in C");
8082 case Type::STK_FixedPoint:
8083 return CK_FloatingToFixedPoint;
8085 llvm_unreachable("Should have returned before this");
8087 case Type::STK_FloatingComplex:
8088 switch (DestTy->getScalarTypeKind()) {
8089 case Type::STK_FloatingComplex:
8090 return CK_FloatingComplexCast;
8091 case Type::STK_IntegralComplex:
8092 return CK_FloatingComplexToIntegralComplex;
8093 case Type::STK_Floating: {
8094 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8095 if (Context.hasSameType(ET, DestTy))
8096 return CK_FloatingComplexToReal;
8097 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
8098 return CK_FloatingCast;
8100 case Type::STK_Bool:
8101 return CK_FloatingComplexToBoolean;
8102 case Type::STK_Integral:
8103 Src = ImpCastExprToType(Src.get(),
8104 SrcTy->castAs<ComplexType>()->getElementType(),
8105 CK_FloatingComplexToReal);
8106 return CK_FloatingToIntegral;
8107 case Type::STK_CPointer:
8108 case Type::STK_ObjCObjectPointer:
8109 case Type::STK_BlockPointer:
8110 llvm_unreachable("valid complex float->pointer cast?");
8111 case Type::STK_MemberPointer:
8112 llvm_unreachable("member pointer type in C");
8113 case Type::STK_FixedPoint:
8114 Diag(Src.get()->getExprLoc(),
8115 diag::err_unimplemented_conversion_with_fixed_point_type)
8116 << SrcTy;
8117 return CK_IntegralCast;
8119 llvm_unreachable("Should have returned before this");
8121 case Type::STK_IntegralComplex:
8122 switch (DestTy->getScalarTypeKind()) {
8123 case Type::STK_FloatingComplex:
8124 return CK_IntegralComplexToFloatingComplex;
8125 case Type::STK_IntegralComplex:
8126 return CK_IntegralComplexCast;
8127 case Type::STK_Integral: {
8128 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8129 if (Context.hasSameType(ET, DestTy))
8130 return CK_IntegralComplexToReal;
8131 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
8132 return CK_IntegralCast;
8134 case Type::STK_Bool:
8135 return CK_IntegralComplexToBoolean;
8136 case Type::STK_Floating:
8137 Src = ImpCastExprToType(Src.get(),
8138 SrcTy->castAs<ComplexType>()->getElementType(),
8139 CK_IntegralComplexToReal);
8140 return CK_IntegralToFloating;
8141 case Type::STK_CPointer:
8142 case Type::STK_ObjCObjectPointer:
8143 case Type::STK_BlockPointer:
8144 llvm_unreachable("valid complex int->pointer cast?");
8145 case Type::STK_MemberPointer:
8146 llvm_unreachable("member pointer type in C");
8147 case Type::STK_FixedPoint:
8148 Diag(Src.get()->getExprLoc(),
8149 diag::err_unimplemented_conversion_with_fixed_point_type)
8150 << SrcTy;
8151 return CK_IntegralCast;
8153 llvm_unreachable("Should have returned before this");
8156 llvm_unreachable("Unhandled scalar cast");
8159 static bool breakDownVectorType(QualType type, uint64_t &len,
8160 QualType &eltType) {
8161 // Vectors are simple.
8162 if (const VectorType *vecType = type->getAs<VectorType>()) {
8163 len = vecType->getNumElements();
8164 eltType = vecType->getElementType();
8165 assert(eltType->isScalarType());
8166 return true;
8169 // We allow lax conversion to and from non-vector types, but only if
8170 // they're real types (i.e. non-complex, non-pointer scalar types).
8171 if (!type->isRealType()) return false;
8173 len = 1;
8174 eltType = type;
8175 return true;
8178 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
8179 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
8180 /// allowed?
8182 /// This will also return false if the two given types do not make sense from
8183 /// the perspective of SVE bitcasts.
8184 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
8185 assert(srcTy->isVectorType() || destTy->isVectorType());
8187 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8188 if (!FirstType->isSVESizelessBuiltinType())
8189 return false;
8191 const auto *VecTy = SecondType->getAs<VectorType>();
8192 return VecTy &&
8193 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
8196 return ValidScalableConversion(srcTy, destTy) ||
8197 ValidScalableConversion(destTy, srcTy);
8200 /// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the
8201 /// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV
8202 /// VLS type) allowed?
8204 /// This will also return false if the two given types do not make sense from
8205 /// the perspective of RVV bitcasts.
8206 bool Sema::isValidRVVBitcast(QualType srcTy, QualType destTy) {
8207 assert(srcTy->isVectorType() || destTy->isVectorType());
8209 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8210 if (!FirstType->isRVVSizelessBuiltinType())
8211 return false;
8213 const auto *VecTy = SecondType->getAs<VectorType>();
8214 return VecTy &&
8215 VecTy->getVectorKind() == VectorType::RVVFixedLengthDataVector;
8218 return ValidScalableConversion(srcTy, destTy) ||
8219 ValidScalableConversion(destTy, srcTy);
8222 /// Are the two types matrix types and do they have the same dimensions i.e.
8223 /// do they have the same number of rows and the same number of columns?
8224 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
8225 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8226 return false;
8228 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8229 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8231 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8232 matSrcType->getNumColumns() == matDestType->getNumColumns();
8235 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
8236 assert(DestTy->isVectorType() || SrcTy->isVectorType());
8238 uint64_t SrcLen, DestLen;
8239 QualType SrcEltTy, DestEltTy;
8240 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
8241 return false;
8242 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
8243 return false;
8245 // ASTContext::getTypeSize will return the size rounded up to a
8246 // power of 2, so instead of using that, we need to use the raw
8247 // element size multiplied by the element count.
8248 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
8249 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
8251 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8254 // This returns true if at least one of the types is an altivec vector.
8255 bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
8256 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
8257 "expected at least one type to be a vector here");
8259 bool IsSrcTyAltivec =
8260 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8261 VectorType::AltiVecVector) ||
8262 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8263 VectorType::AltiVecBool) ||
8264 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8265 VectorType::AltiVecPixel));
8267 bool IsDestTyAltivec = DestTy->isVectorType() &&
8268 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8269 VectorType::AltiVecVector) ||
8270 (DestTy->castAs<VectorType>()->getVectorKind() ==
8271 VectorType::AltiVecBool) ||
8272 (DestTy->castAs<VectorType>()->getVectorKind() ==
8273 VectorType::AltiVecPixel));
8275 return (IsSrcTyAltivec || IsDestTyAltivec);
8278 /// Are the two types lax-compatible vector types? That is, given
8279 /// that one of them is a vector, do they have equal storage sizes,
8280 /// where the storage size is the number of elements times the element
8281 /// size?
8283 /// This will also return false if either of the types is neither a
8284 /// vector nor a real type.
8285 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8286 assert(destTy->isVectorType() || srcTy->isVectorType());
8288 // Disallow lax conversions between scalars and ExtVectors (these
8289 // conversions are allowed for other vector types because common headers
8290 // depend on them). Most scalar OP ExtVector cases are handled by the
8291 // splat path anyway, which does what we want (convert, not bitcast).
8292 // What this rules out for ExtVectors is crazy things like char4*float.
8293 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8294 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8296 return areVectorTypesSameSize(srcTy, destTy);
8299 /// Is this a legal conversion between two types, one of which is
8300 /// known to be a vector type?
8301 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8302 assert(destTy->isVectorType() || srcTy->isVectorType());
8304 switch (Context.getLangOpts().getLaxVectorConversions()) {
8305 case LangOptions::LaxVectorConversionKind::None:
8306 return false;
8308 case LangOptions::LaxVectorConversionKind::Integer:
8309 if (!srcTy->isIntegralOrEnumerationType()) {
8310 auto *Vec = srcTy->getAs<VectorType>();
8311 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8312 return false;
8314 if (!destTy->isIntegralOrEnumerationType()) {
8315 auto *Vec = destTy->getAs<VectorType>();
8316 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8317 return false;
8319 // OK, integer (vector) -> integer (vector) bitcast.
8320 break;
8322 case LangOptions::LaxVectorConversionKind::All:
8323 break;
8326 return areLaxCompatibleVectorTypes(srcTy, destTy);
8329 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8330 CastKind &Kind) {
8331 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8332 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8333 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8334 << DestTy << SrcTy << R;
8336 } else if (SrcTy->isMatrixType()) {
8337 return Diag(R.getBegin(),
8338 diag::err_invalid_conversion_between_matrix_and_type)
8339 << SrcTy << DestTy << R;
8340 } else if (DestTy->isMatrixType()) {
8341 return Diag(R.getBegin(),
8342 diag::err_invalid_conversion_between_matrix_and_type)
8343 << DestTy << SrcTy << R;
8346 Kind = CK_MatrixCast;
8347 return false;
8350 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8351 CastKind &Kind) {
8352 assert(VectorTy->isVectorType() && "Not a vector type!");
8354 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8355 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8356 return Diag(R.getBegin(),
8357 Ty->isVectorType() ?
8358 diag::err_invalid_conversion_between_vectors :
8359 diag::err_invalid_conversion_between_vector_and_integer)
8360 << VectorTy << Ty << R;
8361 } else
8362 return Diag(R.getBegin(),
8363 diag::err_invalid_conversion_between_vector_and_scalar)
8364 << VectorTy << Ty << R;
8366 Kind = CK_BitCast;
8367 return false;
8370 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8371 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8373 if (DestElemTy == SplattedExpr->getType())
8374 return SplattedExpr;
8376 assert(DestElemTy->isFloatingType() ||
8377 DestElemTy->isIntegralOrEnumerationType());
8379 CastKind CK;
8380 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8381 // OpenCL requires that we convert `true` boolean expressions to -1, but
8382 // only when splatting vectors.
8383 if (DestElemTy->isFloatingType()) {
8384 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8385 // in two steps: boolean to signed integral, then to floating.
8386 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8387 CK_BooleanToSignedIntegral);
8388 SplattedExpr = CastExprRes.get();
8389 CK = CK_IntegralToFloating;
8390 } else {
8391 CK = CK_BooleanToSignedIntegral;
8393 } else {
8394 ExprResult CastExprRes = SplattedExpr;
8395 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8396 if (CastExprRes.isInvalid())
8397 return ExprError();
8398 SplattedExpr = CastExprRes.get();
8400 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8403 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8404 Expr *CastExpr, CastKind &Kind) {
8405 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8407 QualType SrcTy = CastExpr->getType();
8409 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8410 // an ExtVectorType.
8411 // In OpenCL, casts between vectors of different types are not allowed.
8412 // (See OpenCL 6.2).
8413 if (SrcTy->isVectorType()) {
8414 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8415 (getLangOpts().OpenCL &&
8416 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
8417 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8418 << DestTy << SrcTy << R;
8419 return ExprError();
8421 Kind = CK_BitCast;
8422 return CastExpr;
8425 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8426 // conversion will take place first from scalar to elt type, and then
8427 // splat from elt type to vector.
8428 if (SrcTy->isPointerType())
8429 return Diag(R.getBegin(),
8430 diag::err_invalid_conversion_between_vector_and_scalar)
8431 << DestTy << SrcTy << R;
8433 Kind = CK_VectorSplat;
8434 return prepareVectorSplat(DestTy, CastExpr);
8437 ExprResult
8438 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8439 Declarator &D, ParsedType &Ty,
8440 SourceLocation RParenLoc, Expr *CastExpr) {
8441 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8442 "ActOnCastExpr(): missing type or expr");
8444 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
8445 if (D.isInvalidType())
8446 return ExprError();
8448 if (getLangOpts().CPlusPlus) {
8449 // Check that there are no default arguments (C++ only).
8450 CheckExtraCXXDefaultArguments(D);
8451 } else {
8452 // Make sure any TypoExprs have been dealt with.
8453 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
8454 if (!Res.isUsable())
8455 return ExprError();
8456 CastExpr = Res.get();
8459 checkUnusedDeclAttributes(D);
8461 QualType castType = castTInfo->getType();
8462 Ty = CreateParsedType(castType, castTInfo);
8464 bool isVectorLiteral = false;
8466 // Check for an altivec or OpenCL literal,
8467 // i.e. all the elements are integer constants.
8468 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8469 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8470 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8471 && castType->isVectorType() && (PE || PLE)) {
8472 if (PLE && PLE->getNumExprs() == 0) {
8473 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8474 return ExprError();
8476 if (PE || PLE->getNumExprs() == 1) {
8477 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8478 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8479 isVectorLiteral = true;
8481 else
8482 isVectorLiteral = true;
8485 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8486 // then handle it as such.
8487 if (isVectorLiteral)
8488 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8490 // If the Expr being casted is a ParenListExpr, handle it specially.
8491 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8492 // sequence of BinOp comma operators.
8493 if (isa<ParenListExpr>(CastExpr)) {
8494 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
8495 if (Result.isInvalid()) return ExprError();
8496 CastExpr = Result.get();
8499 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8500 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8502 CheckTollFreeBridgeCast(castType, CastExpr);
8504 CheckObjCBridgeRelatedCast(castType, CastExpr);
8506 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
8508 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8511 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8512 SourceLocation RParenLoc, Expr *E,
8513 TypeSourceInfo *TInfo) {
8514 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8515 "Expected paren or paren list expression");
8517 Expr **exprs;
8518 unsigned numExprs;
8519 Expr *subExpr;
8520 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8521 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8522 LiteralLParenLoc = PE->getLParenLoc();
8523 LiteralRParenLoc = PE->getRParenLoc();
8524 exprs = PE->getExprs();
8525 numExprs = PE->getNumExprs();
8526 } else { // isa<ParenExpr> by assertion at function entrance
8527 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8528 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8529 subExpr = cast<ParenExpr>(E)->getSubExpr();
8530 exprs = &subExpr;
8531 numExprs = 1;
8534 QualType Ty = TInfo->getType();
8535 assert(Ty->isVectorType() && "Expected vector type");
8537 SmallVector<Expr *, 8> initExprs;
8538 const VectorType *VTy = Ty->castAs<VectorType>();
8539 unsigned numElems = VTy->getNumElements();
8541 // '(...)' form of vector initialization in AltiVec: the number of
8542 // initializers must be one or must match the size of the vector.
8543 // If a single value is specified in the initializer then it will be
8544 // replicated to all the components of the vector
8545 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
8546 VTy->getElementType()))
8547 return ExprError();
8548 if (ShouldSplatAltivecScalarInCast(VTy)) {
8549 // The number of initializers must be one or must match the size of the
8550 // vector. If a single value is specified in the initializer then it will
8551 // be replicated to all the components of the vector
8552 if (numExprs == 1) {
8553 QualType ElemTy = VTy->getElementType();
8554 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8555 if (Literal.isInvalid())
8556 return ExprError();
8557 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8558 PrepareScalarCast(Literal, ElemTy));
8559 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8561 else if (numExprs < numElems) {
8562 Diag(E->getExprLoc(),
8563 diag::err_incorrect_number_of_vector_initializers);
8564 return ExprError();
8566 else
8567 initExprs.append(exprs, exprs + numExprs);
8569 else {
8570 // For OpenCL, when the number of initializers is a single value,
8571 // it will be replicated to all components of the vector.
8572 if (getLangOpts().OpenCL &&
8573 VTy->getVectorKind() == VectorType::GenericVector &&
8574 numExprs == 1) {
8575 QualType ElemTy = VTy->getElementType();
8576 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8577 if (Literal.isInvalid())
8578 return ExprError();
8579 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8580 PrepareScalarCast(Literal, ElemTy));
8581 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8584 initExprs.append(exprs, exprs + numExprs);
8586 // FIXME: This means that pretty-printing the final AST will produce curly
8587 // braces instead of the original commas.
8588 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8589 initExprs, LiteralRParenLoc);
8590 initE->setType(Ty);
8591 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8594 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8595 /// the ParenListExpr into a sequence of comma binary operators.
8596 ExprResult
8597 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8598 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8599 if (!E)
8600 return OrigExpr;
8602 ExprResult Result(E->getExpr(0));
8604 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8605 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8606 E->getExpr(i));
8608 if (Result.isInvalid()) return ExprError();
8610 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8613 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8614 SourceLocation R,
8615 MultiExprArg Val) {
8616 return ParenListExpr::Create(Context, L, Val, R);
8619 /// Emit a specialized diagnostic when one expression is a null pointer
8620 /// constant and the other is not a pointer. Returns true if a diagnostic is
8621 /// emitted.
8622 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8623 SourceLocation QuestionLoc) {
8624 Expr *NullExpr = LHSExpr;
8625 Expr *NonPointerExpr = RHSExpr;
8626 Expr::NullPointerConstantKind NullKind =
8627 NullExpr->isNullPointerConstant(Context,
8628 Expr::NPC_ValueDependentIsNotNull);
8630 if (NullKind == Expr::NPCK_NotNull) {
8631 NullExpr = RHSExpr;
8632 NonPointerExpr = LHSExpr;
8633 NullKind =
8634 NullExpr->isNullPointerConstant(Context,
8635 Expr::NPC_ValueDependentIsNotNull);
8638 if (NullKind == Expr::NPCK_NotNull)
8639 return false;
8641 if (NullKind == Expr::NPCK_ZeroExpression)
8642 return false;
8644 if (NullKind == Expr::NPCK_ZeroLiteral) {
8645 // In this case, check to make sure that we got here from a "NULL"
8646 // string in the source code.
8647 NullExpr = NullExpr->IgnoreParenImpCasts();
8648 SourceLocation loc = NullExpr->getExprLoc();
8649 if (!findMacroSpelling(loc, "NULL"))
8650 return false;
8653 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8654 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8655 << NonPointerExpr->getType() << DiagType
8656 << NonPointerExpr->getSourceRange();
8657 return true;
8660 /// Return false if the condition expression is valid, true otherwise.
8661 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8662 QualType CondTy = Cond->getType();
8664 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8665 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8666 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8667 << CondTy << Cond->getSourceRange();
8668 return true;
8671 // C99 6.5.15p2
8672 if (CondTy->isScalarType()) return false;
8674 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8675 << CondTy << Cond->getSourceRange();
8676 return true;
8679 /// Return false if the NullExpr can be promoted to PointerTy,
8680 /// true otherwise.
8681 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8682 QualType PointerTy) {
8683 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8684 !NullExpr.get()->isNullPointerConstant(S.Context,
8685 Expr::NPC_ValueDependentIsNull))
8686 return true;
8688 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8689 return false;
8692 /// Checks compatibility between two pointers and return the resulting
8693 /// type.
8694 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8695 ExprResult &RHS,
8696 SourceLocation Loc) {
8697 QualType LHSTy = LHS.get()->getType();
8698 QualType RHSTy = RHS.get()->getType();
8700 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8701 // Two identical pointers types are always compatible.
8702 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8705 QualType lhptee, rhptee;
8707 // Get the pointee types.
8708 bool IsBlockPointer = false;
8709 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8710 lhptee = LHSBTy->getPointeeType();
8711 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8712 IsBlockPointer = true;
8713 } else {
8714 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8715 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8718 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8719 // differently qualified versions of compatible types, the result type is
8720 // a pointer to an appropriately qualified version of the composite
8721 // type.
8723 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8724 // clause doesn't make sense for our extensions. E.g. address space 2 should
8725 // be incompatible with address space 3: they may live on different devices or
8726 // anything.
8727 Qualifiers lhQual = lhptee.getQualifiers();
8728 Qualifiers rhQual = rhptee.getQualifiers();
8730 LangAS ResultAddrSpace = LangAS::Default;
8731 LangAS LAddrSpace = lhQual.getAddressSpace();
8732 LangAS RAddrSpace = rhQual.getAddressSpace();
8734 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8735 // spaces is disallowed.
8736 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8737 ResultAddrSpace = LAddrSpace;
8738 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8739 ResultAddrSpace = RAddrSpace;
8740 else {
8741 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8742 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8743 << RHS.get()->getSourceRange();
8744 return QualType();
8747 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8748 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8749 lhQual.removeCVRQualifiers();
8750 rhQual.removeCVRQualifiers();
8752 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8753 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8754 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8755 // qual types are compatible iff
8756 // * corresponded types are compatible
8757 // * CVR qualifiers are equal
8758 // * address spaces are equal
8759 // Thus for conditional operator we merge CVR and address space unqualified
8760 // pointees and if there is a composite type we return a pointer to it with
8761 // merged qualifiers.
8762 LHSCastKind =
8763 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8764 RHSCastKind =
8765 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8766 lhQual.removeAddressSpace();
8767 rhQual.removeAddressSpace();
8769 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8770 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8772 QualType CompositeTy = S.Context.mergeTypes(
8773 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8774 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8776 if (CompositeTy.isNull()) {
8777 // In this situation, we assume void* type. No especially good
8778 // reason, but this is what gcc does, and we do have to pick
8779 // to get a consistent AST.
8780 QualType incompatTy;
8781 incompatTy = S.Context.getPointerType(
8782 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8783 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8784 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8786 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8787 // for casts between types with incompatible address space qualifiers.
8788 // For the following code the compiler produces casts between global and
8789 // local address spaces of the corresponded innermost pointees:
8790 // local int *global *a;
8791 // global int *global *b;
8792 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8793 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8794 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8795 << RHS.get()->getSourceRange();
8797 return incompatTy;
8800 // The pointer types are compatible.
8801 // In case of OpenCL ResultTy should have the address space qualifier
8802 // which is a superset of address spaces of both the 2nd and the 3rd
8803 // operands of the conditional operator.
8804 QualType ResultTy = [&, ResultAddrSpace]() {
8805 if (S.getLangOpts().OpenCL) {
8806 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8807 CompositeQuals.setAddressSpace(ResultAddrSpace);
8808 return S.Context
8809 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8810 .withCVRQualifiers(MergedCVRQual);
8812 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8813 }();
8814 if (IsBlockPointer)
8815 ResultTy = S.Context.getBlockPointerType(ResultTy);
8816 else
8817 ResultTy = S.Context.getPointerType(ResultTy);
8819 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8820 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8821 return ResultTy;
8824 /// Return the resulting type when the operands are both block pointers.
8825 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8826 ExprResult &LHS,
8827 ExprResult &RHS,
8828 SourceLocation Loc) {
8829 QualType LHSTy = LHS.get()->getType();
8830 QualType RHSTy = RHS.get()->getType();
8832 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8833 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8834 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8835 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8836 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8837 return destType;
8839 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8840 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8841 << RHS.get()->getSourceRange();
8842 return QualType();
8845 // We have 2 block pointer types.
8846 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8849 /// Return the resulting type when the operands are both pointers.
8850 static QualType
8851 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8852 ExprResult &RHS,
8853 SourceLocation Loc) {
8854 // get the pointer types
8855 QualType LHSTy = LHS.get()->getType();
8856 QualType RHSTy = RHS.get()->getType();
8858 // get the "pointed to" types
8859 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8860 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8862 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8863 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8864 // Figure out necessary qualifiers (C99 6.5.15p6)
8865 QualType destPointee
8866 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8867 QualType destType = S.Context.getPointerType(destPointee);
8868 // Add qualifiers if necessary.
8869 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8870 // Promote to void*.
8871 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8872 return destType;
8874 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8875 QualType destPointee
8876 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8877 QualType destType = S.Context.getPointerType(destPointee);
8878 // Add qualifiers if necessary.
8879 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8880 // Promote to void*.
8881 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8882 return destType;
8885 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8888 /// Return false if the first expression is not an integer and the second
8889 /// expression is not a pointer, true otherwise.
8890 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8891 Expr* PointerExpr, SourceLocation Loc,
8892 bool IsIntFirstExpr) {
8893 if (!PointerExpr->getType()->isPointerType() ||
8894 !Int.get()->getType()->isIntegerType())
8895 return false;
8897 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8898 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8900 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8901 << Expr1->getType() << Expr2->getType()
8902 << Expr1->getSourceRange() << Expr2->getSourceRange();
8903 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8904 CK_IntegralToPointer);
8905 return true;
8908 /// Simple conversion between integer and floating point types.
8910 /// Used when handling the OpenCL conditional operator where the
8911 /// condition is a vector while the other operands are scalar.
8913 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8914 /// types are either integer or floating type. Between the two
8915 /// operands, the type with the higher rank is defined as the "result
8916 /// type". The other operand needs to be promoted to the same type. No
8917 /// other type promotion is allowed. We cannot use
8918 /// UsualArithmeticConversions() for this purpose, since it always
8919 /// promotes promotable types.
8920 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8921 ExprResult &RHS,
8922 SourceLocation QuestionLoc) {
8923 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8924 if (LHS.isInvalid())
8925 return QualType();
8926 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8927 if (RHS.isInvalid())
8928 return QualType();
8930 // For conversion purposes, we ignore any qualifiers.
8931 // For example, "const float" and "float" are equivalent.
8932 QualType LHSType =
8933 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8934 QualType RHSType =
8935 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8937 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8938 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8939 << LHSType << LHS.get()->getSourceRange();
8940 return QualType();
8943 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8944 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8945 << RHSType << RHS.get()->getSourceRange();
8946 return QualType();
8949 // If both types are identical, no conversion is needed.
8950 if (LHSType == RHSType)
8951 return LHSType;
8953 // Now handle "real" floating types (i.e. float, double, long double).
8954 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8955 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8956 /*IsCompAssign = */ false);
8958 // Finally, we have two differing integer types.
8959 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8960 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8963 /// Convert scalar operands to a vector that matches the
8964 /// condition in length.
8966 /// Used when handling the OpenCL conditional operator where the
8967 /// condition is a vector while the other operands are scalar.
8969 /// We first compute the "result type" for the scalar operands
8970 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8971 /// into a vector of that type where the length matches the condition
8972 /// vector type. s6.11.6 requires that the element types of the result
8973 /// and the condition must have the same number of bits.
8974 static QualType
8975 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8976 QualType CondTy, SourceLocation QuestionLoc) {
8977 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8978 if (ResTy.isNull()) return QualType();
8980 const VectorType *CV = CondTy->getAs<VectorType>();
8981 assert(CV);
8983 // Determine the vector result type
8984 unsigned NumElements = CV->getNumElements();
8985 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8987 // Ensure that all types have the same number of bits
8988 if (S.Context.getTypeSize(CV->getElementType())
8989 != S.Context.getTypeSize(ResTy)) {
8990 // Since VectorTy is created internally, it does not pretty print
8991 // with an OpenCL name. Instead, we just print a description.
8992 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8993 SmallString<64> Str;
8994 llvm::raw_svector_ostream OS(Str);
8995 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8996 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8997 << CondTy << OS.str();
8998 return QualType();
9001 // Convert operands to the vector result type
9002 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
9003 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
9005 return VectorTy;
9008 /// Return false if this is a valid OpenCL condition vector
9009 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
9010 SourceLocation QuestionLoc) {
9011 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
9012 // integral type.
9013 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
9014 assert(CondTy);
9015 QualType EleTy = CondTy->getElementType();
9016 if (EleTy->isIntegerType()) return false;
9018 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
9019 << Cond->getType() << Cond->getSourceRange();
9020 return true;
9023 /// Return false if the vector condition type and the vector
9024 /// result type are compatible.
9026 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
9027 /// number of elements, and their element types have the same number
9028 /// of bits.
9029 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
9030 SourceLocation QuestionLoc) {
9031 const VectorType *CV = CondTy->getAs<VectorType>();
9032 const VectorType *RV = VecResTy->getAs<VectorType>();
9033 assert(CV && RV);
9035 if (CV->getNumElements() != RV->getNumElements()) {
9036 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
9037 << CondTy << VecResTy;
9038 return true;
9041 QualType CVE = CV->getElementType();
9042 QualType RVE = RV->getElementType();
9044 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
9045 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
9046 << CondTy << VecResTy;
9047 return true;
9050 return false;
9053 /// Return the resulting type for the conditional operator in
9054 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
9055 /// s6.3.i) when the condition is a vector type.
9056 static QualType
9057 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
9058 ExprResult &LHS, ExprResult &RHS,
9059 SourceLocation QuestionLoc) {
9060 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
9061 if (Cond.isInvalid())
9062 return QualType();
9063 QualType CondTy = Cond.get()->getType();
9065 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
9066 return QualType();
9068 // If either operand is a vector then find the vector type of the
9069 // result as specified in OpenCL v1.1 s6.3.i.
9070 if (LHS.get()->getType()->isVectorType() ||
9071 RHS.get()->getType()->isVectorType()) {
9072 bool IsBoolVecLang =
9073 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
9074 QualType VecResTy =
9075 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
9076 /*isCompAssign*/ false,
9077 /*AllowBothBool*/ true,
9078 /*AllowBoolConversions*/ false,
9079 /*AllowBooleanOperation*/ IsBoolVecLang,
9080 /*ReportInvalid*/ true);
9081 if (VecResTy.isNull())
9082 return QualType();
9083 // The result type must match the condition type as specified in
9084 // OpenCL v1.1 s6.11.6.
9085 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
9086 return QualType();
9087 return VecResTy;
9090 // Both operands are scalar.
9091 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
9094 /// Return true if the Expr is block type
9095 static bool checkBlockType(Sema &S, const Expr *E) {
9096 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9097 QualType Ty = CE->getCallee()->getType();
9098 if (Ty->isBlockPointerType()) {
9099 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
9100 return true;
9103 return false;
9106 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9107 /// In that case, LHS = cond.
9108 /// C99 6.5.15
9109 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
9110 ExprResult &RHS, ExprValueKind &VK,
9111 ExprObjectKind &OK,
9112 SourceLocation QuestionLoc) {
9114 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
9115 if (!LHSResult.isUsable()) return QualType();
9116 LHS = LHSResult;
9118 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
9119 if (!RHSResult.isUsable()) return QualType();
9120 RHS = RHSResult;
9122 // C++ is sufficiently different to merit its own checker.
9123 if (getLangOpts().CPlusPlus)
9124 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
9126 VK = VK_PRValue;
9127 OK = OK_Ordinary;
9129 if (Context.isDependenceAllowed() &&
9130 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
9131 RHS.get()->isTypeDependent())) {
9132 assert(!getLangOpts().CPlusPlus);
9133 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
9134 RHS.get()->containsErrors()) &&
9135 "should only occur in error-recovery path.");
9136 return Context.DependentTy;
9139 // The OpenCL operator with a vector condition is sufficiently
9140 // different to merit its own checker.
9141 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
9142 Cond.get()->getType()->isExtVectorType())
9143 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
9145 // First, check the condition.
9146 Cond = UsualUnaryConversions(Cond.get());
9147 if (Cond.isInvalid())
9148 return QualType();
9149 if (checkCondition(*this, Cond.get(), QuestionLoc))
9150 return QualType();
9152 // Now check the two expressions.
9153 if (LHS.get()->getType()->isVectorType() ||
9154 RHS.get()->getType()->isVectorType())
9155 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
9156 /*AllowBothBool*/ true,
9157 /*AllowBoolConversions*/ false,
9158 /*AllowBooleanOperation*/ false,
9159 /*ReportInvalid*/ true);
9161 QualType ResTy =
9162 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
9163 if (LHS.isInvalid() || RHS.isInvalid())
9164 return QualType();
9166 // WebAssembly tables are not allowed as conditional LHS or RHS.
9167 QualType LHSTy = LHS.get()->getType();
9168 QualType RHSTy = RHS.get()->getType();
9169 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
9170 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
9171 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9172 return QualType();
9175 // Diagnose attempts to convert between __ibm128, __float128 and long double
9176 // where such conversions currently can't be handled.
9177 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
9178 Diag(QuestionLoc,
9179 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
9180 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9181 return QualType();
9184 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9185 // selection operator (?:).
9186 if (getLangOpts().OpenCL &&
9187 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
9188 return QualType();
9191 // If both operands have arithmetic type, do the usual arithmetic conversions
9192 // to find a common type: C99 6.5.15p3,5.
9193 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
9194 // Disallow invalid arithmetic conversions, such as those between bit-
9195 // precise integers types of different sizes, or between a bit-precise
9196 // integer and another type.
9197 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9198 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9199 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9200 << RHS.get()->getSourceRange();
9201 return QualType();
9204 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
9205 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
9207 return ResTy;
9210 // And if they're both bfloat (which isn't arithmetic), that's fine too.
9211 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
9212 return Context.getCommonSugaredType(LHSTy, RHSTy);
9215 // If both operands are the same structure or union type, the result is that
9216 // type.
9217 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
9218 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
9219 if (LHSRT->getDecl() == RHSRT->getDecl())
9220 // "If both the operands have structure or union type, the result has
9221 // that type." This implies that CV qualifiers are dropped.
9222 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
9223 RHSTy.getUnqualifiedType());
9224 // FIXME: Type of conditional expression must be complete in C mode.
9227 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9228 // The following || allows only one side to be void (a GCC-ism).
9229 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9230 QualType ResTy;
9231 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9232 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
9233 } else if (RHSTy->isVoidType()) {
9234 ResTy = RHSTy;
9235 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9236 << RHS.get()->getSourceRange();
9237 } else {
9238 ResTy = LHSTy;
9239 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9240 << LHS.get()->getSourceRange();
9242 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
9243 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
9244 return ResTy;
9247 // C23 6.5.15p7:
9248 // ... if both the second and third operands have nullptr_t type, the
9249 // result also has that type.
9250 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
9251 return ResTy;
9253 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9254 // the type of the other operand."
9255 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
9256 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
9258 // All objective-c pointer type analysis is done here.
9259 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
9260 QuestionLoc);
9261 if (LHS.isInvalid() || RHS.isInvalid())
9262 return QualType();
9263 if (!compositeType.isNull())
9264 return compositeType;
9267 // Handle block pointer types.
9268 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9269 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9270 QuestionLoc);
9272 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9273 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9274 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9275 QuestionLoc);
9277 // GCC compatibility: soften pointer/integer mismatch. Note that
9278 // null pointers have been filtered out by this point.
9279 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9280 /*IsIntFirstExpr=*/true))
9281 return RHSTy;
9282 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9283 /*IsIntFirstExpr=*/false))
9284 return LHSTy;
9286 // Allow ?: operations in which both operands have the same
9287 // built-in sizeless type.
9288 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
9289 return Context.getCommonSugaredType(LHSTy, RHSTy);
9291 // Emit a better diagnostic if one of the expressions is a null pointer
9292 // constant and the other is not a pointer type. In this case, the user most
9293 // likely forgot to take the address of the other expression.
9294 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9295 return QualType();
9297 // Otherwise, the operands are not compatible.
9298 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9299 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9300 << RHS.get()->getSourceRange();
9301 return QualType();
9304 /// FindCompositeObjCPointerType - Helper method to find composite type of
9305 /// two objective-c pointer types of the two input expressions.
9306 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9307 SourceLocation QuestionLoc) {
9308 QualType LHSTy = LHS.get()->getType();
9309 QualType RHSTy = RHS.get()->getType();
9311 // Handle things like Class and struct objc_class*. Here we case the result
9312 // to the pseudo-builtin, because that will be implicitly cast back to the
9313 // redefinition type if an attempt is made to access its fields.
9314 if (LHSTy->isObjCClassType() &&
9315 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
9316 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9317 return LHSTy;
9319 if (RHSTy->isObjCClassType() &&
9320 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
9321 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9322 return RHSTy;
9324 // And the same for struct objc_object* / id
9325 if (LHSTy->isObjCIdType() &&
9326 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
9327 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9328 return LHSTy;
9330 if (RHSTy->isObjCIdType() &&
9331 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
9332 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9333 return RHSTy;
9335 // And the same for struct objc_selector* / SEL
9336 if (Context.isObjCSelType(LHSTy) &&
9337 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
9338 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
9339 return LHSTy;
9341 if (Context.isObjCSelType(RHSTy) &&
9342 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
9343 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
9344 return RHSTy;
9346 // Check constraints for Objective-C object pointers types.
9347 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
9349 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
9350 // Two identical object pointer types are always compatible.
9351 return LHSTy;
9353 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
9354 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
9355 QualType compositeType = LHSTy;
9357 // If both operands are interfaces and either operand can be
9358 // assigned to the other, use that type as the composite
9359 // type. This allows
9360 // xxx ? (A*) a : (B*) b
9361 // where B is a subclass of A.
9363 // Additionally, as for assignment, if either type is 'id'
9364 // allow silent coercion. Finally, if the types are
9365 // incompatible then make sure to use 'id' as the composite
9366 // type so the result is acceptable for sending messages to.
9368 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
9369 // It could return the composite type.
9370 if (!(compositeType =
9371 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
9372 // Nothing more to do.
9373 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
9374 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
9375 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
9376 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
9377 } else if ((LHSOPT->isObjCQualifiedIdType() ||
9378 RHSOPT->isObjCQualifiedIdType()) &&
9379 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
9380 true)) {
9381 // Need to handle "id<xx>" explicitly.
9382 // GCC allows qualified id and any Objective-C type to devolve to
9383 // id. Currently localizing to here until clear this should be
9384 // part of ObjCQualifiedIdTypesAreCompatible.
9385 compositeType = Context.getObjCIdType();
9386 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
9387 compositeType = Context.getObjCIdType();
9388 } else {
9389 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
9390 << LHSTy << RHSTy
9391 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9392 QualType incompatTy = Context.getObjCIdType();
9393 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
9394 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
9395 return incompatTy;
9397 // The object pointer types are compatible.
9398 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
9399 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
9400 return compositeType;
9402 // Check Objective-C object pointer types and 'void *'
9403 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
9404 if (getLangOpts().ObjCAutoRefCount) {
9405 // ARC forbids the implicit conversion of object pointers to 'void *',
9406 // so these types are not compatible.
9407 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9408 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9409 LHS = RHS = true;
9410 return QualType();
9412 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
9413 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9414 QualType destPointee
9415 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
9416 QualType destType = Context.getPointerType(destPointee);
9417 // Add qualifiers if necessary.
9418 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
9419 // Promote to void*.
9420 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
9421 return destType;
9423 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
9424 if (getLangOpts().ObjCAutoRefCount) {
9425 // ARC forbids the implicit conversion of object pointers to 'void *',
9426 // so these types are not compatible.
9427 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9428 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9429 LHS = RHS = true;
9430 return QualType();
9432 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9433 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
9434 QualType destPointee
9435 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
9436 QualType destType = Context.getPointerType(destPointee);
9437 // Add qualifiers if necessary.
9438 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
9439 // Promote to void*.
9440 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
9441 return destType;
9443 return QualType();
9446 /// SuggestParentheses - Emit a note with a fixit hint that wraps
9447 /// ParenRange in parentheses.
9448 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9449 const PartialDiagnostic &Note,
9450 SourceRange ParenRange) {
9451 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9452 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9453 EndLoc.isValid()) {
9454 Self.Diag(Loc, Note)
9455 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9456 << FixItHint::CreateInsertion(EndLoc, ")");
9457 } else {
9458 // We can't display the parentheses, so just show the bare note.
9459 Self.Diag(Loc, Note) << ParenRange;
9463 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9464 return BinaryOperator::isAdditiveOp(Opc) ||
9465 BinaryOperator::isMultiplicativeOp(Opc) ||
9466 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9467 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9468 // not any of the logical operators. Bitwise-xor is commonly used as a
9469 // logical-xor because there is no logical-xor operator. The logical
9470 // operators, including uses of xor, have a high false positive rate for
9471 // precedence warnings.
9474 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9475 /// expression, either using a built-in or overloaded operator,
9476 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9477 /// expression.
9478 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
9479 Expr **RHSExprs) {
9480 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9481 E = E->IgnoreImpCasts();
9482 E = E->IgnoreConversionOperatorSingleStep();
9483 E = E->IgnoreImpCasts();
9484 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9485 E = MTE->getSubExpr();
9486 E = E->IgnoreImpCasts();
9489 // Built-in binary operator.
9490 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
9491 if (IsArithmeticOp(OP->getOpcode())) {
9492 *Opcode = OP->getOpcode();
9493 *RHSExprs = OP->getRHS();
9494 return true;
9498 // Overloaded operator.
9499 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9500 if (Call->getNumArgs() != 2)
9501 return false;
9503 // Make sure this is really a binary operator that is safe to pass into
9504 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9505 OverloadedOperatorKind OO = Call->getOperator();
9506 if (OO < OO_Plus || OO > OO_Arrow ||
9507 OO == OO_PlusPlus || OO == OO_MinusMinus)
9508 return false;
9510 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9511 if (IsArithmeticOp(OpKind)) {
9512 *Opcode = OpKind;
9513 *RHSExprs = Call->getArg(1);
9514 return true;
9518 return false;
9521 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9522 /// or is a logical expression such as (x==y) which has int type, but is
9523 /// commonly interpreted as boolean.
9524 static bool ExprLooksBoolean(Expr *E) {
9525 E = E->IgnoreParenImpCasts();
9527 if (E->getType()->isBooleanType())
9528 return true;
9529 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
9530 return OP->isComparisonOp() || OP->isLogicalOp();
9531 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
9532 return OP->getOpcode() == UO_LNot;
9533 if (E->getType()->isPointerType())
9534 return true;
9535 // FIXME: What about overloaded operator calls returning "unspecified boolean
9536 // type"s (commonly pointer-to-members)?
9538 return false;
9541 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9542 /// and binary operator are mixed in a way that suggests the programmer assumed
9543 /// the conditional operator has higher precedence, for example:
9544 /// "int x = a + someBinaryCondition ? 1 : 2".
9545 static void DiagnoseConditionalPrecedence(Sema &Self,
9546 SourceLocation OpLoc,
9547 Expr *Condition,
9548 Expr *LHSExpr,
9549 Expr *RHSExpr) {
9550 BinaryOperatorKind CondOpcode;
9551 Expr *CondRHS;
9553 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9554 return;
9555 if (!ExprLooksBoolean(CondRHS))
9556 return;
9558 // The condition is an arithmetic binary expression, with a right-
9559 // hand side that looks boolean, so warn.
9561 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9562 ? diag::warn_precedence_bitwise_conditional
9563 : diag::warn_precedence_conditional;
9565 Self.Diag(OpLoc, DiagID)
9566 << Condition->getSourceRange()
9567 << BinaryOperator::getOpcodeStr(CondOpcode);
9569 SuggestParentheses(
9570 Self, OpLoc,
9571 Self.PDiag(diag::note_precedence_silence)
9572 << BinaryOperator::getOpcodeStr(CondOpcode),
9573 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9575 SuggestParentheses(Self, OpLoc,
9576 Self.PDiag(diag::note_precedence_conditional_first),
9577 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9580 /// Compute the nullability of a conditional expression.
9581 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9582 QualType LHSTy, QualType RHSTy,
9583 ASTContext &Ctx) {
9584 if (!ResTy->isAnyPointerType())
9585 return ResTy;
9587 auto GetNullability = [](QualType Ty) {
9588 std::optional<NullabilityKind> Kind = Ty->getNullability();
9589 if (Kind) {
9590 // For our purposes, treat _Nullable_result as _Nullable.
9591 if (*Kind == NullabilityKind::NullableResult)
9592 return NullabilityKind::Nullable;
9593 return *Kind;
9595 return NullabilityKind::Unspecified;
9598 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9599 NullabilityKind MergedKind;
9601 // Compute nullability of a binary conditional expression.
9602 if (IsBin) {
9603 if (LHSKind == NullabilityKind::NonNull)
9604 MergedKind = NullabilityKind::NonNull;
9605 else
9606 MergedKind = RHSKind;
9607 // Compute nullability of a normal conditional expression.
9608 } else {
9609 if (LHSKind == NullabilityKind::Nullable ||
9610 RHSKind == NullabilityKind::Nullable)
9611 MergedKind = NullabilityKind::Nullable;
9612 else if (LHSKind == NullabilityKind::NonNull)
9613 MergedKind = RHSKind;
9614 else if (RHSKind == NullabilityKind::NonNull)
9615 MergedKind = LHSKind;
9616 else
9617 MergedKind = NullabilityKind::Unspecified;
9620 // Return if ResTy already has the correct nullability.
9621 if (GetNullability(ResTy) == MergedKind)
9622 return ResTy;
9624 // Strip all nullability from ResTy.
9625 while (ResTy->getNullability())
9626 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9628 // Create a new AttributedType with the new nullability kind.
9629 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9630 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9633 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9634 /// in the case of a the GNU conditional expr extension.
9635 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9636 SourceLocation ColonLoc,
9637 Expr *CondExpr, Expr *LHSExpr,
9638 Expr *RHSExpr) {
9639 if (!Context.isDependenceAllowed()) {
9640 // C cannot handle TypoExpr nodes in the condition because it
9641 // doesn't handle dependent types properly, so make sure any TypoExprs have
9642 // been dealt with before checking the operands.
9643 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9644 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9645 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9647 if (!CondResult.isUsable())
9648 return ExprError();
9650 if (LHSExpr) {
9651 if (!LHSResult.isUsable())
9652 return ExprError();
9655 if (!RHSResult.isUsable())
9656 return ExprError();
9658 CondExpr = CondResult.get();
9659 LHSExpr = LHSResult.get();
9660 RHSExpr = RHSResult.get();
9663 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9664 // was the condition.
9665 OpaqueValueExpr *opaqueValue = nullptr;
9666 Expr *commonExpr = nullptr;
9667 if (!LHSExpr) {
9668 commonExpr = CondExpr;
9669 // Lower out placeholder types first. This is important so that we don't
9670 // try to capture a placeholder. This happens in few cases in C++; such
9671 // as Objective-C++'s dictionary subscripting syntax.
9672 if (commonExpr->hasPlaceholderType()) {
9673 ExprResult result = CheckPlaceholderExpr(commonExpr);
9674 if (!result.isUsable()) return ExprError();
9675 commonExpr = result.get();
9677 // We usually want to apply unary conversions *before* saving, except
9678 // in the special case of a C++ l-value conditional.
9679 if (!(getLangOpts().CPlusPlus
9680 && !commonExpr->isTypeDependent()
9681 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9682 && commonExpr->isGLValue()
9683 && commonExpr->isOrdinaryOrBitFieldObject()
9684 && RHSExpr->isOrdinaryOrBitFieldObject()
9685 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9686 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9687 if (commonRes.isInvalid())
9688 return ExprError();
9689 commonExpr = commonRes.get();
9692 // If the common expression is a class or array prvalue, materialize it
9693 // so that we can safely refer to it multiple times.
9694 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9695 commonExpr->getType()->isArrayType())) {
9696 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9697 if (MatExpr.isInvalid())
9698 return ExprError();
9699 commonExpr = MatExpr.get();
9702 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9703 commonExpr->getType(),
9704 commonExpr->getValueKind(),
9705 commonExpr->getObjectKind(),
9706 commonExpr);
9707 LHSExpr = CondExpr = opaqueValue;
9710 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9711 ExprValueKind VK = VK_PRValue;
9712 ExprObjectKind OK = OK_Ordinary;
9713 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9714 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9715 VK, OK, QuestionLoc);
9716 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9717 RHS.isInvalid())
9718 return ExprError();
9720 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9721 RHS.get());
9723 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9725 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9726 Context);
9728 if (!commonExpr)
9729 return new (Context)
9730 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9731 RHS.get(), result, VK, OK);
9733 return new (Context) BinaryConditionalOperator(
9734 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9735 ColonLoc, result, VK, OK);
9738 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
9739 bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType,
9740 AArch64SMECallConversionKind C) {
9741 unsigned FromAttributes = 0, ToAttributes = 0;
9742 if (const auto *FromFn =
9743 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9744 FromAttributes =
9745 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9746 if (const auto *ToFn =
9747 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9748 ToAttributes =
9749 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9751 if (FromAttributes == ToAttributes)
9752 return false;
9754 // If the '__arm_preserves_za' is the only difference between the types,
9755 // check whether we're allowed to add or remove it.
9756 if ((FromAttributes ^ ToAttributes) ==
9757 FunctionType::SME_PStateZAPreservedMask) {
9758 switch (C) {
9759 case AArch64SMECallConversionKind::MatchExactly:
9760 return true;
9761 case AArch64SMECallConversionKind::MayAddPreservesZA:
9762 return !(ToAttributes & FunctionType::SME_PStateZAPreservedMask);
9763 case AArch64SMECallConversionKind::MayDropPreservesZA:
9764 return !(FromAttributes & FunctionType::SME_PStateZAPreservedMask);
9768 // There has been a mismatch of attributes
9769 return true;
9772 // Check if we have a conversion between incompatible cmse function pointer
9773 // types, that is, a conversion between a function pointer with the
9774 // cmse_nonsecure_call attribute and one without.
9775 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9776 QualType ToType) {
9777 if (const auto *ToFn =
9778 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9779 if (const auto *FromFn =
9780 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9781 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9782 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9784 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9787 return false;
9790 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9791 // being closely modeled after the C99 spec:-). The odd characteristic of this
9792 // routine is it effectively iqnores the qualifiers on the top level pointee.
9793 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9794 // FIXME: add a couple examples in this comment.
9795 static Sema::AssignConvertType
9796 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType,
9797 SourceLocation Loc) {
9798 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9799 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9801 // get the "pointed to" type (ignoring qualifiers at the top level)
9802 const Type *lhptee, *rhptee;
9803 Qualifiers lhq, rhq;
9804 std::tie(lhptee, lhq) =
9805 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9806 std::tie(rhptee, rhq) =
9807 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9809 Sema::AssignConvertType ConvTy = Sema::Compatible;
9811 // C99 6.5.16.1p1: This following citation is common to constraints
9812 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9813 // qualifiers of the type *pointed to* by the right;
9815 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9816 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9817 lhq.compatiblyIncludesObjCLifetime(rhq)) {
9818 // Ignore lifetime for further calculation.
9819 lhq.removeObjCLifetime();
9820 rhq.removeObjCLifetime();
9823 if (!lhq.compatiblyIncludes(rhq)) {
9824 // Treat address-space mismatches as fatal.
9825 if (!lhq.isAddressSpaceSupersetOf(rhq))
9826 return Sema::IncompatiblePointerDiscardsQualifiers;
9828 // It's okay to add or remove GC or lifetime qualifiers when converting to
9829 // and from void*.
9830 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9831 .compatiblyIncludes(
9832 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9833 && (lhptee->isVoidType() || rhptee->isVoidType()))
9834 ; // keep old
9836 // Treat lifetime mismatches as fatal.
9837 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9838 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9840 // For GCC/MS compatibility, other qualifier mismatches are treated
9841 // as still compatible in C.
9842 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9845 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9846 // incomplete type and the other is a pointer to a qualified or unqualified
9847 // version of void...
9848 if (lhptee->isVoidType()) {
9849 if (rhptee->isIncompleteOrObjectType())
9850 return ConvTy;
9852 // As an extension, we allow cast to/from void* to function pointer.
9853 assert(rhptee->isFunctionType());
9854 return Sema::FunctionVoidPointer;
9857 if (rhptee->isVoidType()) {
9858 if (lhptee->isIncompleteOrObjectType())
9859 return ConvTy;
9861 // As an extension, we allow cast to/from void* to function pointer.
9862 assert(lhptee->isFunctionType());
9863 return Sema::FunctionVoidPointer;
9866 if (!S.Diags.isIgnored(
9867 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9868 Loc) &&
9869 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9870 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9871 return Sema::IncompatibleFunctionPointerStrict;
9873 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9874 // unqualified versions of compatible types, ...
9875 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9876 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9877 // Check if the pointee types are compatible ignoring the sign.
9878 // We explicitly check for char so that we catch "char" vs
9879 // "unsigned char" on systems where "char" is unsigned.
9880 if (lhptee->isCharType())
9881 ltrans = S.Context.UnsignedCharTy;
9882 else if (lhptee->hasSignedIntegerRepresentation())
9883 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9885 if (rhptee->isCharType())
9886 rtrans = S.Context.UnsignedCharTy;
9887 else if (rhptee->hasSignedIntegerRepresentation())
9888 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9890 if (ltrans == rtrans) {
9891 // Types are compatible ignoring the sign. Qualifier incompatibility
9892 // takes priority over sign incompatibility because the sign
9893 // warning can be disabled.
9894 if (ConvTy != Sema::Compatible)
9895 return ConvTy;
9897 return Sema::IncompatiblePointerSign;
9900 // If we are a multi-level pointer, it's possible that our issue is simply
9901 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9902 // the eventual target type is the same and the pointers have the same
9903 // level of indirection, this must be the issue.
9904 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9905 do {
9906 std::tie(lhptee, lhq) =
9907 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9908 std::tie(rhptee, rhq) =
9909 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9911 // Inconsistent address spaces at this point is invalid, even if the
9912 // address spaces would be compatible.
9913 // FIXME: This doesn't catch address space mismatches for pointers of
9914 // different nesting levels, like:
9915 // __local int *** a;
9916 // int ** b = a;
9917 // It's not clear how to actually determine when such pointers are
9918 // invalidly incompatible.
9919 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9920 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9922 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9924 if (lhptee == rhptee)
9925 return Sema::IncompatibleNestedPointerQualifiers;
9928 // General pointer incompatibility takes priority over qualifiers.
9929 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9930 return Sema::IncompatibleFunctionPointer;
9931 return Sema::IncompatiblePointer;
9933 if (!S.getLangOpts().CPlusPlus &&
9934 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9935 return Sema::IncompatibleFunctionPointer;
9936 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9937 return Sema::IncompatibleFunctionPointer;
9938 if (S.IsInvalidSMECallConversion(
9939 rtrans, ltrans,
9940 Sema::AArch64SMECallConversionKind::MayDropPreservesZA))
9941 return Sema::IncompatibleFunctionPointer;
9942 return ConvTy;
9945 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9946 /// block pointer types are compatible or whether a block and normal pointer
9947 /// are compatible. It is more restrict than comparing two function pointer
9948 // types.
9949 static Sema::AssignConvertType
9950 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9951 QualType RHSType) {
9952 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9953 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9955 QualType lhptee, rhptee;
9957 // get the "pointed to" type (ignoring qualifiers at the top level)
9958 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9959 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9961 // In C++, the types have to match exactly.
9962 if (S.getLangOpts().CPlusPlus)
9963 return Sema::IncompatibleBlockPointer;
9965 Sema::AssignConvertType ConvTy = Sema::Compatible;
9967 // For blocks we enforce that qualifiers are identical.
9968 Qualifiers LQuals = lhptee.getLocalQualifiers();
9969 Qualifiers RQuals = rhptee.getLocalQualifiers();
9970 if (S.getLangOpts().OpenCL) {
9971 LQuals.removeAddressSpace();
9972 RQuals.removeAddressSpace();
9974 if (LQuals != RQuals)
9975 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9977 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9978 // assignment.
9979 // The current behavior is similar to C++ lambdas. A block might be
9980 // assigned to a variable iff its return type and parameters are compatible
9981 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9982 // an assignment. Presumably it should behave in way that a function pointer
9983 // assignment does in C, so for each parameter and return type:
9984 // * CVR and address space of LHS should be a superset of CVR and address
9985 // space of RHS.
9986 // * unqualified types should be compatible.
9987 if (S.getLangOpts().OpenCL) {
9988 if (!S.Context.typesAreBlockPointerCompatible(
9989 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9990 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9991 return Sema::IncompatibleBlockPointer;
9992 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9993 return Sema::IncompatibleBlockPointer;
9995 return ConvTy;
9998 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9999 /// for assignment compatibility.
10000 static Sema::AssignConvertType
10001 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
10002 QualType RHSType) {
10003 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
10004 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
10006 if (LHSType->isObjCBuiltinType()) {
10007 // Class is not compatible with ObjC object pointers.
10008 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
10009 !RHSType->isObjCQualifiedClassType())
10010 return Sema::IncompatiblePointer;
10011 return Sema::Compatible;
10013 if (RHSType->isObjCBuiltinType()) {
10014 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
10015 !LHSType->isObjCQualifiedClassType())
10016 return Sema::IncompatiblePointer;
10017 return Sema::Compatible;
10019 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
10020 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
10022 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
10023 // make an exception for id<P>
10024 !LHSType->isObjCQualifiedIdType())
10025 return Sema::CompatiblePointerDiscardsQualifiers;
10027 if (S.Context.typesAreCompatible(LHSType, RHSType))
10028 return Sema::Compatible;
10029 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
10030 return Sema::IncompatibleObjCQualifiedId;
10031 return Sema::IncompatiblePointer;
10034 Sema::AssignConvertType
10035 Sema::CheckAssignmentConstraints(SourceLocation Loc,
10036 QualType LHSType, QualType RHSType) {
10037 // Fake up an opaque expression. We don't actually care about what
10038 // cast operations are required, so if CheckAssignmentConstraints
10039 // adds casts to this they'll be wasted, but fortunately that doesn't
10040 // usually happen on valid code.
10041 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
10042 ExprResult RHSPtr = &RHSExpr;
10043 CastKind K;
10045 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
10048 /// This helper function returns true if QT is a vector type that has element
10049 /// type ElementType.
10050 static bool isVector(QualType QT, QualType ElementType) {
10051 if (const VectorType *VT = QT->getAs<VectorType>())
10052 return VT->getElementType().getCanonicalType() == ElementType;
10053 return false;
10056 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
10057 /// has code to accommodate several GCC extensions when type checking
10058 /// pointers. Here are some objectionable examples that GCC considers warnings:
10060 /// int a, *pint;
10061 /// short *pshort;
10062 /// struct foo *pfoo;
10064 /// pint = pshort; // warning: assignment from incompatible pointer type
10065 /// a = pint; // warning: assignment makes integer from pointer without a cast
10066 /// pint = a; // warning: assignment makes pointer from integer without a cast
10067 /// pint = pfoo; // warning: assignment from incompatible pointer type
10069 /// As a result, the code for dealing with pointers is more complex than the
10070 /// C99 spec dictates.
10072 /// Sets 'Kind' for any result kind except Incompatible.
10073 Sema::AssignConvertType
10074 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
10075 CastKind &Kind, bool ConvertRHS) {
10076 QualType RHSType = RHS.get()->getType();
10077 QualType OrigLHSType = LHSType;
10079 // Get canonical types. We're not formatting these types, just comparing
10080 // them.
10081 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
10082 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
10084 // Common case: no conversion required.
10085 if (LHSType == RHSType) {
10086 Kind = CK_NoOp;
10087 return Compatible;
10090 // If the LHS has an __auto_type, there are no additional type constraints
10091 // to be worried about.
10092 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
10093 if (AT->isGNUAutoType()) {
10094 Kind = CK_NoOp;
10095 return Compatible;
10099 // If we have an atomic type, try a non-atomic assignment, then just add an
10100 // atomic qualification step.
10101 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
10102 Sema::AssignConvertType result =
10103 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
10104 if (result != Compatible)
10105 return result;
10106 if (Kind != CK_NoOp && ConvertRHS)
10107 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
10108 Kind = CK_NonAtomicToAtomic;
10109 return Compatible;
10112 // If the left-hand side is a reference type, then we are in a
10113 // (rare!) case where we've allowed the use of references in C,
10114 // e.g., as a parameter type in a built-in function. In this case,
10115 // just make sure that the type referenced is compatible with the
10116 // right-hand side type. The caller is responsible for adjusting
10117 // LHSType so that the resulting expression does not have reference
10118 // type.
10119 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
10120 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
10121 Kind = CK_LValueBitCast;
10122 return Compatible;
10124 return Incompatible;
10127 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
10128 // to the same ExtVector type.
10129 if (LHSType->isExtVectorType()) {
10130 if (RHSType->isExtVectorType())
10131 return Incompatible;
10132 if (RHSType->isArithmeticType()) {
10133 // CK_VectorSplat does T -> vector T, so first cast to the element type.
10134 if (ConvertRHS)
10135 RHS = prepareVectorSplat(LHSType, RHS.get());
10136 Kind = CK_VectorSplat;
10137 return Compatible;
10141 // Conversions to or from vector type.
10142 if (LHSType->isVectorType() || RHSType->isVectorType()) {
10143 if (LHSType->isVectorType() && RHSType->isVectorType()) {
10144 // Allow assignments of an AltiVec vector type to an equivalent GCC
10145 // vector type and vice versa
10146 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10147 Kind = CK_BitCast;
10148 return Compatible;
10151 // If we are allowing lax vector conversions, and LHS and RHS are both
10152 // vectors, the total size only needs to be the same. This is a bitcast;
10153 // no bits are changed but the result type is different.
10154 if (isLaxVectorConversion(RHSType, LHSType)) {
10155 // The default for lax vector conversions with Altivec vectors will
10156 // change, so if we are converting between vector types where
10157 // at least one is an Altivec vector, emit a warning.
10158 if (Context.getTargetInfo().getTriple().isPPC() &&
10159 anyAltivecTypes(RHSType, LHSType) &&
10160 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10161 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
10162 << RHSType << LHSType;
10163 Kind = CK_BitCast;
10164 return IncompatibleVectors;
10168 // When the RHS comes from another lax conversion (e.g. binops between
10169 // scalars and vectors) the result is canonicalized as a vector. When the
10170 // LHS is also a vector, the lax is allowed by the condition above. Handle
10171 // the case where LHS is a scalar.
10172 if (LHSType->isScalarType()) {
10173 const VectorType *VecType = RHSType->getAs<VectorType>();
10174 if (VecType && VecType->getNumElements() == 1 &&
10175 isLaxVectorConversion(RHSType, LHSType)) {
10176 if (Context.getTargetInfo().getTriple().isPPC() &&
10177 (VecType->getVectorKind() == VectorType::AltiVecVector ||
10178 VecType->getVectorKind() == VectorType::AltiVecBool ||
10179 VecType->getVectorKind() == VectorType::AltiVecPixel))
10180 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
10181 << RHSType << LHSType;
10182 ExprResult *VecExpr = &RHS;
10183 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
10184 Kind = CK_BitCast;
10185 return Compatible;
10189 // Allow assignments between fixed-length and sizeless SVE vectors.
10190 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
10191 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
10192 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
10193 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
10194 Kind = CK_BitCast;
10195 return Compatible;
10198 // Allow assignments between fixed-length and sizeless RVV vectors.
10199 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
10200 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
10201 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
10202 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
10203 Kind = CK_BitCast;
10204 return Compatible;
10208 return Incompatible;
10211 // Diagnose attempts to convert between __ibm128, __float128 and long double
10212 // where such conversions currently can't be handled.
10213 if (unsupportedTypeConversion(*this, LHSType, RHSType))
10214 return Incompatible;
10216 // Disallow assigning a _Complex to a real type in C++ mode since it simply
10217 // discards the imaginary part.
10218 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
10219 !LHSType->getAs<ComplexType>())
10220 return Incompatible;
10222 // Arithmetic conversions.
10223 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
10224 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
10225 if (ConvertRHS)
10226 Kind = PrepareScalarCast(RHS, LHSType);
10227 return Compatible;
10230 // Conversions to normal pointers.
10231 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
10232 // U* -> T*
10233 if (isa<PointerType>(RHSType)) {
10234 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10235 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
10236 if (AddrSpaceL != AddrSpaceR)
10237 Kind = CK_AddressSpaceConversion;
10238 else if (Context.hasCvrSimilarType(RHSType, LHSType))
10239 Kind = CK_NoOp;
10240 else
10241 Kind = CK_BitCast;
10242 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
10243 RHS.get()->getBeginLoc());
10246 // int -> T*
10247 if (RHSType->isIntegerType()) {
10248 Kind = CK_IntegralToPointer; // FIXME: null?
10249 return IntToPointer;
10252 // C pointers are not compatible with ObjC object pointers,
10253 // with two exceptions:
10254 if (isa<ObjCObjectPointerType>(RHSType)) {
10255 // - conversions to void*
10256 if (LHSPointer->getPointeeType()->isVoidType()) {
10257 Kind = CK_BitCast;
10258 return Compatible;
10261 // - conversions from 'Class' to the redefinition type
10262 if (RHSType->isObjCClassType() &&
10263 Context.hasSameType(LHSType,
10264 Context.getObjCClassRedefinitionType())) {
10265 Kind = CK_BitCast;
10266 return Compatible;
10269 Kind = CK_BitCast;
10270 return IncompatiblePointer;
10273 // U^ -> void*
10274 if (RHSType->getAs<BlockPointerType>()) {
10275 if (LHSPointer->getPointeeType()->isVoidType()) {
10276 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10277 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10278 ->getPointeeType()
10279 .getAddressSpace();
10280 Kind =
10281 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10282 return Compatible;
10286 return Incompatible;
10289 // Conversions to block pointers.
10290 if (isa<BlockPointerType>(LHSType)) {
10291 // U^ -> T^
10292 if (RHSType->isBlockPointerType()) {
10293 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10294 ->getPointeeType()
10295 .getAddressSpace();
10296 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10297 ->getPointeeType()
10298 .getAddressSpace();
10299 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10300 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
10303 // int or null -> T^
10304 if (RHSType->isIntegerType()) {
10305 Kind = CK_IntegralToPointer; // FIXME: null
10306 return IntToBlockPointer;
10309 // id -> T^
10310 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10311 Kind = CK_AnyPointerToBlockPointerCast;
10312 return Compatible;
10315 // void* -> T^
10316 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10317 if (RHSPT->getPointeeType()->isVoidType()) {
10318 Kind = CK_AnyPointerToBlockPointerCast;
10319 return Compatible;
10322 return Incompatible;
10325 // Conversions to Objective-C pointers.
10326 if (isa<ObjCObjectPointerType>(LHSType)) {
10327 // A* -> B*
10328 if (RHSType->isObjCObjectPointerType()) {
10329 Kind = CK_BitCast;
10330 Sema::AssignConvertType result =
10331 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
10332 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10333 result == Compatible &&
10334 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10335 result = IncompatibleObjCWeakRef;
10336 return result;
10339 // int or null -> A*
10340 if (RHSType->isIntegerType()) {
10341 Kind = CK_IntegralToPointer; // FIXME: null
10342 return IntToPointer;
10345 // In general, C pointers are not compatible with ObjC object pointers,
10346 // with two exceptions:
10347 if (isa<PointerType>(RHSType)) {
10348 Kind = CK_CPointerToObjCPointerCast;
10350 // - conversions from 'void*'
10351 if (RHSType->isVoidPointerType()) {
10352 return Compatible;
10355 // - conversions to 'Class' from its redefinition type
10356 if (LHSType->isObjCClassType() &&
10357 Context.hasSameType(RHSType,
10358 Context.getObjCClassRedefinitionType())) {
10359 return Compatible;
10362 return IncompatiblePointer;
10365 // Only under strict condition T^ is compatible with an Objective-C pointer.
10366 if (RHSType->isBlockPointerType() &&
10367 LHSType->isBlockCompatibleObjCPointerType(Context)) {
10368 if (ConvertRHS)
10369 maybeExtendBlockObject(RHS);
10370 Kind = CK_BlockPointerToObjCPointerCast;
10371 return Compatible;
10374 return Incompatible;
10377 // Conversion to nullptr_t (C23 only)
10378 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10379 RHS.get()->isNullPointerConstant(Context,
10380 Expr::NPC_ValueDependentIsNull)) {
10381 // null -> nullptr_t
10382 Kind = CK_NullToPointer;
10383 return Compatible;
10386 // Conversions from pointers that are not covered by the above.
10387 if (isa<PointerType>(RHSType)) {
10388 // T* -> _Bool
10389 if (LHSType == Context.BoolTy) {
10390 Kind = CK_PointerToBoolean;
10391 return Compatible;
10394 // T* -> int
10395 if (LHSType->isIntegerType()) {
10396 Kind = CK_PointerToIntegral;
10397 return PointerToInt;
10400 return Incompatible;
10403 // Conversions from Objective-C pointers that are not covered by the above.
10404 if (isa<ObjCObjectPointerType>(RHSType)) {
10405 // T* -> _Bool
10406 if (LHSType == Context.BoolTy) {
10407 Kind = CK_PointerToBoolean;
10408 return Compatible;
10411 // T* -> int
10412 if (LHSType->isIntegerType()) {
10413 Kind = CK_PointerToIntegral;
10414 return PointerToInt;
10417 return Incompatible;
10420 // struct A -> struct B
10421 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10422 if (Context.typesAreCompatible(LHSType, RHSType)) {
10423 Kind = CK_NoOp;
10424 return Compatible;
10428 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10429 Kind = CK_IntToOCLSampler;
10430 return Compatible;
10433 return Incompatible;
10436 /// Constructs a transparent union from an expression that is
10437 /// used to initialize the transparent union.
10438 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10439 ExprResult &EResult, QualType UnionType,
10440 FieldDecl *Field) {
10441 // Build an initializer list that designates the appropriate member
10442 // of the transparent union.
10443 Expr *E = EResult.get();
10444 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
10445 E, SourceLocation());
10446 Initializer->setType(UnionType);
10447 Initializer->setInitializedFieldInUnion(Field);
10449 // Build a compound literal constructing a value of the transparent
10450 // union type from this initializer list.
10451 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10452 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10453 VK_PRValue, Initializer, false);
10456 Sema::AssignConvertType
10457 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10458 ExprResult &RHS) {
10459 QualType RHSType = RHS.get()->getType();
10461 // If the ArgType is a Union type, we want to handle a potential
10462 // transparent_union GCC extension.
10463 const RecordType *UT = ArgType->getAsUnionType();
10464 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
10465 return Incompatible;
10467 // The field to initialize within the transparent union.
10468 RecordDecl *UD = UT->getDecl();
10469 FieldDecl *InitField = nullptr;
10470 // It's compatible if the expression matches any of the fields.
10471 for (auto *it : UD->fields()) {
10472 if (it->getType()->isPointerType()) {
10473 // If the transparent union contains a pointer type, we allow:
10474 // 1) void pointer
10475 // 2) null pointer constant
10476 if (RHSType->isPointerType())
10477 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10478 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10479 InitField = it;
10480 break;
10483 if (RHS.get()->isNullPointerConstant(Context,
10484 Expr::NPC_ValueDependentIsNull)) {
10485 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10486 CK_NullToPointer);
10487 InitField = it;
10488 break;
10492 CastKind Kind;
10493 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
10494 == Compatible) {
10495 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10496 InitField = it;
10497 break;
10501 if (!InitField)
10502 return Incompatible;
10504 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10505 return Compatible;
10508 Sema::AssignConvertType
10509 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
10510 bool Diagnose,
10511 bool DiagnoseCFAudited,
10512 bool ConvertRHS) {
10513 // We need to be able to tell the caller whether we diagnosed a problem, if
10514 // they ask us to issue diagnostics.
10515 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10517 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10518 // we can't avoid *all* modifications at the moment, so we need some somewhere
10519 // to put the updated value.
10520 ExprResult LocalRHS = CallerRHS;
10521 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10523 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10524 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10525 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10526 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10527 Diag(RHS.get()->getExprLoc(),
10528 diag::warn_noderef_to_dereferenceable_pointer)
10529 << RHS.get()->getSourceRange();
10534 if (getLangOpts().CPlusPlus) {
10535 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10536 // C++ 5.17p3: If the left operand is not of class type, the
10537 // expression is implicitly converted (C++ 4) to the
10538 // cv-unqualified type of the left operand.
10539 QualType RHSType = RHS.get()->getType();
10540 if (Diagnose) {
10541 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10542 AA_Assigning);
10543 } else {
10544 ImplicitConversionSequence ICS =
10545 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10546 /*SuppressUserConversions=*/false,
10547 AllowedExplicit::None,
10548 /*InOverloadResolution=*/false,
10549 /*CStyle=*/false,
10550 /*AllowObjCWritebackConversion=*/false);
10551 if (ICS.isFailure())
10552 return Incompatible;
10553 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10554 ICS, AA_Assigning);
10556 if (RHS.isInvalid())
10557 return Incompatible;
10558 Sema::AssignConvertType result = Compatible;
10559 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10560 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10561 result = IncompatibleObjCWeakRef;
10562 return result;
10565 // FIXME: Currently, we fall through and treat C++ classes like C
10566 // structures.
10567 // FIXME: We also fall through for atomics; not sure what should
10568 // happen there, though.
10569 } else if (RHS.get()->getType() == Context.OverloadTy) {
10570 // As a set of extensions to C, we support overloading on functions. These
10571 // functions need to be resolved here.
10572 DeclAccessPair DAP;
10573 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10574 RHS.get(), LHSType, /*Complain=*/false, DAP))
10575 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10576 else
10577 return Incompatible;
10580 // This check seems unnatural, however it is necessary to ensure the proper
10581 // conversion of functions/arrays. If the conversion were done for all
10582 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10583 // expressions that suppress this implicit conversion (&, sizeof). This needs
10584 // to happen before we check for null pointer conversions because C does not
10585 // undergo the same implicit conversions as C++ does above (by the calls to
10586 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10587 // lvalue to rvalue cast before checking for null pointer constraints. This
10588 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10590 // Suppress this for references: C++ 8.5.3p5.
10591 if (!LHSType->isReferenceType()) {
10592 // FIXME: We potentially allocate here even if ConvertRHS is false.
10593 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
10594 if (RHS.isInvalid())
10595 return Incompatible;
10598 // The constraints are expressed in terms of the atomic, qualified, or
10599 // unqualified type of the LHS.
10600 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10602 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10603 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10604 if ((LHSTypeAfterConversion->isPointerType() ||
10605 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10606 LHSTypeAfterConversion->isBlockPointerType()) &&
10607 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10608 RHS.get()->isNullPointerConstant(Context,
10609 Expr::NPC_ValueDependentIsNull))) {
10610 if (Diagnose || ConvertRHS) {
10611 CastKind Kind;
10612 CXXCastPath Path;
10613 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10614 /*IgnoreBaseAccess=*/false, Diagnose);
10615 if (ConvertRHS)
10616 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10618 return Compatible;
10620 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10621 // unqualified bool, and the right operand is a pointer or its type is
10622 // nullptr_t.
10623 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10624 RHS.get()->getType()->isNullPtrType()) {
10625 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10626 // only handles nullptr -> _Bool due to needing an extra conversion
10627 // step.
10628 // We model this by converting from nullptr -> void * and then let the
10629 // conversion from void * -> _Bool happen naturally.
10630 if (Diagnose || ConvertRHS) {
10631 CastKind Kind;
10632 CXXCastPath Path;
10633 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10634 /*IgnoreBaseAccess=*/false, Diagnose);
10635 if (ConvertRHS)
10636 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10637 &Path);
10641 // OpenCL queue_t type assignment.
10642 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10643 Context, Expr::NPC_ValueDependentIsNull)) {
10644 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10645 return Compatible;
10648 CastKind Kind;
10649 Sema::AssignConvertType result =
10650 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10652 // C99 6.5.16.1p2: The value of the right operand is converted to the
10653 // type of the assignment expression.
10654 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10655 // so that we can use references in built-in functions even in C.
10656 // The getNonReferenceType() call makes sure that the resulting expression
10657 // does not have reference type.
10658 if (result != Incompatible && RHS.get()->getType() != LHSType) {
10659 QualType Ty = LHSType.getNonLValueExprType(Context);
10660 Expr *E = RHS.get();
10662 // Check for various Objective-C errors. If we are not reporting
10663 // diagnostics and just checking for errors, e.g., during overload
10664 // resolution, return Incompatible to indicate the failure.
10665 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10666 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
10667 Diagnose, DiagnoseCFAudited) != ACR_okay) {
10668 if (!Diagnose)
10669 return Incompatible;
10671 if (getLangOpts().ObjC &&
10672 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10673 E->getType(), E, Diagnose) ||
10674 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10675 if (!Diagnose)
10676 return Incompatible;
10677 // Replace the expression with a corrected version and continue so we
10678 // can find further errors.
10679 RHS = E;
10680 return Compatible;
10683 if (ConvertRHS)
10684 RHS = ImpCastExprToType(E, Ty, Kind);
10687 return result;
10690 namespace {
10691 /// The original operand to an operator, prior to the application of the usual
10692 /// arithmetic conversions and converting the arguments of a builtin operator
10693 /// candidate.
10694 struct OriginalOperand {
10695 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10696 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10697 Op = MTE->getSubExpr();
10698 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10699 Op = BTE->getSubExpr();
10700 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10701 Orig = ICE->getSubExprAsWritten();
10702 Conversion = ICE->getConversionFunction();
10706 QualType getType() const { return Orig->getType(); }
10708 Expr *Orig;
10709 NamedDecl *Conversion;
10713 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10714 ExprResult &RHS) {
10715 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10717 Diag(Loc, diag::err_typecheck_invalid_operands)
10718 << OrigLHS.getType() << OrigRHS.getType()
10719 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10721 // If a user-defined conversion was applied to either of the operands prior
10722 // to applying the built-in operator rules, tell the user about it.
10723 if (OrigLHS.Conversion) {
10724 Diag(OrigLHS.Conversion->getLocation(),
10725 diag::note_typecheck_invalid_operands_converted)
10726 << 0 << LHS.get()->getType();
10728 if (OrigRHS.Conversion) {
10729 Diag(OrigRHS.Conversion->getLocation(),
10730 diag::note_typecheck_invalid_operands_converted)
10731 << 1 << RHS.get()->getType();
10734 return QualType();
10737 // Diagnose cases where a scalar was implicitly converted to a vector and
10738 // diagnose the underlying types. Otherwise, diagnose the error
10739 // as invalid vector logical operands for non-C++ cases.
10740 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10741 ExprResult &RHS) {
10742 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10743 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10745 bool LHSNatVec = LHSType->isVectorType();
10746 bool RHSNatVec = RHSType->isVectorType();
10748 if (!(LHSNatVec && RHSNatVec)) {
10749 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10750 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10751 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10752 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10753 << Vector->getSourceRange();
10754 return QualType();
10757 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10758 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10759 << RHS.get()->getSourceRange();
10761 return QualType();
10764 /// Try to convert a value of non-vector type to a vector type by converting
10765 /// the type to the element type of the vector and then performing a splat.
10766 /// If the language is OpenCL, we only use conversions that promote scalar
10767 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10768 /// for float->int.
10770 /// OpenCL V2.0 6.2.6.p2:
10771 /// An error shall occur if any scalar operand type has greater rank
10772 /// than the type of the vector element.
10774 /// \param scalar - if non-null, actually perform the conversions
10775 /// \return true if the operation fails (but without diagnosing the failure)
10776 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10777 QualType scalarTy,
10778 QualType vectorEltTy,
10779 QualType vectorTy,
10780 unsigned &DiagID) {
10781 // The conversion to apply to the scalar before splatting it,
10782 // if necessary.
10783 CastKind scalarCast = CK_NoOp;
10785 if (vectorEltTy->isIntegralType(S.Context)) {
10786 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10787 (scalarTy->isIntegerType() &&
10788 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10789 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10790 return true;
10792 if (!scalarTy->isIntegralType(S.Context))
10793 return true;
10794 scalarCast = CK_IntegralCast;
10795 } else if (vectorEltTy->isRealFloatingType()) {
10796 if (scalarTy->isRealFloatingType()) {
10797 if (S.getLangOpts().OpenCL &&
10798 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10799 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10800 return true;
10802 scalarCast = CK_FloatingCast;
10804 else if (scalarTy->isIntegralType(S.Context))
10805 scalarCast = CK_IntegralToFloating;
10806 else
10807 return true;
10808 } else {
10809 return true;
10812 // Adjust scalar if desired.
10813 if (scalar) {
10814 if (scalarCast != CK_NoOp)
10815 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10816 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10818 return false;
10821 /// Convert vector E to a vector with the same number of elements but different
10822 /// element type.
10823 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10824 const auto *VecTy = E->getType()->getAs<VectorType>();
10825 assert(VecTy && "Expression E must be a vector");
10826 QualType NewVecTy =
10827 VecTy->isExtVectorType()
10828 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10829 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10830 VecTy->getVectorKind());
10832 // Look through the implicit cast. Return the subexpression if its type is
10833 // NewVecTy.
10834 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10835 if (ICE->getSubExpr()->getType() == NewVecTy)
10836 return ICE->getSubExpr();
10838 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10839 return S.ImpCastExprToType(E, NewVecTy, Cast);
10842 /// Test if a (constant) integer Int can be casted to another integer type
10843 /// IntTy without losing precision.
10844 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10845 QualType OtherIntTy) {
10846 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10848 // Reject cases where the value of the Int is unknown as that would
10849 // possibly cause truncation, but accept cases where the scalar can be
10850 // demoted without loss of precision.
10851 Expr::EvalResult EVResult;
10852 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10853 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10854 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10855 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10857 if (CstInt) {
10858 // If the scalar is constant and is of a higher order and has more active
10859 // bits that the vector element type, reject it.
10860 llvm::APSInt Result = EVResult.Val.getInt();
10861 unsigned NumBits = IntSigned
10862 ? (Result.isNegative() ? Result.getSignificantBits()
10863 : Result.getActiveBits())
10864 : Result.getActiveBits();
10865 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10866 return true;
10868 // If the signedness of the scalar type and the vector element type
10869 // differs and the number of bits is greater than that of the vector
10870 // element reject it.
10871 return (IntSigned != OtherIntSigned &&
10872 NumBits > S.Context.getIntWidth(OtherIntTy));
10875 // Reject cases where the value of the scalar is not constant and it's
10876 // order is greater than that of the vector element type.
10877 return (Order < 0);
10880 /// Test if a (constant) integer Int can be casted to floating point type
10881 /// FloatTy without losing precision.
10882 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10883 QualType FloatTy) {
10884 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10886 // Determine if the integer constant can be expressed as a floating point
10887 // number of the appropriate type.
10888 Expr::EvalResult EVResult;
10889 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10891 uint64_t Bits = 0;
10892 if (CstInt) {
10893 // Reject constants that would be truncated if they were converted to
10894 // the floating point type. Test by simple to/from conversion.
10895 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10896 // could be avoided if there was a convertFromAPInt method
10897 // which could signal back if implicit truncation occurred.
10898 llvm::APSInt Result = EVResult.Val.getInt();
10899 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10900 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10901 llvm::APFloat::rmTowardZero);
10902 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10903 !IntTy->hasSignedIntegerRepresentation());
10904 bool Ignored = false;
10905 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10906 &Ignored);
10907 if (Result != ConvertBack)
10908 return true;
10909 } else {
10910 // Reject types that cannot be fully encoded into the mantissa of
10911 // the float.
10912 Bits = S.Context.getTypeSize(IntTy);
10913 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10914 S.Context.getFloatTypeSemantics(FloatTy));
10915 if (Bits > FloatPrec)
10916 return true;
10919 return false;
10922 /// Attempt to convert and splat Scalar into a vector whose types matches
10923 /// Vector following GCC conversion rules. The rule is that implicit
10924 /// conversion can occur when Scalar can be casted to match Vector's element
10925 /// type without causing truncation of Scalar.
10926 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10927 ExprResult *Vector) {
10928 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10929 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10930 QualType VectorEltTy;
10932 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10933 assert(!isa<ExtVectorType>(VT) &&
10934 "ExtVectorTypes should not be handled here!");
10935 VectorEltTy = VT->getElementType();
10936 } else if (VectorTy->isSveVLSBuiltinType()) {
10937 VectorEltTy =
10938 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10939 } else {
10940 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10943 // Reject cases where the vector element type or the scalar element type are
10944 // not integral or floating point types.
10945 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10946 return true;
10948 // The conversion to apply to the scalar before splatting it,
10949 // if necessary.
10950 CastKind ScalarCast = CK_NoOp;
10952 // Accept cases where the vector elements are integers and the scalar is
10953 // an integer.
10954 // FIXME: Notionally if the scalar was a floating point value with a precise
10955 // integral representation, we could cast it to an appropriate integer
10956 // type and then perform the rest of the checks here. GCC will perform
10957 // this conversion in some cases as determined by the input language.
10958 // We should accept it on a language independent basis.
10959 if (VectorEltTy->isIntegralType(S.Context) &&
10960 ScalarTy->isIntegralType(S.Context) &&
10961 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10963 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10964 return true;
10966 ScalarCast = CK_IntegralCast;
10967 } else if (VectorEltTy->isIntegralType(S.Context) &&
10968 ScalarTy->isRealFloatingType()) {
10969 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10970 ScalarCast = CK_FloatingToIntegral;
10971 else
10972 return true;
10973 } else if (VectorEltTy->isRealFloatingType()) {
10974 if (ScalarTy->isRealFloatingType()) {
10976 // Reject cases where the scalar type is not a constant and has a higher
10977 // Order than the vector element type.
10978 llvm::APFloat Result(0.0);
10980 // Determine whether this is a constant scalar. In the event that the
10981 // value is dependent (and thus cannot be evaluated by the constant
10982 // evaluator), skip the evaluation. This will then diagnose once the
10983 // expression is instantiated.
10984 bool CstScalar = Scalar->get()->isValueDependent() ||
10985 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10986 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10987 if (!CstScalar && Order < 0)
10988 return true;
10990 // If the scalar cannot be safely casted to the vector element type,
10991 // reject it.
10992 if (CstScalar) {
10993 bool Truncated = false;
10994 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10995 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10996 if (Truncated)
10997 return true;
11000 ScalarCast = CK_FloatingCast;
11001 } else if (ScalarTy->isIntegralType(S.Context)) {
11002 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
11003 return true;
11005 ScalarCast = CK_IntegralToFloating;
11006 } else
11007 return true;
11008 } else if (ScalarTy->isEnumeralType())
11009 return true;
11011 // Adjust scalar if desired.
11012 if (ScalarCast != CK_NoOp)
11013 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
11014 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
11015 return false;
11018 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
11019 SourceLocation Loc, bool IsCompAssign,
11020 bool AllowBothBool,
11021 bool AllowBoolConversions,
11022 bool AllowBoolOperation,
11023 bool ReportInvalid) {
11024 if (!IsCompAssign) {
11025 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11026 if (LHS.isInvalid())
11027 return QualType();
11029 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11030 if (RHS.isInvalid())
11031 return QualType();
11033 // For conversion purposes, we ignore any qualifiers.
11034 // For example, "const float" and "float" are equivalent.
11035 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11036 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11038 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
11039 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
11040 assert(LHSVecType || RHSVecType);
11042 // AltiVec-style "vector bool op vector bool" combinations are allowed
11043 // for some operators but not others.
11044 if (!AllowBothBool &&
11045 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
11046 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11047 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
11049 // This operation may not be performed on boolean vectors.
11050 if (!AllowBoolOperation &&
11051 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
11052 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
11054 // If the vector types are identical, return.
11055 if (Context.hasSameType(LHSType, RHSType))
11056 return Context.getCommonSugaredType(LHSType, RHSType);
11058 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
11059 if (LHSVecType && RHSVecType &&
11060 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
11061 if (isa<ExtVectorType>(LHSVecType)) {
11062 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11063 return LHSType;
11066 if (!IsCompAssign)
11067 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11068 return RHSType;
11071 // AllowBoolConversions says that bool and non-bool AltiVec vectors
11072 // can be mixed, with the result being the non-bool type. The non-bool
11073 // operand must have integer element type.
11074 if (AllowBoolConversions && LHSVecType && RHSVecType &&
11075 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
11076 (Context.getTypeSize(LHSVecType->getElementType()) ==
11077 Context.getTypeSize(RHSVecType->getElementType()))) {
11078 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
11079 LHSVecType->getElementType()->isIntegerType() &&
11080 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
11081 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11082 return LHSType;
11084 if (!IsCompAssign &&
11085 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
11086 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
11087 RHSVecType->getElementType()->isIntegerType()) {
11088 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11089 return RHSType;
11093 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
11094 // invalid since the ambiguity can affect the ABI.
11095 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
11096 unsigned &SVEorRVV) {
11097 const VectorType *VecType = SecondType->getAs<VectorType>();
11098 SVEorRVV = 0;
11099 if (FirstType->isSizelessBuiltinType() && VecType) {
11100 if (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
11101 VecType->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
11102 return true;
11103 if (VecType->getVectorKind() == VectorType::RVVFixedLengthDataVector) {
11104 SVEorRVV = 1;
11105 return true;
11109 return false;
11112 unsigned SVEorRVV;
11113 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
11114 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
11115 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
11116 << SVEorRVV << LHSType << RHSType;
11117 return QualType();
11120 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
11121 // invalid since the ambiguity can affect the ABI.
11122 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
11123 unsigned &SVEorRVV) {
11124 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
11125 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
11127 SVEorRVV = 0;
11128 if (FirstVecType && SecondVecType) {
11129 if (FirstVecType->getVectorKind() == VectorType::GenericVector) {
11130 if (SecondVecType->getVectorKind() ==
11131 VectorType::SveFixedLengthDataVector ||
11132 SecondVecType->getVectorKind() ==
11133 VectorType::SveFixedLengthPredicateVector)
11134 return true;
11135 if (SecondVecType->getVectorKind() ==
11136 VectorType::RVVFixedLengthDataVector) {
11137 SVEorRVV = 1;
11138 return true;
11141 return false;
11144 if (SecondVecType &&
11145 SecondVecType->getVectorKind() == VectorType::GenericVector) {
11146 if (FirstType->isSVESizelessBuiltinType())
11147 return true;
11148 if (FirstType->isRVVSizelessBuiltinType()) {
11149 SVEorRVV = 1;
11150 return true;
11154 return false;
11157 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
11158 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
11159 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
11160 << SVEorRVV << LHSType << RHSType;
11161 return QualType();
11164 // If there's a vector type and a scalar, try to convert the scalar to
11165 // the vector element type and splat.
11166 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
11167 if (!RHSVecType) {
11168 if (isa<ExtVectorType>(LHSVecType)) {
11169 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
11170 LHSVecType->getElementType(), LHSType,
11171 DiagID))
11172 return LHSType;
11173 } else {
11174 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11175 return LHSType;
11178 if (!LHSVecType) {
11179 if (isa<ExtVectorType>(RHSVecType)) {
11180 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
11181 LHSType, RHSVecType->getElementType(),
11182 RHSType, DiagID))
11183 return RHSType;
11184 } else {
11185 if (LHS.get()->isLValue() ||
11186 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11187 return RHSType;
11191 // FIXME: The code below also handles conversion between vectors and
11192 // non-scalars, we should break this down into fine grained specific checks
11193 // and emit proper diagnostics.
11194 QualType VecType = LHSVecType ? LHSType : RHSType;
11195 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
11196 QualType OtherType = LHSVecType ? RHSType : LHSType;
11197 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
11198 if (isLaxVectorConversion(OtherType, VecType)) {
11199 if (Context.getTargetInfo().getTriple().isPPC() &&
11200 anyAltivecTypes(RHSType, LHSType) &&
11201 !Context.areCompatibleVectorTypes(RHSType, LHSType))
11202 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
11203 // If we're allowing lax vector conversions, only the total (data) size
11204 // needs to be the same. For non compound assignment, if one of the types is
11205 // scalar, the result is always the vector type.
11206 if (!IsCompAssign) {
11207 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
11208 return VecType;
11209 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11210 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11211 // type. Note that this is already done by non-compound assignments in
11212 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11213 // <1 x T> -> T. The result is also a vector type.
11214 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
11215 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
11216 ExprResult *RHSExpr = &RHS;
11217 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
11218 return VecType;
11222 // Okay, the expression is invalid.
11224 // If there's a non-vector, non-real operand, diagnose that.
11225 if ((!RHSVecType && !RHSType->isRealType()) ||
11226 (!LHSVecType && !LHSType->isRealType())) {
11227 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11228 << LHSType << RHSType
11229 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11230 return QualType();
11233 // OpenCL V1.1 6.2.6.p1:
11234 // If the operands are of more than one vector type, then an error shall
11235 // occur. Implicit conversions between vector types are not permitted, per
11236 // section 6.2.1.
11237 if (getLangOpts().OpenCL &&
11238 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
11239 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
11240 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
11241 << RHSType;
11242 return QualType();
11246 // If there is a vector type that is not a ExtVector and a scalar, we reach
11247 // this point if scalar could not be converted to the vector's element type
11248 // without truncation.
11249 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
11250 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
11251 QualType Scalar = LHSVecType ? RHSType : LHSType;
11252 QualType Vector = LHSVecType ? LHSType : RHSType;
11253 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11254 Diag(Loc,
11255 diag::err_typecheck_vector_not_convertable_implict_truncation)
11256 << ScalarOrVector << Scalar << Vector;
11258 return QualType();
11261 // Otherwise, use the generic diagnostic.
11262 Diag(Loc, DiagID)
11263 << LHSType << RHSType
11264 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11265 return QualType();
11268 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11269 SourceLocation Loc,
11270 bool IsCompAssign,
11271 ArithConvKind OperationKind) {
11272 if (!IsCompAssign) {
11273 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11274 if (LHS.isInvalid())
11275 return QualType();
11277 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11278 if (RHS.isInvalid())
11279 return QualType();
11281 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11282 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11284 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11285 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11287 unsigned DiagID = diag::err_typecheck_invalid_operands;
11288 if ((OperationKind == ACK_Arithmetic) &&
11289 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11290 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11291 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11292 << RHS.get()->getSourceRange();
11293 return QualType();
11296 if (Context.hasSameType(LHSType, RHSType))
11297 return LHSType;
11299 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11300 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11301 return LHSType;
11303 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11304 if (LHS.get()->isLValue() ||
11305 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11306 return RHSType;
11309 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11310 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11311 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11312 << LHSType << RHSType << LHS.get()->getSourceRange()
11313 << RHS.get()->getSourceRange();
11314 return QualType();
11317 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11318 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11319 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11320 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11321 << LHSType << RHSType << LHS.get()->getSourceRange()
11322 << RHS.get()->getSourceRange();
11323 return QualType();
11326 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11327 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11328 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11329 bool ScalarOrVector =
11330 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11332 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11333 << ScalarOrVector << Scalar << Vector;
11335 return QualType();
11338 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11339 << RHS.get()->getSourceRange();
11340 return QualType();
11343 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
11344 // expression. These are mainly cases where the null pointer is used as an
11345 // integer instead of a pointer.
11346 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11347 SourceLocation Loc, bool IsCompare) {
11348 // The canonical way to check for a GNU null is with isNullPointerConstant,
11349 // but we use a bit of a hack here for speed; this is a relatively
11350 // hot path, and isNullPointerConstant is slow.
11351 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11352 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11354 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11356 // Avoid analyzing cases where the result will either be invalid (and
11357 // diagnosed as such) or entirely valid and not something to warn about.
11358 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11359 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11360 return;
11362 // Comparison operations would not make sense with a null pointer no matter
11363 // what the other expression is.
11364 if (!IsCompare) {
11365 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11366 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11367 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11368 return;
11371 // The rest of the operations only make sense with a null pointer
11372 // if the other expression is a pointer.
11373 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11374 NonNullType->canDecayToPointerType())
11375 return;
11377 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11378 << LHSNull /* LHS is NULL */ << NonNullType
11379 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11382 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11383 SourceLocation Loc) {
11384 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11385 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11386 if (!LUE || !RUE)
11387 return;
11388 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11389 RUE->getKind() != UETT_SizeOf)
11390 return;
11392 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11393 QualType LHSTy = LHSArg->getType();
11394 QualType RHSTy;
11396 if (RUE->isArgumentType())
11397 RHSTy = RUE->getArgumentType().getNonReferenceType();
11398 else
11399 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11401 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11402 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11403 return;
11405 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11406 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11407 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11408 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11409 << LHSArgDecl;
11411 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11412 QualType ArrayElemTy = ArrayTy->getElementType();
11413 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11414 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11415 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11416 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11417 return;
11418 S.Diag(Loc, diag::warn_division_sizeof_array)
11419 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11420 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11421 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11422 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11423 << LHSArgDecl;
11426 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11430 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11431 ExprResult &RHS,
11432 SourceLocation Loc, bool IsDiv) {
11433 // Check for division/remainder by zero.
11434 Expr::EvalResult RHSValue;
11435 if (!RHS.get()->isValueDependent() &&
11436 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11437 RHSValue.Val.getInt() == 0)
11438 S.DiagRuntimeBehavior(Loc, RHS.get(),
11439 S.PDiag(diag::warn_remainder_division_by_zero)
11440 << IsDiv << RHS.get()->getSourceRange());
11443 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11444 SourceLocation Loc,
11445 bool IsCompAssign, bool IsDiv) {
11446 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11448 QualType LHSTy = LHS.get()->getType();
11449 QualType RHSTy = RHS.get()->getType();
11450 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11451 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11452 /*AllowBothBool*/ getLangOpts().AltiVec,
11453 /*AllowBoolConversions*/ false,
11454 /*AllowBooleanOperation*/ false,
11455 /*ReportInvalid*/ true);
11456 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11457 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11458 ACK_Arithmetic);
11459 if (!IsDiv &&
11460 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11461 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11462 // For division, only matrix-by-scalar is supported. Other combinations with
11463 // matrix types are invalid.
11464 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11465 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11467 QualType compType = UsualArithmeticConversions(
11468 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11469 if (LHS.isInvalid() || RHS.isInvalid())
11470 return QualType();
11473 if (compType.isNull() || !compType->isArithmeticType())
11474 return InvalidOperands(Loc, LHS, RHS);
11475 if (IsDiv) {
11476 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11477 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11479 return compType;
11482 QualType Sema::CheckRemainderOperands(
11483 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11484 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11486 if (LHS.get()->getType()->isVectorType() ||
11487 RHS.get()->getType()->isVectorType()) {
11488 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11489 RHS.get()->getType()->hasIntegerRepresentation())
11490 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11491 /*AllowBothBool*/ getLangOpts().AltiVec,
11492 /*AllowBoolConversions*/ false,
11493 /*AllowBooleanOperation*/ false,
11494 /*ReportInvalid*/ true);
11495 return InvalidOperands(Loc, LHS, RHS);
11498 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11499 RHS.get()->getType()->isSveVLSBuiltinType()) {
11500 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11501 RHS.get()->getType()->hasIntegerRepresentation())
11502 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11503 ACK_Arithmetic);
11505 return InvalidOperands(Loc, LHS, RHS);
11508 QualType compType = UsualArithmeticConversions(
11509 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11510 if (LHS.isInvalid() || RHS.isInvalid())
11511 return QualType();
11513 if (compType.isNull() || !compType->isIntegerType())
11514 return InvalidOperands(Loc, LHS, RHS);
11515 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11516 return compType;
11519 /// Diagnose invalid arithmetic on two void pointers.
11520 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11521 Expr *LHSExpr, Expr *RHSExpr) {
11522 S.Diag(Loc, S.getLangOpts().CPlusPlus
11523 ? diag::err_typecheck_pointer_arith_void_type
11524 : diag::ext_gnu_void_ptr)
11525 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11526 << RHSExpr->getSourceRange();
11529 /// Diagnose invalid arithmetic on a void pointer.
11530 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11531 Expr *Pointer) {
11532 S.Diag(Loc, S.getLangOpts().CPlusPlus
11533 ? diag::err_typecheck_pointer_arith_void_type
11534 : diag::ext_gnu_void_ptr)
11535 << 0 /* one pointer */ << Pointer->getSourceRange();
11538 /// Diagnose invalid arithmetic on a null pointer.
11540 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11541 /// idiom, which we recognize as a GNU extension.
11543 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11544 Expr *Pointer, bool IsGNUIdiom) {
11545 if (IsGNUIdiom)
11546 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11547 << Pointer->getSourceRange();
11548 else
11549 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11550 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11553 /// Diagnose invalid subraction on a null pointer.
11555 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11556 Expr *Pointer, bool BothNull) {
11557 // Null - null is valid in C++ [expr.add]p7
11558 if (BothNull && S.getLangOpts().CPlusPlus)
11559 return;
11561 // Is this s a macro from a system header?
11562 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
11563 return;
11565 S.DiagRuntimeBehavior(Loc, Pointer,
11566 S.PDiag(diag::warn_pointer_sub_null_ptr)
11567 << S.getLangOpts().CPlusPlus
11568 << Pointer->getSourceRange());
11571 /// Diagnose invalid arithmetic on two function pointers.
11572 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11573 Expr *LHS, Expr *RHS) {
11574 assert(LHS->getType()->isAnyPointerType());
11575 assert(RHS->getType()->isAnyPointerType());
11576 S.Diag(Loc, S.getLangOpts().CPlusPlus
11577 ? diag::err_typecheck_pointer_arith_function_type
11578 : diag::ext_gnu_ptr_func_arith)
11579 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11580 // We only show the second type if it differs from the first.
11581 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
11582 RHS->getType())
11583 << RHS->getType()->getPointeeType()
11584 << LHS->getSourceRange() << RHS->getSourceRange();
11587 /// Diagnose invalid arithmetic on a function pointer.
11588 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11589 Expr *Pointer) {
11590 assert(Pointer->getType()->isAnyPointerType());
11591 S.Diag(Loc, S.getLangOpts().CPlusPlus
11592 ? diag::err_typecheck_pointer_arith_function_type
11593 : diag::ext_gnu_ptr_func_arith)
11594 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11595 << 0 /* one pointer, so only one type */
11596 << Pointer->getSourceRange();
11599 /// Emit error if Operand is incomplete pointer type
11601 /// \returns True if pointer has incomplete type
11602 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11603 Expr *Operand) {
11604 QualType ResType = Operand->getType();
11605 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11606 ResType = ResAtomicType->getValueType();
11608 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
11609 QualType PointeeTy = ResType->getPointeeType();
11610 return S.RequireCompleteSizedType(
11611 Loc, PointeeTy,
11612 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11613 Operand->getSourceRange());
11616 /// Check the validity of an arithmetic pointer operand.
11618 /// If the operand has pointer type, this code will check for pointer types
11619 /// which are invalid in arithmetic operations. These will be diagnosed
11620 /// appropriately, including whether or not the use is supported as an
11621 /// extension.
11623 /// \returns True when the operand is valid to use (even if as an extension).
11624 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11625 Expr *Operand) {
11626 QualType ResType = Operand->getType();
11627 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11628 ResType = ResAtomicType->getValueType();
11630 if (!ResType->isAnyPointerType()) return true;
11632 QualType PointeeTy = ResType->getPointeeType();
11633 if (PointeeTy->isVoidType()) {
11634 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11635 return !S.getLangOpts().CPlusPlus;
11637 if (PointeeTy->isFunctionType()) {
11638 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11639 return !S.getLangOpts().CPlusPlus;
11642 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11644 return true;
11647 /// Check the validity of a binary arithmetic operation w.r.t. pointer
11648 /// operands.
11650 /// This routine will diagnose any invalid arithmetic on pointer operands much
11651 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
11652 /// for emitting a single diagnostic even for operations where both LHS and RHS
11653 /// are (potentially problematic) pointers.
11655 /// \returns True when the operand is valid to use (even if as an extension).
11656 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11657 Expr *LHSExpr, Expr *RHSExpr) {
11658 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11659 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11660 if (!isLHSPointer && !isRHSPointer) return true;
11662 QualType LHSPointeeTy, RHSPointeeTy;
11663 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11664 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11666 // if both are pointers check if operation is valid wrt address spaces
11667 if (isLHSPointer && isRHSPointer) {
11668 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
11669 S.Diag(Loc,
11670 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11671 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11672 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11673 return false;
11677 // Check for arithmetic on pointers to incomplete types.
11678 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11679 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11680 if (isLHSVoidPtr || isRHSVoidPtr) {
11681 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11682 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11683 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11685 return !S.getLangOpts().CPlusPlus;
11688 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11689 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11690 if (isLHSFuncPtr || isRHSFuncPtr) {
11691 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11692 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11693 RHSExpr);
11694 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11696 return !S.getLangOpts().CPlusPlus;
11699 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11700 return false;
11701 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11702 return false;
11704 return true;
11707 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11708 /// literal.
11709 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11710 Expr *LHSExpr, Expr *RHSExpr) {
11711 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11712 Expr* IndexExpr = RHSExpr;
11713 if (!StrExpr) {
11714 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11715 IndexExpr = LHSExpr;
11718 bool IsStringPlusInt = StrExpr &&
11719 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11720 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11721 return;
11723 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11724 Self.Diag(OpLoc, diag::warn_string_plus_int)
11725 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11727 // Only print a fixit for "str" + int, not for int + "str".
11728 if (IndexExpr == RHSExpr) {
11729 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11730 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11731 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11732 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11733 << FixItHint::CreateInsertion(EndLoc, "]");
11734 } else
11735 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11738 /// Emit a warning when adding a char literal to a string.
11739 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11740 Expr *LHSExpr, Expr *RHSExpr) {
11741 const Expr *StringRefExpr = LHSExpr;
11742 const CharacterLiteral *CharExpr =
11743 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11745 if (!CharExpr) {
11746 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11747 StringRefExpr = RHSExpr;
11750 if (!CharExpr || !StringRefExpr)
11751 return;
11753 const QualType StringType = StringRefExpr->getType();
11755 // Return if not a PointerType.
11756 if (!StringType->isAnyPointerType())
11757 return;
11759 // Return if not a CharacterType.
11760 if (!StringType->getPointeeType()->isAnyCharacterType())
11761 return;
11763 ASTContext &Ctx = Self.getASTContext();
11764 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11766 const QualType CharType = CharExpr->getType();
11767 if (!CharType->isAnyCharacterType() &&
11768 CharType->isIntegerType() &&
11769 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11770 Self.Diag(OpLoc, diag::warn_string_plus_char)
11771 << DiagRange << Ctx.CharTy;
11772 } else {
11773 Self.Diag(OpLoc, diag::warn_string_plus_char)
11774 << DiagRange << CharExpr->getType();
11777 // Only print a fixit for str + char, not for char + str.
11778 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11779 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11780 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11781 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11782 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11783 << FixItHint::CreateInsertion(EndLoc, "]");
11784 } else {
11785 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11789 /// Emit error when two pointers are incompatible.
11790 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11791 Expr *LHSExpr, Expr *RHSExpr) {
11792 assert(LHSExpr->getType()->isAnyPointerType());
11793 assert(RHSExpr->getType()->isAnyPointerType());
11794 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11795 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11796 << RHSExpr->getSourceRange();
11799 // C99 6.5.6
11800 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11801 SourceLocation Loc, BinaryOperatorKind Opc,
11802 QualType* CompLHSTy) {
11803 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11805 if (LHS.get()->getType()->isVectorType() ||
11806 RHS.get()->getType()->isVectorType()) {
11807 QualType compType =
11808 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11809 /*AllowBothBool*/ getLangOpts().AltiVec,
11810 /*AllowBoolConversions*/ getLangOpts().ZVector,
11811 /*AllowBooleanOperation*/ false,
11812 /*ReportInvalid*/ true);
11813 if (CompLHSTy) *CompLHSTy = compType;
11814 return compType;
11817 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11818 RHS.get()->getType()->isSveVLSBuiltinType()) {
11819 QualType compType =
11820 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11821 if (CompLHSTy)
11822 *CompLHSTy = compType;
11823 return compType;
11826 if (LHS.get()->getType()->isConstantMatrixType() ||
11827 RHS.get()->getType()->isConstantMatrixType()) {
11828 QualType compType =
11829 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11830 if (CompLHSTy)
11831 *CompLHSTy = compType;
11832 return compType;
11835 QualType compType = UsualArithmeticConversions(
11836 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11837 if (LHS.isInvalid() || RHS.isInvalid())
11838 return QualType();
11840 // Diagnose "string literal" '+' int and string '+' "char literal".
11841 if (Opc == BO_Add) {
11842 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11843 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11846 // handle the common case first (both operands are arithmetic).
11847 if (!compType.isNull() && compType->isArithmeticType()) {
11848 if (CompLHSTy) *CompLHSTy = compType;
11849 return compType;
11852 // Type-checking. Ultimately the pointer's going to be in PExp;
11853 // note that we bias towards the LHS being the pointer.
11854 Expr *PExp = LHS.get(), *IExp = RHS.get();
11856 bool isObjCPointer;
11857 if (PExp->getType()->isPointerType()) {
11858 isObjCPointer = false;
11859 } else if (PExp->getType()->isObjCObjectPointerType()) {
11860 isObjCPointer = true;
11861 } else {
11862 std::swap(PExp, IExp);
11863 if (PExp->getType()->isPointerType()) {
11864 isObjCPointer = false;
11865 } else if (PExp->getType()->isObjCObjectPointerType()) {
11866 isObjCPointer = true;
11867 } else {
11868 return InvalidOperands(Loc, LHS, RHS);
11871 assert(PExp->getType()->isAnyPointerType());
11873 if (!IExp->getType()->isIntegerType())
11874 return InvalidOperands(Loc, LHS, RHS);
11876 // Adding to a null pointer results in undefined behavior.
11877 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11878 Context, Expr::NPC_ValueDependentIsNotNull)) {
11879 // In C++ adding zero to a null pointer is defined.
11880 Expr::EvalResult KnownVal;
11881 if (!getLangOpts().CPlusPlus ||
11882 (!IExp->isValueDependent() &&
11883 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11884 KnownVal.Val.getInt() != 0))) {
11885 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11886 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11887 Context, BO_Add, PExp, IExp);
11888 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11892 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11893 return QualType();
11895 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11896 return QualType();
11898 // Check array bounds for pointer arithemtic
11899 CheckArrayAccess(PExp, IExp);
11901 if (CompLHSTy) {
11902 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11903 if (LHSTy.isNull()) {
11904 LHSTy = LHS.get()->getType();
11905 if (Context.isPromotableIntegerType(LHSTy))
11906 LHSTy = Context.getPromotedIntegerType(LHSTy);
11908 *CompLHSTy = LHSTy;
11911 return PExp->getType();
11914 // C99 6.5.6
11915 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11916 SourceLocation Loc,
11917 QualType* CompLHSTy) {
11918 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11920 if (LHS.get()->getType()->isVectorType() ||
11921 RHS.get()->getType()->isVectorType()) {
11922 QualType compType =
11923 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11924 /*AllowBothBool*/ getLangOpts().AltiVec,
11925 /*AllowBoolConversions*/ getLangOpts().ZVector,
11926 /*AllowBooleanOperation*/ false,
11927 /*ReportInvalid*/ true);
11928 if (CompLHSTy) *CompLHSTy = compType;
11929 return compType;
11932 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11933 RHS.get()->getType()->isSveVLSBuiltinType()) {
11934 QualType compType =
11935 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11936 if (CompLHSTy)
11937 *CompLHSTy = compType;
11938 return compType;
11941 if (LHS.get()->getType()->isConstantMatrixType() ||
11942 RHS.get()->getType()->isConstantMatrixType()) {
11943 QualType compType =
11944 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11945 if (CompLHSTy)
11946 *CompLHSTy = compType;
11947 return compType;
11950 QualType compType = UsualArithmeticConversions(
11951 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11952 if (LHS.isInvalid() || RHS.isInvalid())
11953 return QualType();
11955 // Enforce type constraints: C99 6.5.6p3.
11957 // Handle the common case first (both operands are arithmetic).
11958 if (!compType.isNull() && compType->isArithmeticType()) {
11959 if (CompLHSTy) *CompLHSTy = compType;
11960 return compType;
11963 // Either ptr - int or ptr - ptr.
11964 if (LHS.get()->getType()->isAnyPointerType()) {
11965 QualType lpointee = LHS.get()->getType()->getPointeeType();
11967 // Diagnose bad cases where we step over interface counts.
11968 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11969 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11970 return QualType();
11972 // The result type of a pointer-int computation is the pointer type.
11973 if (RHS.get()->getType()->isIntegerType()) {
11974 // Subtracting from a null pointer should produce a warning.
11975 // The last argument to the diagnose call says this doesn't match the
11976 // GNU int-to-pointer idiom.
11977 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11978 Expr::NPC_ValueDependentIsNotNull)) {
11979 // In C++ adding zero to a null pointer is defined.
11980 Expr::EvalResult KnownVal;
11981 if (!getLangOpts().CPlusPlus ||
11982 (!RHS.get()->isValueDependent() &&
11983 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11984 KnownVal.Val.getInt() != 0))) {
11985 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11989 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11990 return QualType();
11992 // Check array bounds for pointer arithemtic
11993 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11994 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11996 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11997 return LHS.get()->getType();
12000 // Handle pointer-pointer subtractions.
12001 if (const PointerType *RHSPTy
12002 = RHS.get()->getType()->getAs<PointerType>()) {
12003 QualType rpointee = RHSPTy->getPointeeType();
12005 if (getLangOpts().CPlusPlus) {
12006 // Pointee types must be the same: C++ [expr.add]
12007 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
12008 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
12010 } else {
12011 // Pointee types must be compatible C99 6.5.6p3
12012 if (!Context.typesAreCompatible(
12013 Context.getCanonicalType(lpointee).getUnqualifiedType(),
12014 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
12015 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
12016 return QualType();
12020 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
12021 LHS.get(), RHS.get()))
12022 return QualType();
12024 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12025 Context, Expr::NPC_ValueDependentIsNotNull);
12026 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12027 Context, Expr::NPC_ValueDependentIsNotNull);
12029 // Subtracting nullptr or from nullptr is suspect
12030 if (LHSIsNullPtr)
12031 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
12032 if (RHSIsNullPtr)
12033 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
12035 // The pointee type may have zero size. As an extension, a structure or
12036 // union may have zero size or an array may have zero length. In this
12037 // case subtraction does not make sense.
12038 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
12039 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
12040 if (ElementSize.isZero()) {
12041 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
12042 << rpointee.getUnqualifiedType()
12043 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12047 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12048 return Context.getPointerDiffType();
12052 return InvalidOperands(Loc, LHS, RHS);
12055 static bool isScopedEnumerationType(QualType T) {
12056 if (const EnumType *ET = T->getAs<EnumType>())
12057 return ET->getDecl()->isScoped();
12058 return false;
12061 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
12062 SourceLocation Loc, BinaryOperatorKind Opc,
12063 QualType LHSType) {
12064 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
12065 // so skip remaining warnings as we don't want to modify values within Sema.
12066 if (S.getLangOpts().OpenCL)
12067 return;
12069 // Check right/shifter operand
12070 Expr::EvalResult RHSResult;
12071 if (RHS.get()->isValueDependent() ||
12072 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
12073 return;
12074 llvm::APSInt Right = RHSResult.Val.getInt();
12076 if (Right.isNegative()) {
12077 S.DiagRuntimeBehavior(Loc, RHS.get(),
12078 S.PDiag(diag::warn_shift_negative)
12079 << RHS.get()->getSourceRange());
12080 return;
12083 QualType LHSExprType = LHS.get()->getType();
12084 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
12085 if (LHSExprType->isBitIntType())
12086 LeftSize = S.Context.getIntWidth(LHSExprType);
12087 else if (LHSExprType->isFixedPointType()) {
12088 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
12089 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
12091 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
12092 if (Right.uge(LeftBits)) {
12093 S.DiagRuntimeBehavior(Loc, RHS.get(),
12094 S.PDiag(diag::warn_shift_gt_typewidth)
12095 << RHS.get()->getSourceRange());
12096 return;
12099 // FIXME: We probably need to handle fixed point types specially here.
12100 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12101 return;
12103 // When left shifting an ICE which is signed, we can check for overflow which
12104 // according to C++ standards prior to C++2a has undefined behavior
12105 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12106 // more than the maximum value representable in the result type, so never
12107 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12108 // expression is still probably a bug.)
12109 Expr::EvalResult LHSResult;
12110 if (LHS.get()->isValueDependent() ||
12111 LHSType->hasUnsignedIntegerRepresentation() ||
12112 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
12113 return;
12114 llvm::APSInt Left = LHSResult.Val.getInt();
12116 // Don't warn if signed overflow is defined, then all the rest of the
12117 // diagnostics will not be triggered because the behavior is defined.
12118 // Also don't warn in C++20 mode (and newer), as signed left shifts
12119 // always wrap and never overflow.
12120 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12121 return;
12123 // If LHS does not have a non-negative value then, the
12124 // behavior is undefined before C++2a. Warn about it.
12125 if (Left.isNegative()) {
12126 S.DiagRuntimeBehavior(Loc, LHS.get(),
12127 S.PDiag(diag::warn_shift_lhs_negative)
12128 << LHS.get()->getSourceRange());
12129 return;
12132 llvm::APInt ResultBits =
12133 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12134 if (LeftBits.uge(ResultBits))
12135 return;
12136 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
12137 Result = Result.shl(Right);
12139 // Print the bit representation of the signed integer as an unsigned
12140 // hexadecimal number.
12141 SmallString<40> HexResult;
12142 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
12144 // If we are only missing a sign bit, this is less likely to result in actual
12145 // bugs -- if the result is cast back to an unsigned type, it will have the
12146 // expected value. Thus we place this behind a different warning that can be
12147 // turned off separately if needed.
12148 if (LeftBits == ResultBits - 1) {
12149 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
12150 << HexResult << LHSType
12151 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12152 return;
12155 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
12156 << HexResult.str() << Result.getSignificantBits() << LHSType
12157 << Left.getBitWidth() << LHS.get()->getSourceRange()
12158 << RHS.get()->getSourceRange();
12161 /// Return the resulting type when a vector is shifted
12162 /// by a scalar or vector shift amount.
12163 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
12164 SourceLocation Loc, bool IsCompAssign) {
12165 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12166 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12167 !LHS.get()->getType()->isVectorType()) {
12168 S.Diag(Loc, diag::err_shift_rhs_only_vector)
12169 << RHS.get()->getType() << LHS.get()->getType()
12170 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12171 return QualType();
12174 if (!IsCompAssign) {
12175 LHS = S.UsualUnaryConversions(LHS.get());
12176 if (LHS.isInvalid()) return QualType();
12179 RHS = S.UsualUnaryConversions(RHS.get());
12180 if (RHS.isInvalid()) return QualType();
12182 QualType LHSType = LHS.get()->getType();
12183 // Note that LHS might be a scalar because the routine calls not only in
12184 // OpenCL case.
12185 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12186 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12188 // Note that RHS might not be a vector.
12189 QualType RHSType = RHS.get()->getType();
12190 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12191 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12193 // Do not allow shifts for boolean vectors.
12194 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12195 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12196 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12197 << LHS.get()->getType() << RHS.get()->getType()
12198 << LHS.get()->getSourceRange();
12199 return QualType();
12202 // The operands need to be integers.
12203 if (!LHSEleType->isIntegerType()) {
12204 S.Diag(Loc, diag::err_typecheck_expect_int)
12205 << LHS.get()->getType() << LHS.get()->getSourceRange();
12206 return QualType();
12209 if (!RHSEleType->isIntegerType()) {
12210 S.Diag(Loc, diag::err_typecheck_expect_int)
12211 << RHS.get()->getType() << RHS.get()->getSourceRange();
12212 return QualType();
12215 if (!LHSVecTy) {
12216 assert(RHSVecTy);
12217 if (IsCompAssign)
12218 return RHSType;
12219 if (LHSEleType != RHSEleType) {
12220 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
12221 LHSEleType = RHSEleType;
12223 QualType VecTy =
12224 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
12225 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
12226 LHSType = VecTy;
12227 } else if (RHSVecTy) {
12228 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12229 // are applied component-wise. So if RHS is a vector, then ensure
12230 // that the number of elements is the same as LHS...
12231 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12232 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12233 << LHS.get()->getType() << RHS.get()->getType()
12234 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12235 return QualType();
12237 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12238 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12239 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12240 if (LHSBT != RHSBT &&
12241 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12242 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12243 << LHS.get()->getType() << RHS.get()->getType()
12244 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12247 } else {
12248 // ...else expand RHS to match the number of elements in LHS.
12249 QualType VecTy =
12250 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12251 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12254 return LHSType;
12257 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12258 ExprResult &RHS, SourceLocation Loc,
12259 bool IsCompAssign) {
12260 if (!IsCompAssign) {
12261 LHS = S.UsualUnaryConversions(LHS.get());
12262 if (LHS.isInvalid())
12263 return QualType();
12266 RHS = S.UsualUnaryConversions(RHS.get());
12267 if (RHS.isInvalid())
12268 return QualType();
12270 QualType LHSType = LHS.get()->getType();
12271 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12272 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12273 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12274 : LHSType;
12276 // Note that RHS might not be a vector
12277 QualType RHSType = RHS.get()->getType();
12278 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12279 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12280 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12281 : RHSType;
12283 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12284 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12285 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12286 << LHSType << RHSType << LHS.get()->getSourceRange();
12287 return QualType();
12290 if (!LHSEleType->isIntegerType()) {
12291 S.Diag(Loc, diag::err_typecheck_expect_int)
12292 << LHS.get()->getType() << LHS.get()->getSourceRange();
12293 return QualType();
12296 if (!RHSEleType->isIntegerType()) {
12297 S.Diag(Loc, diag::err_typecheck_expect_int)
12298 << RHS.get()->getType() << RHS.get()->getSourceRange();
12299 return QualType();
12302 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12303 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12304 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12305 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12306 << LHSType << RHSType << LHS.get()->getSourceRange()
12307 << RHS.get()->getSourceRange();
12308 return QualType();
12311 if (!LHSType->isSveVLSBuiltinType()) {
12312 assert(RHSType->isSveVLSBuiltinType());
12313 if (IsCompAssign)
12314 return RHSType;
12315 if (LHSEleType != RHSEleType) {
12316 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12317 LHSEleType = RHSEleType;
12319 const llvm::ElementCount VecSize =
12320 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12321 QualType VecTy =
12322 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12323 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12324 LHSType = VecTy;
12325 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12326 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12327 S.Context.getTypeSize(LHSBuiltinTy)) {
12328 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12329 << LHSType << RHSType << LHS.get()->getSourceRange()
12330 << RHS.get()->getSourceRange();
12331 return QualType();
12333 } else {
12334 const llvm::ElementCount VecSize =
12335 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12336 if (LHSEleType != RHSEleType) {
12337 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12338 RHSEleType = LHSEleType;
12340 QualType VecTy =
12341 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12342 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12345 return LHSType;
12348 // C99 6.5.7
12349 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12350 SourceLocation Loc, BinaryOperatorKind Opc,
12351 bool IsCompAssign) {
12352 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12354 // Vector shifts promote their scalar inputs to vector type.
12355 if (LHS.get()->getType()->isVectorType() ||
12356 RHS.get()->getType()->isVectorType()) {
12357 if (LangOpts.ZVector) {
12358 // The shift operators for the z vector extensions work basically
12359 // like general shifts, except that neither the LHS nor the RHS is
12360 // allowed to be a "vector bool".
12361 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12362 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
12363 return InvalidOperands(Loc, LHS, RHS);
12364 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12365 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
12366 return InvalidOperands(Loc, LHS, RHS);
12368 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12371 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12372 RHS.get()->getType()->isSveVLSBuiltinType())
12373 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12375 // Shifts don't perform usual arithmetic conversions, they just do integer
12376 // promotions on each operand. C99 6.5.7p3
12378 // For the LHS, do usual unary conversions, but then reset them away
12379 // if this is a compound assignment.
12380 ExprResult OldLHS = LHS;
12381 LHS = UsualUnaryConversions(LHS.get());
12382 if (LHS.isInvalid())
12383 return QualType();
12384 QualType LHSType = LHS.get()->getType();
12385 if (IsCompAssign) LHS = OldLHS;
12387 // The RHS is simpler.
12388 RHS = UsualUnaryConversions(RHS.get());
12389 if (RHS.isInvalid())
12390 return QualType();
12391 QualType RHSType = RHS.get()->getType();
12393 // C99 6.5.7p2: Each of the operands shall have integer type.
12394 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12395 if ((!LHSType->isFixedPointOrIntegerType() &&
12396 !LHSType->hasIntegerRepresentation()) ||
12397 !RHSType->hasIntegerRepresentation())
12398 return InvalidOperands(Loc, LHS, RHS);
12400 // C++0x: Don't allow scoped enums. FIXME: Use something better than
12401 // hasIntegerRepresentation() above instead of this.
12402 if (isScopedEnumerationType(LHSType) ||
12403 isScopedEnumerationType(RHSType)) {
12404 return InvalidOperands(Loc, LHS, RHS);
12406 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12408 // "The type of the result is that of the promoted left operand."
12409 return LHSType;
12412 /// Diagnose bad pointer comparisons.
12413 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12414 ExprResult &LHS, ExprResult &RHS,
12415 bool IsError) {
12416 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12417 : diag::ext_typecheck_comparison_of_distinct_pointers)
12418 << LHS.get()->getType() << RHS.get()->getType()
12419 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12422 /// Returns false if the pointers are converted to a composite type,
12423 /// true otherwise.
12424 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12425 ExprResult &LHS, ExprResult &RHS) {
12426 // C++ [expr.rel]p2:
12427 // [...] Pointer conversions (4.10) and qualification
12428 // conversions (4.4) are performed on pointer operands (or on
12429 // a pointer operand and a null pointer constant) to bring
12430 // them to their composite pointer type. [...]
12432 // C++ [expr.eq]p1 uses the same notion for (in)equality
12433 // comparisons of pointers.
12435 QualType LHSType = LHS.get()->getType();
12436 QualType RHSType = RHS.get()->getType();
12437 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12438 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12440 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12441 if (T.isNull()) {
12442 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12443 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12444 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12445 else
12446 S.InvalidOperands(Loc, LHS, RHS);
12447 return true;
12450 return false;
12453 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12454 ExprResult &LHS,
12455 ExprResult &RHS,
12456 bool IsError) {
12457 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12458 : diag::ext_typecheck_comparison_of_fptr_to_void)
12459 << LHS.get()->getType() << RHS.get()->getType()
12460 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12463 static bool isObjCObjectLiteral(ExprResult &E) {
12464 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12465 case Stmt::ObjCArrayLiteralClass:
12466 case Stmt::ObjCDictionaryLiteralClass:
12467 case Stmt::ObjCStringLiteralClass:
12468 case Stmt::ObjCBoxedExprClass:
12469 return true;
12470 default:
12471 // Note that ObjCBoolLiteral is NOT an object literal!
12472 return false;
12476 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12477 const ObjCObjectPointerType *Type =
12478 LHS->getType()->getAs<ObjCObjectPointerType>();
12480 // If this is not actually an Objective-C object, bail out.
12481 if (!Type)
12482 return false;
12484 // Get the LHS object's interface type.
12485 QualType InterfaceType = Type->getPointeeType();
12487 // If the RHS isn't an Objective-C object, bail out.
12488 if (!RHS->getType()->isObjCObjectPointerType())
12489 return false;
12491 // Try to find the -isEqual: method.
12492 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
12493 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
12494 InterfaceType,
12495 /*IsInstance=*/true);
12496 if (!Method) {
12497 if (Type->isObjCIdType()) {
12498 // For 'id', just check the global pool.
12499 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
12500 /*receiverId=*/true);
12501 } else {
12502 // Check protocols.
12503 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
12504 /*IsInstance=*/true);
12508 if (!Method)
12509 return false;
12511 QualType T = Method->parameters()[0]->getType();
12512 if (!T->isObjCObjectPointerType())
12513 return false;
12515 QualType R = Method->getReturnType();
12516 if (!R->isScalarType())
12517 return false;
12519 return true;
12522 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
12523 FromE = FromE->IgnoreParenImpCasts();
12524 switch (FromE->getStmtClass()) {
12525 default:
12526 break;
12527 case Stmt::ObjCStringLiteralClass:
12528 // "string literal"
12529 return LK_String;
12530 case Stmt::ObjCArrayLiteralClass:
12531 // "array literal"
12532 return LK_Array;
12533 case Stmt::ObjCDictionaryLiteralClass:
12534 // "dictionary literal"
12535 return LK_Dictionary;
12536 case Stmt::BlockExprClass:
12537 return LK_Block;
12538 case Stmt::ObjCBoxedExprClass: {
12539 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
12540 switch (Inner->getStmtClass()) {
12541 case Stmt::IntegerLiteralClass:
12542 case Stmt::FloatingLiteralClass:
12543 case Stmt::CharacterLiteralClass:
12544 case Stmt::ObjCBoolLiteralExprClass:
12545 case Stmt::CXXBoolLiteralExprClass:
12546 // "numeric literal"
12547 return LK_Numeric;
12548 case Stmt::ImplicitCastExprClass: {
12549 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
12550 // Boolean literals can be represented by implicit casts.
12551 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
12552 return LK_Numeric;
12553 break;
12555 default:
12556 break;
12558 return LK_Boxed;
12561 return LK_None;
12564 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12565 ExprResult &LHS, ExprResult &RHS,
12566 BinaryOperator::Opcode Opc){
12567 Expr *Literal;
12568 Expr *Other;
12569 if (isObjCObjectLiteral(LHS)) {
12570 Literal = LHS.get();
12571 Other = RHS.get();
12572 } else {
12573 Literal = RHS.get();
12574 Other = LHS.get();
12577 // Don't warn on comparisons against nil.
12578 Other = Other->IgnoreParenCasts();
12579 if (Other->isNullPointerConstant(S.getASTContext(),
12580 Expr::NPC_ValueDependentIsNotNull))
12581 return;
12583 // This should be kept in sync with warn_objc_literal_comparison.
12584 // LK_String should always be after the other literals, since it has its own
12585 // warning flag.
12586 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
12587 assert(LiteralKind != Sema::LK_Block);
12588 if (LiteralKind == Sema::LK_None) {
12589 llvm_unreachable("Unknown Objective-C object literal kind");
12592 if (LiteralKind == Sema::LK_String)
12593 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12594 << Literal->getSourceRange();
12595 else
12596 S.Diag(Loc, diag::warn_objc_literal_comparison)
12597 << LiteralKind << Literal->getSourceRange();
12599 if (BinaryOperator::isEqualityOp(Opc) &&
12600 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12601 SourceLocation Start = LHS.get()->getBeginLoc();
12602 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
12603 CharSourceRange OpRange =
12604 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12606 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12607 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12608 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12609 << FixItHint::CreateInsertion(End, "]");
12613 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12614 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12615 ExprResult &RHS, SourceLocation Loc,
12616 BinaryOperatorKind Opc) {
12617 // Check that left hand side is !something.
12618 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12619 if (!UO || UO->getOpcode() != UO_LNot) return;
12621 // Only check if the right hand side is non-bool arithmetic type.
12622 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12624 // Make sure that the something in !something is not bool.
12625 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12626 if (SubExpr->isKnownToHaveBooleanValue()) return;
12628 // Emit warning.
12629 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12630 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12631 << Loc << IsBitwiseOp;
12633 // First note suggest !(x < y)
12634 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12635 SourceLocation FirstClose = RHS.get()->getEndLoc();
12636 FirstClose = S.getLocForEndOfToken(FirstClose);
12637 if (FirstClose.isInvalid())
12638 FirstOpen = SourceLocation();
12639 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12640 << IsBitwiseOp
12641 << FixItHint::CreateInsertion(FirstOpen, "(")
12642 << FixItHint::CreateInsertion(FirstClose, ")");
12644 // Second note suggests (!x) < y
12645 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12646 SourceLocation SecondClose = LHS.get()->getEndLoc();
12647 SecondClose = S.getLocForEndOfToken(SecondClose);
12648 if (SecondClose.isInvalid())
12649 SecondOpen = SourceLocation();
12650 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12651 << FixItHint::CreateInsertion(SecondOpen, "(")
12652 << FixItHint::CreateInsertion(SecondClose, ")");
12655 // Returns true if E refers to a non-weak array.
12656 static bool checkForArray(const Expr *E) {
12657 const ValueDecl *D = nullptr;
12658 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12659 D = DR->getDecl();
12660 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12661 if (Mem->isImplicitAccess())
12662 D = Mem->getMemberDecl();
12664 if (!D)
12665 return false;
12666 return D->getType()->isArrayType() && !D->isWeak();
12669 /// Diagnose some forms of syntactically-obvious tautological comparison.
12670 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12671 Expr *LHS, Expr *RHS,
12672 BinaryOperatorKind Opc) {
12673 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12674 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12676 QualType LHSType = LHS->getType();
12677 QualType RHSType = RHS->getType();
12678 if (LHSType->hasFloatingRepresentation() ||
12679 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12680 S.inTemplateInstantiation())
12681 return;
12683 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12684 // Tautological diagnostics.
12685 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12686 return;
12688 // Comparisons between two array types are ill-formed for operator<=>, so
12689 // we shouldn't emit any additional warnings about it.
12690 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12691 return;
12693 // For non-floating point types, check for self-comparisons of the form
12694 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12695 // often indicate logic errors in the program.
12697 // NOTE: Don't warn about comparison expressions resulting from macro
12698 // expansion. Also don't warn about comparisons which are only self
12699 // comparisons within a template instantiation. The warnings should catch
12700 // obvious cases in the definition of the template anyways. The idea is to
12701 // warn when the typed comparison operator will always evaluate to the same
12702 // result.
12704 // Used for indexing into %select in warn_comparison_always
12705 enum {
12706 AlwaysConstant,
12707 AlwaysTrue,
12708 AlwaysFalse,
12709 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12712 // C++2a [depr.array.comp]:
12713 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12714 // operands of array type are deprecated.
12715 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12716 RHSStripped->getType()->isArrayType()) {
12717 S.Diag(Loc, diag::warn_depr_array_comparison)
12718 << LHS->getSourceRange() << RHS->getSourceRange()
12719 << LHSStripped->getType() << RHSStripped->getType();
12720 // Carry on to produce the tautological comparison warning, if this
12721 // expression is potentially-evaluated, we can resolve the array to a
12722 // non-weak declaration, and so on.
12725 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12726 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12727 unsigned Result;
12728 switch (Opc) {
12729 case BO_EQ:
12730 case BO_LE:
12731 case BO_GE:
12732 Result = AlwaysTrue;
12733 break;
12734 case BO_NE:
12735 case BO_LT:
12736 case BO_GT:
12737 Result = AlwaysFalse;
12738 break;
12739 case BO_Cmp:
12740 Result = AlwaysEqual;
12741 break;
12742 default:
12743 Result = AlwaysConstant;
12744 break;
12746 S.DiagRuntimeBehavior(Loc, nullptr,
12747 S.PDiag(diag::warn_comparison_always)
12748 << 0 /*self-comparison*/
12749 << Result);
12750 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12751 // What is it always going to evaluate to?
12752 unsigned Result;
12753 switch (Opc) {
12754 case BO_EQ: // e.g. array1 == array2
12755 Result = AlwaysFalse;
12756 break;
12757 case BO_NE: // e.g. array1 != array2
12758 Result = AlwaysTrue;
12759 break;
12760 default: // e.g. array1 <= array2
12761 // The best we can say is 'a constant'
12762 Result = AlwaysConstant;
12763 break;
12765 S.DiagRuntimeBehavior(Loc, nullptr,
12766 S.PDiag(diag::warn_comparison_always)
12767 << 1 /*array comparison*/
12768 << Result);
12772 if (isa<CastExpr>(LHSStripped))
12773 LHSStripped = LHSStripped->IgnoreParenCasts();
12774 if (isa<CastExpr>(RHSStripped))
12775 RHSStripped = RHSStripped->IgnoreParenCasts();
12777 // Warn about comparisons against a string constant (unless the other
12778 // operand is null); the user probably wants string comparison function.
12779 Expr *LiteralString = nullptr;
12780 Expr *LiteralStringStripped = nullptr;
12781 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12782 !RHSStripped->isNullPointerConstant(S.Context,
12783 Expr::NPC_ValueDependentIsNull)) {
12784 LiteralString = LHS;
12785 LiteralStringStripped = LHSStripped;
12786 } else if ((isa<StringLiteral>(RHSStripped) ||
12787 isa<ObjCEncodeExpr>(RHSStripped)) &&
12788 !LHSStripped->isNullPointerConstant(S.Context,
12789 Expr::NPC_ValueDependentIsNull)) {
12790 LiteralString = RHS;
12791 LiteralStringStripped = RHSStripped;
12794 if (LiteralString) {
12795 S.DiagRuntimeBehavior(Loc, nullptr,
12796 S.PDiag(diag::warn_stringcompare)
12797 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12798 << LiteralString->getSourceRange());
12802 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12803 switch (CK) {
12804 default: {
12805 #ifndef NDEBUG
12806 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12807 << "\n";
12808 #endif
12809 llvm_unreachable("unhandled cast kind");
12811 case CK_UserDefinedConversion:
12812 return ICK_Identity;
12813 case CK_LValueToRValue:
12814 return ICK_Lvalue_To_Rvalue;
12815 case CK_ArrayToPointerDecay:
12816 return ICK_Array_To_Pointer;
12817 case CK_FunctionToPointerDecay:
12818 return ICK_Function_To_Pointer;
12819 case CK_IntegralCast:
12820 return ICK_Integral_Conversion;
12821 case CK_FloatingCast:
12822 return ICK_Floating_Conversion;
12823 case CK_IntegralToFloating:
12824 case CK_FloatingToIntegral:
12825 return ICK_Floating_Integral;
12826 case CK_IntegralComplexCast:
12827 case CK_FloatingComplexCast:
12828 case CK_FloatingComplexToIntegralComplex:
12829 case CK_IntegralComplexToFloatingComplex:
12830 return ICK_Complex_Conversion;
12831 case CK_FloatingComplexToReal:
12832 case CK_FloatingRealToComplex:
12833 case CK_IntegralComplexToReal:
12834 case CK_IntegralRealToComplex:
12835 return ICK_Complex_Real;
12839 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12840 QualType FromType,
12841 SourceLocation Loc) {
12842 // Check for a narrowing implicit conversion.
12843 StandardConversionSequence SCS;
12844 SCS.setAsIdentityConversion();
12845 SCS.setToType(0, FromType);
12846 SCS.setToType(1, ToType);
12847 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12848 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12850 APValue PreNarrowingValue;
12851 QualType PreNarrowingType;
12852 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12853 PreNarrowingType,
12854 /*IgnoreFloatToIntegralConversion*/ true)) {
12855 case NK_Dependent_Narrowing:
12856 // Implicit conversion to a narrower type, but the expression is
12857 // value-dependent so we can't tell whether it's actually narrowing.
12858 case NK_Not_Narrowing:
12859 return false;
12861 case NK_Constant_Narrowing:
12862 // Implicit conversion to a narrower type, and the value is not a constant
12863 // expression.
12864 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12865 << /*Constant*/ 1
12866 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12867 return true;
12869 case NK_Variable_Narrowing:
12870 // Implicit conversion to a narrower type, and the value is not a constant
12871 // expression.
12872 case NK_Type_Narrowing:
12873 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12874 << /*Constant*/ 0 << FromType << ToType;
12875 // TODO: It's not a constant expression, but what if the user intended it
12876 // to be? Can we produce notes to help them figure out why it isn't?
12877 return true;
12879 llvm_unreachable("unhandled case in switch");
12882 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12883 ExprResult &LHS,
12884 ExprResult &RHS,
12885 SourceLocation Loc) {
12886 QualType LHSType = LHS.get()->getType();
12887 QualType RHSType = RHS.get()->getType();
12888 // Dig out the original argument type and expression before implicit casts
12889 // were applied. These are the types/expressions we need to check the
12890 // [expr.spaceship] requirements against.
12891 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12892 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12893 QualType LHSStrippedType = LHSStripped.get()->getType();
12894 QualType RHSStrippedType = RHSStripped.get()->getType();
12896 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12897 // other is not, the program is ill-formed.
12898 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12899 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12900 return QualType();
12903 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12904 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12905 RHSStrippedType->isEnumeralType();
12906 if (NumEnumArgs == 1) {
12907 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12908 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12909 if (OtherTy->hasFloatingRepresentation()) {
12910 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12911 return QualType();
12914 if (NumEnumArgs == 2) {
12915 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12916 // type E, the operator yields the result of converting the operands
12917 // to the underlying type of E and applying <=> to the converted operands.
12918 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12919 S.InvalidOperands(Loc, LHS, RHS);
12920 return QualType();
12922 QualType IntType =
12923 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12924 assert(IntType->isArithmeticType());
12926 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12927 // promote the boolean type, and all other promotable integer types, to
12928 // avoid this.
12929 if (S.Context.isPromotableIntegerType(IntType))
12930 IntType = S.Context.getPromotedIntegerType(IntType);
12932 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12933 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12934 LHSType = RHSType = IntType;
12937 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12938 // usual arithmetic conversions are applied to the operands.
12939 QualType Type =
12940 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12941 if (LHS.isInvalid() || RHS.isInvalid())
12942 return QualType();
12943 if (Type.isNull())
12944 return S.InvalidOperands(Loc, LHS, RHS);
12946 std::optional<ComparisonCategoryType> CCT =
12947 getComparisonCategoryForBuiltinCmp(Type);
12948 if (!CCT)
12949 return S.InvalidOperands(Loc, LHS, RHS);
12951 bool HasNarrowing = checkThreeWayNarrowingConversion(
12952 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12953 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12954 RHS.get()->getBeginLoc());
12955 if (HasNarrowing)
12956 return QualType();
12958 assert(!Type.isNull() && "composite type for <=> has not been set");
12960 return S.CheckComparisonCategoryType(
12961 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12964 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12965 ExprResult &RHS,
12966 SourceLocation Loc,
12967 BinaryOperatorKind Opc) {
12968 if (Opc == BO_Cmp)
12969 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12971 // C99 6.5.8p3 / C99 6.5.9p4
12972 QualType Type =
12973 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12974 if (LHS.isInvalid() || RHS.isInvalid())
12975 return QualType();
12976 if (Type.isNull())
12977 return S.InvalidOperands(Loc, LHS, RHS);
12978 assert(Type->isArithmeticType() || Type->isEnumeralType());
12980 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12981 return S.InvalidOperands(Loc, LHS, RHS);
12983 // Check for comparisons of floating point operands using != and ==.
12984 if (Type->hasFloatingRepresentation())
12985 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12987 // The result of comparisons is 'bool' in C++, 'int' in C.
12988 return S.Context.getLogicalOperationType();
12991 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12992 if (!NullE.get()->getType()->isAnyPointerType())
12993 return;
12994 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12995 if (!E.get()->getType()->isAnyPointerType() &&
12996 E.get()->isNullPointerConstant(Context,
12997 Expr::NPC_ValueDependentIsNotNull) ==
12998 Expr::NPCK_ZeroExpression) {
12999 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
13000 if (CL->getValue() == 0)
13001 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13002 << NullValue
13003 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
13004 NullValue ? "NULL" : "(void *)0");
13005 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
13006 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
13007 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
13008 if (T == Context.CharTy)
13009 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13010 << NullValue
13011 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
13012 NullValue ? "NULL" : "(void *)0");
13017 // C99 6.5.8, C++ [expr.rel]
13018 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
13019 SourceLocation Loc,
13020 BinaryOperatorKind Opc) {
13021 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
13022 bool IsThreeWay = Opc == BO_Cmp;
13023 bool IsOrdered = IsRelational || IsThreeWay;
13024 auto IsAnyPointerType = [](ExprResult E) {
13025 QualType Ty = E.get()->getType();
13026 return Ty->isPointerType() || Ty->isMemberPointerType();
13029 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
13030 // type, array-to-pointer, ..., conversions are performed on both operands to
13031 // bring them to their composite type.
13032 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
13033 // any type-related checks.
13034 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
13035 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13036 if (LHS.isInvalid())
13037 return QualType();
13038 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13039 if (RHS.isInvalid())
13040 return QualType();
13041 } else {
13042 LHS = DefaultLvalueConversion(LHS.get());
13043 if (LHS.isInvalid())
13044 return QualType();
13045 RHS = DefaultLvalueConversion(RHS.get());
13046 if (RHS.isInvalid())
13047 return QualType();
13050 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
13051 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
13052 CheckPtrComparisonWithNullChar(LHS, RHS);
13053 CheckPtrComparisonWithNullChar(RHS, LHS);
13056 // Handle vector comparisons separately.
13057 if (LHS.get()->getType()->isVectorType() ||
13058 RHS.get()->getType()->isVectorType())
13059 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
13061 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13062 RHS.get()->getType()->isSveVLSBuiltinType())
13063 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
13065 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13066 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13068 QualType LHSType = LHS.get()->getType();
13069 QualType RHSType = RHS.get()->getType();
13070 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
13071 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13072 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
13074 if ((LHSType->isPointerType() &&
13075 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
13076 (RHSType->isPointerType() &&
13077 RHSType->getPointeeType().isWebAssemblyReferenceType()))
13078 return InvalidOperands(Loc, LHS, RHS);
13080 const Expr::NullPointerConstantKind LHSNullKind =
13081 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
13082 const Expr::NullPointerConstantKind RHSNullKind =
13083 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
13084 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13085 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13087 auto computeResultTy = [&]() {
13088 if (Opc != BO_Cmp)
13089 return Context.getLogicalOperationType();
13090 assert(getLangOpts().CPlusPlus);
13091 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13093 QualType CompositeTy = LHS.get()->getType();
13094 assert(!CompositeTy->isReferenceType());
13096 std::optional<ComparisonCategoryType> CCT =
13097 getComparisonCategoryForBuiltinCmp(CompositeTy);
13098 if (!CCT)
13099 return InvalidOperands(Loc, LHS, RHS);
13101 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13102 // P0946R0: Comparisons between a null pointer constant and an object
13103 // pointer result in std::strong_equality, which is ill-formed under
13104 // P1959R0.
13105 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13106 << (LHSIsNull ? LHS.get()->getSourceRange()
13107 : RHS.get()->getSourceRange());
13108 return QualType();
13111 return CheckComparisonCategoryType(
13112 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
13115 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13116 bool IsEquality = Opc == BO_EQ;
13117 if (RHSIsNull)
13118 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
13119 RHS.get()->getSourceRange());
13120 else
13121 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
13122 LHS.get()->getSourceRange());
13125 if (IsOrdered && LHSType->isFunctionPointerType() &&
13126 RHSType->isFunctionPointerType()) {
13127 // Valid unless a relational comparison of function pointers
13128 bool IsError = Opc == BO_Cmp;
13129 auto DiagID =
13130 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13131 : getLangOpts().CPlusPlus
13132 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13133 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13134 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13135 << RHS.get()->getSourceRange();
13136 if (IsError)
13137 return QualType();
13140 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13141 (RHSType->isIntegerType() && !RHSIsNull)) {
13142 // Skip normal pointer conversion checks in this case; we have better
13143 // diagnostics for this below.
13144 } else if (getLangOpts().CPlusPlus) {
13145 // Equality comparison of a function pointer to a void pointer is invalid,
13146 // but we allow it as an extension.
13147 // FIXME: If we really want to allow this, should it be part of composite
13148 // pointer type computation so it works in conditionals too?
13149 if (!IsOrdered &&
13150 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13151 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13152 // This is a gcc extension compatibility comparison.
13153 // In a SFINAE context, we treat this as a hard error to maintain
13154 // conformance with the C++ standard.
13155 diagnoseFunctionPointerToVoidComparison(
13156 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
13158 if (isSFINAEContext())
13159 return QualType();
13161 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13162 return computeResultTy();
13165 // C++ [expr.eq]p2:
13166 // If at least one operand is a pointer [...] bring them to their
13167 // composite pointer type.
13168 // C++ [expr.spaceship]p6
13169 // If at least one of the operands is of pointer type, [...] bring them
13170 // to their composite pointer type.
13171 // C++ [expr.rel]p2:
13172 // If both operands are pointers, [...] bring them to their composite
13173 // pointer type.
13174 // For <=>, the only valid non-pointer types are arrays and functions, and
13175 // we already decayed those, so this is really the same as the relational
13176 // comparison rule.
13177 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13178 (IsOrdered ? 2 : 1) &&
13179 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13180 RHSType->isObjCObjectPointerType()))) {
13181 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13182 return QualType();
13183 return computeResultTy();
13185 } else if (LHSType->isPointerType() &&
13186 RHSType->isPointerType()) { // C99 6.5.8p2
13187 // All of the following pointer-related warnings are GCC extensions, except
13188 // when handling null pointer constants.
13189 QualType LCanPointeeTy =
13190 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13191 QualType RCanPointeeTy =
13192 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13194 // C99 6.5.9p2 and C99 6.5.8p2
13195 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
13196 RCanPointeeTy.getUnqualifiedType())) {
13197 if (IsRelational) {
13198 // Pointers both need to point to complete or incomplete types
13199 if ((LCanPointeeTy->isIncompleteType() !=
13200 RCanPointeeTy->isIncompleteType()) &&
13201 !getLangOpts().C11) {
13202 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13203 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13204 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13205 << RCanPointeeTy->isIncompleteType();
13208 } else if (!IsRelational &&
13209 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13210 // Valid unless comparison between non-null pointer and function pointer
13211 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13212 && !LHSIsNull && !RHSIsNull)
13213 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13214 /*isError*/false);
13215 } else {
13216 // Invalid
13217 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13219 if (LCanPointeeTy != RCanPointeeTy) {
13220 // Treat NULL constant as a special case in OpenCL.
13221 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13222 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
13223 Diag(Loc,
13224 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13225 << LHSType << RHSType << 0 /* comparison */
13226 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13229 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13230 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13231 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13232 : CK_BitCast;
13233 if (LHSIsNull && !RHSIsNull)
13234 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13235 else
13236 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13238 return computeResultTy();
13242 // C++ [expr.eq]p4:
13243 // Two operands of type std::nullptr_t or one operand of type
13244 // std::nullptr_t and the other a null pointer constant compare
13245 // equal.
13246 // C23 6.5.9p5:
13247 // If both operands have type nullptr_t or one operand has type nullptr_t
13248 // and the other is a null pointer constant, they compare equal if the
13249 // former is a null pointer.
13250 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13251 if (LHSType->isNullPtrType()) {
13252 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13253 return computeResultTy();
13255 if (RHSType->isNullPtrType()) {
13256 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13257 return computeResultTy();
13261 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13262 // C23 6.5.9p6:
13263 // Otherwise, at least one operand is a pointer. If one is a pointer and
13264 // the other is a null pointer constant or has type nullptr_t, they
13265 // compare equal
13266 if (LHSIsNull && RHSType->isPointerType()) {
13267 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13268 return computeResultTy();
13270 if (RHSIsNull && LHSType->isPointerType()) {
13271 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13272 return computeResultTy();
13276 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13277 // These aren't covered by the composite pointer type rules.
13278 if (!IsOrdered && RHSType->isNullPtrType() &&
13279 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13280 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13281 return computeResultTy();
13283 if (!IsOrdered && LHSType->isNullPtrType() &&
13284 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13285 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13286 return computeResultTy();
13289 if (getLangOpts().CPlusPlus) {
13290 if (IsRelational &&
13291 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13292 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13293 // HACK: Relational comparison of nullptr_t against a pointer type is
13294 // invalid per DR583, but we allow it within std::less<> and friends,
13295 // since otherwise common uses of it break.
13296 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13297 // friends to have std::nullptr_t overload candidates.
13298 DeclContext *DC = CurContext;
13299 if (isa<FunctionDecl>(DC))
13300 DC = DC->getParent();
13301 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13302 if (CTSD->isInStdNamespace() &&
13303 llvm::StringSwitch<bool>(CTSD->getName())
13304 .Cases("less", "less_equal", "greater", "greater_equal", true)
13305 .Default(false)) {
13306 if (RHSType->isNullPtrType())
13307 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13308 else
13309 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13310 return computeResultTy();
13315 // C++ [expr.eq]p2:
13316 // If at least one operand is a pointer to member, [...] bring them to
13317 // their composite pointer type.
13318 if (!IsOrdered &&
13319 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13320 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13321 return QualType();
13322 else
13323 return computeResultTy();
13327 // Handle block pointer types.
13328 if (!IsOrdered && LHSType->isBlockPointerType() &&
13329 RHSType->isBlockPointerType()) {
13330 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13331 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13333 if (!LHSIsNull && !RHSIsNull &&
13334 !Context.typesAreCompatible(lpointee, rpointee)) {
13335 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13336 << LHSType << RHSType << LHS.get()->getSourceRange()
13337 << RHS.get()->getSourceRange();
13339 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13340 return computeResultTy();
13343 // Allow block pointers to be compared with null pointer constants.
13344 if (!IsOrdered
13345 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13346 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13347 if (!LHSIsNull && !RHSIsNull) {
13348 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13349 ->getPointeeType()->isVoidType())
13350 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13351 ->getPointeeType()->isVoidType())))
13352 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13353 << LHSType << RHSType << LHS.get()->getSourceRange()
13354 << RHS.get()->getSourceRange();
13356 if (LHSIsNull && !RHSIsNull)
13357 LHS = ImpCastExprToType(LHS.get(), RHSType,
13358 RHSType->isPointerType() ? CK_BitCast
13359 : CK_AnyPointerToBlockPointerCast);
13360 else
13361 RHS = ImpCastExprToType(RHS.get(), LHSType,
13362 LHSType->isPointerType() ? CK_BitCast
13363 : CK_AnyPointerToBlockPointerCast);
13364 return computeResultTy();
13367 if (LHSType->isObjCObjectPointerType() ||
13368 RHSType->isObjCObjectPointerType()) {
13369 const PointerType *LPT = LHSType->getAs<PointerType>();
13370 const PointerType *RPT = RHSType->getAs<PointerType>();
13371 if (LPT || RPT) {
13372 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13373 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13375 if (!LPtrToVoid && !RPtrToVoid &&
13376 !Context.typesAreCompatible(LHSType, RHSType)) {
13377 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13378 /*isError*/false);
13380 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13381 // the RHS, but we have test coverage for this behavior.
13382 // FIXME: Consider using convertPointersToCompositeType in C++.
13383 if (LHSIsNull && !RHSIsNull) {
13384 Expr *E = LHS.get();
13385 if (getLangOpts().ObjCAutoRefCount)
13386 CheckObjCConversion(SourceRange(), RHSType, E,
13387 CCK_ImplicitConversion);
13388 LHS = ImpCastExprToType(E, RHSType,
13389 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13391 else {
13392 Expr *E = RHS.get();
13393 if (getLangOpts().ObjCAutoRefCount)
13394 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
13395 /*Diagnose=*/true,
13396 /*DiagnoseCFAudited=*/false, Opc);
13397 RHS = ImpCastExprToType(E, LHSType,
13398 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13400 return computeResultTy();
13402 if (LHSType->isObjCObjectPointerType() &&
13403 RHSType->isObjCObjectPointerType()) {
13404 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13405 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13406 /*isError*/false);
13407 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
13408 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13410 if (LHSIsNull && !RHSIsNull)
13411 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13412 else
13413 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13414 return computeResultTy();
13417 if (!IsOrdered && LHSType->isBlockPointerType() &&
13418 RHSType->isBlockCompatibleObjCPointerType(Context)) {
13419 LHS = ImpCastExprToType(LHS.get(), RHSType,
13420 CK_BlockPointerToObjCPointerCast);
13421 return computeResultTy();
13422 } else if (!IsOrdered &&
13423 LHSType->isBlockCompatibleObjCPointerType(Context) &&
13424 RHSType->isBlockPointerType()) {
13425 RHS = ImpCastExprToType(RHS.get(), LHSType,
13426 CK_BlockPointerToObjCPointerCast);
13427 return computeResultTy();
13430 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13431 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13432 unsigned DiagID = 0;
13433 bool isError = false;
13434 if (LangOpts.DebuggerSupport) {
13435 // Under a debugger, allow the comparison of pointers to integers,
13436 // since users tend to want to compare addresses.
13437 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13438 (RHSIsNull && RHSType->isIntegerType())) {
13439 if (IsOrdered) {
13440 isError = getLangOpts().CPlusPlus;
13441 DiagID =
13442 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13443 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13445 } else if (getLangOpts().CPlusPlus) {
13446 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13447 isError = true;
13448 } else if (IsOrdered)
13449 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13450 else
13451 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13453 if (DiagID) {
13454 Diag(Loc, DiagID)
13455 << LHSType << RHSType << LHS.get()->getSourceRange()
13456 << RHS.get()->getSourceRange();
13457 if (isError)
13458 return QualType();
13461 if (LHSType->isIntegerType())
13462 LHS = ImpCastExprToType(LHS.get(), RHSType,
13463 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13464 else
13465 RHS = ImpCastExprToType(RHS.get(), LHSType,
13466 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13467 return computeResultTy();
13470 // Handle block pointers.
13471 if (!IsOrdered && RHSIsNull
13472 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13473 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13474 return computeResultTy();
13476 if (!IsOrdered && LHSIsNull
13477 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13478 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13479 return computeResultTy();
13482 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13483 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13484 return computeResultTy();
13487 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13488 return computeResultTy();
13491 if (LHSIsNull && RHSType->isQueueT()) {
13492 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13493 return computeResultTy();
13496 if (LHSType->isQueueT() && RHSIsNull) {
13497 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13498 return computeResultTy();
13502 return InvalidOperands(Loc, LHS, RHS);
13505 // Return a signed ext_vector_type that is of identical size and number of
13506 // elements. For floating point vectors, return an integer type of identical
13507 // size and number of elements. In the non ext_vector_type case, search from
13508 // the largest type to the smallest type to avoid cases where long long == long,
13509 // where long gets picked over long long.
13510 QualType Sema::GetSignedVectorType(QualType V) {
13511 const VectorType *VTy = V->castAs<VectorType>();
13512 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13514 if (isa<ExtVectorType>(VTy)) {
13515 if (VTy->isExtVectorBoolType())
13516 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13517 if (TypeSize == Context.getTypeSize(Context.CharTy))
13518 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13519 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13520 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13521 if (TypeSize == Context.getTypeSize(Context.IntTy))
13522 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13523 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13524 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13525 if (TypeSize == Context.getTypeSize(Context.LongTy))
13526 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13527 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13528 "Unhandled vector element size in vector compare");
13529 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13532 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13533 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13534 VectorType::GenericVector);
13535 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13536 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13537 VectorType::GenericVector);
13538 if (TypeSize == Context.getTypeSize(Context.LongTy))
13539 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13540 VectorType::GenericVector);
13541 if (TypeSize == Context.getTypeSize(Context.IntTy))
13542 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13543 VectorType::GenericVector);
13544 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13545 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13546 VectorType::GenericVector);
13547 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13548 "Unhandled vector element size in vector compare");
13549 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13550 VectorType::GenericVector);
13553 QualType Sema::GetSignedSizelessVectorType(QualType V) {
13554 const BuiltinType *VTy = V->castAs<BuiltinType>();
13555 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13557 const QualType ETy = V->getSveEltType(Context);
13558 const auto TypeSize = Context.getTypeSize(ETy);
13560 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13561 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13562 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13565 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
13566 /// operates on extended vector types. Instead of producing an IntTy result,
13567 /// like a scalar comparison, a vector comparison produces a vector of integer
13568 /// types.
13569 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13570 SourceLocation Loc,
13571 BinaryOperatorKind Opc) {
13572 if (Opc == BO_Cmp) {
13573 Diag(Loc, diag::err_three_way_vector_comparison);
13574 return QualType();
13577 // Check to make sure we're operating on vectors of the same type and width,
13578 // Allowing one side to be a scalar of element type.
13579 QualType vType =
13580 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13581 /*AllowBothBool*/ true,
13582 /*AllowBoolConversions*/ getLangOpts().ZVector,
13583 /*AllowBooleanOperation*/ true,
13584 /*ReportInvalid*/ true);
13585 if (vType.isNull())
13586 return vType;
13588 QualType LHSType = LHS.get()->getType();
13590 // Determine the return type of a vector compare. By default clang will return
13591 // a scalar for all vector compares except vector bool and vector pixel.
13592 // With the gcc compiler we will always return a vector type and with the xl
13593 // compiler we will always return a scalar type. This switch allows choosing
13594 // which behavior is prefered.
13595 if (getLangOpts().AltiVec) {
13596 switch (getLangOpts().getAltivecSrcCompat()) {
13597 case LangOptions::AltivecSrcCompatKind::Mixed:
13598 // If AltiVec, the comparison results in a numeric type, i.e.
13599 // bool for C++, int for C
13600 if (vType->castAs<VectorType>()->getVectorKind() ==
13601 VectorType::AltiVecVector)
13602 return Context.getLogicalOperationType();
13603 else
13604 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13605 break;
13606 case LangOptions::AltivecSrcCompatKind::GCC:
13607 // For GCC we always return the vector type.
13608 break;
13609 case LangOptions::AltivecSrcCompatKind::XL:
13610 return Context.getLogicalOperationType();
13611 break;
13615 // For non-floating point types, check for self-comparisons of the form
13616 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13617 // often indicate logic errors in the program.
13618 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13620 // Check for comparisons of floating point operands using != and ==.
13621 if (LHSType->hasFloatingRepresentation()) {
13622 assert(RHS.get()->getType()->hasFloatingRepresentation());
13623 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13626 // Return a signed type for the vector.
13627 return GetSignedVectorType(vType);
13630 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13631 ExprResult &RHS,
13632 SourceLocation Loc,
13633 BinaryOperatorKind Opc) {
13634 if (Opc == BO_Cmp) {
13635 Diag(Loc, diag::err_three_way_vector_comparison);
13636 return QualType();
13639 // Check to make sure we're operating on vectors of the same type and width,
13640 // Allowing one side to be a scalar of element type.
13641 QualType vType = CheckSizelessVectorOperands(
13642 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
13644 if (vType.isNull())
13645 return vType;
13647 QualType LHSType = LHS.get()->getType();
13649 // For non-floating point types, check for self-comparisons of the form
13650 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13651 // often indicate logic errors in the program.
13652 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13654 // Check for comparisons of floating point operands using != and ==.
13655 if (LHSType->hasFloatingRepresentation()) {
13656 assert(RHS.get()->getType()->hasFloatingRepresentation());
13657 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13660 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13661 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13663 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13664 RHSBuiltinTy->isSVEBool())
13665 return LHSType;
13667 // Return a signed type for the vector.
13668 return GetSignedSizelessVectorType(vType);
13671 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13672 const ExprResult &XorRHS,
13673 const SourceLocation Loc) {
13674 // Do not diagnose macros.
13675 if (Loc.isMacroID())
13676 return;
13678 // Do not diagnose if both LHS and RHS are macros.
13679 if (XorLHS.get()->getExprLoc().isMacroID() &&
13680 XorRHS.get()->getExprLoc().isMacroID())
13681 return;
13683 bool Negative = false;
13684 bool ExplicitPlus = false;
13685 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13686 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13688 if (!LHSInt)
13689 return;
13690 if (!RHSInt) {
13691 // Check negative literals.
13692 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13693 UnaryOperatorKind Opc = UO->getOpcode();
13694 if (Opc != UO_Minus && Opc != UO_Plus)
13695 return;
13696 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13697 if (!RHSInt)
13698 return;
13699 Negative = (Opc == UO_Minus);
13700 ExplicitPlus = !Negative;
13701 } else {
13702 return;
13706 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13707 llvm::APInt RightSideValue = RHSInt->getValue();
13708 if (LeftSideValue != 2 && LeftSideValue != 10)
13709 return;
13711 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13712 return;
13714 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13715 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13716 llvm::StringRef ExprStr =
13717 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
13719 CharSourceRange XorRange =
13720 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
13721 llvm::StringRef XorStr =
13722 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
13723 // Do not diagnose if xor keyword/macro is used.
13724 if (XorStr == "xor")
13725 return;
13727 std::string LHSStr = std::string(Lexer::getSourceText(
13728 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13729 S.getSourceManager(), S.getLangOpts()));
13730 std::string RHSStr = std::string(Lexer::getSourceText(
13731 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13732 S.getSourceManager(), S.getLangOpts()));
13734 if (Negative) {
13735 RightSideValue = -RightSideValue;
13736 RHSStr = "-" + RHSStr;
13737 } else if (ExplicitPlus) {
13738 RHSStr = "+" + RHSStr;
13741 StringRef LHSStrRef = LHSStr;
13742 StringRef RHSStrRef = RHSStr;
13743 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13744 // literals.
13745 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
13746 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
13747 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
13748 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
13749 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
13750 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
13751 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13752 return;
13754 bool SuggestXor =
13755 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13756 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13757 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13758 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13759 std::string SuggestedExpr = "1 << " + RHSStr;
13760 bool Overflow = false;
13761 llvm::APInt One = (LeftSideValue - 1);
13762 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13763 if (Overflow) {
13764 if (RightSideIntValue < 64)
13765 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13766 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13767 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13768 else if (RightSideIntValue == 64)
13769 S.Diag(Loc, diag::warn_xor_used_as_pow)
13770 << ExprStr << toString(XorValue, 10, true);
13771 else
13772 return;
13773 } else {
13774 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13775 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13776 << toString(PowValue, 10, true)
13777 << FixItHint::CreateReplacement(
13778 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13781 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13782 << ("0x2 ^ " + RHSStr) << SuggestXor;
13783 } else if (LeftSideValue == 10) {
13784 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13785 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13786 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13787 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13788 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13789 << ("0xA ^ " + RHSStr) << SuggestXor;
13793 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13794 SourceLocation Loc) {
13795 // Ensure that either both operands are of the same vector type, or
13796 // one operand is of a vector type and the other is of its element type.
13797 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13798 /*AllowBothBool*/ true,
13799 /*AllowBoolConversions*/ false,
13800 /*AllowBooleanOperation*/ false,
13801 /*ReportInvalid*/ false);
13802 if (vType.isNull())
13803 return InvalidOperands(Loc, LHS, RHS);
13804 if (getLangOpts().OpenCL &&
13805 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13806 vType->hasFloatingRepresentation())
13807 return InvalidOperands(Loc, LHS, RHS);
13808 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13809 // usage of the logical operators && and || with vectors in C. This
13810 // check could be notionally dropped.
13811 if (!getLangOpts().CPlusPlus &&
13812 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13813 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13815 return GetSignedVectorType(LHS.get()->getType());
13818 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13819 SourceLocation Loc,
13820 bool IsCompAssign) {
13821 if (!IsCompAssign) {
13822 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13823 if (LHS.isInvalid())
13824 return QualType();
13826 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13827 if (RHS.isInvalid())
13828 return QualType();
13830 // For conversion purposes, we ignore any qualifiers.
13831 // For example, "const float" and "float" are equivalent.
13832 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13833 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13835 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13836 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13837 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13839 if (Context.hasSameType(LHSType, RHSType))
13840 return Context.getCommonSugaredType(LHSType, RHSType);
13842 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13843 // case we have to return InvalidOperands.
13844 ExprResult OriginalLHS = LHS;
13845 ExprResult OriginalRHS = RHS;
13846 if (LHSMatType && !RHSMatType) {
13847 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13848 if (!RHS.isInvalid())
13849 return LHSType;
13851 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13854 if (!LHSMatType && RHSMatType) {
13855 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13856 if (!LHS.isInvalid())
13857 return RHSType;
13858 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13861 return InvalidOperands(Loc, LHS, RHS);
13864 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13865 SourceLocation Loc,
13866 bool IsCompAssign) {
13867 if (!IsCompAssign) {
13868 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13869 if (LHS.isInvalid())
13870 return QualType();
13872 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13873 if (RHS.isInvalid())
13874 return QualType();
13876 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13877 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13878 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13880 if (LHSMatType && RHSMatType) {
13881 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13882 return InvalidOperands(Loc, LHS, RHS);
13884 if (Context.hasSameType(LHSMatType, RHSMatType))
13885 return Context.getCommonSugaredType(
13886 LHS.get()->getType().getUnqualifiedType(),
13887 RHS.get()->getType().getUnqualifiedType());
13889 QualType LHSELTy = LHSMatType->getElementType(),
13890 RHSELTy = RHSMatType->getElementType();
13891 if (!Context.hasSameType(LHSELTy, RHSELTy))
13892 return InvalidOperands(Loc, LHS, RHS);
13894 return Context.getConstantMatrixType(
13895 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13896 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13898 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13901 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13902 switch (Opc) {
13903 default:
13904 return false;
13905 case BO_And:
13906 case BO_AndAssign:
13907 case BO_Or:
13908 case BO_OrAssign:
13909 case BO_Xor:
13910 case BO_XorAssign:
13911 return true;
13915 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13916 SourceLocation Loc,
13917 BinaryOperatorKind Opc) {
13918 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13920 bool IsCompAssign =
13921 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13923 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13925 if (LHS.get()->getType()->isVectorType() ||
13926 RHS.get()->getType()->isVectorType()) {
13927 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13928 RHS.get()->getType()->hasIntegerRepresentation())
13929 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13930 /*AllowBothBool*/ true,
13931 /*AllowBoolConversions*/ getLangOpts().ZVector,
13932 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13933 /*ReportInvalid*/ true);
13934 return InvalidOperands(Loc, LHS, RHS);
13937 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13938 RHS.get()->getType()->isSveVLSBuiltinType()) {
13939 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13940 RHS.get()->getType()->hasIntegerRepresentation())
13941 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13942 ACK_BitwiseOp);
13943 return InvalidOperands(Loc, LHS, RHS);
13946 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13947 RHS.get()->getType()->isSveVLSBuiltinType()) {
13948 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13949 RHS.get()->getType()->hasIntegerRepresentation())
13950 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13951 ACK_BitwiseOp);
13952 return InvalidOperands(Loc, LHS, RHS);
13955 if (Opc == BO_And)
13956 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13958 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13959 RHS.get()->getType()->hasFloatingRepresentation())
13960 return InvalidOperands(Loc, LHS, RHS);
13962 ExprResult LHSResult = LHS, RHSResult = RHS;
13963 QualType compType = UsualArithmeticConversions(
13964 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13965 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13966 return QualType();
13967 LHS = LHSResult.get();
13968 RHS = RHSResult.get();
13970 if (Opc == BO_Xor)
13971 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13973 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13974 return compType;
13975 return InvalidOperands(Loc, LHS, RHS);
13978 // C99 6.5.[13,14]
13979 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13980 SourceLocation Loc,
13981 BinaryOperatorKind Opc) {
13982 // Check vector operands differently.
13983 if (LHS.get()->getType()->isVectorType() ||
13984 RHS.get()->getType()->isVectorType())
13985 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13987 bool EnumConstantInBoolContext = false;
13988 for (const ExprResult &HS : {LHS, RHS}) {
13989 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13990 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13991 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13992 EnumConstantInBoolContext = true;
13996 if (EnumConstantInBoolContext)
13997 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13999 // WebAssembly tables can't be used with logical operators.
14000 QualType LHSTy = LHS.get()->getType();
14001 QualType RHSTy = RHS.get()->getType();
14002 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
14003 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
14004 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
14005 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
14006 return InvalidOperands(Loc, LHS, RHS);
14009 // Diagnose cases where the user write a logical and/or but probably meant a
14010 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
14011 // is a constant.
14012 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
14013 !LHS.get()->getType()->isBooleanType() &&
14014 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
14015 // Don't warn in macros or template instantiations.
14016 !Loc.isMacroID() && !inTemplateInstantiation()) {
14017 // If the RHS can be constant folded, and if it constant folds to something
14018 // that isn't 0 or 1 (which indicate a potential logical operation that
14019 // happened to fold to true/false) then warn.
14020 // Parens on the RHS are ignored.
14021 Expr::EvalResult EVResult;
14022 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
14023 llvm::APSInt Result = EVResult.Val.getInt();
14024 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
14025 !RHS.get()->getExprLoc().isMacroID()) ||
14026 (Result != 0 && Result != 1)) {
14027 Diag(Loc, diag::warn_logical_instead_of_bitwise)
14028 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
14029 // Suggest replacing the logical operator with the bitwise version
14030 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
14031 << (Opc == BO_LAnd ? "&" : "|")
14032 << FixItHint::CreateReplacement(
14033 SourceRange(Loc, getLocForEndOfToken(Loc)),
14034 Opc == BO_LAnd ? "&" : "|");
14035 if (Opc == BO_LAnd)
14036 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14037 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
14038 << FixItHint::CreateRemoval(
14039 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
14040 RHS.get()->getEndLoc()));
14045 if (!Context.getLangOpts().CPlusPlus) {
14046 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14047 // not operate on the built-in scalar and vector float types.
14048 if (Context.getLangOpts().OpenCL &&
14049 Context.getLangOpts().OpenCLVersion < 120) {
14050 if (LHS.get()->getType()->isFloatingType() ||
14051 RHS.get()->getType()->isFloatingType())
14052 return InvalidOperands(Loc, LHS, RHS);
14055 LHS = UsualUnaryConversions(LHS.get());
14056 if (LHS.isInvalid())
14057 return QualType();
14059 RHS = UsualUnaryConversions(RHS.get());
14060 if (RHS.isInvalid())
14061 return QualType();
14063 if (!LHS.get()->getType()->isScalarType() ||
14064 !RHS.get()->getType()->isScalarType())
14065 return InvalidOperands(Loc, LHS, RHS);
14067 return Context.IntTy;
14070 // The following is safe because we only use this method for
14071 // non-overloadable operands.
14073 // C++ [expr.log.and]p1
14074 // C++ [expr.log.or]p1
14075 // The operands are both contextually converted to type bool.
14076 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
14077 if (LHSRes.isInvalid())
14078 return InvalidOperands(Loc, LHS, RHS);
14079 LHS = LHSRes;
14081 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
14082 if (RHSRes.isInvalid())
14083 return InvalidOperands(Loc, LHS, RHS);
14084 RHS = RHSRes;
14086 // C++ [expr.log.and]p2
14087 // C++ [expr.log.or]p2
14088 // The result is a bool.
14089 return Context.BoolTy;
14092 static bool IsReadonlyMessage(Expr *E, Sema &S) {
14093 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14094 if (!ME) return false;
14095 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
14096 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14097 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14098 if (!Base) return false;
14099 return Base->getMethodDecl() != nullptr;
14102 /// Is the given expression (which must be 'const') a reference to a
14103 /// variable which was originally non-const, but which has become
14104 /// 'const' due to being captured within a block?
14105 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
14106 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
14107 assert(E->isLValue() && E->getType().isConstQualified());
14108 E = E->IgnoreParens();
14110 // Must be a reference to a declaration from an enclosing scope.
14111 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14112 if (!DRE) return NCCK_None;
14113 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
14115 // The declaration must be a variable which is not declared 'const'.
14116 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
14117 if (!var) return NCCK_None;
14118 if (var->getType().isConstQualified()) return NCCK_None;
14119 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
14121 // Decide whether the first capture was for a block or a lambda.
14122 DeclContext *DC = S.CurContext, *Prev = nullptr;
14123 // Decide whether the first capture was for a block or a lambda.
14124 while (DC) {
14125 // For init-capture, it is possible that the variable belongs to the
14126 // template pattern of the current context.
14127 if (auto *FD = dyn_cast<FunctionDecl>(DC))
14128 if (var->isInitCapture() &&
14129 FD->getTemplateInstantiationPattern() == var->getDeclContext())
14130 break;
14131 if (DC == var->getDeclContext())
14132 break;
14133 Prev = DC;
14134 DC = DC->getParent();
14136 // Unless we have an init-capture, we've gone one step too far.
14137 if (!var->isInitCapture())
14138 DC = Prev;
14139 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
14142 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14143 Ty = Ty.getNonReferenceType();
14144 if (IsDereference && Ty->isPointerType())
14145 Ty = Ty->getPointeeType();
14146 return !Ty.isConstQualified();
14149 // Update err_typecheck_assign_const and note_typecheck_assign_const
14150 // when this enum is changed.
14151 enum {
14152 ConstFunction,
14153 ConstVariable,
14154 ConstMember,
14155 ConstMethod,
14156 NestedConstMember,
14157 ConstUnknown, // Keep as last element
14160 /// Emit the "read-only variable not assignable" error and print notes to give
14161 /// more information about why the variable is not assignable, such as pointing
14162 /// to the declaration of a const variable, showing that a method is const, or
14163 /// that the function is returning a const reference.
14164 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14165 SourceLocation Loc) {
14166 SourceRange ExprRange = E->getSourceRange();
14168 // Only emit one error on the first const found. All other consts will emit
14169 // a note to the error.
14170 bool DiagnosticEmitted = false;
14172 // Track if the current expression is the result of a dereference, and if the
14173 // next checked expression is the result of a dereference.
14174 bool IsDereference = false;
14175 bool NextIsDereference = false;
14177 // Loop to process MemberExpr chains.
14178 while (true) {
14179 IsDereference = NextIsDereference;
14181 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14182 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14183 NextIsDereference = ME->isArrow();
14184 const ValueDecl *VD = ME->getMemberDecl();
14185 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14186 // Mutable fields can be modified even if the class is const.
14187 if (Field->isMutable()) {
14188 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14189 break;
14192 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14193 if (!DiagnosticEmitted) {
14194 S.Diag(Loc, diag::err_typecheck_assign_const)
14195 << ExprRange << ConstMember << false /*static*/ << Field
14196 << Field->getType();
14197 DiagnosticEmitted = true;
14199 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14200 << ConstMember << false /*static*/ << Field << Field->getType()
14201 << Field->getSourceRange();
14203 E = ME->getBase();
14204 continue;
14205 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14206 if (VDecl->getType().isConstQualified()) {
14207 if (!DiagnosticEmitted) {
14208 S.Diag(Loc, diag::err_typecheck_assign_const)
14209 << ExprRange << ConstMember << true /*static*/ << VDecl
14210 << VDecl->getType();
14211 DiagnosticEmitted = true;
14213 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14214 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14215 << VDecl->getSourceRange();
14217 // Static fields do not inherit constness from parents.
14218 break;
14220 break; // End MemberExpr
14221 } else if (const ArraySubscriptExpr *ASE =
14222 dyn_cast<ArraySubscriptExpr>(E)) {
14223 E = ASE->getBase()->IgnoreParenImpCasts();
14224 continue;
14225 } else if (const ExtVectorElementExpr *EVE =
14226 dyn_cast<ExtVectorElementExpr>(E)) {
14227 E = EVE->getBase()->IgnoreParenImpCasts();
14228 continue;
14230 break;
14233 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14234 // Function calls
14235 const FunctionDecl *FD = CE->getDirectCallee();
14236 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14237 if (!DiagnosticEmitted) {
14238 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14239 << ConstFunction << FD;
14240 DiagnosticEmitted = true;
14242 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
14243 diag::note_typecheck_assign_const)
14244 << ConstFunction << FD << FD->getReturnType()
14245 << FD->getReturnTypeSourceRange();
14247 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14248 // Point to variable declaration.
14249 if (const ValueDecl *VD = DRE->getDecl()) {
14250 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14251 if (!DiagnosticEmitted) {
14252 S.Diag(Loc, diag::err_typecheck_assign_const)
14253 << ExprRange << ConstVariable << VD << VD->getType();
14254 DiagnosticEmitted = true;
14256 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14257 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14260 } else if (isa<CXXThisExpr>(E)) {
14261 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14262 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14263 if (MD->isConst()) {
14264 if (!DiagnosticEmitted) {
14265 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14266 << ConstMethod << MD;
14267 DiagnosticEmitted = true;
14269 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
14270 << ConstMethod << MD << MD->getSourceRange();
14276 if (DiagnosticEmitted)
14277 return;
14279 // Can't determine a more specific message, so display the generic error.
14280 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14283 enum OriginalExprKind {
14284 OEK_Variable,
14285 OEK_Member,
14286 OEK_LValue
14289 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14290 const RecordType *Ty,
14291 SourceLocation Loc, SourceRange Range,
14292 OriginalExprKind OEK,
14293 bool &DiagnosticEmitted) {
14294 std::vector<const RecordType *> RecordTypeList;
14295 RecordTypeList.push_back(Ty);
14296 unsigned NextToCheckIndex = 0;
14297 // We walk the record hierarchy breadth-first to ensure that we print
14298 // diagnostics in field nesting order.
14299 while (RecordTypeList.size() > NextToCheckIndex) {
14300 bool IsNested = NextToCheckIndex > 0;
14301 for (const FieldDecl *Field :
14302 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
14303 // First, check every field for constness.
14304 QualType FieldTy = Field->getType();
14305 if (FieldTy.isConstQualified()) {
14306 if (!DiagnosticEmitted) {
14307 S.Diag(Loc, diag::err_typecheck_assign_const)
14308 << Range << NestedConstMember << OEK << VD
14309 << IsNested << Field;
14310 DiagnosticEmitted = true;
14312 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14313 << NestedConstMember << IsNested << Field
14314 << FieldTy << Field->getSourceRange();
14317 // Then we append it to the list to check next in order.
14318 FieldTy = FieldTy.getCanonicalType();
14319 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
14320 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14321 RecordTypeList.push_back(FieldRecTy);
14324 ++NextToCheckIndex;
14328 /// Emit an error for the case where a record we are trying to assign to has a
14329 /// const-qualified field somewhere in its hierarchy.
14330 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14331 SourceLocation Loc) {
14332 QualType Ty = E->getType();
14333 assert(Ty->isRecordType() && "lvalue was not record?");
14334 SourceRange Range = E->getSourceRange();
14335 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
14336 bool DiagEmitted = false;
14338 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14339 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14340 Range, OEK_Member, DiagEmitted);
14341 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14342 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14343 Range, OEK_Variable, DiagEmitted);
14344 else
14345 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14346 Range, OEK_LValue, DiagEmitted);
14347 if (!DiagEmitted)
14348 DiagnoseConstAssignment(S, E, Loc);
14351 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14352 /// emit an error and return true. If so, return false.
14353 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14354 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14356 S.CheckShadowingDeclModification(E, Loc);
14358 SourceLocation OrigLoc = Loc;
14359 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
14360 &Loc);
14361 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14362 IsLV = Expr::MLV_InvalidMessageExpression;
14363 if (IsLV == Expr::MLV_Valid)
14364 return false;
14366 unsigned DiagID = 0;
14367 bool NeedType = false;
14368 switch (IsLV) { // C99 6.5.16p2
14369 case Expr::MLV_ConstQualified:
14370 // Use a specialized diagnostic when we're assigning to an object
14371 // from an enclosing function or block.
14372 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14373 if (NCCK == NCCK_Block)
14374 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14375 else
14376 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14377 break;
14380 // In ARC, use some specialized diagnostics for occasions where we
14381 // infer 'const'. These are always pseudo-strong variables.
14382 if (S.getLangOpts().ObjCAutoRefCount) {
14383 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14384 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14385 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14387 // Use the normal diagnostic if it's pseudo-__strong but the
14388 // user actually wrote 'const'.
14389 if (var->isARCPseudoStrong() &&
14390 (!var->getTypeSourceInfo() ||
14391 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14392 // There are three pseudo-strong cases:
14393 // - self
14394 ObjCMethodDecl *method = S.getCurMethodDecl();
14395 if (method && var == method->getSelfDecl()) {
14396 DiagID = method->isClassMethod()
14397 ? diag::err_typecheck_arc_assign_self_class_method
14398 : diag::err_typecheck_arc_assign_self;
14400 // - Objective-C externally_retained attribute.
14401 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14402 isa<ParmVarDecl>(var)) {
14403 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14405 // - fast enumeration variables
14406 } else {
14407 DiagID = diag::err_typecheck_arr_assign_enumeration;
14410 SourceRange Assign;
14411 if (Loc != OrigLoc)
14412 Assign = SourceRange(OrigLoc, OrigLoc);
14413 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14414 // We need to preserve the AST regardless, so migration tool
14415 // can do its job.
14416 return false;
14421 // If none of the special cases above are triggered, then this is a
14422 // simple const assignment.
14423 if (DiagID == 0) {
14424 DiagnoseConstAssignment(S, E, Loc);
14425 return true;
14428 break;
14429 case Expr::MLV_ConstAddrSpace:
14430 DiagnoseConstAssignment(S, E, Loc);
14431 return true;
14432 case Expr::MLV_ConstQualifiedField:
14433 DiagnoseRecursiveConstFields(S, E, Loc);
14434 return true;
14435 case Expr::MLV_ArrayType:
14436 case Expr::MLV_ArrayTemporary:
14437 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14438 NeedType = true;
14439 break;
14440 case Expr::MLV_NotObjectType:
14441 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14442 NeedType = true;
14443 break;
14444 case Expr::MLV_LValueCast:
14445 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14446 break;
14447 case Expr::MLV_Valid:
14448 llvm_unreachable("did not take early return for MLV_Valid");
14449 case Expr::MLV_InvalidExpression:
14450 case Expr::MLV_MemberFunction:
14451 case Expr::MLV_ClassTemporary:
14452 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14453 break;
14454 case Expr::MLV_IncompleteType:
14455 case Expr::MLV_IncompleteVoidType:
14456 return S.RequireCompleteType(Loc, E->getType(),
14457 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14458 case Expr::MLV_DuplicateVectorComponents:
14459 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14460 break;
14461 case Expr::MLV_NoSetterProperty:
14462 llvm_unreachable("readonly properties should be processed differently");
14463 case Expr::MLV_InvalidMessageExpression:
14464 DiagID = diag::err_readonly_message_assignment;
14465 break;
14466 case Expr::MLV_SubObjCPropertySetting:
14467 DiagID = diag::err_no_subobject_property_setting;
14468 break;
14471 SourceRange Assign;
14472 if (Loc != OrigLoc)
14473 Assign = SourceRange(OrigLoc, OrigLoc);
14474 if (NeedType)
14475 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14476 else
14477 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14478 return true;
14481 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14482 SourceLocation Loc,
14483 Sema &Sema) {
14484 if (Sema.inTemplateInstantiation())
14485 return;
14486 if (Sema.isUnevaluatedContext())
14487 return;
14488 if (Loc.isInvalid() || Loc.isMacroID())
14489 return;
14490 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14491 return;
14493 // C / C++ fields
14494 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14495 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14496 if (ML && MR) {
14497 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14498 return;
14499 const ValueDecl *LHSDecl =
14500 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14501 const ValueDecl *RHSDecl =
14502 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14503 if (LHSDecl != RHSDecl)
14504 return;
14505 if (LHSDecl->getType().isVolatileQualified())
14506 return;
14507 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14508 if (RefTy->getPointeeType().isVolatileQualified())
14509 return;
14511 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14514 // Objective-C instance variables
14515 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14516 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14517 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14518 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14519 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14520 if (RL && RR && RL->getDecl() == RR->getDecl())
14521 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14525 // C99 6.5.16.1
14526 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14527 SourceLocation Loc,
14528 QualType CompoundType,
14529 BinaryOperatorKind Opc) {
14530 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14532 // Verify that LHS is a modifiable lvalue, and emit error if not.
14533 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14534 return QualType();
14536 QualType LHSType = LHSExpr->getType();
14537 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14538 CompoundType;
14539 // OpenCL v1.2 s6.1.1.1 p2:
14540 // The half data type can only be used to declare a pointer to a buffer that
14541 // contains half values
14542 if (getLangOpts().OpenCL &&
14543 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14544 LHSType->isHalfType()) {
14545 Diag(Loc, diag::err_opencl_half_load_store) << 1
14546 << LHSType.getUnqualifiedType();
14547 return QualType();
14550 // WebAssembly tables can't be used on RHS of an assignment expression.
14551 if (RHSType->isWebAssemblyTableType()) {
14552 Diag(Loc, diag::err_wasm_table_art) << 0;
14553 return QualType();
14556 AssignConvertType ConvTy;
14557 if (CompoundType.isNull()) {
14558 Expr *RHSCheck = RHS.get();
14560 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14562 QualType LHSTy(LHSType);
14563 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14564 if (RHS.isInvalid())
14565 return QualType();
14566 // Special case of NSObject attributes on c-style pointer types.
14567 if (ConvTy == IncompatiblePointer &&
14568 ((Context.isObjCNSObjectType(LHSType) &&
14569 RHSType->isObjCObjectPointerType()) ||
14570 (Context.isObjCNSObjectType(RHSType) &&
14571 LHSType->isObjCObjectPointerType())))
14572 ConvTy = Compatible;
14574 if (ConvTy == Compatible &&
14575 LHSType->isObjCObjectType())
14576 Diag(Loc, diag::err_objc_object_assignment)
14577 << LHSType;
14579 // If the RHS is a unary plus or minus, check to see if they = and + are
14580 // right next to each other. If so, the user may have typo'd "x =+ 4"
14581 // instead of "x += 4".
14582 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14583 RHSCheck = ICE->getSubExpr();
14584 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14585 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14586 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14587 // Only if the two operators are exactly adjacent.
14588 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14589 // And there is a space or other character before the subexpr of the
14590 // unary +/-. We don't want to warn on "x=-1".
14591 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14592 UO->getSubExpr()->getBeginLoc().isFileID()) {
14593 Diag(Loc, diag::warn_not_compound_assign)
14594 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14595 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14599 if (ConvTy == Compatible) {
14600 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14601 // Warn about retain cycles where a block captures the LHS, but
14602 // not if the LHS is a simple variable into which the block is
14603 // being stored...unless that variable can be captured by reference!
14604 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14605 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14606 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14607 checkRetainCycles(LHSExpr, RHS.get());
14610 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14611 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14612 // It is safe to assign a weak reference into a strong variable.
14613 // Although this code can still have problems:
14614 // id x = self.weakProp;
14615 // id y = self.weakProp;
14616 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14617 // paths through the function. This should be revisited if
14618 // -Wrepeated-use-of-weak is made flow-sensitive.
14619 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14620 // variable, which will be valid for the current autorelease scope.
14621 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14622 RHS.get()->getBeginLoc()))
14623 getCurFunction()->markSafeWeakUse(RHS.get());
14625 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14626 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14629 } else {
14630 // Compound assignment "x += y"
14631 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14634 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
14635 RHS.get(), AA_Assigning))
14636 return QualType();
14638 CheckForNullPointerDereference(*this, LHSExpr);
14640 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14641 if (CompoundType.isNull()) {
14642 // C++2a [expr.ass]p5:
14643 // A simple-assignment whose left operand is of a volatile-qualified
14644 // type is deprecated unless the assignment is either a discarded-value
14645 // expression or an unevaluated operand
14646 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14650 // C11 6.5.16p3: The type of an assignment expression is the type of the
14651 // left operand would have after lvalue conversion.
14652 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14653 // qualified type, the value has the unqualified version of the type of the
14654 // lvalue; additionally, if the lvalue has atomic type, the value has the
14655 // non-atomic version of the type of the lvalue.
14656 // C++ 5.17p1: the type of the assignment expression is that of its left
14657 // operand.
14658 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14661 // Scenarios to ignore if expression E is:
14662 // 1. an explicit cast expression into void
14663 // 2. a function call expression that returns void
14664 static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14665 E = E->IgnoreParens();
14667 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14668 if (CE->getCastKind() == CK_ToVoid) {
14669 return true;
14672 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14673 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14674 CE->getSubExpr()->getType()->isDependentType()) {
14675 return true;
14679 if (const auto *CE = dyn_cast<CallExpr>(E))
14680 return CE->getCallReturnType(Context)->isVoidType();
14681 return false;
14684 // Look for instances where it is likely the comma operator is confused with
14685 // another operator. There is an explicit list of acceptable expressions for
14686 // the left hand side of the comma operator, otherwise emit a warning.
14687 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14688 // No warnings in macros
14689 if (Loc.isMacroID())
14690 return;
14692 // Don't warn in template instantiations.
14693 if (inTemplateInstantiation())
14694 return;
14696 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14697 // instead, skip more than needed, then call back into here with the
14698 // CommaVisitor in SemaStmt.cpp.
14699 // The listed locations are the initialization and increment portions
14700 // of a for loop. The additional checks are on the condition of
14701 // if statements, do/while loops, and for loops.
14702 // Differences in scope flags for C89 mode requires the extra logic.
14703 const unsigned ForIncrementFlags =
14704 getLangOpts().C99 || getLangOpts().CPlusPlus
14705 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14706 : Scope::ContinueScope | Scope::BreakScope;
14707 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14708 const unsigned ScopeFlags = getCurScope()->getFlags();
14709 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14710 (ScopeFlags & ForInitFlags) == ForInitFlags)
14711 return;
14713 // If there are multiple comma operators used together, get the RHS of the
14714 // of the comma operator as the LHS.
14715 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14716 if (BO->getOpcode() != BO_Comma)
14717 break;
14718 LHS = BO->getRHS();
14721 // Only allow some expressions on LHS to not warn.
14722 if (IgnoreCommaOperand(LHS, Context))
14723 return;
14725 Diag(Loc, diag::warn_comma_operator);
14726 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14727 << LHS->getSourceRange()
14728 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
14729 LangOpts.CPlusPlus ? "static_cast<void>("
14730 : "(void)(")
14731 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14732 ")");
14735 // C99 6.5.17
14736 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14737 SourceLocation Loc) {
14738 LHS = S.CheckPlaceholderExpr(LHS.get());
14739 RHS = S.CheckPlaceholderExpr(RHS.get());
14740 if (LHS.isInvalid() || RHS.isInvalid())
14741 return QualType();
14743 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14744 // operands, but not unary promotions.
14745 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14747 // So we treat the LHS as a ignored value, and in C++ we allow the
14748 // containing site to determine what should be done with the RHS.
14749 LHS = S.IgnoredValueConversions(LHS.get());
14750 if (LHS.isInvalid())
14751 return QualType();
14753 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14755 if (!S.getLangOpts().CPlusPlus) {
14756 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
14757 if (RHS.isInvalid())
14758 return QualType();
14759 if (!RHS.get()->getType()->isVoidType())
14760 S.RequireCompleteType(Loc, RHS.get()->getType(),
14761 diag::err_incomplete_type);
14764 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14765 S.DiagnoseCommaOperator(LHS.get(), Loc);
14767 return RHS.get()->getType();
14770 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14771 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14772 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14773 ExprValueKind &VK,
14774 ExprObjectKind &OK,
14775 SourceLocation OpLoc,
14776 bool IsInc, bool IsPrefix) {
14777 if (Op->isTypeDependent())
14778 return S.Context.DependentTy;
14780 QualType ResType = Op->getType();
14781 // Atomic types can be used for increment / decrement where the non-atomic
14782 // versions can, so ignore the _Atomic() specifier for the purpose of
14783 // checking.
14784 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14785 ResType = ResAtomicType->getValueType();
14787 assert(!ResType.isNull() && "no type for increment/decrement expression");
14789 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14790 // Decrement of bool is not allowed.
14791 if (!IsInc) {
14792 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14793 return QualType();
14795 // Increment of bool sets it to true, but is deprecated.
14796 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14797 : diag::warn_increment_bool)
14798 << Op->getSourceRange();
14799 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14800 // Error on enum increments and decrements in C++ mode
14801 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14802 return QualType();
14803 } else if (ResType->isRealType()) {
14804 // OK!
14805 } else if (ResType->isPointerType()) {
14806 // C99 6.5.2.4p2, 6.5.6p2
14807 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14808 return QualType();
14809 } else if (ResType->isObjCObjectPointerType()) {
14810 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14811 // Otherwise, we just need a complete type.
14812 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14813 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14814 return QualType();
14815 } else if (ResType->isAnyComplexType()) {
14816 // C99 does not support ++/-- on complex types, we allow as an extension.
14817 S.Diag(OpLoc, diag::ext_integer_increment_complex)
14818 << ResType << Op->getSourceRange();
14819 } else if (ResType->isPlaceholderType()) {
14820 ExprResult PR = S.CheckPlaceholderExpr(Op);
14821 if (PR.isInvalid()) return QualType();
14822 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14823 IsInc, IsPrefix);
14824 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14825 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14826 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14827 (ResType->castAs<VectorType>()->getVectorKind() !=
14828 VectorType::AltiVecBool)) {
14829 // The z vector extensions allow ++ and -- for non-bool vectors.
14830 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14831 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14832 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14833 } else {
14834 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14835 << ResType << int(IsInc) << Op->getSourceRange();
14836 return QualType();
14838 // At this point, we know we have a real, complex or pointer type.
14839 // Now make sure the operand is a modifiable lvalue.
14840 if (CheckForModifiableLvalue(Op, OpLoc, S))
14841 return QualType();
14842 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14843 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14844 // An operand with volatile-qualified type is deprecated
14845 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14846 << IsInc << ResType;
14848 // In C++, a prefix increment is the same type as the operand. Otherwise
14849 // (in C or with postfix), the increment is the unqualified type of the
14850 // operand.
14851 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14852 VK = VK_LValue;
14853 OK = Op->getObjectKind();
14854 return ResType;
14855 } else {
14856 VK = VK_PRValue;
14857 return ResType.getUnqualifiedType();
14862 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14863 /// This routine allows us to typecheck complex/recursive expressions
14864 /// where the declaration is needed for type checking. We only need to
14865 /// handle cases when the expression references a function designator
14866 /// or is an lvalue. Here are some examples:
14867 /// - &(x) => x
14868 /// - &*****f => f for f a function designator.
14869 /// - &s.xx => s
14870 /// - &s.zz[1].yy -> s, if zz is an array
14871 /// - *(x + 1) -> x, if x is an array
14872 /// - &"123"[2] -> 0
14873 /// - & __real__ x -> x
14875 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14876 /// members.
14877 static ValueDecl *getPrimaryDecl(Expr *E) {
14878 switch (E->getStmtClass()) {
14879 case Stmt::DeclRefExprClass:
14880 return cast<DeclRefExpr>(E)->getDecl();
14881 case Stmt::MemberExprClass:
14882 // If this is an arrow operator, the address is an offset from
14883 // the base's value, so the object the base refers to is
14884 // irrelevant.
14885 if (cast<MemberExpr>(E)->isArrow())
14886 return nullptr;
14887 // Otherwise, the expression refers to a part of the base
14888 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14889 case Stmt::ArraySubscriptExprClass: {
14890 // FIXME: This code shouldn't be necessary! We should catch the implicit
14891 // promotion of register arrays earlier.
14892 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14893 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14894 if (ICE->getSubExpr()->getType()->isArrayType())
14895 return getPrimaryDecl(ICE->getSubExpr());
14897 return nullptr;
14899 case Stmt::UnaryOperatorClass: {
14900 UnaryOperator *UO = cast<UnaryOperator>(E);
14902 switch(UO->getOpcode()) {
14903 case UO_Real:
14904 case UO_Imag:
14905 case UO_Extension:
14906 return getPrimaryDecl(UO->getSubExpr());
14907 default:
14908 return nullptr;
14911 case Stmt::ParenExprClass:
14912 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14913 case Stmt::ImplicitCastExprClass:
14914 // If the result of an implicit cast is an l-value, we care about
14915 // the sub-expression; otherwise, the result here doesn't matter.
14916 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14917 case Stmt::CXXUuidofExprClass:
14918 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14919 default:
14920 return nullptr;
14924 namespace {
14925 enum {
14926 AO_Bit_Field = 0,
14927 AO_Vector_Element = 1,
14928 AO_Property_Expansion = 2,
14929 AO_Register_Variable = 3,
14930 AO_Matrix_Element = 4,
14931 AO_No_Error = 5
14934 /// Diagnose invalid operand for address of operations.
14936 /// \param Type The type of operand which cannot have its address taken.
14937 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14938 Expr *E, unsigned Type) {
14939 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14942 /// CheckAddressOfOperand - The operand of & must be either a function
14943 /// designator or an lvalue designating an object. If it is an lvalue, the
14944 /// object cannot be declared with storage class register or be a bit field.
14945 /// Note: The usual conversions are *not* applied to the operand of the &
14946 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14947 /// In C++, the operand might be an overloaded function name, in which case
14948 /// we allow the '&' but retain the overloaded-function type.
14949 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14950 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14951 if (PTy->getKind() == BuiltinType::Overload) {
14952 Expr *E = OrigOp.get()->IgnoreParens();
14953 if (!isa<OverloadExpr>(E)) {
14954 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14955 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14956 << OrigOp.get()->getSourceRange();
14957 return QualType();
14960 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14961 if (isa<UnresolvedMemberExpr>(Ovl))
14962 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14963 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14964 << OrigOp.get()->getSourceRange();
14965 return QualType();
14968 return Context.OverloadTy;
14971 if (PTy->getKind() == BuiltinType::UnknownAny)
14972 return Context.UnknownAnyTy;
14974 if (PTy->getKind() == BuiltinType::BoundMember) {
14975 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14976 << OrigOp.get()->getSourceRange();
14977 return QualType();
14980 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14981 if (OrigOp.isInvalid()) return QualType();
14984 if (OrigOp.get()->isTypeDependent())
14985 return Context.DependentTy;
14987 assert(!OrigOp.get()->hasPlaceholderType());
14989 // Make sure to ignore parentheses in subsequent checks
14990 Expr *op = OrigOp.get()->IgnoreParens();
14992 // In OpenCL captures for blocks called as lambda functions
14993 // are located in the private address space. Blocks used in
14994 // enqueue_kernel can be located in a different address space
14995 // depending on a vendor implementation. Thus preventing
14996 // taking an address of the capture to avoid invalid AS casts.
14997 if (LangOpts.OpenCL) {
14998 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14999 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15000 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
15001 return QualType();
15005 if (getLangOpts().C99) {
15006 // Implement C99-only parts of addressof rules.
15007 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
15008 if (uOp->getOpcode() == UO_Deref)
15009 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15010 // (assuming the deref expression is valid).
15011 return uOp->getSubExpr()->getType();
15013 // Technically, there should be a check for array subscript
15014 // expressions here, but the result of one is always an lvalue anyway.
15016 ValueDecl *dcl = getPrimaryDecl(op);
15018 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
15019 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15020 op->getBeginLoc()))
15021 return QualType();
15023 Expr::LValueClassification lval = op->ClassifyLValue(Context);
15024 unsigned AddressOfError = AO_No_Error;
15026 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15027 bool sfinae = (bool)isSFINAEContext();
15028 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
15029 : diag::ext_typecheck_addrof_temporary)
15030 << op->getType() << op->getSourceRange();
15031 if (sfinae)
15032 return QualType();
15033 // Materialize the temporary as an lvalue so that we can take its address.
15034 OrigOp = op =
15035 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
15036 } else if (isa<ObjCSelectorExpr>(op)) {
15037 return Context.getPointerType(op->getType());
15038 } else if (lval == Expr::LV_MemberFunction) {
15039 // If it's an instance method, make a member pointer.
15040 // The expression must have exactly the form &A::foo.
15042 // If the underlying expression isn't a decl ref, give up.
15043 if (!isa<DeclRefExpr>(op)) {
15044 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15045 << OrigOp.get()->getSourceRange();
15046 return QualType();
15048 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
15049 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
15051 // The id-expression was parenthesized.
15052 if (OrigOp.get() != DRE) {
15053 Diag(OpLoc, diag::err_parens_pointer_member_function)
15054 << OrigOp.get()->getSourceRange();
15056 // The method was named without a qualifier.
15057 } else if (!DRE->getQualifier()) {
15058 if (MD->getParent()->getName().empty())
15059 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15060 << op->getSourceRange();
15061 else {
15062 SmallString<32> Str;
15063 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
15064 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15065 << op->getSourceRange()
15066 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
15070 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
15071 if (isa<CXXDestructorDecl>(MD))
15072 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
15074 QualType MPTy = Context.getMemberPointerType(
15075 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
15076 // Under the MS ABI, lock down the inheritance model now.
15077 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15078 (void)isCompleteType(OpLoc, MPTy);
15079 return MPTy;
15080 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15081 // C99 6.5.3.2p1
15082 // The operand must be either an l-value or a function designator
15083 if (!op->getType()->isFunctionType()) {
15084 // Use a special diagnostic for loads from property references.
15085 if (isa<PseudoObjectExpr>(op)) {
15086 AddressOfError = AO_Property_Expansion;
15087 } else {
15088 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15089 << op->getType() << op->getSourceRange();
15090 return QualType();
15093 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15094 // The operand cannot be a bit-field
15095 AddressOfError = AO_Bit_Field;
15096 } else if (op->getObjectKind() == OK_VectorComponent) {
15097 // The operand cannot be an element of a vector
15098 AddressOfError = AO_Vector_Element;
15099 } else if (op->getObjectKind() == OK_MatrixComponent) {
15100 // The operand cannot be an element of a matrix.
15101 AddressOfError = AO_Matrix_Element;
15102 } else if (dcl) { // C99 6.5.3.2p1
15103 // We have an lvalue with a decl. Make sure the decl is not declared
15104 // with the register storage-class specifier.
15105 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15106 // in C++ it is not error to take address of a register
15107 // variable (c++03 7.1.1P3)
15108 if (vd->getStorageClass() == SC_Register &&
15109 !getLangOpts().CPlusPlus) {
15110 AddressOfError = AO_Register_Variable;
15112 } else if (isa<MSPropertyDecl>(dcl)) {
15113 AddressOfError = AO_Property_Expansion;
15114 } else if (isa<FunctionTemplateDecl>(dcl)) {
15115 return Context.OverloadTy;
15116 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15117 // Okay: we can take the address of a field.
15118 // Could be a pointer to member, though, if there is an explicit
15119 // scope qualifier for the class.
15120 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
15121 DeclContext *Ctx = dcl->getDeclContext();
15122 if (Ctx && Ctx->isRecord()) {
15123 if (dcl->getType()->isReferenceType()) {
15124 Diag(OpLoc,
15125 diag::err_cannot_form_pointer_to_member_of_reference_type)
15126 << dcl->getDeclName() << dcl->getType();
15127 return QualType();
15130 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15131 Ctx = Ctx->getParent();
15133 QualType MPTy = Context.getMemberPointerType(
15134 op->getType(),
15135 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
15136 // Under the MS ABI, lock down the inheritance model now.
15137 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15138 (void)isCompleteType(OpLoc, MPTy);
15139 return MPTy;
15142 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
15143 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
15144 llvm_unreachable("Unknown/unexpected decl type");
15147 if (AddressOfError != AO_No_Error) {
15148 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15149 return QualType();
15152 if (lval == Expr::LV_IncompleteVoidType) {
15153 // Taking the address of a void variable is technically illegal, but we
15154 // allow it in cases which are otherwise valid.
15155 // Example: "extern void x; void* y = &x;".
15156 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15159 // If the operand has type "type", the result has type "pointer to type".
15160 if (op->getType()->isObjCObjectType())
15161 return Context.getObjCObjectPointerType(op->getType());
15163 // Cannot take the address of WebAssembly references or tables.
15164 if (Context.getTargetInfo().getTriple().isWasm()) {
15165 QualType OpTy = op->getType();
15166 if (OpTy.isWebAssemblyReferenceType()) {
15167 Diag(OpLoc, diag::err_wasm_ca_reference)
15168 << 1 << OrigOp.get()->getSourceRange();
15169 return QualType();
15171 if (OpTy->isWebAssemblyTableType()) {
15172 Diag(OpLoc, diag::err_wasm_table_pr)
15173 << 1 << OrigOp.get()->getSourceRange();
15174 return QualType();
15178 CheckAddressOfPackedMember(op);
15180 return Context.getPointerType(op->getType());
15183 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15184 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15185 if (!DRE)
15186 return;
15187 const Decl *D = DRE->getDecl();
15188 if (!D)
15189 return;
15190 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15191 if (!Param)
15192 return;
15193 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15194 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15195 return;
15196 if (FunctionScopeInfo *FD = S.getCurFunction())
15197 FD->ModifiedNonNullParams.insert(Param);
15200 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15201 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15202 SourceLocation OpLoc,
15203 bool IsAfterAmp = false) {
15204 if (Op->isTypeDependent())
15205 return S.Context.DependentTy;
15207 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15208 if (ConvResult.isInvalid())
15209 return QualType();
15210 Op = ConvResult.get();
15211 QualType OpTy = Op->getType();
15212 QualType Result;
15214 if (isa<CXXReinterpretCastExpr>(Op)) {
15215 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15216 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15217 Op->getSourceRange());
15220 if (const PointerType *PT = OpTy->getAs<PointerType>())
15222 Result = PT->getPointeeType();
15224 else if (const ObjCObjectPointerType *OPT =
15225 OpTy->getAs<ObjCObjectPointerType>())
15226 Result = OPT->getPointeeType();
15227 else {
15228 ExprResult PR = S.CheckPlaceholderExpr(Op);
15229 if (PR.isInvalid()) return QualType();
15230 if (PR.get() != Op)
15231 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15234 if (Result.isNull()) {
15235 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15236 << OpTy << Op->getSourceRange();
15237 return QualType();
15240 if (Result->isVoidType()) {
15241 // C++ [expr.unary.op]p1:
15242 // [...] the expression to which [the unary * operator] is applied shall
15243 // be a pointer to an object type, or a pointer to a function type
15244 LangOptions LO = S.getLangOpts();
15245 if (LO.CPlusPlus)
15246 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15247 << OpTy << Op->getSourceRange();
15248 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15249 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15250 << OpTy << Op->getSourceRange();
15253 // Dereferences are usually l-values...
15254 VK = VK_LValue;
15256 // ...except that certain expressions are never l-values in C.
15257 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15258 VK = VK_PRValue;
15260 return Result;
15263 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15264 BinaryOperatorKind Opc;
15265 switch (Kind) {
15266 default: llvm_unreachable("Unknown binop!");
15267 case tok::periodstar: Opc = BO_PtrMemD; break;
15268 case tok::arrowstar: Opc = BO_PtrMemI; break;
15269 case tok::star: Opc = BO_Mul; break;
15270 case tok::slash: Opc = BO_Div; break;
15271 case tok::percent: Opc = BO_Rem; break;
15272 case tok::plus: Opc = BO_Add; break;
15273 case tok::minus: Opc = BO_Sub; break;
15274 case tok::lessless: Opc = BO_Shl; break;
15275 case tok::greatergreater: Opc = BO_Shr; break;
15276 case tok::lessequal: Opc = BO_LE; break;
15277 case tok::less: Opc = BO_LT; break;
15278 case tok::greaterequal: Opc = BO_GE; break;
15279 case tok::greater: Opc = BO_GT; break;
15280 case tok::exclaimequal: Opc = BO_NE; break;
15281 case tok::equalequal: Opc = BO_EQ; break;
15282 case tok::spaceship: Opc = BO_Cmp; break;
15283 case tok::amp: Opc = BO_And; break;
15284 case tok::caret: Opc = BO_Xor; break;
15285 case tok::pipe: Opc = BO_Or; break;
15286 case tok::ampamp: Opc = BO_LAnd; break;
15287 case tok::pipepipe: Opc = BO_LOr; break;
15288 case tok::equal: Opc = BO_Assign; break;
15289 case tok::starequal: Opc = BO_MulAssign; break;
15290 case tok::slashequal: Opc = BO_DivAssign; break;
15291 case tok::percentequal: Opc = BO_RemAssign; break;
15292 case tok::plusequal: Opc = BO_AddAssign; break;
15293 case tok::minusequal: Opc = BO_SubAssign; break;
15294 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15295 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15296 case tok::ampequal: Opc = BO_AndAssign; break;
15297 case tok::caretequal: Opc = BO_XorAssign; break;
15298 case tok::pipeequal: Opc = BO_OrAssign; break;
15299 case tok::comma: Opc = BO_Comma; break;
15301 return Opc;
15304 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15305 tok::TokenKind Kind) {
15306 UnaryOperatorKind Opc;
15307 switch (Kind) {
15308 default: llvm_unreachable("Unknown unary op!");
15309 case tok::plusplus: Opc = UO_PreInc; break;
15310 case tok::minusminus: Opc = UO_PreDec; break;
15311 case tok::amp: Opc = UO_AddrOf; break;
15312 case tok::star: Opc = UO_Deref; break;
15313 case tok::plus: Opc = UO_Plus; break;
15314 case tok::minus: Opc = UO_Minus; break;
15315 case tok::tilde: Opc = UO_Not; break;
15316 case tok::exclaim: Opc = UO_LNot; break;
15317 case tok::kw___real: Opc = UO_Real; break;
15318 case tok::kw___imag: Opc = UO_Imag; break;
15319 case tok::kw___extension__: Opc = UO_Extension; break;
15321 return Opc;
15324 const FieldDecl *
15325 Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15326 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15327 // common for setters.
15328 // struct A {
15329 // int X;
15330 // -void setX(int X) { X = X; }
15331 // +void setX(int X) { this->X = X; }
15332 // };
15334 // Only consider parameters for self assignment fixes.
15335 if (!isa<ParmVarDecl>(SelfAssigned))
15336 return nullptr;
15337 const auto *Method =
15338 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15339 if (!Method)
15340 return nullptr;
15342 const CXXRecordDecl *Parent = Method->getParent();
15343 // In theory this is fixable if the lambda explicitly captures this, but
15344 // that's added complexity that's rarely going to be used.
15345 if (Parent->isLambda())
15346 return nullptr;
15348 // FIXME: Use an actual Lookup operation instead of just traversing fields
15349 // in order to get base class fields.
15350 auto Field =
15351 llvm::find_if(Parent->fields(),
15352 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15353 return F->getDeclName() == Name;
15355 return (Field != Parent->field_end()) ? *Field : nullptr;
15358 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15359 /// This warning suppressed in the event of macro expansions.
15360 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15361 SourceLocation OpLoc, bool IsBuiltin) {
15362 if (S.inTemplateInstantiation())
15363 return;
15364 if (S.isUnevaluatedContext())
15365 return;
15366 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15367 return;
15368 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15369 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15370 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15371 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15372 if (!LHSDeclRef || !RHSDeclRef ||
15373 LHSDeclRef->getLocation().isMacroID() ||
15374 RHSDeclRef->getLocation().isMacroID())
15375 return;
15376 const ValueDecl *LHSDecl =
15377 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15378 const ValueDecl *RHSDecl =
15379 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15380 if (LHSDecl != RHSDecl)
15381 return;
15382 if (LHSDecl->getType().isVolatileQualified())
15383 return;
15384 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15385 if (RefTy->getPointeeType().isVolatileQualified())
15386 return;
15388 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15389 : diag::warn_self_assignment_overloaded)
15390 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15391 << RHSExpr->getSourceRange();
15392 if (const FieldDecl *SelfAssignField =
15393 S.getSelfAssignmentClassMemberCandidate(RHSDecl))
15394 Diag << 1 << SelfAssignField
15395 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15396 else
15397 Diag << 0;
15400 /// Check if a bitwise-& is performed on an Objective-C pointer. This
15401 /// is usually indicative of introspection within the Objective-C pointer.
15402 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15403 SourceLocation OpLoc) {
15404 if (!S.getLangOpts().ObjC)
15405 return;
15407 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15408 const Expr *LHS = L.get();
15409 const Expr *RHS = R.get();
15411 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15412 ObjCPointerExpr = LHS;
15413 OtherExpr = RHS;
15415 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15416 ObjCPointerExpr = RHS;
15417 OtherExpr = LHS;
15420 // This warning is deliberately made very specific to reduce false
15421 // positives with logic that uses '&' for hashing. This logic mainly
15422 // looks for code trying to introspect into tagged pointers, which
15423 // code should generally never do.
15424 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15425 unsigned Diag = diag::warn_objc_pointer_masking;
15426 // Determine if we are introspecting the result of performSelectorXXX.
15427 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15428 // Special case messages to -performSelector and friends, which
15429 // can return non-pointer values boxed in a pointer value.
15430 // Some clients may wish to silence warnings in this subcase.
15431 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15432 Selector S = ME->getSelector();
15433 StringRef SelArg0 = S.getNameForSlot(0);
15434 if (SelArg0.startswith("performSelector"))
15435 Diag = diag::warn_objc_pointer_masking_performSelector;
15438 S.Diag(OpLoc, Diag)
15439 << ObjCPointerExpr->getSourceRange();
15443 static NamedDecl *getDeclFromExpr(Expr *E) {
15444 if (!E)
15445 return nullptr;
15446 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
15447 return DRE->getDecl();
15448 if (auto *ME = dyn_cast<MemberExpr>(E))
15449 return ME->getMemberDecl();
15450 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
15451 return IRE->getDecl();
15452 return nullptr;
15455 // This helper function promotes a binary operator's operands (which are of a
15456 // half vector type) to a vector of floats and then truncates the result to
15457 // a vector of either half or short.
15458 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15459 BinaryOperatorKind Opc, QualType ResultTy,
15460 ExprValueKind VK, ExprObjectKind OK,
15461 bool IsCompAssign, SourceLocation OpLoc,
15462 FPOptionsOverride FPFeatures) {
15463 auto &Context = S.getASTContext();
15464 assert((isVector(ResultTy, Context.HalfTy) ||
15465 isVector(ResultTy, Context.ShortTy)) &&
15466 "Result must be a vector of half or short");
15467 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15468 isVector(RHS.get()->getType(), Context.HalfTy) &&
15469 "both operands expected to be a half vector");
15471 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15472 QualType BinOpResTy = RHS.get()->getType();
15474 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15475 // change BinOpResTy to a vector of ints.
15476 if (isVector(ResultTy, Context.ShortTy))
15477 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15479 if (IsCompAssign)
15480 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15481 ResultTy, VK, OK, OpLoc, FPFeatures,
15482 BinOpResTy, BinOpResTy);
15484 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15485 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15486 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15487 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15490 static std::pair<ExprResult, ExprResult>
15491 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
15492 Expr *RHSExpr) {
15493 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15494 if (!S.Context.isDependenceAllowed()) {
15495 // C cannot handle TypoExpr nodes on either side of a binop because it
15496 // doesn't handle dependent types properly, so make sure any TypoExprs have
15497 // been dealt with before checking the operands.
15498 LHS = S.CorrectDelayedTyposInExpr(LHS);
15499 RHS = S.CorrectDelayedTyposInExpr(
15500 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15501 [Opc, LHS](Expr *E) {
15502 if (Opc != BO_Assign)
15503 return ExprResult(E);
15504 // Avoid correcting the RHS to the same Expr as the LHS.
15505 Decl *D = getDeclFromExpr(E);
15506 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
15509 return std::make_pair(LHS, RHS);
15512 /// Returns true if conversion between vectors of halfs and vectors of floats
15513 /// is needed.
15514 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15515 Expr *E0, Expr *E1 = nullptr) {
15516 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15517 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15518 return false;
15520 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15521 QualType Ty = E->IgnoreImplicit()->getType();
15523 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15524 // to vectors of floats. Although the element type of the vectors is __fp16,
15525 // the vectors shouldn't be treated as storage-only types. See the
15526 // discussion here: https://reviews.llvm.org/rG825235c140e7
15527 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15528 if (VT->getVectorKind() == VectorType::NeonVector)
15529 return false;
15530 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15532 return false;
15535 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15538 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
15539 /// operator @p Opc at location @c TokLoc. This routine only supports
15540 /// built-in operations; ActOnBinOp handles overloaded operators.
15541 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15542 BinaryOperatorKind Opc,
15543 Expr *LHSExpr, Expr *RHSExpr) {
15544 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15545 // The syntax only allows initializer lists on the RHS of assignment,
15546 // so we don't need to worry about accepting invalid code for
15547 // non-assignment operators.
15548 // C++11 5.17p9:
15549 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15550 // of x = {} is x = T().
15551 InitializationKind Kind = InitializationKind::CreateDirectList(
15552 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15553 InitializedEntity Entity =
15554 InitializedEntity::InitializeTemporary(LHSExpr->getType());
15555 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15556 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15557 if (Init.isInvalid())
15558 return Init;
15559 RHSExpr = Init.get();
15562 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15563 QualType ResultTy; // Result type of the binary operator.
15564 // The following two variables are used for compound assignment operators
15565 QualType CompLHSTy; // Type of LHS after promotions for computation
15566 QualType CompResultTy; // Type of computation result
15567 ExprValueKind VK = VK_PRValue;
15568 ExprObjectKind OK = OK_Ordinary;
15569 bool ConvertHalfVec = false;
15571 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15572 if (!LHS.isUsable() || !RHS.isUsable())
15573 return ExprError();
15575 if (getLangOpts().OpenCL) {
15576 QualType LHSTy = LHSExpr->getType();
15577 QualType RHSTy = RHSExpr->getType();
15578 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15579 // the ATOMIC_VAR_INIT macro.
15580 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15581 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15582 if (BO_Assign == Opc)
15583 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15584 else
15585 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15586 return ExprError();
15589 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15590 // only with a builtin functions and therefore should be disallowed here.
15591 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15592 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15593 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15594 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15595 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15596 return ExprError();
15600 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15601 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15603 switch (Opc) {
15604 case BO_Assign:
15605 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15606 if (getLangOpts().CPlusPlus &&
15607 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15608 VK = LHS.get()->getValueKind();
15609 OK = LHS.get()->getObjectKind();
15611 if (!ResultTy.isNull()) {
15612 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15613 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15615 // Avoid copying a block to the heap if the block is assigned to a local
15616 // auto variable that is declared in the same scope as the block. This
15617 // optimization is unsafe if the local variable is declared in an outer
15618 // scope. For example:
15620 // BlockTy b;
15621 // {
15622 // b = ^{...};
15623 // }
15624 // // It is unsafe to invoke the block here if it wasn't copied to the
15625 // // heap.
15626 // b();
15628 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15629 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15630 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15631 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15632 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15634 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15635 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15636 NTCUC_Assignment, NTCUK_Copy);
15638 RecordModifiableNonNullParam(*this, LHS.get());
15639 break;
15640 case BO_PtrMemD:
15641 case BO_PtrMemI:
15642 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15643 Opc == BO_PtrMemI);
15644 break;
15645 case BO_Mul:
15646 case BO_Div:
15647 ConvertHalfVec = true;
15648 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
15649 Opc == BO_Div);
15650 break;
15651 case BO_Rem:
15652 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15653 break;
15654 case BO_Add:
15655 ConvertHalfVec = true;
15656 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15657 break;
15658 case BO_Sub:
15659 ConvertHalfVec = true;
15660 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
15661 break;
15662 case BO_Shl:
15663 case BO_Shr:
15664 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15665 break;
15666 case BO_LE:
15667 case BO_LT:
15668 case BO_GE:
15669 case BO_GT:
15670 ConvertHalfVec = true;
15671 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15672 break;
15673 case BO_EQ:
15674 case BO_NE:
15675 ConvertHalfVec = true;
15676 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15677 break;
15678 case BO_Cmp:
15679 ConvertHalfVec = true;
15680 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15681 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15682 break;
15683 case BO_And:
15684 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15685 [[fallthrough]];
15686 case BO_Xor:
15687 case BO_Or:
15688 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15689 break;
15690 case BO_LAnd:
15691 case BO_LOr:
15692 ConvertHalfVec = true;
15693 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15694 break;
15695 case BO_MulAssign:
15696 case BO_DivAssign:
15697 ConvertHalfVec = true;
15698 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
15699 Opc == BO_DivAssign);
15700 CompLHSTy = CompResultTy;
15701 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15702 ResultTy =
15703 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15704 break;
15705 case BO_RemAssign:
15706 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15707 CompLHSTy = CompResultTy;
15708 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15709 ResultTy =
15710 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15711 break;
15712 case BO_AddAssign:
15713 ConvertHalfVec = true;
15714 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15715 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15716 ResultTy =
15717 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15718 break;
15719 case BO_SubAssign:
15720 ConvertHalfVec = true;
15721 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
15722 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15723 ResultTy =
15724 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15725 break;
15726 case BO_ShlAssign:
15727 case BO_ShrAssign:
15728 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15729 CompLHSTy = CompResultTy;
15730 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15731 ResultTy =
15732 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15733 break;
15734 case BO_AndAssign:
15735 case BO_OrAssign: // fallthrough
15736 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15737 [[fallthrough]];
15738 case BO_XorAssign:
15739 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15740 CompLHSTy = CompResultTy;
15741 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15742 ResultTy =
15743 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15744 break;
15745 case BO_Comma:
15746 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15747 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15748 VK = RHS.get()->getValueKind();
15749 OK = RHS.get()->getObjectKind();
15751 break;
15753 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15754 return ExprError();
15756 // Some of the binary operations require promoting operands of half vector to
15757 // float vectors and truncating the result back to half vector. For now, we do
15758 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15759 // arm64).
15760 assert(
15761 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15762 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15763 "both sides are half vectors or neither sides are");
15764 ConvertHalfVec =
15765 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15767 // Check for array bounds violations for both sides of the BinaryOperator
15768 CheckArrayAccess(LHS.get());
15769 CheckArrayAccess(RHS.get());
15771 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15772 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15773 &Context.Idents.get("object_setClass"),
15774 SourceLocation(), LookupOrdinaryName);
15775 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15776 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15777 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15778 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
15779 "object_setClass(")
15780 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15781 ",")
15782 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15784 else
15785 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15787 else if (const ObjCIvarRefExpr *OIRE =
15788 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15789 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15791 // Opc is not a compound assignment if CompResultTy is null.
15792 if (CompResultTy.isNull()) {
15793 if (ConvertHalfVec)
15794 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15795 OpLoc, CurFPFeatureOverrides());
15796 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15797 VK, OK, OpLoc, CurFPFeatureOverrides());
15800 // Handle compound assignments.
15801 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15802 OK_ObjCProperty) {
15803 VK = VK_LValue;
15804 OK = LHS.get()->getObjectKind();
15807 // The LHS is not converted to the result type for fixed-point compound
15808 // assignment as the common type is computed on demand. Reset the CompLHSTy
15809 // to the LHS type we would have gotten after unary conversions.
15810 if (CompResultTy->isFixedPointType())
15811 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15813 if (ConvertHalfVec)
15814 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15815 OpLoc, CurFPFeatureOverrides());
15817 return CompoundAssignOperator::Create(
15818 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15819 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15822 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15823 /// operators are mixed in a way that suggests that the programmer forgot that
15824 /// comparison operators have higher precedence. The most typical example of
15825 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15826 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15827 SourceLocation OpLoc, Expr *LHSExpr,
15828 Expr *RHSExpr) {
15829 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15830 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15832 // Check that one of the sides is a comparison operator and the other isn't.
15833 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15834 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15835 if (isLeftComp == isRightComp)
15836 return;
15838 // Bitwise operations are sometimes used as eager logical ops.
15839 // Don't diagnose this.
15840 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15841 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15842 if (isLeftBitwise || isRightBitwise)
15843 return;
15845 SourceRange DiagRange = isLeftComp
15846 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15847 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15848 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15849 SourceRange ParensRange =
15850 isLeftComp
15851 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15852 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15854 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15855 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15856 SuggestParentheses(Self, OpLoc,
15857 Self.PDiag(diag::note_precedence_silence) << OpStr,
15858 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15859 SuggestParentheses(Self, OpLoc,
15860 Self.PDiag(diag::note_precedence_bitwise_first)
15861 << BinaryOperator::getOpcodeStr(Opc),
15862 ParensRange);
15865 /// It accepts a '&&' expr that is inside a '||' one.
15866 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15867 /// in parentheses.
15868 static void
15869 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15870 BinaryOperator *Bop) {
15871 assert(Bop->getOpcode() == BO_LAnd);
15872 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15873 << Bop->getSourceRange() << OpLoc;
15874 SuggestParentheses(Self, Bop->getOperatorLoc(),
15875 Self.PDiag(diag::note_precedence_silence)
15876 << Bop->getOpcodeStr(),
15877 Bop->getSourceRange());
15880 /// Look for '&&' in the left hand of a '||' expr.
15881 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15882 Expr *LHSExpr, Expr *RHSExpr) {
15883 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15884 if (Bop->getOpcode() == BO_LAnd) {
15885 // If it's "string_literal && a || b" don't warn since the precedence
15886 // doesn't matter.
15887 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15888 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15889 } else if (Bop->getOpcode() == BO_LOr) {
15890 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15891 // If it's "a || b && string_literal || c" we didn't warn earlier for
15892 // "a || b && string_literal", but warn now.
15893 if (RBop->getOpcode() == BO_LAnd &&
15894 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15895 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15901 /// Look for '&&' in the right hand of a '||' expr.
15902 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15903 Expr *LHSExpr, Expr *RHSExpr) {
15904 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15905 if (Bop->getOpcode() == BO_LAnd) {
15906 // If it's "a || b && string_literal" don't warn since the precedence
15907 // doesn't matter.
15908 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15909 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15914 /// Look for bitwise op in the left or right hand of a bitwise op with
15915 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15916 /// the '&' expression in parentheses.
15917 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15918 SourceLocation OpLoc, Expr *SubExpr) {
15919 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15920 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15921 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15922 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15923 << Bop->getSourceRange() << OpLoc;
15924 SuggestParentheses(S, Bop->getOperatorLoc(),
15925 S.PDiag(diag::note_precedence_silence)
15926 << Bop->getOpcodeStr(),
15927 Bop->getSourceRange());
15932 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15933 Expr *SubExpr, StringRef Shift) {
15934 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15935 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15936 StringRef Op = Bop->getOpcodeStr();
15937 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15938 << Bop->getSourceRange() << OpLoc << Shift << Op;
15939 SuggestParentheses(S, Bop->getOperatorLoc(),
15940 S.PDiag(diag::note_precedence_silence) << Op,
15941 Bop->getSourceRange());
15946 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15947 Expr *LHSExpr, Expr *RHSExpr) {
15948 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15949 if (!OCE)
15950 return;
15952 FunctionDecl *FD = OCE->getDirectCallee();
15953 if (!FD || !FD->isOverloadedOperator())
15954 return;
15956 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15957 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15958 return;
15960 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15961 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15962 << (Kind == OO_LessLess);
15963 SuggestParentheses(S, OCE->getOperatorLoc(),
15964 S.PDiag(diag::note_precedence_silence)
15965 << (Kind == OO_LessLess ? "<<" : ">>"),
15966 OCE->getSourceRange());
15967 SuggestParentheses(
15968 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15969 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15972 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15973 /// precedence.
15974 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15975 SourceLocation OpLoc, Expr *LHSExpr,
15976 Expr *RHSExpr){
15977 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15978 if (BinaryOperator::isBitwiseOp(Opc))
15979 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15981 // Diagnose "arg1 & arg2 | arg3"
15982 if ((Opc == BO_Or || Opc == BO_Xor) &&
15983 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15984 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15985 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15988 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15989 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15990 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15991 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15992 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15995 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15996 || Opc == BO_Shr) {
15997 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15998 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15999 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
16002 // Warn on overloaded shift operators and comparisons, such as:
16003 // cout << 5 == 4;
16004 if (BinaryOperator::isComparisonOp(Opc))
16005 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
16008 // Binary Operators. 'Tok' is the token for the operator.
16009 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
16010 tok::TokenKind Kind,
16011 Expr *LHSExpr, Expr *RHSExpr) {
16012 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16013 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16014 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16016 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16017 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
16019 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
16022 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
16023 UnresolvedSetImpl &Functions) {
16024 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
16025 if (OverOp != OO_None && OverOp != OO_Equal)
16026 LookupOverloadedOperatorName(OverOp, S, Functions);
16028 // In C++20 onwards, we may have a second operator to look up.
16029 if (getLangOpts().CPlusPlus20) {
16030 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
16031 LookupOverloadedOperatorName(ExtraOp, S, Functions);
16035 /// Build an overloaded binary operator expression in the given scope.
16036 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
16037 BinaryOperatorKind Opc,
16038 Expr *LHS, Expr *RHS) {
16039 switch (Opc) {
16040 case BO_Assign:
16041 // In the non-overloaded case, we warn about self-assignment (x = x) for
16042 // both simple assignment and certain compound assignments where algebra
16043 // tells us the operation yields a constant result. When the operator is
16044 // overloaded, we can't do the latter because we don't want to assume that
16045 // those algebraic identities still apply; for example, a path-building
16046 // library might use operator/= to append paths. But it's still reasonable
16047 // to assume that simple assignment is just moving/copying values around
16048 // and so self-assignment is likely a bug.
16049 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
16050 [[fallthrough]];
16051 case BO_DivAssign:
16052 case BO_RemAssign:
16053 case BO_SubAssign:
16054 case BO_AndAssign:
16055 case BO_OrAssign:
16056 case BO_XorAssign:
16057 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
16058 break;
16059 default:
16060 break;
16063 // Find all of the overloaded operators visible from this point.
16064 UnresolvedSet<16> Functions;
16065 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
16067 // Build the (potentially-overloaded, potentially-dependent)
16068 // binary operation.
16069 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16072 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
16073 BinaryOperatorKind Opc,
16074 Expr *LHSExpr, Expr *RHSExpr) {
16075 ExprResult LHS, RHS;
16076 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
16077 if (!LHS.isUsable() || !RHS.isUsable())
16078 return ExprError();
16079 LHSExpr = LHS.get();
16080 RHSExpr = RHS.get();
16082 // We want to end up calling one of checkPseudoObjectAssignment
16083 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16084 // both expressions are overloadable or either is type-dependent),
16085 // or CreateBuiltinBinOp (in any other case). We also want to get
16086 // any placeholder types out of the way.
16088 // Handle pseudo-objects in the LHS.
16089 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16090 // Assignments with a pseudo-object l-value need special analysis.
16091 if (pty->getKind() == BuiltinType::PseudoObject &&
16092 BinaryOperator::isAssignmentOp(Opc))
16093 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16095 // Don't resolve overloads if the other type is overloadable.
16096 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16097 // We can't actually test that if we still have a placeholder,
16098 // though. Fortunately, none of the exceptions we see in that
16099 // code below are valid when the LHS is an overload set. Note
16100 // that an overload set can be dependently-typed, but it never
16101 // instantiates to having an overloadable type.
16102 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16103 if (resolvedRHS.isInvalid()) return ExprError();
16104 RHSExpr = resolvedRHS.get();
16106 if (RHSExpr->isTypeDependent() ||
16107 RHSExpr->getType()->isOverloadableType())
16108 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16111 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16112 // template, diagnose the missing 'template' keyword instead of diagnosing
16113 // an invalid use of a bound member function.
16115 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16116 // to C++1z [over.over]/1.4, but we already checked for that case above.
16117 if (Opc == BO_LT && inTemplateInstantiation() &&
16118 (pty->getKind() == BuiltinType::BoundMember ||
16119 pty->getKind() == BuiltinType::Overload)) {
16120 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16121 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16122 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16123 return isa<FunctionTemplateDecl>(ND);
16124 })) {
16125 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16126 : OE->getNameLoc(),
16127 diag::err_template_kw_missing)
16128 << OE->getName().getAsString() << "";
16129 return ExprError();
16133 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16134 if (LHS.isInvalid()) return ExprError();
16135 LHSExpr = LHS.get();
16138 // Handle pseudo-objects in the RHS.
16139 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16140 // An overload in the RHS can potentially be resolved by the type
16141 // being assigned to.
16142 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16143 if (getLangOpts().CPlusPlus &&
16144 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16145 LHSExpr->getType()->isOverloadableType()))
16146 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16148 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
16151 // Don't resolve overloads if the other type is overloadable.
16152 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16153 LHSExpr->getType()->isOverloadableType())
16154 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16156 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16157 if (!resolvedRHS.isUsable()) return ExprError();
16158 RHSExpr = resolvedRHS.get();
16161 if (getLangOpts().CPlusPlus) {
16162 // If either expression is type-dependent, always build an
16163 // overloaded op.
16164 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
16165 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16167 // Otherwise, build an overloaded op if either expression has an
16168 // overloadable type.
16169 if (LHSExpr->getType()->isOverloadableType() ||
16170 RHSExpr->getType()->isOverloadableType())
16171 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16174 if (getLangOpts().RecoveryAST &&
16175 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16176 assert(!getLangOpts().CPlusPlus);
16177 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16178 "Should only occur in error-recovery path.");
16179 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16180 // C [6.15.16] p3:
16181 // An assignment expression has the value of the left operand after the
16182 // assignment, but is not an lvalue.
16183 return CompoundAssignOperator::Create(
16184 Context, LHSExpr, RHSExpr, Opc,
16185 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
16186 OpLoc, CurFPFeatureOverrides());
16187 QualType ResultType;
16188 switch (Opc) {
16189 case BO_Assign:
16190 ResultType = LHSExpr->getType().getUnqualifiedType();
16191 break;
16192 case BO_LT:
16193 case BO_GT:
16194 case BO_LE:
16195 case BO_GE:
16196 case BO_EQ:
16197 case BO_NE:
16198 case BO_LAnd:
16199 case BO_LOr:
16200 // These operators have a fixed result type regardless of operands.
16201 ResultType = Context.IntTy;
16202 break;
16203 case BO_Comma:
16204 ResultType = RHSExpr->getType();
16205 break;
16206 default:
16207 ResultType = Context.DependentTy;
16208 break;
16210 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16211 VK_PRValue, OK_Ordinary, OpLoc,
16212 CurFPFeatureOverrides());
16215 // Build a built-in binary operation.
16216 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
16219 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16220 if (T.isNull() || T->isDependentType())
16221 return false;
16223 if (!Ctx.isPromotableIntegerType(T))
16224 return true;
16226 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16229 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16230 UnaryOperatorKind Opc, Expr *InputExpr,
16231 bool IsAfterAmp) {
16232 ExprResult Input = InputExpr;
16233 ExprValueKind VK = VK_PRValue;
16234 ExprObjectKind OK = OK_Ordinary;
16235 QualType resultType;
16236 bool CanOverflow = false;
16238 bool ConvertHalfVec = false;
16239 if (getLangOpts().OpenCL) {
16240 QualType Ty = InputExpr->getType();
16241 // The only legal unary operation for atomics is '&'.
16242 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16243 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16244 // only with a builtin functions and therefore should be disallowed here.
16245 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16246 || Ty->isBlockPointerType())) {
16247 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16248 << InputExpr->getType()
16249 << Input.get()->getSourceRange());
16253 if (getLangOpts().HLSL && OpLoc.isValid()) {
16254 if (Opc == UO_AddrOf)
16255 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16256 if (Opc == UO_Deref)
16257 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16260 switch (Opc) {
16261 case UO_PreInc:
16262 case UO_PreDec:
16263 case UO_PostInc:
16264 case UO_PostDec:
16265 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
16266 OpLoc,
16267 Opc == UO_PreInc ||
16268 Opc == UO_PostInc,
16269 Opc == UO_PreInc ||
16270 Opc == UO_PreDec);
16271 CanOverflow = isOverflowingIntegerType(Context, resultType);
16272 break;
16273 case UO_AddrOf:
16274 resultType = CheckAddressOfOperand(Input, OpLoc);
16275 CheckAddressOfNoDeref(InputExpr);
16276 RecordModifiableNonNullParam(*this, InputExpr);
16277 break;
16278 case UO_Deref: {
16279 Input = DefaultFunctionArrayLvalueConversion(Input.get());
16280 if (Input.isInvalid()) return ExprError();
16281 resultType =
16282 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16283 break;
16285 case UO_Plus:
16286 case UO_Minus:
16287 CanOverflow = Opc == UO_Minus &&
16288 isOverflowingIntegerType(Context, Input.get()->getType());
16289 Input = UsualUnaryConversions(Input.get());
16290 if (Input.isInvalid()) return ExprError();
16291 // Unary plus and minus require promoting an operand of half vector to a
16292 // float vector and truncating the result back to a half vector. For now, we
16293 // do this only when HalfArgsAndReturns is set (that is, when the target is
16294 // arm or arm64).
16295 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16297 // If the operand is a half vector, promote it to a float vector.
16298 if (ConvertHalfVec)
16299 Input = convertVector(Input.get(), Context.FloatTy, *this);
16300 resultType = Input.get()->getType();
16301 if (resultType->isDependentType())
16302 break;
16303 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16304 break;
16305 else if (resultType->isVectorType() &&
16306 // The z vector extensions don't allow + or - with bool vectors.
16307 (!Context.getLangOpts().ZVector ||
16308 resultType->castAs<VectorType>()->getVectorKind() !=
16309 VectorType::AltiVecBool))
16310 break;
16311 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16312 break;
16313 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16314 Opc == UO_Plus &&
16315 resultType->isPointerType())
16316 break;
16318 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16319 << resultType << Input.get()->getSourceRange());
16321 case UO_Not: // bitwise complement
16322 Input = UsualUnaryConversions(Input.get());
16323 if (Input.isInvalid())
16324 return ExprError();
16325 resultType = Input.get()->getType();
16326 if (resultType->isDependentType())
16327 break;
16328 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16329 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16330 // C99 does not support '~' for complex conjugation.
16331 Diag(OpLoc, diag::ext_integer_complement_complex)
16332 << resultType << Input.get()->getSourceRange();
16333 else if (resultType->hasIntegerRepresentation())
16334 break;
16335 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16336 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16337 // on vector float types.
16338 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16339 if (!T->isIntegerType())
16340 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16341 << resultType << Input.get()->getSourceRange());
16342 } else {
16343 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16344 << resultType << Input.get()->getSourceRange());
16346 break;
16348 case UO_LNot: // logical negation
16349 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16350 Input = DefaultFunctionArrayLvalueConversion(Input.get());
16351 if (Input.isInvalid()) return ExprError();
16352 resultType = Input.get()->getType();
16354 // Though we still have to promote half FP to float...
16355 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16356 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
16357 resultType = Context.FloatTy;
16360 // WebAsembly tables can't be used in unary expressions.
16361 if (resultType->isPointerType() &&
16362 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16363 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16364 << resultType << Input.get()->getSourceRange());
16367 if (resultType->isDependentType())
16368 break;
16369 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16370 // C99 6.5.3.3p1: ok, fallthrough;
16371 if (Context.getLangOpts().CPlusPlus) {
16372 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16373 // operand contextually converted to bool.
16374 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16375 ScalarTypeToBooleanCastKind(resultType));
16376 } else if (Context.getLangOpts().OpenCL &&
16377 Context.getLangOpts().OpenCLVersion < 120) {
16378 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16379 // operate on scalar float types.
16380 if (!resultType->isIntegerType() && !resultType->isPointerType())
16381 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16382 << resultType << Input.get()->getSourceRange());
16384 } else if (resultType->isExtVectorType()) {
16385 if (Context.getLangOpts().OpenCL &&
16386 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16387 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16388 // operate on vector float types.
16389 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16390 if (!T->isIntegerType())
16391 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16392 << resultType << Input.get()->getSourceRange());
16394 // Vector logical not returns the signed variant of the operand type.
16395 resultType = GetSignedVectorType(resultType);
16396 break;
16397 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
16398 const VectorType *VTy = resultType->castAs<VectorType>();
16399 if (VTy->getVectorKind() != VectorType::GenericVector)
16400 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16401 << resultType << Input.get()->getSourceRange());
16403 // Vector logical not returns the signed variant of the operand type.
16404 resultType = GetSignedVectorType(resultType);
16405 break;
16406 } else {
16407 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16408 << resultType << Input.get()->getSourceRange());
16411 // LNot always has type int. C99 6.5.3.3p5.
16412 // In C++, it's bool. C++ 5.3.1p8
16413 resultType = Context.getLogicalOperationType();
16414 break;
16415 case UO_Real:
16416 case UO_Imag:
16417 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16418 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
16419 // complex l-values to ordinary l-values and all other values to r-values.
16420 if (Input.isInvalid()) return ExprError();
16421 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16422 if (Input.get()->isGLValue() &&
16423 Input.get()->getObjectKind() == OK_Ordinary)
16424 VK = Input.get()->getValueKind();
16425 } else if (!getLangOpts().CPlusPlus) {
16426 // In C, a volatile scalar is read by __imag. In C++, it is not.
16427 Input = DefaultLvalueConversion(Input.get());
16429 break;
16430 case UO_Extension:
16431 resultType = Input.get()->getType();
16432 VK = Input.get()->getValueKind();
16433 OK = Input.get()->getObjectKind();
16434 break;
16435 case UO_Coawait:
16436 // It's unnecessary to represent the pass-through operator co_await in the
16437 // AST; just return the input expression instead.
16438 assert(!Input.get()->getType()->isDependentType() &&
16439 "the co_await expression must be non-dependant before "
16440 "building operator co_await");
16441 return Input;
16443 if (resultType.isNull() || Input.isInvalid())
16444 return ExprError();
16446 // Check for array bounds violations in the operand of the UnaryOperator,
16447 // except for the '*' and '&' operators that have to be handled specially
16448 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16449 // that are explicitly defined as valid by the standard).
16450 if (Opc != UO_AddrOf && Opc != UO_Deref)
16451 CheckArrayAccess(Input.get());
16453 auto *UO =
16454 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16455 OpLoc, CanOverflow, CurFPFeatureOverrides());
16457 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16458 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16459 !isUnevaluatedContext())
16460 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16462 // Convert the result back to a half vector.
16463 if (ConvertHalfVec)
16464 return convertVector(UO, Context.HalfTy, *this);
16465 return UO;
16468 /// Determine whether the given expression is a qualified member
16469 /// access expression, of a form that could be turned into a pointer to member
16470 /// with the address-of operator.
16471 bool Sema::isQualifiedMemberAccess(Expr *E) {
16472 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16473 if (!DRE->getQualifier())
16474 return false;
16476 ValueDecl *VD = DRE->getDecl();
16477 if (!VD->isCXXClassMember())
16478 return false;
16480 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
16481 return true;
16482 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16483 return Method->isInstance();
16485 return false;
16488 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16489 if (!ULE->getQualifier())
16490 return false;
16492 for (NamedDecl *D : ULE->decls()) {
16493 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16494 if (Method->isInstance())
16495 return true;
16496 } else {
16497 // Overload set does not contain methods.
16498 break;
16502 return false;
16505 return false;
16508 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16509 UnaryOperatorKind Opc, Expr *Input,
16510 bool IsAfterAmp) {
16511 // First things first: handle placeholders so that the
16512 // overloaded-operator check considers the right type.
16513 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16514 // Increment and decrement of pseudo-object references.
16515 if (pty->getKind() == BuiltinType::PseudoObject &&
16516 UnaryOperator::isIncrementDecrementOp(Opc))
16517 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
16519 // extension is always a builtin operator.
16520 if (Opc == UO_Extension)
16521 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16523 // & gets special logic for several kinds of placeholder.
16524 // The builtin code knows what to do.
16525 if (Opc == UO_AddrOf &&
16526 (pty->getKind() == BuiltinType::Overload ||
16527 pty->getKind() == BuiltinType::UnknownAny ||
16528 pty->getKind() == BuiltinType::BoundMember))
16529 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16531 // Anything else needs to be handled now.
16532 ExprResult Result = CheckPlaceholderExpr(Input);
16533 if (Result.isInvalid()) return ExprError();
16534 Input = Result.get();
16537 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16538 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16539 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16540 // Find all of the overloaded operators visible from this point.
16541 UnresolvedSet<16> Functions;
16542 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16543 if (S && OverOp != OO_None)
16544 LookupOverloadedOperatorName(OverOp, S, Functions);
16546 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16549 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16552 // Unary Operators. 'Tok' is the token for the operator.
16553 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16554 Expr *Input, bool IsAfterAmp) {
16555 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16556 IsAfterAmp);
16559 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16560 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16561 LabelDecl *TheDecl) {
16562 TheDecl->markUsed(Context);
16563 // Create the AST node. The address of a label always has type 'void*'.
16564 auto *Res = new (Context) AddrLabelExpr(
16565 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16567 if (getCurFunction())
16568 getCurFunction()->AddrLabels.push_back(Res);
16570 return Res;
16573 void Sema::ActOnStartStmtExpr() {
16574 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
16575 // Make sure we diagnose jumping into a statement expression.
16576 setFunctionHasBranchProtectedScope();
16579 void Sema::ActOnStmtExprError() {
16580 // Note that function is also called by TreeTransform when leaving a
16581 // StmtExpr scope without rebuilding anything.
16583 DiscardCleanupsInEvaluationContext();
16584 PopExpressionEvaluationContext();
16587 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16588 SourceLocation RPLoc) {
16589 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16592 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16593 SourceLocation RPLoc, unsigned TemplateDepth) {
16594 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16595 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16597 if (hasAnyUnrecoverableErrorsInThisFunction())
16598 DiscardCleanupsInEvaluationContext();
16599 assert(!Cleanup.exprNeedsCleanups() &&
16600 "cleanups within StmtExpr not correctly bound!");
16601 PopExpressionEvaluationContext();
16603 // FIXME: there are a variety of strange constraints to enforce here, for
16604 // example, it is not possible to goto into a stmt expression apparently.
16605 // More semantic analysis is needed.
16607 // If there are sub-stmts in the compound stmt, take the type of the last one
16608 // as the type of the stmtexpr.
16609 QualType Ty = Context.VoidTy;
16610 bool StmtExprMayBindToTemp = false;
16611 if (!Compound->body_empty()) {
16612 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16613 if (const auto *LastStmt =
16614 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16615 if (const Expr *Value = LastStmt->getExprStmt()) {
16616 StmtExprMayBindToTemp = true;
16617 Ty = Value->getType();
16622 // FIXME: Check that expression type is complete/non-abstract; statement
16623 // expressions are not lvalues.
16624 Expr *ResStmtExpr =
16625 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16626 if (StmtExprMayBindToTemp)
16627 return MaybeBindToTemporary(ResStmtExpr);
16628 return ResStmtExpr;
16631 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16632 if (ER.isInvalid())
16633 return ExprError();
16635 // Do function/array conversion on the last expression, but not
16636 // lvalue-to-rvalue. However, initialize an unqualified type.
16637 ER = DefaultFunctionArrayConversion(ER.get());
16638 if (ER.isInvalid())
16639 return ExprError();
16640 Expr *E = ER.get();
16642 if (E->isTypeDependent())
16643 return E;
16645 // In ARC, if the final expression ends in a consume, splice
16646 // the consume out and bind it later. In the alternate case
16647 // (when dealing with a retainable type), the result
16648 // initialization will create a produce. In both cases the
16649 // result will be +1, and we'll need to balance that out with
16650 // a bind.
16651 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16652 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16653 return Cast->getSubExpr();
16655 // FIXME: Provide a better location for the initialization.
16656 return PerformCopyInitialization(
16657 InitializedEntity::InitializeStmtExprResult(
16658 E->getBeginLoc(), E->getType().getUnqualifiedType()),
16659 SourceLocation(), E);
16662 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16663 TypeSourceInfo *TInfo,
16664 ArrayRef<OffsetOfComponent> Components,
16665 SourceLocation RParenLoc) {
16666 QualType ArgTy = TInfo->getType();
16667 bool Dependent = ArgTy->isDependentType();
16668 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16670 // We must have at least one component that refers to the type, and the first
16671 // one is known to be a field designator. Verify that the ArgTy represents
16672 // a struct/union/class.
16673 if (!Dependent && !ArgTy->isRecordType())
16674 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16675 << ArgTy << TypeRange);
16677 // Type must be complete per C99 7.17p3 because a declaring a variable
16678 // with an incomplete type would be ill-formed.
16679 if (!Dependent
16680 && RequireCompleteType(BuiltinLoc, ArgTy,
16681 diag::err_offsetof_incomplete_type, TypeRange))
16682 return ExprError();
16684 bool DidWarnAboutNonPOD = false;
16685 QualType CurrentType = ArgTy;
16686 SmallVector<OffsetOfNode, 4> Comps;
16687 SmallVector<Expr*, 4> Exprs;
16688 for (const OffsetOfComponent &OC : Components) {
16689 if (OC.isBrackets) {
16690 // Offset of an array sub-field. TODO: Should we allow vector elements?
16691 if (!CurrentType->isDependentType()) {
16692 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16693 if(!AT)
16694 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16695 << CurrentType);
16696 CurrentType = AT->getElementType();
16697 } else
16698 CurrentType = Context.DependentTy;
16700 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16701 if (IdxRval.isInvalid())
16702 return ExprError();
16703 Expr *Idx = IdxRval.get();
16705 // The expression must be an integral expression.
16706 // FIXME: An integral constant expression?
16707 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16708 !Idx->getType()->isIntegerType())
16709 return ExprError(
16710 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16711 << Idx->getSourceRange());
16713 // Record this array index.
16714 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16715 Exprs.push_back(Idx);
16716 continue;
16719 // Offset of a field.
16720 if (CurrentType->isDependentType()) {
16721 // We have the offset of a field, but we can't look into the dependent
16722 // type. Just record the identifier of the field.
16723 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16724 CurrentType = Context.DependentTy;
16725 continue;
16728 // We need to have a complete type to look into.
16729 if (RequireCompleteType(OC.LocStart, CurrentType,
16730 diag::err_offsetof_incomplete_type))
16731 return ExprError();
16733 // Look for the designated field.
16734 const RecordType *RC = CurrentType->getAs<RecordType>();
16735 if (!RC)
16736 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16737 << CurrentType);
16738 RecordDecl *RD = RC->getDecl();
16740 // C++ [lib.support.types]p5:
16741 // The macro offsetof accepts a restricted set of type arguments in this
16742 // International Standard. type shall be a POD structure or a POD union
16743 // (clause 9).
16744 // C++11 [support.types]p4:
16745 // If type is not a standard-layout class (Clause 9), the results are
16746 // undefined.
16747 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16748 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16749 unsigned DiagID =
16750 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16751 : diag::ext_offsetof_non_pod_type;
16753 if (!IsSafe && !DidWarnAboutNonPOD &&
16754 DiagRuntimeBehavior(BuiltinLoc, nullptr,
16755 PDiag(DiagID)
16756 << SourceRange(Components[0].LocStart, OC.LocEnd)
16757 << CurrentType))
16758 DidWarnAboutNonPOD = true;
16761 // Look for the field.
16762 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16763 LookupQualifiedName(R, RD);
16764 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16765 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16766 if (!MemberDecl) {
16767 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16768 MemberDecl = IndirectMemberDecl->getAnonField();
16771 if (!MemberDecl) {
16772 // Lookup could be ambiguous when looking up a placeholder variable
16773 // __builtin_offsetof(S, _).
16774 // In that case we would already have emitted a diagnostic
16775 if (!R.isAmbiguous())
16776 Diag(BuiltinLoc, diag::err_no_member)
16777 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16778 return ExprError();
16781 // C99 7.17p3:
16782 // (If the specified member is a bit-field, the behavior is undefined.)
16784 // We diagnose this as an error.
16785 if (MemberDecl->isBitField()) {
16786 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16787 << MemberDecl->getDeclName()
16788 << SourceRange(BuiltinLoc, RParenLoc);
16789 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16790 return ExprError();
16793 RecordDecl *Parent = MemberDecl->getParent();
16794 if (IndirectMemberDecl)
16795 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16797 // If the member was found in a base class, introduce OffsetOfNodes for
16798 // the base class indirections.
16799 CXXBasePaths Paths;
16800 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16801 Paths)) {
16802 if (Paths.getDetectedVirtual()) {
16803 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16804 << MemberDecl->getDeclName()
16805 << SourceRange(BuiltinLoc, RParenLoc);
16806 return ExprError();
16809 CXXBasePath &Path = Paths.front();
16810 for (const CXXBasePathElement &B : Path)
16811 Comps.push_back(OffsetOfNode(B.Base));
16814 if (IndirectMemberDecl) {
16815 for (auto *FI : IndirectMemberDecl->chain()) {
16816 assert(isa<FieldDecl>(FI));
16817 Comps.push_back(OffsetOfNode(OC.LocStart,
16818 cast<FieldDecl>(FI), OC.LocEnd));
16820 } else
16821 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16823 CurrentType = MemberDecl->getType().getNonReferenceType();
16826 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16827 Comps, Exprs, RParenLoc);
16830 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16831 SourceLocation BuiltinLoc,
16832 SourceLocation TypeLoc,
16833 ParsedType ParsedArgTy,
16834 ArrayRef<OffsetOfComponent> Components,
16835 SourceLocation RParenLoc) {
16837 TypeSourceInfo *ArgTInfo;
16838 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16839 if (ArgTy.isNull())
16840 return ExprError();
16842 if (!ArgTInfo)
16843 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16845 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16849 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16850 Expr *CondExpr,
16851 Expr *LHSExpr, Expr *RHSExpr,
16852 SourceLocation RPLoc) {
16853 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16855 ExprValueKind VK = VK_PRValue;
16856 ExprObjectKind OK = OK_Ordinary;
16857 QualType resType;
16858 bool CondIsTrue = false;
16859 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16860 resType = Context.DependentTy;
16861 } else {
16862 // The conditional expression is required to be a constant expression.
16863 llvm::APSInt condEval(32);
16864 ExprResult CondICE = VerifyIntegerConstantExpression(
16865 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16866 if (CondICE.isInvalid())
16867 return ExprError();
16868 CondExpr = CondICE.get();
16869 CondIsTrue = condEval.getZExtValue();
16871 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16872 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16874 resType = ActiveExpr->getType();
16875 VK = ActiveExpr->getValueKind();
16876 OK = ActiveExpr->getObjectKind();
16879 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16880 resType, VK, OK, RPLoc, CondIsTrue);
16883 //===----------------------------------------------------------------------===//
16884 // Clang Extensions.
16885 //===----------------------------------------------------------------------===//
16887 /// ActOnBlockStart - This callback is invoked when a block literal is started.
16888 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16889 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16891 if (LangOpts.CPlusPlus) {
16892 MangleNumberingContext *MCtx;
16893 Decl *ManglingContextDecl;
16894 std::tie(MCtx, ManglingContextDecl) =
16895 getCurrentMangleNumberContext(Block->getDeclContext());
16896 if (MCtx) {
16897 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16898 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16902 PushBlockScope(CurScope, Block);
16903 CurContext->addDecl(Block);
16904 if (CurScope)
16905 PushDeclContext(CurScope, Block);
16906 else
16907 CurContext = Block;
16909 getCurBlock()->HasImplicitReturnType = true;
16911 // Enter a new evaluation context to insulate the block from any
16912 // cleanups from the enclosing full-expression.
16913 PushExpressionEvaluationContext(
16914 ExpressionEvaluationContext::PotentiallyEvaluated);
16917 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16918 Scope *CurScope) {
16919 assert(ParamInfo.getIdentifier() == nullptr &&
16920 "block-id should have no identifier!");
16921 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16922 BlockScopeInfo *CurBlock = getCurBlock();
16924 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16925 QualType T = Sig->getType();
16927 // FIXME: We should allow unexpanded parameter packs here, but that would,
16928 // in turn, make the block expression contain unexpanded parameter packs.
16929 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16930 // Drop the parameters.
16931 FunctionProtoType::ExtProtoInfo EPI;
16932 EPI.HasTrailingReturn = false;
16933 EPI.TypeQuals.addConst();
16934 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
16935 Sig = Context.getTrivialTypeSourceInfo(T);
16938 // GetTypeForDeclarator always produces a function type for a block
16939 // literal signature. Furthermore, it is always a FunctionProtoType
16940 // unless the function was written with a typedef.
16941 assert(T->isFunctionType() &&
16942 "GetTypeForDeclarator made a non-function block signature");
16944 // Look for an explicit signature in that function type.
16945 FunctionProtoTypeLoc ExplicitSignature;
16947 if ((ExplicitSignature = Sig->getTypeLoc()
16948 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16950 // Check whether that explicit signature was synthesized by
16951 // GetTypeForDeclarator. If so, don't save that as part of the
16952 // written signature.
16953 if (ExplicitSignature.getLocalRangeBegin() ==
16954 ExplicitSignature.getLocalRangeEnd()) {
16955 // This would be much cheaper if we stored TypeLocs instead of
16956 // TypeSourceInfos.
16957 TypeLoc Result = ExplicitSignature.getReturnLoc();
16958 unsigned Size = Result.getFullDataSize();
16959 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16960 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16962 ExplicitSignature = FunctionProtoTypeLoc();
16966 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16967 CurBlock->FunctionType = T;
16969 const auto *Fn = T->castAs<FunctionType>();
16970 QualType RetTy = Fn->getReturnType();
16971 bool isVariadic =
16972 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16974 CurBlock->TheDecl->setIsVariadic(isVariadic);
16976 // Context.DependentTy is used as a placeholder for a missing block
16977 // return type. TODO: what should we do with declarators like:
16978 // ^ * { ... }
16979 // If the answer is "apply template argument deduction"....
16980 if (RetTy != Context.DependentTy) {
16981 CurBlock->ReturnType = RetTy;
16982 CurBlock->TheDecl->setBlockMissingReturnType(false);
16983 CurBlock->HasImplicitReturnType = false;
16986 // Push block parameters from the declarator if we had them.
16987 SmallVector<ParmVarDecl*, 8> Params;
16988 if (ExplicitSignature) {
16989 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16990 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16991 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16992 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16993 // Diagnose this as an extension in C17 and earlier.
16994 if (!getLangOpts().C23)
16995 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16997 Params.push_back(Param);
17000 // Fake up parameter variables if we have a typedef, like
17001 // ^ fntype { ... }
17002 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17003 for (const auto &I : Fn->param_types()) {
17004 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
17005 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
17006 Params.push_back(Param);
17010 // Set the parameters on the block decl.
17011 if (!Params.empty()) {
17012 CurBlock->TheDecl->setParams(Params);
17013 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
17014 /*CheckParameterNames=*/false);
17017 // Finally we can process decl attributes.
17018 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
17020 // Put the parameter variables in scope.
17021 for (auto *AI : CurBlock->TheDecl->parameters()) {
17022 AI->setOwningFunction(CurBlock->TheDecl);
17024 // If this has an identifier, add it to the scope stack.
17025 if (AI->getIdentifier()) {
17026 CheckShadow(CurBlock->TheScope, AI);
17028 PushOnScopeChains(AI, CurBlock->TheScope);
17031 if (AI->isInvalidDecl())
17032 CurBlock->TheDecl->setInvalidDecl();
17036 /// ActOnBlockError - If there is an error parsing a block, this callback
17037 /// is invoked to pop the information about the block from the action impl.
17038 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17039 // Leave the expression-evaluation context.
17040 DiscardCleanupsInEvaluationContext();
17041 PopExpressionEvaluationContext();
17043 // Pop off CurBlock, handle nested blocks.
17044 PopDeclContext();
17045 PopFunctionScopeInfo();
17048 /// ActOnBlockStmtExpr - This is called when the body of a block statement
17049 /// literal was successfully completed. ^(int x){...}
17050 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
17051 Stmt *Body, Scope *CurScope) {
17052 // If blocks are disabled, emit an error.
17053 if (!LangOpts.Blocks)
17054 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
17056 // Leave the expression-evaluation context.
17057 if (hasAnyUnrecoverableErrorsInThisFunction())
17058 DiscardCleanupsInEvaluationContext();
17059 assert(!Cleanup.exprNeedsCleanups() &&
17060 "cleanups within block not correctly bound!");
17061 PopExpressionEvaluationContext();
17063 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
17064 BlockDecl *BD = BSI->TheDecl;
17066 if (BSI->HasImplicitReturnType)
17067 deduceClosureReturnType(*BSI);
17069 QualType RetTy = Context.VoidTy;
17070 if (!BSI->ReturnType.isNull())
17071 RetTy = BSI->ReturnType;
17073 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17074 QualType BlockTy;
17076 // If the user wrote a function type in some form, try to use that.
17077 if (!BSI->FunctionType.isNull()) {
17078 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17080 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17081 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17083 // Turn protoless block types into nullary block types.
17084 if (isa<FunctionNoProtoType>(FTy)) {
17085 FunctionProtoType::ExtProtoInfo EPI;
17086 EPI.ExtInfo = Ext;
17087 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
17089 // Otherwise, if we don't need to change anything about the function type,
17090 // preserve its sugar structure.
17091 } else if (FTy->getReturnType() == RetTy &&
17092 (!NoReturn || FTy->getNoReturnAttr())) {
17093 BlockTy = BSI->FunctionType;
17095 // Otherwise, make the minimal modifications to the function type.
17096 } else {
17097 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
17098 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
17099 EPI.TypeQuals = Qualifiers();
17100 EPI.ExtInfo = Ext;
17101 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17104 // If we don't have a function type, just build one from nothing.
17105 } else {
17106 FunctionProtoType::ExtProtoInfo EPI;
17107 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17108 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
17111 DiagnoseUnusedParameters(BD->parameters());
17112 BlockTy = Context.getBlockPointerType(BlockTy);
17114 // If needed, diagnose invalid gotos and switches in the block.
17115 if (getCurFunction()->NeedsScopeChecking() &&
17116 !PP.isCodeCompletionEnabled())
17117 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
17119 BD->setBody(cast<CompoundStmt>(Body));
17121 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17122 DiagnoseUnguardedAvailabilityViolations(BD);
17124 // Try to apply the named return value optimization. We have to check again
17125 // if we can do this, though, because blocks keep return statements around
17126 // to deduce an implicit return type.
17127 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17128 !BD->isDependentContext())
17129 computeNRVO(Body, BSI);
17131 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17132 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17133 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
17134 NTCUK_Destruct|NTCUK_Copy);
17136 PopDeclContext();
17138 // Set the captured variables on the block.
17139 SmallVector<BlockDecl::Capture, 4> Captures;
17140 for (Capture &Cap : BSI->Captures) {
17141 if (Cap.isInvalid() || Cap.isThisCapture())
17142 continue;
17143 // Cap.getVariable() is always a VarDecl because
17144 // blocks cannot capture structured bindings or other ValueDecl kinds.
17145 auto *Var = cast<VarDecl>(Cap.getVariable());
17146 Expr *CopyExpr = nullptr;
17147 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17148 if (const RecordType *Record =
17149 Cap.getCaptureType()->getAs<RecordType>()) {
17150 // The capture logic needs the destructor, so make sure we mark it.
17151 // Usually this is unnecessary because most local variables have
17152 // their destructors marked at declaration time, but parameters are
17153 // an exception because it's technically only the call site that
17154 // actually requires the destructor.
17155 if (isa<ParmVarDecl>(Var))
17156 FinalizeVarWithDestructor(Var, Record);
17158 // Enter a separate potentially-evaluated context while building block
17159 // initializers to isolate their cleanups from those of the block
17160 // itself.
17161 // FIXME: Is this appropriate even when the block itself occurs in an
17162 // unevaluated operand?
17163 EnterExpressionEvaluationContext EvalContext(
17164 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17166 SourceLocation Loc = Cap.getLocation();
17168 ExprResult Result = BuildDeclarationNameExpr(
17169 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17171 // According to the blocks spec, the capture of a variable from
17172 // the stack requires a const copy constructor. This is not true
17173 // of the copy/move done to move a __block variable to the heap.
17174 if (!Result.isInvalid() &&
17175 !Result.get()->getType().isConstQualified()) {
17176 Result = ImpCastExprToType(Result.get(),
17177 Result.get()->getType().withConst(),
17178 CK_NoOp, VK_LValue);
17181 if (!Result.isInvalid()) {
17182 Result = PerformCopyInitialization(
17183 InitializedEntity::InitializeBlock(Var->getLocation(),
17184 Cap.getCaptureType()),
17185 Loc, Result.get());
17188 // Build a full-expression copy expression if initialization
17189 // succeeded and used a non-trivial constructor. Recover from
17190 // errors by pretending that the copy isn't necessary.
17191 if (!Result.isInvalid() &&
17192 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17193 ->isTrivial()) {
17194 Result = MaybeCreateExprWithCleanups(Result);
17195 CopyExpr = Result.get();
17200 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17201 CopyExpr);
17202 Captures.push_back(NewCap);
17204 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17206 // Pop the block scope now but keep it alive to the end of this function.
17207 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
17208 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17210 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
17212 // If the block isn't obviously global, i.e. it captures anything at
17213 // all, then we need to do a few things in the surrounding context:
17214 if (Result->getBlockDecl()->hasCaptures()) {
17215 // First, this expression has a new cleanup object.
17216 ExprCleanupObjects.push_back(Result->getBlockDecl());
17217 Cleanup.setExprNeedsCleanups(true);
17219 // It also gets a branch-protected scope if any of the captured
17220 // variables needs destruction.
17221 for (const auto &CI : Result->getBlockDecl()->captures()) {
17222 const VarDecl *var = CI.getVariable();
17223 if (var->getType().isDestructedType() != QualType::DK_none) {
17224 setFunctionHasBranchProtectedScope();
17225 break;
17230 if (getCurFunction())
17231 getCurFunction()->addBlock(BD);
17233 if (BD->isInvalidDecl())
17234 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17235 {Result}, Result->getType());
17236 return Result;
17239 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17240 SourceLocation RPLoc) {
17241 TypeSourceInfo *TInfo;
17242 GetTypeFromParser(Ty, &TInfo);
17243 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17246 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17247 Expr *E, TypeSourceInfo *TInfo,
17248 SourceLocation RPLoc) {
17249 Expr *OrigExpr = E;
17250 bool IsMS = false;
17252 // CUDA device code does not support varargs.
17253 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17254 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17255 CUDAFunctionTarget T = IdentifyCUDATarget(F);
17256 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
17257 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17261 // NVPTX does not support va_arg expression.
17262 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17263 Context.getTargetInfo().getTriple().isNVPTX())
17264 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17266 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17267 // as Microsoft ABI on an actual Microsoft platform, where
17268 // __builtin_ms_va_list and __builtin_va_list are the same.)
17269 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17270 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17271 QualType MSVaListType = Context.getBuiltinMSVaListType();
17272 if (Context.hasSameType(MSVaListType, E->getType())) {
17273 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17274 return ExprError();
17275 IsMS = true;
17279 // Get the va_list type
17280 QualType VaListType = Context.getBuiltinVaListType();
17281 if (!IsMS) {
17282 if (VaListType->isArrayType()) {
17283 // Deal with implicit array decay; for example, on x86-64,
17284 // va_list is an array, but it's supposed to decay to
17285 // a pointer for va_arg.
17286 VaListType = Context.getArrayDecayedType(VaListType);
17287 // Make sure the input expression also decays appropriately.
17288 ExprResult Result = UsualUnaryConversions(E);
17289 if (Result.isInvalid())
17290 return ExprError();
17291 E = Result.get();
17292 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17293 // If va_list is a record type and we are compiling in C++ mode,
17294 // check the argument using reference binding.
17295 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17296 Context, Context.getLValueReferenceType(VaListType), false);
17297 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
17298 if (Init.isInvalid())
17299 return ExprError();
17300 E = Init.getAs<Expr>();
17301 } else {
17302 // Otherwise, the va_list argument must be an l-value because
17303 // it is modified by va_arg.
17304 if (!E->isTypeDependent() &&
17305 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17306 return ExprError();
17310 if (!IsMS && !E->isTypeDependent() &&
17311 !Context.hasSameType(VaListType, E->getType()))
17312 return ExprError(
17313 Diag(E->getBeginLoc(),
17314 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17315 << OrigExpr->getType() << E->getSourceRange());
17317 if (!TInfo->getType()->isDependentType()) {
17318 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17319 diag::err_second_parameter_to_va_arg_incomplete,
17320 TInfo->getTypeLoc()))
17321 return ExprError();
17323 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
17324 TInfo->getType(),
17325 diag::err_second_parameter_to_va_arg_abstract,
17326 TInfo->getTypeLoc()))
17327 return ExprError();
17329 if (!TInfo->getType().isPODType(Context)) {
17330 Diag(TInfo->getTypeLoc().getBeginLoc(),
17331 TInfo->getType()->isObjCLifetimeType()
17332 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17333 : diag::warn_second_parameter_to_va_arg_not_pod)
17334 << TInfo->getType()
17335 << TInfo->getTypeLoc().getSourceRange();
17338 // Check for va_arg where arguments of the given type will be promoted
17339 // (i.e. this va_arg is guaranteed to have undefined behavior).
17340 QualType PromoteType;
17341 if (Context.isPromotableIntegerType(TInfo->getType())) {
17342 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17343 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17344 // and C23 7.16.1.1p2 says, in part:
17345 // If type is not compatible with the type of the actual next argument
17346 // (as promoted according to the default argument promotions), the
17347 // behavior is undefined, except for the following cases:
17348 // - both types are pointers to qualified or unqualified versions of
17349 // compatible types;
17350 // - one type is compatible with a signed integer type, the other
17351 // type is compatible with the corresponding unsigned integer type,
17352 // and the value is representable in both types;
17353 // - one type is pointer to qualified or unqualified void and the
17354 // other is a pointer to a qualified or unqualified character type;
17355 // - or, the type of the next argument is nullptr_t and type is a
17356 // pointer type that has the same representation and alignment
17357 // requirements as a pointer to a character type.
17358 // Given that type compatibility is the primary requirement (ignoring
17359 // qualifications), you would think we could call typesAreCompatible()
17360 // directly to test this. However, in C++, that checks for *same type*,
17361 // which causes false positives when passing an enumeration type to
17362 // va_arg. Instead, get the underlying type of the enumeration and pass
17363 // that.
17364 QualType UnderlyingType = TInfo->getType();
17365 if (const auto *ET = UnderlyingType->getAs<EnumType>())
17366 UnderlyingType = ET->getDecl()->getIntegerType();
17367 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17368 /*CompareUnqualified*/ true))
17369 PromoteType = QualType();
17371 // If the types are still not compatible, we need to test whether the
17372 // promoted type and the underlying type are the same except for
17373 // signedness. Ask the AST for the correctly corresponding type and see
17374 // if that's compatible.
17375 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17376 PromoteType->isUnsignedIntegerType() !=
17377 UnderlyingType->isUnsignedIntegerType()) {
17378 UnderlyingType =
17379 UnderlyingType->isUnsignedIntegerType()
17380 ? Context.getCorrespondingSignedType(UnderlyingType)
17381 : Context.getCorrespondingUnsignedType(UnderlyingType);
17382 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17383 /*CompareUnqualified*/ true))
17384 PromoteType = QualType();
17387 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17388 PromoteType = Context.DoubleTy;
17389 if (!PromoteType.isNull())
17390 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
17391 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17392 << TInfo->getType()
17393 << PromoteType
17394 << TInfo->getTypeLoc().getSourceRange());
17397 QualType T = TInfo->getType().getNonLValueExprType(Context);
17398 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17401 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17402 // The type of __null will be int or long, depending on the size of
17403 // pointers on the target.
17404 QualType Ty;
17405 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17406 if (pw == Context.getTargetInfo().getIntWidth())
17407 Ty = Context.IntTy;
17408 else if (pw == Context.getTargetInfo().getLongWidth())
17409 Ty = Context.LongTy;
17410 else if (pw == Context.getTargetInfo().getLongLongWidth())
17411 Ty = Context.LongLongTy;
17412 else {
17413 llvm_unreachable("I don't know size of pointer!");
17416 return new (Context) GNUNullExpr(Ty, TokenLoc);
17419 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17420 CXXRecordDecl *ImplDecl = nullptr;
17422 // Fetch the std::source_location::__impl decl.
17423 if (NamespaceDecl *Std = S.getStdNamespace()) {
17424 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17425 Loc, Sema::LookupOrdinaryName);
17426 if (S.LookupQualifiedName(ResultSL, Std)) {
17427 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17428 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17429 Loc, Sema::LookupOrdinaryName);
17430 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17431 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17432 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17438 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17439 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17440 return nullptr;
17443 // Verify that __impl is a trivial struct type, with no base classes, and with
17444 // only the four expected fields.
17445 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17446 ImplDecl->getNumBases() != 0) {
17447 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17448 return nullptr;
17451 unsigned Count = 0;
17452 for (FieldDecl *F : ImplDecl->fields()) {
17453 StringRef Name = F->getName();
17455 if (Name == "_M_file_name") {
17456 if (F->getType() !=
17457 S.Context.getPointerType(S.Context.CharTy.withConst()))
17458 break;
17459 Count++;
17460 } else if (Name == "_M_function_name") {
17461 if (F->getType() !=
17462 S.Context.getPointerType(S.Context.CharTy.withConst()))
17463 break;
17464 Count++;
17465 } else if (Name == "_M_line") {
17466 if (!F->getType()->isIntegerType())
17467 break;
17468 Count++;
17469 } else if (Name == "_M_column") {
17470 if (!F->getType()->isIntegerType())
17471 break;
17472 Count++;
17473 } else {
17474 Count = 100; // invalid
17475 break;
17478 if (Count != 4) {
17479 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17480 return nullptr;
17483 return ImplDecl;
17486 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
17487 SourceLocation BuiltinLoc,
17488 SourceLocation RPLoc) {
17489 QualType ResultTy;
17490 switch (Kind) {
17491 case SourceLocExpr::File:
17492 case SourceLocExpr::FileName:
17493 case SourceLocExpr::Function:
17494 case SourceLocExpr::FuncSig: {
17495 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17496 ResultTy =
17497 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17498 break;
17500 case SourceLocExpr::Line:
17501 case SourceLocExpr::Column:
17502 ResultTy = Context.UnsignedIntTy;
17503 break;
17504 case SourceLocExpr::SourceLocStruct:
17505 if (!StdSourceLocationImplDecl) {
17506 StdSourceLocationImplDecl =
17507 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17508 if (!StdSourceLocationImplDecl)
17509 return ExprError();
17511 ResultTy = Context.getPointerType(
17512 Context.getRecordType(StdSourceLocationImplDecl).withConst());
17513 break;
17516 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17519 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
17520 QualType ResultTy,
17521 SourceLocation BuiltinLoc,
17522 SourceLocation RPLoc,
17523 DeclContext *ParentContext) {
17524 return new (Context)
17525 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17528 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
17529 bool Diagnose) {
17530 if (!getLangOpts().ObjC)
17531 return false;
17533 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
17534 if (!PT)
17535 return false;
17536 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
17538 // Ignore any parens, implicit casts (should only be
17539 // array-to-pointer decays), and not-so-opaque values. The last is
17540 // important for making this trigger for property assignments.
17541 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
17542 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
17543 if (OV->getSourceExpr())
17544 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
17546 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
17547 if (!PT->isObjCIdType() &&
17548 !(ID && ID->getIdentifier()->isStr("NSString")))
17549 return false;
17550 if (!SL->isOrdinary())
17551 return false;
17553 if (Diagnose) {
17554 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
17555 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
17556 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
17558 return true;
17561 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
17562 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
17563 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
17564 !SrcExpr->isNullPointerConstant(
17565 getASTContext(), Expr::NPC_NeverValueDependent)) {
17566 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
17567 return false;
17568 if (Diagnose) {
17569 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
17570 << /*number*/1
17571 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
17572 Expr *NumLit =
17573 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
17574 if (NumLit)
17575 Exp = NumLit;
17577 return true;
17580 return false;
17583 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17584 const Expr *SrcExpr) {
17585 if (!DstType->isFunctionPointerType() ||
17586 !SrcExpr->getType()->isFunctionType())
17587 return false;
17589 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17590 if (!DRE)
17591 return false;
17593 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17594 if (!FD)
17595 return false;
17597 return !S.checkAddressOfFunctionIsAvailable(FD,
17598 /*Complain=*/true,
17599 SrcExpr->getBeginLoc());
17602 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17603 SourceLocation Loc,
17604 QualType DstType, QualType SrcType,
17605 Expr *SrcExpr, AssignmentAction Action,
17606 bool *Complained) {
17607 if (Complained)
17608 *Complained = false;
17610 // Decode the result (notice that AST's are still created for extensions).
17611 bool CheckInferredResultType = false;
17612 bool isInvalid = false;
17613 unsigned DiagKind = 0;
17614 ConversionFixItGenerator ConvHints;
17615 bool MayHaveConvFixit = false;
17616 bool MayHaveFunctionDiff = false;
17617 const ObjCInterfaceDecl *IFace = nullptr;
17618 const ObjCProtocolDecl *PDecl = nullptr;
17620 switch (ConvTy) {
17621 case Compatible:
17622 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17623 return false;
17625 case PointerToInt:
17626 if (getLangOpts().CPlusPlus) {
17627 DiagKind = diag::err_typecheck_convert_pointer_int;
17628 isInvalid = true;
17629 } else {
17630 DiagKind = diag::ext_typecheck_convert_pointer_int;
17632 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17633 MayHaveConvFixit = true;
17634 break;
17635 case IntToPointer:
17636 if (getLangOpts().CPlusPlus) {
17637 DiagKind = diag::err_typecheck_convert_int_pointer;
17638 isInvalid = true;
17639 } else {
17640 DiagKind = diag::ext_typecheck_convert_int_pointer;
17642 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17643 MayHaveConvFixit = true;
17644 break;
17645 case IncompatibleFunctionPointerStrict:
17646 DiagKind =
17647 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17648 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17649 MayHaveConvFixit = true;
17650 break;
17651 case IncompatibleFunctionPointer:
17652 if (getLangOpts().CPlusPlus) {
17653 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17654 isInvalid = true;
17655 } else {
17656 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17658 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17659 MayHaveConvFixit = true;
17660 break;
17661 case IncompatiblePointer:
17662 if (Action == AA_Passing_CFAudited) {
17663 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17664 } else if (getLangOpts().CPlusPlus) {
17665 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17666 isInvalid = true;
17667 } else {
17668 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17670 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17671 SrcType->isObjCObjectPointerType();
17672 if (!CheckInferredResultType) {
17673 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17674 } else if (CheckInferredResultType) {
17675 SrcType = SrcType.getUnqualifiedType();
17676 DstType = DstType.getUnqualifiedType();
17678 MayHaveConvFixit = true;
17679 break;
17680 case IncompatiblePointerSign:
17681 if (getLangOpts().CPlusPlus) {
17682 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17683 isInvalid = true;
17684 } else {
17685 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17687 break;
17688 case FunctionVoidPointer:
17689 if (getLangOpts().CPlusPlus) {
17690 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17691 isInvalid = true;
17692 } else {
17693 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17695 break;
17696 case IncompatiblePointerDiscardsQualifiers: {
17697 // Perform array-to-pointer decay if necessary.
17698 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17700 isInvalid = true;
17702 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17703 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17704 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17705 DiagKind = diag::err_typecheck_incompatible_address_space;
17706 break;
17708 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17709 DiagKind = diag::err_typecheck_incompatible_ownership;
17710 break;
17713 llvm_unreachable("unknown error case for discarding qualifiers!");
17714 // fallthrough
17716 case CompatiblePointerDiscardsQualifiers:
17717 // If the qualifiers lost were because we were applying the
17718 // (deprecated) C++ conversion from a string literal to a char*
17719 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17720 // Ideally, this check would be performed in
17721 // checkPointerTypesForAssignment. However, that would require a
17722 // bit of refactoring (so that the second argument is an
17723 // expression, rather than a type), which should be done as part
17724 // of a larger effort to fix checkPointerTypesForAssignment for
17725 // C++ semantics.
17726 if (getLangOpts().CPlusPlus &&
17727 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
17728 return false;
17729 if (getLangOpts().CPlusPlus) {
17730 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17731 isInvalid = true;
17732 } else {
17733 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17736 break;
17737 case IncompatibleNestedPointerQualifiers:
17738 if (getLangOpts().CPlusPlus) {
17739 isInvalid = true;
17740 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17741 } else {
17742 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17744 break;
17745 case IncompatibleNestedPointerAddressSpaceMismatch:
17746 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17747 isInvalid = true;
17748 break;
17749 case IntToBlockPointer:
17750 DiagKind = diag::err_int_to_block_pointer;
17751 isInvalid = true;
17752 break;
17753 case IncompatibleBlockPointer:
17754 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17755 isInvalid = true;
17756 break;
17757 case IncompatibleObjCQualifiedId: {
17758 if (SrcType->isObjCQualifiedIdType()) {
17759 const ObjCObjectPointerType *srcOPT =
17760 SrcType->castAs<ObjCObjectPointerType>();
17761 for (auto *srcProto : srcOPT->quals()) {
17762 PDecl = srcProto;
17763 break;
17765 if (const ObjCInterfaceType *IFaceT =
17766 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17767 IFace = IFaceT->getDecl();
17769 else if (DstType->isObjCQualifiedIdType()) {
17770 const ObjCObjectPointerType *dstOPT =
17771 DstType->castAs<ObjCObjectPointerType>();
17772 for (auto *dstProto : dstOPT->quals()) {
17773 PDecl = dstProto;
17774 break;
17776 if (const ObjCInterfaceType *IFaceT =
17777 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17778 IFace = IFaceT->getDecl();
17780 if (getLangOpts().CPlusPlus) {
17781 DiagKind = diag::err_incompatible_qualified_id;
17782 isInvalid = true;
17783 } else {
17784 DiagKind = diag::warn_incompatible_qualified_id;
17786 break;
17788 case IncompatibleVectors:
17789 if (getLangOpts().CPlusPlus) {
17790 DiagKind = diag::err_incompatible_vectors;
17791 isInvalid = true;
17792 } else {
17793 DiagKind = diag::warn_incompatible_vectors;
17795 break;
17796 case IncompatibleObjCWeakRef:
17797 DiagKind = diag::err_arc_weak_unavailable_assign;
17798 isInvalid = true;
17799 break;
17800 case Incompatible:
17801 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17802 if (Complained)
17803 *Complained = true;
17804 return true;
17807 DiagKind = diag::err_typecheck_convert_incompatible;
17808 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17809 MayHaveConvFixit = true;
17810 isInvalid = true;
17811 MayHaveFunctionDiff = true;
17812 break;
17815 QualType FirstType, SecondType;
17816 switch (Action) {
17817 case AA_Assigning:
17818 case AA_Initializing:
17819 // The destination type comes first.
17820 FirstType = DstType;
17821 SecondType = SrcType;
17822 break;
17824 case AA_Returning:
17825 case AA_Passing:
17826 case AA_Passing_CFAudited:
17827 case AA_Converting:
17828 case AA_Sending:
17829 case AA_Casting:
17830 // The source type comes first.
17831 FirstType = SrcType;
17832 SecondType = DstType;
17833 break;
17836 PartialDiagnostic FDiag = PDiag(DiagKind);
17837 AssignmentAction ActionForDiag = Action;
17838 if (Action == AA_Passing_CFAudited)
17839 ActionForDiag = AA_Passing;
17841 FDiag << FirstType << SecondType << ActionForDiag
17842 << SrcExpr->getSourceRange();
17844 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17845 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17846 auto isPlainChar = [](const clang::Type *Type) {
17847 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17848 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17850 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17851 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17854 // If we can fix the conversion, suggest the FixIts.
17855 if (!ConvHints.isNull()) {
17856 for (FixItHint &H : ConvHints.Hints)
17857 FDiag << H;
17860 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17862 if (MayHaveFunctionDiff)
17863 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17865 Diag(Loc, FDiag);
17866 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17867 DiagKind == diag::err_incompatible_qualified_id) &&
17868 PDecl && IFace && !IFace->hasDefinition())
17869 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17870 << IFace << PDecl;
17872 if (SecondType == Context.OverloadTy)
17873 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17874 FirstType, /*TakingAddress=*/true);
17876 if (CheckInferredResultType)
17877 EmitRelatedResultTypeNote(SrcExpr);
17879 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17880 EmitRelatedResultTypeNoteForReturn(DstType);
17882 if (Complained)
17883 *Complained = true;
17884 return isInvalid;
17887 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17888 llvm::APSInt *Result,
17889 AllowFoldKind CanFold) {
17890 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17891 public:
17892 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17893 QualType T) override {
17894 return S.Diag(Loc, diag::err_ice_not_integral)
17895 << T << S.LangOpts.CPlusPlus;
17897 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17898 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17900 } Diagnoser;
17902 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17905 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17906 llvm::APSInt *Result,
17907 unsigned DiagID,
17908 AllowFoldKind CanFold) {
17909 class IDDiagnoser : public VerifyICEDiagnoser {
17910 unsigned DiagID;
17912 public:
17913 IDDiagnoser(unsigned DiagID)
17914 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17916 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17917 return S.Diag(Loc, DiagID);
17919 } Diagnoser(DiagID);
17921 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17924 Sema::SemaDiagnosticBuilder
17925 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17926 QualType T) {
17927 return diagnoseNotICE(S, Loc);
17930 Sema::SemaDiagnosticBuilder
17931 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17932 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17935 ExprResult
17936 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17937 VerifyICEDiagnoser &Diagnoser,
17938 AllowFoldKind CanFold) {
17939 SourceLocation DiagLoc = E->getBeginLoc();
17941 if (getLangOpts().CPlusPlus11) {
17942 // C++11 [expr.const]p5:
17943 // If an expression of literal class type is used in a context where an
17944 // integral constant expression is required, then that class type shall
17945 // have a single non-explicit conversion function to an integral or
17946 // unscoped enumeration type
17947 ExprResult Converted;
17948 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17949 VerifyICEDiagnoser &BaseDiagnoser;
17950 public:
17951 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17952 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17953 BaseDiagnoser.Suppress, true),
17954 BaseDiagnoser(BaseDiagnoser) {}
17956 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17957 QualType T) override {
17958 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17961 SemaDiagnosticBuilder diagnoseIncomplete(
17962 Sema &S, SourceLocation Loc, QualType T) override {
17963 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17966 SemaDiagnosticBuilder diagnoseExplicitConv(
17967 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17968 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17971 SemaDiagnosticBuilder noteExplicitConv(
17972 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17973 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17974 << ConvTy->isEnumeralType() << ConvTy;
17977 SemaDiagnosticBuilder diagnoseAmbiguous(
17978 Sema &S, SourceLocation Loc, QualType T) override {
17979 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17982 SemaDiagnosticBuilder noteAmbiguous(
17983 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17984 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17985 << ConvTy->isEnumeralType() << ConvTy;
17988 SemaDiagnosticBuilder diagnoseConversion(
17989 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17990 llvm_unreachable("conversion functions are permitted");
17992 } ConvertDiagnoser(Diagnoser);
17994 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17995 ConvertDiagnoser);
17996 if (Converted.isInvalid())
17997 return Converted;
17998 E = Converted.get();
17999 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
18000 return ExprError();
18001 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18002 // An ICE must be of integral or unscoped enumeration type.
18003 if (!Diagnoser.Suppress)
18004 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
18005 << E->getSourceRange();
18006 return ExprError();
18009 ExprResult RValueExpr = DefaultLvalueConversion(E);
18010 if (RValueExpr.isInvalid())
18011 return ExprError();
18013 E = RValueExpr.get();
18015 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18016 // in the non-ICE case.
18017 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
18018 if (Result)
18019 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
18020 if (!isa<ConstantExpr>(E))
18021 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
18022 : ConstantExpr::Create(Context, E);
18023 return E;
18026 Expr::EvalResult EvalResult;
18027 SmallVector<PartialDiagnosticAt, 8> Notes;
18028 EvalResult.Diag = &Notes;
18030 // Try to evaluate the expression, and produce diagnostics explaining why it's
18031 // not a constant expression as a side-effect.
18032 bool Folded =
18033 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
18034 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
18036 if (!isa<ConstantExpr>(E))
18037 E = ConstantExpr::Create(Context, E, EvalResult.Val);
18039 // In C++11, we can rely on diagnostics being produced for any expression
18040 // which is not a constant expression. If no diagnostics were produced, then
18041 // this is a constant expression.
18042 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18043 if (Result)
18044 *Result = EvalResult.Val.getInt();
18045 return E;
18048 // If our only note is the usual "invalid subexpression" note, just point
18049 // the caret at its location rather than producing an essentially
18050 // redundant note.
18051 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18052 diag::note_invalid_subexpr_in_const_expr) {
18053 DiagLoc = Notes[0].first;
18054 Notes.clear();
18057 if (!Folded || !CanFold) {
18058 if (!Diagnoser.Suppress) {
18059 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18060 for (const PartialDiagnosticAt &Note : Notes)
18061 Diag(Note.first, Note.second);
18064 return ExprError();
18067 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18068 for (const PartialDiagnosticAt &Note : Notes)
18069 Diag(Note.first, Note.second);
18071 if (Result)
18072 *Result = EvalResult.Val.getInt();
18073 return E;
18076 namespace {
18077 // Handle the case where we conclude a expression which we speculatively
18078 // considered to be unevaluated is actually evaluated.
18079 class TransformToPE : public TreeTransform<TransformToPE> {
18080 typedef TreeTransform<TransformToPE> BaseTransform;
18082 public:
18083 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18085 // Make sure we redo semantic analysis
18086 bool AlwaysRebuild() { return true; }
18087 bool ReplacingOriginal() { return true; }
18089 // We need to special-case DeclRefExprs referring to FieldDecls which
18090 // are not part of a member pointer formation; normal TreeTransforming
18091 // doesn't catch this case because of the way we represent them in the AST.
18092 // FIXME: This is a bit ugly; is it really the best way to handle this
18093 // case?
18095 // Error on DeclRefExprs referring to FieldDecls.
18096 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18097 if (isa<FieldDecl>(E->getDecl()) &&
18098 !SemaRef.isUnevaluatedContext())
18099 return SemaRef.Diag(E->getLocation(),
18100 diag::err_invalid_non_static_member_use)
18101 << E->getDecl() << E->getSourceRange();
18103 return BaseTransform::TransformDeclRefExpr(E);
18106 // Exception: filter out member pointer formation
18107 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18108 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18109 return E;
18111 return BaseTransform::TransformUnaryOperator(E);
18114 // The body of a lambda-expression is in a separate expression evaluation
18115 // context so never needs to be transformed.
18116 // FIXME: Ideally we wouldn't transform the closure type either, and would
18117 // just recreate the capture expressions and lambda expression.
18118 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18119 return SkipLambdaBody(E, Body);
18124 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18125 assert(isUnevaluatedContext() &&
18126 "Should only transform unevaluated expressions");
18127 ExprEvalContexts.back().Context =
18128 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18129 if (isUnevaluatedContext())
18130 return E;
18131 return TransformToPE(*this).TransformExpr(E);
18134 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18135 assert(isUnevaluatedContext() &&
18136 "Should only transform unevaluated expressions");
18137 ExprEvalContexts.back().Context =
18138 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
18139 if (isUnevaluatedContext())
18140 return TInfo;
18141 return TransformToPE(*this).TransformType(TInfo);
18144 void
18145 Sema::PushExpressionEvaluationContext(
18146 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18147 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18148 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18149 LambdaContextDecl, ExprContext);
18151 // Discarded statements and immediate contexts nested in other
18152 // discarded statements or immediate context are themselves
18153 // a discarded statement or an immediate context, respectively.
18154 ExprEvalContexts.back().InDiscardedStatement =
18155 ExprEvalContexts[ExprEvalContexts.size() - 2]
18156 .isDiscardedStatementContext();
18158 // C++23 [expr.const]/p15
18159 // An expression or conversion is in an immediate function context if [...]
18160 // it is a subexpression of a manifestly constant-evaluated expression or
18161 // conversion.
18162 const auto &Prev = ExprEvalContexts[ExprEvalContexts.size() - 2];
18163 ExprEvalContexts.back().InImmediateFunctionContext =
18164 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18166 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18167 Prev.InImmediateEscalatingFunctionContext;
18169 Cleanup.reset();
18170 if (!MaybeODRUseExprs.empty())
18171 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18174 void
18175 Sema::PushExpressionEvaluationContext(
18176 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18177 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18178 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18179 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18182 namespace {
18184 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18185 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18186 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18187 if (E->getOpcode() == UO_Deref)
18188 return CheckPossibleDeref(S, E->getSubExpr());
18189 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18190 return CheckPossibleDeref(S, E->getBase());
18191 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18192 return CheckPossibleDeref(S, E->getBase());
18193 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18194 QualType Inner;
18195 QualType Ty = E->getType();
18196 if (const auto *Ptr = Ty->getAs<PointerType>())
18197 Inner = Ptr->getPointeeType();
18198 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18199 Inner = Arr->getElementType();
18200 else
18201 return nullptr;
18203 if (Inner->hasAttr(attr::NoDeref))
18204 return E;
18206 return nullptr;
18209 } // namespace
18211 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18212 for (const Expr *E : Rec.PossibleDerefs) {
18213 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18214 if (DeclRef) {
18215 const ValueDecl *Decl = DeclRef->getDecl();
18216 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18217 << Decl->getName() << E->getSourceRange();
18218 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18219 } else {
18220 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18221 << E->getSourceRange();
18224 Rec.PossibleDerefs.clear();
18227 /// Check whether E, which is either a discarded-value expression or an
18228 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
18229 /// and if so, remove it from the list of volatile-qualified assignments that
18230 /// we are going to warn are deprecated.
18231 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18232 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18233 return;
18235 // Note: ignoring parens here is not justified by the standard rules, but
18236 // ignoring parentheses seems like a more reasonable approach, and this only
18237 // drives a deprecation warning so doesn't affect conformance.
18238 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18239 if (BO->getOpcode() == BO_Assign) {
18240 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18241 llvm::erase_value(LHSs, BO->getLHS());
18246 void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18247 assert(!FunctionScopes.empty() && "Expected a function scope");
18248 assert(getLangOpts().CPlusPlus20 &&
18249 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18250 "Cannot mark an immediate escalating expression outside of an "
18251 "immediate escalating context");
18252 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18253 Call && Call->getCallee()) {
18254 if (auto *DeclRef =
18255 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18256 DeclRef->setIsImmediateEscalating(true);
18257 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18258 Ctr->setIsImmediateEscalating(true);
18259 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18260 DeclRef->setIsImmediateEscalating(true);
18261 } else {
18262 assert(false && "expected an immediately escalating expression");
18264 getCurFunction()->FoundImmediateEscalatingExpression = true;
18267 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18268 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18269 !Decl->isImmediateFunction() || isConstantEvaluated() ||
18270 isCheckingDefaultArgumentOrInitializer() ||
18271 RebuildingImmediateInvocation || isImmediateFunctionContext())
18272 return E;
18274 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18275 /// It's OK if this fails; we'll also remove this in
18276 /// HandleImmediateInvocations, but catching it here allows us to avoid
18277 /// walking the AST looking for it in simple cases.
18278 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18279 if (auto *DeclRef =
18280 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18281 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18283 // C++23 [expr.const]/p16
18284 // An expression or conversion is immediate-escalating if it is not initially
18285 // in an immediate function context and it is [...] an immediate invocation
18286 // that is not a constant expression and is not a subexpression of an
18287 // immediate invocation.
18288 APValue Cached;
18289 auto CheckConstantExpressionAndKeepResult = [&]() {
18290 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18291 Expr::EvalResult Eval;
18292 Eval.Diag = &Notes;
18293 bool Res = E.get()->EvaluateAsConstantExpr(
18294 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18295 if (Res && Notes.empty()) {
18296 Cached = std::move(Eval.Val);
18297 return true;
18299 return false;
18302 if (!E.get()->isValueDependent() &&
18303 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18304 !CheckConstantExpressionAndKeepResult()) {
18305 MarkExpressionAsImmediateEscalating(E.get());
18306 return E;
18309 if (Cleanup.exprNeedsCleanups()) {
18310 // Since an immediate invocation is a full expression itself - it requires
18311 // an additional ExprWithCleanups node, but it can participate to a bigger
18312 // full expression which actually requires cleanups to be run after so
18313 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18314 // may discard cleanups for outer expression too early.
18316 // Note that ExprWithCleanups created here must always have empty cleanup
18317 // objects:
18318 // - compound literals do not create cleanup objects in C++ and immediate
18319 // invocations are C++-only.
18320 // - blocks are not allowed inside constant expressions and compiler will
18321 // issue an error if they appear there.
18323 // Hence, in correct code any cleanup objects created inside current
18324 // evaluation context must be outside the immediate invocation.
18325 E = ExprWithCleanups::Create(getASTContext(), E.get(),
18326 Cleanup.cleanupsHaveSideEffects(), {});
18329 ConstantExpr *Res = ConstantExpr::Create(
18330 getASTContext(), E.get(),
18331 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18332 getASTContext()),
18333 /*IsImmediateInvocation*/ true);
18334 if (Cached.hasValue())
18335 Res->MoveIntoResult(Cached, getASTContext());
18336 /// Value-dependent constant expressions should not be immediately
18337 /// evaluated until they are instantiated.
18338 if (!Res->isValueDependent())
18339 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18340 return Res;
18343 static void EvaluateAndDiagnoseImmediateInvocation(
18344 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18345 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18346 Expr::EvalResult Eval;
18347 Eval.Diag = &Notes;
18348 ConstantExpr *CE = Candidate.getPointer();
18349 bool Result = CE->EvaluateAsConstantExpr(
18350 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18351 if (!Result || !Notes.empty()) {
18352 SemaRef.FailedImmediateInvocations.insert(CE);
18353 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18354 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18355 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18356 FunctionDecl *FD = nullptr;
18357 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18358 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18359 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18360 FD = Call->getConstructor();
18361 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18362 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18364 assert(FD && FD->isImmediateFunction() &&
18365 "could not find an immediate function in this expression");
18366 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18367 << FD << FD->isConsteval();
18368 if (auto Context =
18369 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18370 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18371 << Context->Decl;
18372 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18374 if (!FD->isConsteval())
18375 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18376 for (auto &Note : Notes)
18377 SemaRef.Diag(Note.first, Note.second);
18378 return;
18380 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
18383 static void RemoveNestedImmediateInvocation(
18384 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18385 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18386 struct ComplexRemove : TreeTransform<ComplexRemove> {
18387 using Base = TreeTransform<ComplexRemove>;
18388 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18389 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18390 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18391 CurrentII;
18392 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18393 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18394 SmallVector<Sema::ImmediateInvocationCandidate,
18395 4>::reverse_iterator Current)
18396 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18397 void RemoveImmediateInvocation(ConstantExpr* E) {
18398 auto It = std::find_if(CurrentII, IISet.rend(),
18399 [E](Sema::ImmediateInvocationCandidate Elem) {
18400 return Elem.getPointer() == E;
18402 // It is possible that some subexpression of the current immediate
18403 // invocation was handled from another expression evaluation context. Do
18404 // not handle the current immediate invocation if some of its
18405 // subexpressions failed before.
18406 if (It == IISet.rend()) {
18407 if (SemaRef.FailedImmediateInvocations.contains(E))
18408 CurrentII->setInt(1);
18409 } else {
18410 It->setInt(1); // Mark as deleted
18413 ExprResult TransformConstantExpr(ConstantExpr *E) {
18414 if (!E->isImmediateInvocation())
18415 return Base::TransformConstantExpr(E);
18416 RemoveImmediateInvocation(E);
18417 return Base::TransformExpr(E->getSubExpr());
18419 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18420 /// we need to remove its DeclRefExpr from the DRSet.
18421 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18422 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18423 return Base::TransformCXXOperatorCallExpr(E);
18425 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
18426 /// here.
18427 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18428 if (!Init)
18429 return Init;
18430 /// ConstantExpr are the first layer of implicit node to be removed so if
18431 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18432 if (auto *CE = dyn_cast<ConstantExpr>(Init))
18433 if (CE->isImmediateInvocation())
18434 RemoveImmediateInvocation(CE);
18435 return Base::TransformInitializer(Init, NotCopyInit);
18437 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18438 DRSet.erase(E);
18439 return E;
18441 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18442 // Do not rebuild lambdas to avoid creating a new type.
18443 // Lambdas have already been processed inside their eval context.
18444 return E;
18446 bool AlwaysRebuild() { return false; }
18447 bool ReplacingOriginal() { return true; }
18448 bool AllowSkippingCXXConstructExpr() {
18449 bool Res = AllowSkippingFirstCXXConstructExpr;
18450 AllowSkippingFirstCXXConstructExpr = true;
18451 return Res;
18453 bool AllowSkippingFirstCXXConstructExpr = true;
18454 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18455 Rec.ImmediateInvocationCandidates, It);
18457 /// CXXConstructExpr with a single argument are getting skipped by
18458 /// TreeTransform in some situtation because they could be implicit. This
18459 /// can only occur for the top-level CXXConstructExpr because it is used
18460 /// nowhere in the expression being transformed therefore will not be rebuilt.
18461 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18462 /// skipping the first CXXConstructExpr.
18463 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18464 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18466 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18467 // The result may not be usable in case of previous compilation errors.
18468 // In this case evaluation of the expression may result in crash so just
18469 // don't do anything further with the result.
18470 if (Res.isUsable()) {
18471 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
18472 It->getPointer()->setSubExpr(Res.get());
18476 static void
18477 HandleImmediateInvocations(Sema &SemaRef,
18478 Sema::ExpressionEvaluationContextRecord &Rec) {
18479 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18480 Rec.ReferenceToConsteval.size() == 0) ||
18481 SemaRef.RebuildingImmediateInvocation)
18482 return;
18484 /// When we have more than 1 ImmediateInvocationCandidates or previously
18485 /// failed immediate invocations, we need to check for nested
18486 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18487 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18488 /// invocation.
18489 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18490 !SemaRef.FailedImmediateInvocations.empty()) {
18492 /// Prevent sema calls during the tree transform from adding pointers that
18493 /// are already in the sets.
18494 llvm::SaveAndRestore DisableIITracking(
18495 SemaRef.RebuildingImmediateInvocation, true);
18497 /// Prevent diagnostic during tree transfrom as they are duplicates
18498 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18500 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18501 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18502 if (!It->getInt())
18503 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18504 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18505 Rec.ReferenceToConsteval.size()) {
18506 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
18507 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18508 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18509 bool VisitDeclRefExpr(DeclRefExpr *E) {
18510 DRSet.erase(E);
18511 return DRSet.size();
18513 } Visitor(Rec.ReferenceToConsteval);
18514 Visitor.TraverseStmt(
18515 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18517 for (auto CE : Rec.ImmediateInvocationCandidates)
18518 if (!CE.getInt())
18519 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
18520 for (auto *DR : Rec.ReferenceToConsteval) {
18521 // If the expression is immediate escalating, it is not an error;
18522 // The outer context itself becomes immediate and further errors,
18523 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18524 if (DR->isImmediateEscalating())
18525 continue;
18526 auto *FD = cast<FunctionDecl>(DR->getDecl());
18527 const NamedDecl *ND = FD;
18528 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18529 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18530 ND = MD->getParent();
18532 // C++23 [expr.const]/p16
18533 // An expression or conversion is immediate-escalating if it is not
18534 // initially in an immediate function context and it is [...] a
18535 // potentially-evaluated id-expression that denotes an immediate function
18536 // that is not a subexpression of an immediate invocation.
18537 bool ImmediateEscalating = false;
18538 bool IsPotentiallyEvaluated =
18539 Rec.Context ==
18540 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18541 Rec.Context ==
18542 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18543 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18544 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18546 if (!Rec.InImmediateEscalatingFunctionContext ||
18547 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18548 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18549 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18550 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18551 if (auto Context =
18552 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18553 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18554 << Context->Decl;
18555 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18557 if (FD->isImmediateEscalating() && !FD->isConsteval())
18558 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18560 } else {
18561 SemaRef.MarkExpressionAsImmediateEscalating(DR);
18566 void Sema::PopExpressionEvaluationContext() {
18567 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18568 unsigned NumTypos = Rec.NumTypos;
18570 if (!Rec.Lambdas.empty()) {
18571 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18572 if (!getLangOpts().CPlusPlus20 &&
18573 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18574 Rec.isUnevaluated() ||
18575 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18576 unsigned D;
18577 if (Rec.isUnevaluated()) {
18578 // C++11 [expr.prim.lambda]p2:
18579 // A lambda-expression shall not appear in an unevaluated operand
18580 // (Clause 5).
18581 D = diag::err_lambda_unevaluated_operand;
18582 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18583 // C++1y [expr.const]p2:
18584 // A conditional-expression e is a core constant expression unless the
18585 // evaluation of e, following the rules of the abstract machine, would
18586 // evaluate [...] a lambda-expression.
18587 D = diag::err_lambda_in_constant_expression;
18588 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18589 // C++17 [expr.prim.lamda]p2:
18590 // A lambda-expression shall not appear [...] in a template-argument.
18591 D = diag::err_lambda_in_invalid_context;
18592 } else
18593 llvm_unreachable("Couldn't infer lambda error message.");
18595 for (const auto *L : Rec.Lambdas)
18596 Diag(L->getBeginLoc(), D);
18600 WarnOnPendingNoDerefs(Rec);
18601 HandleImmediateInvocations(*this, Rec);
18603 // Warn on any volatile-qualified simple-assignments that are not discarded-
18604 // value expressions nor unevaluated operands (those cases get removed from
18605 // this list by CheckUnusedVolatileAssignment).
18606 for (auto *BO : Rec.VolatileAssignmentLHSs)
18607 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18608 << BO->getType();
18610 // When are coming out of an unevaluated context, clear out any
18611 // temporaries that we may have created as part of the evaluation of
18612 // the expression in that context: they aren't relevant because they
18613 // will never be constructed.
18614 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18615 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18616 ExprCleanupObjects.end());
18617 Cleanup = Rec.ParentCleanup;
18618 CleanupVarDeclMarking();
18619 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
18620 // Otherwise, merge the contexts together.
18621 } else {
18622 Cleanup.mergeFrom(Rec.ParentCleanup);
18623 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
18624 Rec.SavedMaybeODRUseExprs.end());
18627 // Pop the current expression evaluation context off the stack.
18628 ExprEvalContexts.pop_back();
18630 // The global expression evaluation context record is never popped.
18631 ExprEvalContexts.back().NumTypos += NumTypos;
18634 void Sema::DiscardCleanupsInEvaluationContext() {
18635 ExprCleanupObjects.erase(
18636 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18637 ExprCleanupObjects.end());
18638 Cleanup.reset();
18639 MaybeODRUseExprs.clear();
18642 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18643 ExprResult Result = CheckPlaceholderExpr(E);
18644 if (Result.isInvalid())
18645 return ExprError();
18646 E = Result.get();
18647 if (!E->getType()->isVariablyModifiedType())
18648 return E;
18649 return TransformToPotentiallyEvaluated(E);
18652 /// Are we in a context that is potentially constant evaluated per C++20
18653 /// [expr.const]p12?
18654 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18655 /// C++2a [expr.const]p12:
18656 // An expression or conversion is potentially constant evaluated if it is
18657 switch (SemaRef.ExprEvalContexts.back().Context) {
18658 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18659 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18661 // -- a manifestly constant-evaluated expression,
18662 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18663 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18664 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18665 // -- a potentially-evaluated expression,
18666 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18667 // -- an immediate subexpression of a braced-init-list,
18669 // -- [FIXME] an expression of the form & cast-expression that occurs
18670 // within a templated entity
18671 // -- a subexpression of one of the above that is not a subexpression of
18672 // a nested unevaluated operand.
18673 return true;
18675 case Sema::ExpressionEvaluationContext::Unevaluated:
18676 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18677 // Expressions in this context are never evaluated.
18678 return false;
18680 llvm_unreachable("Invalid context");
18683 /// Return true if this function has a calling convention that requires mangling
18684 /// in the size of the parameter pack.
18685 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18686 // These manglings don't do anything on non-Windows or non-x86 platforms, so
18687 // we don't need parameter type sizes.
18688 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
18689 if (!TT.isOSWindows() || !TT.isX86())
18690 return false;
18692 // If this is C++ and this isn't an extern "C" function, parameters do not
18693 // need to be complete. In this case, C++ mangling will apply, which doesn't
18694 // use the size of the parameters.
18695 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18696 return false;
18698 // Stdcall, fastcall, and vectorcall need this special treatment.
18699 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18700 switch (CC) {
18701 case CC_X86StdCall:
18702 case CC_X86FastCall:
18703 case CC_X86VectorCall:
18704 return true;
18705 default:
18706 break;
18708 return false;
18711 /// Require that all of the parameter types of function be complete. Normally,
18712 /// parameter types are only required to be complete when a function is called
18713 /// or defined, but to mangle functions with certain calling conventions, the
18714 /// mangler needs to know the size of the parameter list. In this situation,
18715 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18716 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18717 /// result in a linker error. Clang doesn't implement this behavior, and instead
18718 /// attempts to error at compile time.
18719 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18720 SourceLocation Loc) {
18721 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18722 FunctionDecl *FD;
18723 ParmVarDecl *Param;
18725 public:
18726 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18727 : FD(FD), Param(Param) {}
18729 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18730 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18731 StringRef CCName;
18732 switch (CC) {
18733 case CC_X86StdCall:
18734 CCName = "stdcall";
18735 break;
18736 case CC_X86FastCall:
18737 CCName = "fastcall";
18738 break;
18739 case CC_X86VectorCall:
18740 CCName = "vectorcall";
18741 break;
18742 default:
18743 llvm_unreachable("CC does not need mangling");
18746 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18747 << Param->getDeclName() << FD->getDeclName() << CCName;
18751 for (ParmVarDecl *Param : FD->parameters()) {
18752 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18753 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18757 namespace {
18758 enum class OdrUseContext {
18759 /// Declarations in this context are not odr-used.
18760 None,
18761 /// Declarations in this context are formally odr-used, but this is a
18762 /// dependent context.
18763 Dependent,
18764 /// Declarations in this context are odr-used but not actually used (yet).
18765 FormallyOdrUsed,
18766 /// Declarations in this context are used.
18767 Used
18771 /// Are we within a context in which references to resolved functions or to
18772 /// variables result in odr-use?
18773 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18774 OdrUseContext Result;
18776 switch (SemaRef.ExprEvalContexts.back().Context) {
18777 case Sema::ExpressionEvaluationContext::Unevaluated:
18778 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18779 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18780 return OdrUseContext::None;
18782 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18783 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18784 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18785 Result = OdrUseContext::Used;
18786 break;
18788 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18789 Result = OdrUseContext::FormallyOdrUsed;
18790 break;
18792 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18793 // A default argument formally results in odr-use, but doesn't actually
18794 // result in a use in any real sense until it itself is used.
18795 Result = OdrUseContext::FormallyOdrUsed;
18796 break;
18799 if (SemaRef.CurContext->isDependentContext())
18800 return OdrUseContext::Dependent;
18802 return Result;
18805 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18806 if (!Func->isConstexpr())
18807 return false;
18809 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18810 return true;
18811 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18812 return CCD && CCD->getInheritedConstructor();
18815 /// Mark a function referenced, and check whether it is odr-used
18816 /// (C++ [basic.def.odr]p2, C99 6.9p3)
18817 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18818 bool MightBeOdrUse) {
18819 assert(Func && "No function?");
18821 Func->setReferenced();
18823 // Recursive functions aren't really used until they're used from some other
18824 // context.
18825 bool IsRecursiveCall = CurContext == Func;
18827 // C++11 [basic.def.odr]p3:
18828 // A function whose name appears as a potentially-evaluated expression is
18829 // odr-used if it is the unique lookup result or the selected member of a
18830 // set of overloaded functions [...].
18832 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18833 // can just check that here.
18834 OdrUseContext OdrUse =
18835 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18836 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18837 OdrUse = OdrUseContext::FormallyOdrUsed;
18839 // Trivial default constructors and destructors are never actually used.
18840 // FIXME: What about other special members?
18841 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18842 OdrUse == OdrUseContext::Used) {
18843 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18844 if (Constructor->isDefaultConstructor())
18845 OdrUse = OdrUseContext::FormallyOdrUsed;
18846 if (isa<CXXDestructorDecl>(Func))
18847 OdrUse = OdrUseContext::FormallyOdrUsed;
18850 // C++20 [expr.const]p12:
18851 // A function [...] is needed for constant evaluation if it is [...] a
18852 // constexpr function that is named by an expression that is potentially
18853 // constant evaluated
18854 bool NeededForConstantEvaluation =
18855 isPotentiallyConstantEvaluatedContext(*this) &&
18856 isImplicitlyDefinableConstexprFunction(Func);
18858 // Determine whether we require a function definition to exist, per
18859 // C++11 [temp.inst]p3:
18860 // Unless a function template specialization has been explicitly
18861 // instantiated or explicitly specialized, the function template
18862 // specialization is implicitly instantiated when the specialization is
18863 // referenced in a context that requires a function definition to exist.
18864 // C++20 [temp.inst]p7:
18865 // The existence of a definition of a [...] function is considered to
18866 // affect the semantics of the program if the [...] function is needed for
18867 // constant evaluation by an expression
18868 // C++20 [basic.def.odr]p10:
18869 // Every program shall contain exactly one definition of every non-inline
18870 // function or variable that is odr-used in that program outside of a
18871 // discarded statement
18872 // C++20 [special]p1:
18873 // The implementation will implicitly define [defaulted special members]
18874 // if they are odr-used or needed for constant evaluation.
18876 // Note that we skip the implicit instantiation of templates that are only
18877 // used in unused default arguments or by recursive calls to themselves.
18878 // This is formally non-conforming, but seems reasonable in practice.
18879 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
18880 NeededForConstantEvaluation);
18882 // C++14 [temp.expl.spec]p6:
18883 // If a template [...] is explicitly specialized then that specialization
18884 // shall be declared before the first use of that specialization that would
18885 // cause an implicit instantiation to take place, in every translation unit
18886 // in which such a use occurs
18887 if (NeedDefinition &&
18888 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18889 Func->getMemberSpecializationInfo()))
18890 checkSpecializationReachability(Loc, Func);
18892 if (getLangOpts().CUDA)
18893 CheckCUDACall(Loc, Func);
18895 // If we need a definition, try to create one.
18896 if (NeedDefinition && !Func->getBody()) {
18897 runWithSufficientStackSpace(Loc, [&] {
18898 if (CXXConstructorDecl *Constructor =
18899 dyn_cast<CXXConstructorDecl>(Func)) {
18900 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18901 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18902 if (Constructor->isDefaultConstructor()) {
18903 if (Constructor->isTrivial() &&
18904 !Constructor->hasAttr<DLLExportAttr>())
18905 return;
18906 DefineImplicitDefaultConstructor(Loc, Constructor);
18907 } else if (Constructor->isCopyConstructor()) {
18908 DefineImplicitCopyConstructor(Loc, Constructor);
18909 } else if (Constructor->isMoveConstructor()) {
18910 DefineImplicitMoveConstructor(Loc, Constructor);
18912 } else if (Constructor->getInheritedConstructor()) {
18913 DefineInheritingConstructor(Loc, Constructor);
18915 } else if (CXXDestructorDecl *Destructor =
18916 dyn_cast<CXXDestructorDecl>(Func)) {
18917 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18918 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18919 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18920 return;
18921 DefineImplicitDestructor(Loc, Destructor);
18923 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18924 MarkVTableUsed(Loc, Destructor->getParent());
18925 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18926 if (MethodDecl->isOverloadedOperator() &&
18927 MethodDecl->getOverloadedOperator() == OO_Equal) {
18928 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18929 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18930 if (MethodDecl->isCopyAssignmentOperator())
18931 DefineImplicitCopyAssignment(Loc, MethodDecl);
18932 else if (MethodDecl->isMoveAssignmentOperator())
18933 DefineImplicitMoveAssignment(Loc, MethodDecl);
18935 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18936 MethodDecl->getParent()->isLambda()) {
18937 CXXConversionDecl *Conversion =
18938 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18939 if (Conversion->isLambdaToBlockPointerConversion())
18940 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
18941 else
18942 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
18943 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18944 MarkVTableUsed(Loc, MethodDecl->getParent());
18947 if (Func->isDefaulted() && !Func->isDeleted()) {
18948 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
18949 if (DCK != DefaultedComparisonKind::None)
18950 DefineDefaultedComparison(Loc, Func, DCK);
18953 // Implicit instantiation of function templates and member functions of
18954 // class templates.
18955 if (Func->isImplicitlyInstantiable()) {
18956 TemplateSpecializationKind TSK =
18957 Func->getTemplateSpecializationKindForInstantiation();
18958 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18959 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18960 if (FirstInstantiation) {
18961 PointOfInstantiation = Loc;
18962 if (auto *MSI = Func->getMemberSpecializationInfo())
18963 MSI->setPointOfInstantiation(Loc);
18964 // FIXME: Notify listener.
18965 else
18966 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18967 } else if (TSK != TSK_ImplicitInstantiation) {
18968 // Use the point of use as the point of instantiation, instead of the
18969 // point of explicit instantiation (which we track as the actual point
18970 // of instantiation). This gives better backtraces in diagnostics.
18971 PointOfInstantiation = Loc;
18974 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18975 Func->isConstexpr()) {
18976 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18977 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18978 CodeSynthesisContexts.size())
18979 PendingLocalImplicitInstantiations.push_back(
18980 std::make_pair(Func, PointOfInstantiation));
18981 else if (Func->isConstexpr())
18982 // Do not defer instantiations of constexpr functions, to avoid the
18983 // expression evaluator needing to call back into Sema if it sees a
18984 // call to such a function.
18985 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18986 else {
18987 Func->setInstantiationIsPending(true);
18988 PendingInstantiations.push_back(
18989 std::make_pair(Func, PointOfInstantiation));
18990 // Notify the consumer that a function was implicitly instantiated.
18991 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18994 } else {
18995 // Walk redefinitions, as some of them may be instantiable.
18996 for (auto *i : Func->redecls()) {
18997 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18998 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19004 // If a constructor was defined in the context of a default parameter
19005 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19006 // context), its initializers may not be referenced yet.
19007 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19008 EnterExpressionEvaluationContext EvalContext(
19009 *this,
19010 Constructor->isImmediateFunction()
19011 ? ExpressionEvaluationContext::ImmediateFunctionContext
19012 : ExpressionEvaluationContext::PotentiallyEvaluated,
19013 Constructor);
19014 for (CXXCtorInitializer *Init : Constructor->inits()) {
19015 if (Init->isInClassMemberInitializer())
19016 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19017 MarkDeclarationsReferencedInExpr(Init->getInit());
19022 // C++14 [except.spec]p17:
19023 // An exception-specification is considered to be needed when:
19024 // - the function is odr-used or, if it appears in an unevaluated operand,
19025 // would be odr-used if the expression were potentially-evaluated;
19027 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19028 // function is a pure virtual function we're calling, and in that case the
19029 // function was selected by overload resolution and we need to resolve its
19030 // exception specification for a different reason.
19031 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19032 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
19033 ResolveExceptionSpec(Loc, FPT);
19035 // If this is the first "real" use, act on that.
19036 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19037 // Keep track of used but undefined functions.
19038 if (!Func->isDefined()) {
19039 if (mightHaveNonExternalLinkage(Func))
19040 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19041 else if (Func->getMostRecentDecl()->isInlined() &&
19042 !LangOpts.GNUInline &&
19043 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19044 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19045 else if (isExternalWithNoLinkageType(Func))
19046 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19049 // Some x86 Windows calling conventions mangle the size of the parameter
19050 // pack into the name. Computing the size of the parameters requires the
19051 // parameter types to be complete. Check that now.
19052 if (funcHasParameterSizeMangling(*this, Func))
19053 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
19055 // In the MS C++ ABI, the compiler emits destructor variants where they are
19056 // used. If the destructor is used here but defined elsewhere, mark the
19057 // virtual base destructors referenced. If those virtual base destructors
19058 // are inline, this will ensure they are defined when emitting the complete
19059 // destructor variant. This checking may be redundant if the destructor is
19060 // provided later in this TU.
19061 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19062 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19063 CXXRecordDecl *Parent = Dtor->getParent();
19064 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19065 CheckCompleteDestructorVariant(Loc, Dtor);
19069 Func->markUsed(Context);
19073 /// Directly mark a variable odr-used. Given a choice, prefer to use
19074 /// MarkVariableReferenced since it does additional checks and then
19075 /// calls MarkVarDeclODRUsed.
19076 /// If the variable must be captured:
19077 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19078 /// - else capture it in the DeclContext that maps to the
19079 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19080 static void
19081 MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19082 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19083 // Keep track of used but undefined variables.
19084 // FIXME: We shouldn't suppress this warning for static data members.
19085 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19086 assert(Var && "expected a capturable variable");
19088 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19089 (!Var->isExternallyVisible() || Var->isInline() ||
19090 SemaRef.isExternalWithNoLinkageType(Var)) &&
19091 !(Var->isStaticDataMember() && Var->hasInit())) {
19092 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19093 if (old.isInvalid())
19094 old = Loc;
19096 QualType CaptureType, DeclRefType;
19097 if (SemaRef.LangOpts.OpenMP)
19098 SemaRef.tryCaptureOpenMPLambdas(V);
19099 SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit,
19100 /*EllipsisLoc*/ SourceLocation(),
19101 /*BuildAndDiagnose*/ true, CaptureType,
19102 DeclRefType, FunctionScopeIndexToStopAt);
19104 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19105 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19106 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
19107 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
19108 if (VarTarget == Sema::CVT_Host &&
19109 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
19110 UserTarget == Sema::CFT_Global)) {
19111 // Diagnose ODR-use of host global variables in device functions.
19112 // Reference of device global variables in host functions is allowed
19113 // through shadow variables therefore it is not diagnosed.
19114 if (SemaRef.LangOpts.CUDAIsDevice) {
19115 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19116 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19117 SemaRef.targetDiag(Var->getLocation(),
19118 Var->getType().isConstQualified()
19119 ? diag::note_cuda_const_var_unpromoted
19120 : diag::note_cuda_host_var);
19122 } else if (VarTarget == Sema::CVT_Device &&
19123 (UserTarget == Sema::CFT_Host ||
19124 UserTarget == Sema::CFT_HostDevice)) {
19125 // Record a CUDA/HIP device side variable if it is ODR-used
19126 // by host code. This is done conservatively, when the variable is
19127 // referenced in any of the following contexts:
19128 // - a non-function context
19129 // - a host function
19130 // - a host device function
19131 // This makes the ODR-use of the device side variable by host code to
19132 // be visible in the device compilation for the compiler to be able to
19133 // emit template variables instantiated by host code only and to
19134 // externalize the static device side variable ODR-used by host code.
19135 if (!Var->hasExternalStorage())
19136 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
19137 else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
19138 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
19142 V->markUsed(SemaRef.Context);
19145 void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19146 SourceLocation Loc,
19147 unsigned CapturingScopeIndex) {
19148 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19151 void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,
19152 ValueDecl *var) {
19153 DeclContext *VarDC = var->getDeclContext();
19155 // If the parameter still belongs to the translation unit, then
19156 // we're actually just using one parameter in the declaration of
19157 // the next.
19158 if (isa<ParmVarDecl>(var) &&
19159 isa<TranslationUnitDecl>(VarDC))
19160 return;
19162 // For C code, don't diagnose about capture if we're not actually in code
19163 // right now; it's impossible to write a non-constant expression outside of
19164 // function context, so we'll get other (more useful) diagnostics later.
19166 // For C++, things get a bit more nasty... it would be nice to suppress this
19167 // diagnostic for certain cases like using a local variable in an array bound
19168 // for a member of a local class, but the correct predicate is not obvious.
19169 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19170 return;
19172 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19173 unsigned ContextKind = 3; // unknown
19174 if (isa<CXXMethodDecl>(VarDC) &&
19175 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19176 ContextKind = 2;
19177 } else if (isa<FunctionDecl>(VarDC)) {
19178 ContextKind = 0;
19179 } else if (isa<BlockDecl>(VarDC)) {
19180 ContextKind = 1;
19183 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19184 << var << ValueKind << ContextKind << VarDC;
19185 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19186 << var;
19188 // FIXME: Add additional diagnostic info about class etc. which prevents
19189 // capture.
19192 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19193 ValueDecl *Var,
19194 bool &SubCapturesAreNested,
19195 QualType &CaptureType,
19196 QualType &DeclRefType) {
19197 // Check whether we've already captured it.
19198 if (CSI->CaptureMap.count(Var)) {
19199 // If we found a capture, any subcaptures are nested.
19200 SubCapturesAreNested = true;
19202 // Retrieve the capture type for this variable.
19203 CaptureType = CSI->getCapture(Var).getCaptureType();
19205 // Compute the type of an expression that refers to this variable.
19206 DeclRefType = CaptureType.getNonReferenceType();
19208 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19209 // are mutable in the sense that user can change their value - they are
19210 // private instances of the captured declarations.
19211 const Capture &Cap = CSI->getCapture(Var);
19212 if (Cap.isCopyCapture() &&
19213 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
19214 !(isa<CapturedRegionScopeInfo>(CSI) &&
19215 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19216 DeclRefType.addConst();
19217 return true;
19219 return false;
19222 // Only block literals, captured statements, and lambda expressions can
19223 // capture; other scopes don't work.
19224 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19225 ValueDecl *Var,
19226 SourceLocation Loc,
19227 const bool Diagnose,
19228 Sema &S) {
19229 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
19230 return getLambdaAwareParentOfDeclContext(DC);
19232 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19233 if (Underlying) {
19234 if (Underlying->hasLocalStorage() && Diagnose)
19235 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
19237 return nullptr;
19240 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19241 // certain types of variables (unnamed, variably modified types etc.)
19242 // so check for eligibility.
19243 static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19244 SourceLocation Loc, const bool Diagnose,
19245 Sema &S) {
19247 assert((isa<VarDecl, BindingDecl>(Var)) &&
19248 "Only variables and structured bindings can be captured");
19250 bool IsBlock = isa<BlockScopeInfo>(CSI);
19251 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19253 // Lambdas are not allowed to capture unnamed variables
19254 // (e.g. anonymous unions).
19255 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19256 // assuming that's the intent.
19257 if (IsLambda && !Var->getDeclName()) {
19258 if (Diagnose) {
19259 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19260 S.Diag(Var->getLocation(), diag::note_declared_at);
19262 return false;
19265 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19266 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19267 if (Diagnose) {
19268 S.Diag(Loc, diag::err_ref_vm_type);
19269 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19271 return false;
19273 // Prohibit structs with flexible array members too.
19274 // We cannot capture what is in the tail end of the struct.
19275 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
19276 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
19277 if (Diagnose) {
19278 if (IsBlock)
19279 S.Diag(Loc, diag::err_ref_flexarray_type);
19280 else
19281 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19282 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19284 return false;
19287 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19288 // Lambdas and captured statements are not allowed to capture __block
19289 // variables; they don't support the expected semantics.
19290 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19291 if (Diagnose) {
19292 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19293 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19295 return false;
19297 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19298 if (S.getLangOpts().OpenCL && IsBlock &&
19299 Var->getType()->isBlockPointerType()) {
19300 if (Diagnose)
19301 S.Diag(Loc, diag::err_opencl_block_ref_block);
19302 return false;
19305 if (isa<BindingDecl>(Var)) {
19306 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19307 if (Diagnose)
19308 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
19309 return false;
19310 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19311 S.Diag(Loc, S.LangOpts.CPlusPlus20
19312 ? diag::warn_cxx17_compat_capture_binding
19313 : diag::ext_capture_binding)
19314 << Var;
19315 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19319 return true;
19322 // Returns true if the capture by block was successful.
19323 static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19324 SourceLocation Loc, const bool BuildAndDiagnose,
19325 QualType &CaptureType, QualType &DeclRefType,
19326 const bool Nested, Sema &S, bool Invalid) {
19327 bool ByRef = false;
19329 // Blocks are not allowed to capture arrays, excepting OpenCL.
19330 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19331 // (decayed to pointers).
19332 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19333 if (BuildAndDiagnose) {
19334 S.Diag(Loc, diag::err_ref_array_type);
19335 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19336 Invalid = true;
19337 } else {
19338 return false;
19342 // Forbid the block-capture of autoreleasing variables.
19343 if (!Invalid &&
19344 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19345 if (BuildAndDiagnose) {
19346 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19347 << /*block*/ 0;
19348 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19349 Invalid = true;
19350 } else {
19351 return false;
19355 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19356 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19357 QualType PointeeTy = PT->getPointeeType();
19359 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19360 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19361 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19362 if (BuildAndDiagnose) {
19363 SourceLocation VarLoc = Var->getLocation();
19364 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19365 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19370 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19371 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19372 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
19373 // Block capture by reference does not change the capture or
19374 // declaration reference types.
19375 ByRef = true;
19376 } else {
19377 // Block capture by copy introduces 'const'.
19378 CaptureType = CaptureType.getNonReferenceType().withConst();
19379 DeclRefType = CaptureType;
19382 // Actually capture the variable.
19383 if (BuildAndDiagnose)
19384 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19385 CaptureType, Invalid);
19387 return !Invalid;
19390 /// Capture the given variable in the captured region.
19391 static bool captureInCapturedRegion(
19392 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19393 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19394 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
19395 bool IsTopScope, Sema &S, bool Invalid) {
19396 // By default, capture variables by reference.
19397 bool ByRef = true;
19398 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19399 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19400 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19401 // Using an LValue reference type is consistent with Lambdas (see below).
19402 if (S.isOpenMPCapturedDecl(Var)) {
19403 bool HasConst = DeclRefType.isConstQualified();
19404 DeclRefType = DeclRefType.getUnqualifiedType();
19405 // Don't lose diagnostics about assignments to const.
19406 if (HasConst)
19407 DeclRefType.addConst();
19409 // Do not capture firstprivates in tasks.
19410 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
19411 OMPC_unknown)
19412 return true;
19413 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19414 RSI->OpenMPCaptureLevel);
19417 if (ByRef)
19418 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19419 else
19420 CaptureType = DeclRefType;
19422 // Actually capture the variable.
19423 if (BuildAndDiagnose)
19424 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19425 Loc, SourceLocation(), CaptureType, Invalid);
19427 return !Invalid;
19430 /// Capture the given variable in the lambda.
19431 static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19432 SourceLocation Loc, const bool BuildAndDiagnose,
19433 QualType &CaptureType, QualType &DeclRefType,
19434 const bool RefersToCapturedVariable,
19435 const Sema::TryCaptureKind Kind,
19436 SourceLocation EllipsisLoc, const bool IsTopScope,
19437 Sema &S, bool Invalid) {
19438 // Determine whether we are capturing by reference or by value.
19439 bool ByRef = false;
19440 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19441 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19442 } else {
19443 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19446 BindingDecl *BD = dyn_cast<BindingDecl>(Var);
19447 // FIXME: We should support capturing structured bindings in OpenMP.
19448 if (!Invalid && BD && S.LangOpts.OpenMP) {
19449 if (BuildAndDiagnose) {
19450 S.Diag(Loc, diag::err_capture_binding_openmp) << Var;
19451 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19453 Invalid = true;
19456 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19457 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19458 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19459 Invalid = true;
19462 // Compute the type of the field that will capture this variable.
19463 if (ByRef) {
19464 // C++11 [expr.prim.lambda]p15:
19465 // An entity is captured by reference if it is implicitly or
19466 // explicitly captured but not captured by copy. It is
19467 // unspecified whether additional unnamed non-static data
19468 // members are declared in the closure type for entities
19469 // captured by reference.
19471 // FIXME: It is not clear whether we want to build an lvalue reference
19472 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19473 // to do the former, while EDG does the latter. Core issue 1249 will
19474 // clarify, but for now we follow GCC because it's a more permissive and
19475 // easily defensible position.
19476 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19477 } else {
19478 // C++11 [expr.prim.lambda]p14:
19479 // For each entity captured by copy, an unnamed non-static
19480 // data member is declared in the closure type. The
19481 // declaration order of these members is unspecified. The type
19482 // of such a data member is the type of the corresponding
19483 // captured entity if the entity is not a reference to an
19484 // object, or the referenced type otherwise. [Note: If the
19485 // captured entity is a reference to a function, the
19486 // corresponding data member is also a reference to a
19487 // function. - end note ]
19488 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19489 if (!RefType->getPointeeType()->isFunctionType())
19490 CaptureType = RefType->getPointeeType();
19493 // Forbid the lambda copy-capture of autoreleasing variables.
19494 if (!Invalid &&
19495 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19496 if (BuildAndDiagnose) {
19497 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19498 S.Diag(Var->getLocation(), diag::note_previous_decl)
19499 << Var->getDeclName();
19500 Invalid = true;
19501 } else {
19502 return false;
19506 // Make sure that by-copy captures are of a complete and non-abstract type.
19507 if (!Invalid && BuildAndDiagnose) {
19508 if (!CaptureType->isDependentType() &&
19509 S.RequireCompleteSizedType(
19510 Loc, CaptureType,
19511 diag::err_capture_of_incomplete_or_sizeless_type,
19512 Var->getDeclName()))
19513 Invalid = true;
19514 else if (S.RequireNonAbstractType(Loc, CaptureType,
19515 diag::err_capture_of_abstract_type))
19516 Invalid = true;
19520 // Compute the type of a reference to this captured variable.
19521 if (ByRef)
19522 DeclRefType = CaptureType.getNonReferenceType();
19523 else {
19524 // C++ [expr.prim.lambda]p5:
19525 // The closure type for a lambda-expression has a public inline
19526 // function call operator [...]. This function call operator is
19527 // declared const (9.3.1) if and only if the lambda-expression's
19528 // parameter-declaration-clause is not followed by mutable.
19529 DeclRefType = CaptureType.getNonReferenceType();
19530 if (!LSI->Mutable && !CaptureType->isReferenceType())
19531 DeclRefType.addConst();
19534 // Add the capture.
19535 if (BuildAndDiagnose)
19536 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19537 Loc, EllipsisLoc, CaptureType, Invalid);
19539 return !Invalid;
19542 static bool canCaptureVariableByCopy(ValueDecl *Var,
19543 const ASTContext &Context) {
19544 // Offer a Copy fix even if the type is dependent.
19545 if (Var->getType()->isDependentType())
19546 return true;
19547 QualType T = Var->getType().getNonReferenceType();
19548 if (T.isTriviallyCopyableType(Context))
19549 return true;
19550 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19552 if (!(RD = RD->getDefinition()))
19553 return false;
19554 if (RD->hasSimpleCopyConstructor())
19555 return true;
19556 if (RD->hasUserDeclaredCopyConstructor())
19557 for (CXXConstructorDecl *Ctor : RD->ctors())
19558 if (Ctor->isCopyConstructor())
19559 return !Ctor->isDeleted();
19561 return false;
19564 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19565 /// default capture. Fixes may be omitted if they aren't allowed by the
19566 /// standard, for example we can't emit a default copy capture fix-it if we
19567 /// already explicitly copy capture capture another variable.
19568 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19569 ValueDecl *Var) {
19570 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19571 // Don't offer Capture by copy of default capture by copy fixes if Var is
19572 // known not to be copy constructible.
19573 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19575 SmallString<32> FixBuffer;
19576 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19577 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19578 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19579 if (ShouldOfferCopyFix) {
19580 // Offer fixes to insert an explicit capture for the variable.
19581 // [] -> [VarName]
19582 // [OtherCapture] -> [OtherCapture, VarName]
19583 FixBuffer.assign({Separator, Var->getName()});
19584 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19585 << Var << /*value*/ 0
19586 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19588 // As above but capture by reference.
19589 FixBuffer.assign({Separator, "&", Var->getName()});
19590 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19591 << Var << /*reference*/ 1
19592 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19595 // Only try to offer default capture if there are no captures excluding this
19596 // and init captures.
19597 // [this]: OK.
19598 // [X = Y]: OK.
19599 // [&A, &B]: Don't offer.
19600 // [A, B]: Don't offer.
19601 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19602 return !C.isThisCapture() && !C.isInitCapture();
19604 return;
19606 // The default capture specifiers, '=' or '&', must appear first in the
19607 // capture body.
19608 SourceLocation DefaultInsertLoc =
19609 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
19611 if (ShouldOfferCopyFix) {
19612 bool CanDefaultCopyCapture = true;
19613 // [=, *this] OK since c++17
19614 // [=, this] OK since c++20
19615 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19616 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19617 ? LSI->getCXXThisCapture().isCopyCapture()
19618 : false;
19619 // We can't use default capture by copy if any captures already specified
19620 // capture by copy.
19621 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19622 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19623 })) {
19624 FixBuffer.assign({"=", Separator});
19625 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19626 << /*value*/ 0
19627 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19631 // We can't use default capture by reference if any captures already specified
19632 // capture by reference.
19633 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19634 return !C.isInitCapture() && C.isReferenceCapture() &&
19635 !C.isThisCapture();
19636 })) {
19637 FixBuffer.assign({"&", Separator});
19638 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19639 << /*reference*/ 1
19640 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19644 bool Sema::tryCaptureVariable(
19645 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19646 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19647 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19648 // An init-capture is notionally from the context surrounding its
19649 // declaration, but its parent DC is the lambda class.
19650 DeclContext *VarDC = Var->getDeclContext();
19651 DeclContext *DC = CurContext;
19653 // tryCaptureVariable is called every time a DeclRef is formed,
19654 // it can therefore have non-negigible impact on performances.
19655 // For local variables and when there is no capturing scope,
19656 // we can bailout early.
19657 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19658 return true;
19660 const auto *VD = dyn_cast<VarDecl>(Var);
19661 if (VD) {
19662 if (VD->isInitCapture())
19663 VarDC = VarDC->getParent();
19664 } else {
19665 VD = Var->getPotentiallyDecomposedVarDecl();
19667 assert(VD && "Cannot capture a null variable");
19669 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19670 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19671 // We need to sync up the Declaration Context with the
19672 // FunctionScopeIndexToStopAt
19673 if (FunctionScopeIndexToStopAt) {
19674 unsigned FSIndex = FunctionScopes.size() - 1;
19675 while (FSIndex != MaxFunctionScopesIndex) {
19676 DC = getLambdaAwareParentOfDeclContext(DC);
19677 --FSIndex;
19681 // Capture global variables if it is required to use private copy of this
19682 // variable.
19683 bool IsGlobal = !VD->hasLocalStorage();
19684 if (IsGlobal &&
19685 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19686 MaxFunctionScopesIndex)))
19687 return true;
19689 if (isa<VarDecl>(Var))
19690 Var = cast<VarDecl>(Var->getCanonicalDecl());
19692 // Walk up the stack to determine whether we can capture the variable,
19693 // performing the "simple" checks that don't depend on type. We stop when
19694 // we've either hit the declared scope of the variable or find an existing
19695 // capture of that variable. We start from the innermost capturing-entity
19696 // (the DC) and ensure that all intervening capturing-entities
19697 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19698 // declcontext can either capture the variable or have already captured
19699 // the variable.
19700 CaptureType = Var->getType();
19701 DeclRefType = CaptureType.getNonReferenceType();
19702 bool Nested = false;
19703 bool Explicit = (Kind != TryCapture_Implicit);
19704 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19705 do {
19707 LambdaScopeInfo *LSI = nullptr;
19708 if (!FunctionScopes.empty())
19709 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19710 FunctionScopes[FunctionScopesIndex]);
19712 bool IsInScopeDeclarationContext =
19713 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19715 if (LSI && !LSI->AfterParameterList) {
19716 // This allows capturing parameters from a default value which does not
19717 // seems correct
19718 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19719 return true;
19721 // If the variable is declared in the current context, there is no need to
19722 // capture it.
19723 if (IsInScopeDeclarationContext &&
19724 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19725 return true;
19727 // Only block literals, captured statements, and lambda expressions can
19728 // capture; other scopes don't work.
19729 DeclContext *ParentDC =
19730 !IsInScopeDeclarationContext
19731 ? DC->getParent()
19732 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19733 BuildAndDiagnose, *this);
19734 // We need to check for the parent *first* because, if we *have*
19735 // private-captured a global variable, we need to recursively capture it in
19736 // intermediate blocks, lambdas, etc.
19737 if (!ParentDC) {
19738 if (IsGlobal) {
19739 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19740 break;
19742 return true;
19745 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19746 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19748 // Check whether we've already captured it.
19749 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19750 DeclRefType)) {
19751 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19752 break;
19755 // When evaluating some attributes (like enable_if) we might refer to a
19756 // function parameter appertaining to the same declaration as that
19757 // attribute.
19758 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19759 Parm && Parm->getDeclContext() == DC)
19760 return true;
19762 // If we are instantiating a generic lambda call operator body,
19763 // we do not want to capture new variables. What was captured
19764 // during either a lambdas transformation or initial parsing
19765 // should be used.
19766 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19767 if (BuildAndDiagnose) {
19768 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19769 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19770 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19771 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19772 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19773 buildLambdaCaptureFixit(*this, LSI, Var);
19774 } else
19775 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
19777 return true;
19780 // Try to capture variable-length arrays types.
19781 if (Var->getType()->isVariablyModifiedType()) {
19782 // We're going to walk down into the type and look for VLA
19783 // expressions.
19784 QualType QTy = Var->getType();
19785 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19786 QTy = PVD->getOriginalType();
19787 captureVariablyModifiedType(Context, QTy, CSI);
19790 if (getLangOpts().OpenMP) {
19791 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19792 // OpenMP private variables should not be captured in outer scope, so
19793 // just break here. Similarly, global variables that are captured in a
19794 // target region should not be captured outside the scope of the region.
19795 if (RSI->CapRegionKind == CR_OpenMP) {
19796 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
19797 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19798 // If the variable is private (i.e. not captured) and has variably
19799 // modified type, we still need to capture the type for correct
19800 // codegen in all regions, associated with the construct. Currently,
19801 // it is captured in the innermost captured region only.
19802 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19803 Var->getType()->isVariablyModifiedType()) {
19804 QualType QTy = Var->getType();
19805 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19806 QTy = PVD->getOriginalType();
19807 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
19808 I < E; ++I) {
19809 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19810 FunctionScopes[FunctionScopesIndex - I]);
19811 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19812 "Wrong number of captured regions associated with the "
19813 "OpenMP construct.");
19814 captureVariablyModifiedType(Context, QTy, OuterRSI);
19817 bool IsTargetCap =
19818 IsOpenMPPrivateDecl != OMPC_private &&
19819 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19820 RSI->OpenMPCaptureLevel);
19821 // Do not capture global if it is not privatized in outer regions.
19822 bool IsGlobalCap =
19823 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
19824 RSI->OpenMPCaptureLevel);
19826 // When we detect target captures we are looking from inside the
19827 // target region, therefore we need to propagate the capture from the
19828 // enclosing region. Therefore, the capture is not initially nested.
19829 if (IsTargetCap)
19830 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
19832 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19833 (IsGlobal && !IsGlobalCap)) {
19834 Nested = !IsTargetCap;
19835 bool HasConst = DeclRefType.isConstQualified();
19836 DeclRefType = DeclRefType.getUnqualifiedType();
19837 // Don't lose diagnostics about assignments to const.
19838 if (HasConst)
19839 DeclRefType.addConst();
19840 CaptureType = Context.getLValueReferenceType(DeclRefType);
19841 break;
19846 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19847 // No capture-default, and this is not an explicit capture
19848 // so cannot capture this variable.
19849 if (BuildAndDiagnose) {
19850 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19851 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19852 auto *LSI = cast<LambdaScopeInfo>(CSI);
19853 if (LSI->Lambda) {
19854 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19855 buildLambdaCaptureFixit(*this, LSI, Var);
19857 // FIXME: If we error out because an outer lambda can not implicitly
19858 // capture a variable that an inner lambda explicitly captures, we
19859 // should have the inner lambda do the explicit capture - because
19860 // it makes for cleaner diagnostics later. This would purely be done
19861 // so that the diagnostic does not misleadingly claim that a variable
19862 // can not be captured by a lambda implicitly even though it is captured
19863 // explicitly. Suggestion:
19864 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19865 // at the function head
19866 // - cache the StartingDeclContext - this must be a lambda
19867 // - captureInLambda in the innermost lambda the variable.
19869 return true;
19871 Explicit = false;
19872 FunctionScopesIndex--;
19873 if (IsInScopeDeclarationContext)
19874 DC = ParentDC;
19875 } while (!VarDC->Equals(DC));
19877 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19878 // computing the type of the capture at each step, checking type-specific
19879 // requirements, and adding captures if requested.
19880 // If the variable had already been captured previously, we start capturing
19881 // at the lambda nested within that one.
19882 bool Invalid = false;
19883 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19884 ++I) {
19885 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19887 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19888 // certain types of variables (unnamed, variably modified types etc.)
19889 // so check for eligibility.
19890 if (!Invalid)
19891 Invalid =
19892 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19894 // After encountering an error, if we're actually supposed to capture, keep
19895 // capturing in nested contexts to suppress any follow-on diagnostics.
19896 if (Invalid && !BuildAndDiagnose)
19897 return true;
19899 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19900 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19901 DeclRefType, Nested, *this, Invalid);
19902 Nested = true;
19903 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19904 Invalid = !captureInCapturedRegion(
19905 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19906 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19907 Nested = true;
19908 } else {
19909 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19910 Invalid =
19911 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19912 DeclRefType, Nested, Kind, EllipsisLoc,
19913 /*IsTopScope*/ I == N - 1, *this, Invalid);
19914 Nested = true;
19917 if (Invalid && !BuildAndDiagnose)
19918 return true;
19920 return Invalid;
19923 bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
19924 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19925 QualType CaptureType;
19926 QualType DeclRefType;
19927 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19928 /*BuildAndDiagnose=*/true, CaptureType,
19929 DeclRefType, nullptr);
19932 bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
19933 QualType CaptureType;
19934 QualType DeclRefType;
19935 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19936 /*BuildAndDiagnose=*/false, CaptureType,
19937 DeclRefType, nullptr);
19940 QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
19941 QualType CaptureType;
19942 QualType DeclRefType;
19944 // Determine whether we can capture this variable.
19945 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19946 /*BuildAndDiagnose=*/false, CaptureType,
19947 DeclRefType, nullptr))
19948 return QualType();
19950 return DeclRefType;
19953 namespace {
19954 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19955 // The produced TemplateArgumentListInfo* points to data stored within this
19956 // object, so should only be used in contexts where the pointer will not be
19957 // used after the CopiedTemplateArgs object is destroyed.
19958 class CopiedTemplateArgs {
19959 bool HasArgs;
19960 TemplateArgumentListInfo TemplateArgStorage;
19961 public:
19962 template<typename RefExpr>
19963 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19964 if (HasArgs)
19965 E->copyTemplateArgumentsInto(TemplateArgStorage);
19967 operator TemplateArgumentListInfo*()
19968 #ifdef __has_cpp_attribute
19969 #if __has_cpp_attribute(clang::lifetimebound)
19970 [[clang::lifetimebound]]
19971 #endif
19972 #endif
19974 return HasArgs ? &TemplateArgStorage : nullptr;
19979 /// Walk the set of potential results of an expression and mark them all as
19980 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19982 /// \return A new expression if we found any potential results, ExprEmpty() if
19983 /// not, and ExprError() if we diagnosed an error.
19984 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
19985 NonOdrUseReason NOUR) {
19986 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19987 // an object that satisfies the requirements for appearing in a
19988 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19989 // is immediately applied." This function handles the lvalue-to-rvalue
19990 // conversion part.
19992 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19993 // transform it into the relevant kind of non-odr-use node and rebuild the
19994 // tree of nodes leading to it.
19996 // This is a mini-TreeTransform that only transforms a restricted subset of
19997 // nodes (and only certain operands of them).
19999 // Rebuild a subexpression.
20000 auto Rebuild = [&](Expr *Sub) {
20001 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20004 // Check whether a potential result satisfies the requirements of NOUR.
20005 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20006 // Any entity other than a VarDecl is always odr-used whenever it's named
20007 // in a potentially-evaluated expression.
20008 auto *VD = dyn_cast<VarDecl>(D);
20009 if (!VD)
20010 return true;
20012 // C++2a [basic.def.odr]p4:
20013 // A variable x whose name appears as a potentially-evalauted expression
20014 // e is odr-used by e unless
20015 // -- x is a reference that is usable in constant expressions, or
20016 // -- x is a variable of non-reference type that is usable in constant
20017 // expressions and has no mutable subobjects, and e is an element of
20018 // the set of potential results of an expression of
20019 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20020 // conversion is applied, or
20021 // -- x is a variable of non-reference type, and e is an element of the
20022 // set of potential results of a discarded-value expression to which
20023 // the lvalue-to-rvalue conversion is not applied
20025 // We check the first bullet and the "potentially-evaluated" condition in
20026 // BuildDeclRefExpr. We check the type requirements in the second bullet
20027 // in CheckLValueToRValueConversionOperand below.
20028 switch (NOUR) {
20029 case NOUR_None:
20030 case NOUR_Unevaluated:
20031 llvm_unreachable("unexpected non-odr-use-reason");
20033 case NOUR_Constant:
20034 // Constant references were handled when they were built.
20035 if (VD->getType()->isReferenceType())
20036 return true;
20037 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20038 if (RD->hasMutableFields())
20039 return true;
20040 if (!VD->isUsableInConstantExpressions(S.Context))
20041 return true;
20042 break;
20044 case NOUR_Discarded:
20045 if (VD->getType()->isReferenceType())
20046 return true;
20047 break;
20049 return false;
20052 // Mark that this expression does not constitute an odr-use.
20053 auto MarkNotOdrUsed = [&] {
20054 S.MaybeODRUseExprs.remove(E);
20055 if (LambdaScopeInfo *LSI = S.getCurLambda())
20056 LSI->markVariableExprAsNonODRUsed(E);
20059 // C++2a [basic.def.odr]p2:
20060 // The set of potential results of an expression e is defined as follows:
20061 switch (E->getStmtClass()) {
20062 // -- If e is an id-expression, ...
20063 case Expr::DeclRefExprClass: {
20064 auto *DRE = cast<DeclRefExpr>(E);
20065 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20066 break;
20068 // Rebuild as a non-odr-use DeclRefExpr.
20069 MarkNotOdrUsed();
20070 return DeclRefExpr::Create(
20071 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20072 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20073 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20074 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20077 case Expr::FunctionParmPackExprClass: {
20078 auto *FPPE = cast<FunctionParmPackExpr>(E);
20079 // If any of the declarations in the pack is odr-used, then the expression
20080 // as a whole constitutes an odr-use.
20081 for (VarDecl *D : *FPPE)
20082 if (IsPotentialResultOdrUsed(D))
20083 return ExprEmpty();
20085 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20086 // nothing cares about whether we marked this as an odr-use, but it might
20087 // be useful for non-compiler tools.
20088 MarkNotOdrUsed();
20089 break;
20092 // -- If e is a subscripting operation with an array operand...
20093 case Expr::ArraySubscriptExprClass: {
20094 auto *ASE = cast<ArraySubscriptExpr>(E);
20095 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20096 if (!OldBase->getType()->isArrayType())
20097 break;
20098 ExprResult Base = Rebuild(OldBase);
20099 if (!Base.isUsable())
20100 return Base;
20101 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20102 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20103 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20104 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20105 ASE->getRBracketLoc());
20108 case Expr::MemberExprClass: {
20109 auto *ME = cast<MemberExpr>(E);
20110 // -- If e is a class member access expression [...] naming a non-static
20111 // data member...
20112 if (isa<FieldDecl>(ME->getMemberDecl())) {
20113 ExprResult Base = Rebuild(ME->getBase());
20114 if (!Base.isUsable())
20115 return Base;
20116 return MemberExpr::Create(
20117 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20118 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20119 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20120 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20121 ME->getObjectKind(), ME->isNonOdrUse());
20124 if (ME->getMemberDecl()->isCXXInstanceMember())
20125 break;
20127 // -- If e is a class member access expression naming a static data member,
20128 // ...
20129 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20130 break;
20132 // Rebuild as a non-odr-use MemberExpr.
20133 MarkNotOdrUsed();
20134 return MemberExpr::Create(
20135 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20136 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20137 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20138 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20141 case Expr::BinaryOperatorClass: {
20142 auto *BO = cast<BinaryOperator>(E);
20143 Expr *LHS = BO->getLHS();
20144 Expr *RHS = BO->getRHS();
20145 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20146 if (BO->getOpcode() == BO_PtrMemD) {
20147 ExprResult Sub = Rebuild(LHS);
20148 if (!Sub.isUsable())
20149 return Sub;
20150 LHS = Sub.get();
20151 // -- If e is a comma expression, ...
20152 } else if (BO->getOpcode() == BO_Comma) {
20153 ExprResult Sub = Rebuild(RHS);
20154 if (!Sub.isUsable())
20155 return Sub;
20156 RHS = Sub.get();
20157 } else {
20158 break;
20160 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
20161 LHS, RHS);
20164 // -- If e has the form (e1)...
20165 case Expr::ParenExprClass: {
20166 auto *PE = cast<ParenExpr>(E);
20167 ExprResult Sub = Rebuild(PE->getSubExpr());
20168 if (!Sub.isUsable())
20169 return Sub;
20170 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20173 // -- If e is a glvalue conditional expression, ...
20174 // We don't apply this to a binary conditional operator. FIXME: Should we?
20175 case Expr::ConditionalOperatorClass: {
20176 auto *CO = cast<ConditionalOperator>(E);
20177 ExprResult LHS = Rebuild(CO->getLHS());
20178 if (LHS.isInvalid())
20179 return ExprError();
20180 ExprResult RHS = Rebuild(CO->getRHS());
20181 if (RHS.isInvalid())
20182 return ExprError();
20183 if (!LHS.isUsable() && !RHS.isUsable())
20184 return ExprEmpty();
20185 if (!LHS.isUsable())
20186 LHS = CO->getLHS();
20187 if (!RHS.isUsable())
20188 RHS = CO->getRHS();
20189 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20190 CO->getCond(), LHS.get(), RHS.get());
20193 // [Clang extension]
20194 // -- If e has the form __extension__ e1...
20195 case Expr::UnaryOperatorClass: {
20196 auto *UO = cast<UnaryOperator>(E);
20197 if (UO->getOpcode() != UO_Extension)
20198 break;
20199 ExprResult Sub = Rebuild(UO->getSubExpr());
20200 if (!Sub.isUsable())
20201 return Sub;
20202 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20203 Sub.get());
20206 // [Clang extension]
20207 // -- If e has the form _Generic(...), the set of potential results is the
20208 // union of the sets of potential results of the associated expressions.
20209 case Expr::GenericSelectionExprClass: {
20210 auto *GSE = cast<GenericSelectionExpr>(E);
20212 SmallVector<Expr *, 4> AssocExprs;
20213 bool AnyChanged = false;
20214 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20215 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20216 if (AssocExpr.isInvalid())
20217 return ExprError();
20218 if (AssocExpr.isUsable()) {
20219 AssocExprs.push_back(AssocExpr.get());
20220 AnyChanged = true;
20221 } else {
20222 AssocExprs.push_back(OrigAssocExpr);
20226 void *ExOrTy = nullptr;
20227 bool IsExpr = GSE->isExprPredicate();
20228 if (IsExpr)
20229 ExOrTy = GSE->getControllingExpr();
20230 else
20231 ExOrTy = GSE->getControllingType();
20232 return AnyChanged ? S.CreateGenericSelectionExpr(
20233 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20234 GSE->getRParenLoc(), IsExpr, ExOrTy,
20235 GSE->getAssocTypeSourceInfos(), AssocExprs)
20236 : ExprEmpty();
20239 // [Clang extension]
20240 // -- If e has the form __builtin_choose_expr(...), the set of potential
20241 // results is the union of the sets of potential results of the
20242 // second and third subexpressions.
20243 case Expr::ChooseExprClass: {
20244 auto *CE = cast<ChooseExpr>(E);
20246 ExprResult LHS = Rebuild(CE->getLHS());
20247 if (LHS.isInvalid())
20248 return ExprError();
20250 ExprResult RHS = Rebuild(CE->getLHS());
20251 if (RHS.isInvalid())
20252 return ExprError();
20254 if (!LHS.get() && !RHS.get())
20255 return ExprEmpty();
20256 if (!LHS.isUsable())
20257 LHS = CE->getLHS();
20258 if (!RHS.isUsable())
20259 RHS = CE->getRHS();
20261 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20262 RHS.get(), CE->getRParenLoc());
20265 // Step through non-syntactic nodes.
20266 case Expr::ConstantExprClass: {
20267 auto *CE = cast<ConstantExpr>(E);
20268 ExprResult Sub = Rebuild(CE->getSubExpr());
20269 if (!Sub.isUsable())
20270 return Sub;
20271 return ConstantExpr::Create(S.Context, Sub.get());
20274 // We could mostly rely on the recursive rebuilding to rebuild implicit
20275 // casts, but not at the top level, so rebuild them here.
20276 case Expr::ImplicitCastExprClass: {
20277 auto *ICE = cast<ImplicitCastExpr>(E);
20278 // Only step through the narrow set of cast kinds we expect to encounter.
20279 // Anything else suggests we've left the region in which potential results
20280 // can be found.
20281 switch (ICE->getCastKind()) {
20282 case CK_NoOp:
20283 case CK_DerivedToBase:
20284 case CK_UncheckedDerivedToBase: {
20285 ExprResult Sub = Rebuild(ICE->getSubExpr());
20286 if (!Sub.isUsable())
20287 return Sub;
20288 CXXCastPath Path(ICE->path());
20289 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20290 ICE->getValueKind(), &Path);
20293 default:
20294 break;
20296 break;
20299 default:
20300 break;
20303 // Can't traverse through this node. Nothing to do.
20304 return ExprEmpty();
20307 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20308 // Check whether the operand is or contains an object of non-trivial C union
20309 // type.
20310 if (E->getType().isVolatileQualified() &&
20311 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20312 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20313 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
20314 Sema::NTCUC_LValueToRValueVolatile,
20315 NTCUK_Destruct|NTCUK_Copy);
20317 // C++2a [basic.def.odr]p4:
20318 // [...] an expression of non-volatile-qualified non-class type to which
20319 // the lvalue-to-rvalue conversion is applied [...]
20320 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
20321 return E;
20323 ExprResult Result =
20324 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
20325 if (Result.isInvalid())
20326 return ExprError();
20327 return Result.get() ? Result : E;
20330 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20331 Res = CorrectDelayedTyposInExpr(Res);
20333 if (!Res.isUsable())
20334 return Res;
20336 // If a constant-expression is a reference to a variable where we delay
20337 // deciding whether it is an odr-use, just assume we will apply the
20338 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20339 // (a non-type template argument), we have special handling anyway.
20340 return CheckLValueToRValueConversionOperand(Res.get());
20343 void Sema::CleanupVarDeclMarking() {
20344 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20345 // call.
20346 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20347 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20349 for (Expr *E : LocalMaybeODRUseExprs) {
20350 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20351 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20352 DRE->getLocation(), *this);
20353 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20354 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20355 *this);
20356 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20357 for (VarDecl *VD : *FP)
20358 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20359 } else {
20360 llvm_unreachable("Unexpected expression");
20364 assert(MaybeODRUseExprs.empty() &&
20365 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20368 static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20369 ValueDecl *Var, Expr *E) {
20370 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20371 if (!VD)
20372 return;
20374 const bool RefersToEnclosingScope =
20375 (SemaRef.CurContext != VD->getDeclContext() &&
20376 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20377 if (RefersToEnclosingScope) {
20378 LambdaScopeInfo *const LSI =
20379 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20380 if (LSI && (!LSI->CallOperator ||
20381 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20382 // If a variable could potentially be odr-used, defer marking it so
20383 // until we finish analyzing the full expression for any
20384 // lvalue-to-rvalue
20385 // or discarded value conversions that would obviate odr-use.
20386 // Add it to the list of potential captures that will be analyzed
20387 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20388 // unless the variable is a reference that was initialized by a constant
20389 // expression (this will never need to be captured or odr-used).
20391 // FIXME: We can simplify this a lot after implementing P0588R1.
20392 assert(E && "Capture variable should be used in an expression.");
20393 if (!Var->getType()->isReferenceType() ||
20394 !VD->isUsableInConstantExpressions(SemaRef.Context))
20395 LSI->addPotentialCapture(E->IgnoreParens());
20400 static void DoMarkVarDeclReferenced(
20401 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20402 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20403 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20404 isa<FunctionParmPackExpr>(E)) &&
20405 "Invalid Expr argument to DoMarkVarDeclReferenced");
20406 Var->setReferenced();
20408 if (Var->isInvalidDecl())
20409 return;
20411 auto *MSI = Var->getMemberSpecializationInfo();
20412 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20413 : Var->getTemplateSpecializationKind();
20415 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20416 bool UsableInConstantExpr =
20417 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
20419 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20420 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
20423 // C++20 [expr.const]p12:
20424 // A variable [...] is needed for constant evaluation if it is [...] a
20425 // variable whose name appears as a potentially constant evaluated
20426 // expression that is either a contexpr variable or is of non-volatile
20427 // const-qualified integral type or of reference type
20428 bool NeededForConstantEvaluation =
20429 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20431 bool NeedDefinition =
20432 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
20434 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20435 "Can't instantiate a partial template specialization.");
20437 // If this might be a member specialization of a static data member, check
20438 // the specialization is visible. We already did the checks for variable
20439 // template specializations when we created them.
20440 if (NeedDefinition && TSK != TSK_Undeclared &&
20441 !isa<VarTemplateSpecializationDecl>(Var))
20442 SemaRef.checkSpecializationVisibility(Loc, Var);
20444 // Perform implicit instantiation of static data members, static data member
20445 // templates of class templates, and variable template specializations. Delay
20446 // instantiations of variable templates, except for those that could be used
20447 // in a constant expression.
20448 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20449 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20450 // instantiation declaration if a variable is usable in a constant
20451 // expression (among other cases).
20452 bool TryInstantiating =
20453 TSK == TSK_ImplicitInstantiation ||
20454 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20456 if (TryInstantiating) {
20457 SourceLocation PointOfInstantiation =
20458 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20459 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20460 if (FirstInstantiation) {
20461 PointOfInstantiation = Loc;
20462 if (MSI)
20463 MSI->setPointOfInstantiation(PointOfInstantiation);
20464 // FIXME: Notify listener.
20465 else
20466 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20469 if (UsableInConstantExpr) {
20470 // Do not defer instantiations of variables that could be used in a
20471 // constant expression.
20472 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20473 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20476 // Re-set the member to trigger a recomputation of the dependence bits
20477 // for the expression.
20478 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20479 DRE->setDecl(DRE->getDecl());
20480 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20481 ME->setMemberDecl(ME->getMemberDecl());
20482 } else if (FirstInstantiation) {
20483 SemaRef.PendingInstantiations
20484 .push_back(std::make_pair(Var, PointOfInstantiation));
20485 } else {
20486 bool Inserted = false;
20487 for (auto &I : SemaRef.SavedPendingInstantiations) {
20488 auto Iter = llvm::find_if(
20489 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20490 return P.first == Var;
20492 if (Iter != I.end()) {
20493 SemaRef.PendingInstantiations.push_back(*Iter);
20494 I.erase(Iter);
20495 Inserted = true;
20496 break;
20500 // FIXME: For a specialization of a variable template, we don't
20501 // distinguish between "declaration and type implicitly instantiated"
20502 // and "implicit instantiation of definition requested", so we have
20503 // no direct way to avoid enqueueing the pending instantiation
20504 // multiple times.
20505 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20506 SemaRef.PendingInstantiations
20507 .push_back(std::make_pair(Var, PointOfInstantiation));
20512 // C++2a [basic.def.odr]p4:
20513 // A variable x whose name appears as a potentially-evaluated expression e
20514 // is odr-used by e unless
20515 // -- x is a reference that is usable in constant expressions
20516 // -- x is a variable of non-reference type that is usable in constant
20517 // expressions and has no mutable subobjects [FIXME], and e is an
20518 // element of the set of potential results of an expression of
20519 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20520 // conversion is applied
20521 // -- x is a variable of non-reference type, and e is an element of the set
20522 // of potential results of a discarded-value expression to which the
20523 // lvalue-to-rvalue conversion is not applied [FIXME]
20525 // We check the first part of the second bullet here, and
20526 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20527 // FIXME: To get the third bullet right, we need to delay this even for
20528 // variables that are not usable in constant expressions.
20530 // If we already know this isn't an odr-use, there's nothing more to do.
20531 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20532 if (DRE->isNonOdrUse())
20533 return;
20534 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20535 if (ME->isNonOdrUse())
20536 return;
20538 switch (OdrUse) {
20539 case OdrUseContext::None:
20540 // In some cases, a variable may not have been marked unevaluated, if it
20541 // appears in a defaukt initializer.
20542 assert((!E || isa<FunctionParmPackExpr>(E) ||
20543 SemaRef.isUnevaluatedContext()) &&
20544 "missing non-odr-use marking for unevaluated decl ref");
20545 break;
20547 case OdrUseContext::FormallyOdrUsed:
20548 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20549 // behavior.
20550 break;
20552 case OdrUseContext::Used:
20553 // If we might later find that this expression isn't actually an odr-use,
20554 // delay the marking.
20555 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
20556 SemaRef.MaybeODRUseExprs.insert(E);
20557 else
20558 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20559 break;
20561 case OdrUseContext::Dependent:
20562 // If this is a dependent context, we don't need to mark variables as
20563 // odr-used, but we may still need to track them for lambda capture.
20564 // FIXME: Do we also need to do this inside dependent typeid expressions
20565 // (which are modeled as unevaluated at this point)?
20566 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20567 break;
20571 static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20572 BindingDecl *BD, Expr *E) {
20573 BD->setReferenced();
20575 if (BD->isInvalidDecl())
20576 return;
20578 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20579 if (OdrUse == OdrUseContext::Used) {
20580 QualType CaptureType, DeclRefType;
20581 SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,
20582 /*EllipsisLoc*/ SourceLocation(),
20583 /*BuildAndDiagnose*/ true, CaptureType,
20584 DeclRefType,
20585 /*FunctionScopeIndexToStopAt*/ nullptr);
20586 } else if (OdrUse == OdrUseContext::Dependent) {
20587 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20591 /// Mark a variable referenced, and check whether it is odr-used
20592 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
20593 /// used directly for normal expressions referring to VarDecl.
20594 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20595 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20598 static void
20599 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20600 bool MightBeOdrUse,
20601 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20602 if (SemaRef.isInOpenMPDeclareTargetContext())
20603 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
20605 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20606 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20607 return;
20610 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20611 DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);
20612 return;
20615 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20617 // If this is a call to a method via a cast, also mark the method in the
20618 // derived class used in case codegen can devirtualize the call.
20619 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20620 if (!ME)
20621 return;
20622 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20623 if (!MD)
20624 return;
20625 // Only attempt to devirtualize if this is truly a virtual call.
20626 bool IsVirtualCall = MD->isVirtual() &&
20627 ME->performsVirtualDispatch(SemaRef.getLangOpts());
20628 if (!IsVirtualCall)
20629 return;
20631 // If it's possible to devirtualize the call, mark the called function
20632 // referenced.
20633 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20634 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20635 if (DM)
20636 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20639 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
20641 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
20642 /// handled with care if the DeclRefExpr is not newly-created.
20643 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20644 // TODO: update this with DR# once a defect report is filed.
20645 // C++11 defect. The address of a pure member should not be an ODR use, even
20646 // if it's a qualified reference.
20647 bool OdrUse = true;
20648 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20649 if (Method->isVirtual() &&
20650 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20651 OdrUse = false;
20653 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20654 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
20655 !isImmediateFunctionContext() &&
20656 !isCheckingDefaultArgumentOrInitializer() &&
20657 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20658 !FD->isDependentContext())
20659 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20661 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20662 RefsMinusAssignments);
20665 /// Perform reference-marking and odr-use handling for a MemberExpr.
20666 void Sema::MarkMemberReferenced(MemberExpr *E) {
20667 // C++11 [basic.def.odr]p2:
20668 // A non-overloaded function whose name appears as a potentially-evaluated
20669 // expression or a member of a set of candidate functions, if selected by
20670 // overload resolution when referred to from a potentially-evaluated
20671 // expression, is odr-used, unless it is a pure virtual function and its
20672 // name is not explicitly qualified.
20673 bool MightBeOdrUse = true;
20674 if (E->performsVirtualDispatch(getLangOpts())) {
20675 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20676 if (Method->isPure())
20677 MightBeOdrUse = false;
20679 SourceLocation Loc =
20680 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20681 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20682 RefsMinusAssignments);
20685 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20686 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20687 for (VarDecl *VD : *E)
20688 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20689 RefsMinusAssignments);
20692 /// Perform marking for a reference to an arbitrary declaration. It
20693 /// marks the declaration referenced, and performs odr-use checking for
20694 /// functions and variables. This method should not be used when building a
20695 /// normal expression which refers to a variable.
20696 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20697 bool MightBeOdrUse) {
20698 if (MightBeOdrUse) {
20699 if (auto *VD = dyn_cast<VarDecl>(D)) {
20700 MarkVariableReferenced(Loc, VD);
20701 return;
20704 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20705 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20706 return;
20708 D->setReferenced();
20711 namespace {
20712 // Mark all of the declarations used by a type as referenced.
20713 // FIXME: Not fully implemented yet! We need to have a better understanding
20714 // of when we're entering a context we should not recurse into.
20715 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20716 // TreeTransforms rebuilding the type in a new context. Rather than
20717 // duplicating the TreeTransform logic, we should consider reusing it here.
20718 // Currently that causes problems when rebuilding LambdaExprs.
20719 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
20720 Sema &S;
20721 SourceLocation Loc;
20723 public:
20724 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
20726 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
20728 bool TraverseTemplateArgument(const TemplateArgument &Arg);
20732 bool MarkReferencedDecls::TraverseTemplateArgument(
20733 const TemplateArgument &Arg) {
20735 // A non-type template argument is a constant-evaluated context.
20736 EnterExpressionEvaluationContext Evaluated(
20737 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20738 if (Arg.getKind() == TemplateArgument::Declaration) {
20739 if (Decl *D = Arg.getAsDecl())
20740 S.MarkAnyDeclReferenced(Loc, D, true);
20741 } else if (Arg.getKind() == TemplateArgument::Expression) {
20742 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
20746 return Inherited::TraverseTemplateArgument(Arg);
20749 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20750 MarkReferencedDecls Marker(*this, Loc);
20751 Marker.TraverseType(T);
20754 namespace {
20755 /// Helper class that marks all of the declarations referenced by
20756 /// potentially-evaluated subexpressions as "referenced".
20757 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20758 public:
20759 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20760 bool SkipLocalVariables;
20761 ArrayRef<const Expr *> StopAt;
20763 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20764 ArrayRef<const Expr *> StopAt)
20765 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20767 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20768 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20771 void Visit(Expr *E) {
20772 if (llvm::is_contained(StopAt, E))
20773 return;
20774 Inherited::Visit(E);
20777 void VisitConstantExpr(ConstantExpr *E) {
20778 // Don't mark declarations within a ConstantExpression, as this expression
20779 // will be evaluated and folded to a value.
20782 void VisitDeclRefExpr(DeclRefExpr *E) {
20783 // If we were asked not to visit local variables, don't.
20784 if (SkipLocalVariables) {
20785 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20786 if (VD->hasLocalStorage())
20787 return;
20790 // FIXME: This can trigger the instantiation of the initializer of a
20791 // variable, which can cause the expression to become value-dependent
20792 // or error-dependent. Do we need to propagate the new dependence bits?
20793 S.MarkDeclRefReferenced(E);
20796 void VisitMemberExpr(MemberExpr *E) {
20797 S.MarkMemberReferenced(E);
20798 Visit(E->getBase());
20801 } // namespace
20803 /// Mark any declarations that appear within this expression or any
20804 /// potentially-evaluated subexpressions as "referenced".
20806 /// \param SkipLocalVariables If true, don't mark local variables as
20807 /// 'referenced'.
20808 /// \param StopAt Subexpressions that we shouldn't recurse into.
20809 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20810 bool SkipLocalVariables,
20811 ArrayRef<const Expr*> StopAt) {
20812 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20815 /// Emit a diagnostic when statements are reachable.
20816 /// FIXME: check for reachability even in expressions for which we don't build a
20817 /// CFG (eg, in the initializer of a global or in a constant expression).
20818 /// For example,
20819 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20820 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20821 const PartialDiagnostic &PD) {
20822 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20823 if (!FunctionScopes.empty())
20824 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20825 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20826 return true;
20829 // The initializer of a constexpr variable or of the first declaration of a
20830 // static data member is not syntactically a constant evaluated constant,
20831 // but nonetheless is always required to be a constant expression, so we
20832 // can skip diagnosing.
20833 // FIXME: Using the mangling context here is a hack.
20834 if (auto *VD = dyn_cast_or_null<VarDecl>(
20835 ExprEvalContexts.back().ManglingContextDecl)) {
20836 if (VD->isConstexpr() ||
20837 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20838 return false;
20839 // FIXME: For any other kind of variable, we should build a CFG for its
20840 // initializer and check whether the context in question is reachable.
20843 Diag(Loc, PD);
20844 return true;
20847 /// Emit a diagnostic that describes an effect on the run-time behavior
20848 /// of the program being compiled.
20850 /// This routine emits the given diagnostic when the code currently being
20851 /// type-checked is "potentially evaluated", meaning that there is a
20852 /// possibility that the code will actually be executable. Code in sizeof()
20853 /// expressions, code used only during overload resolution, etc., are not
20854 /// potentially evaluated. This routine will suppress such diagnostics or,
20855 /// in the absolutely nutty case of potentially potentially evaluated
20856 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
20857 /// later.
20859 /// This routine should be used for all diagnostics that describe the run-time
20860 /// behavior of a program, such as passing a non-POD value through an ellipsis.
20861 /// Failure to do so will likely result in spurious diagnostics or failures
20862 /// during overload resolution or within sizeof/alignof/typeof/typeid.
20863 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20864 const PartialDiagnostic &PD) {
20866 if (ExprEvalContexts.back().isDiscardedStatementContext())
20867 return false;
20869 switch (ExprEvalContexts.back().Context) {
20870 case ExpressionEvaluationContext::Unevaluated:
20871 case ExpressionEvaluationContext::UnevaluatedList:
20872 case ExpressionEvaluationContext::UnevaluatedAbstract:
20873 case ExpressionEvaluationContext::DiscardedStatement:
20874 // The argument will never be evaluated, so don't complain.
20875 break;
20877 case ExpressionEvaluationContext::ConstantEvaluated:
20878 case ExpressionEvaluationContext::ImmediateFunctionContext:
20879 // Relevant diagnostics should be produced by constant evaluation.
20880 break;
20882 case ExpressionEvaluationContext::PotentiallyEvaluated:
20883 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
20884 return DiagIfReachable(Loc, Stmts, PD);
20887 return false;
20890 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
20891 const PartialDiagnostic &PD) {
20892 return DiagRuntimeBehavior(
20893 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20896 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
20897 CallExpr *CE, FunctionDecl *FD) {
20898 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20899 return false;
20901 // If we're inside a decltype's expression, don't check for a valid return
20902 // type or construct temporaries until we know whether this is the last call.
20903 if (ExprEvalContexts.back().ExprContext ==
20904 ExpressionEvaluationContextRecord::EK_Decltype) {
20905 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20906 return false;
20909 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20910 FunctionDecl *FD;
20911 CallExpr *CE;
20913 public:
20914 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20915 : FD(FD), CE(CE) { }
20917 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20918 if (!FD) {
20919 S.Diag(Loc, diag::err_call_incomplete_return)
20920 << T << CE->getSourceRange();
20921 return;
20924 S.Diag(Loc, diag::err_call_function_incomplete_return)
20925 << CE->getSourceRange() << FD << T;
20926 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20927 << FD->getDeclName();
20929 } Diagnoser(FD, CE);
20931 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20932 return true;
20934 return false;
20937 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20938 // will prevent this condition from triggering, which is what we want.
20939 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
20940 SourceLocation Loc;
20942 unsigned diagnostic = diag::warn_condition_is_assignment;
20943 bool IsOrAssign = false;
20945 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20946 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20947 return;
20949 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20951 // Greylist some idioms by putting them into a warning subcategory.
20952 if (ObjCMessageExpr *ME
20953 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20954 Selector Sel = ME->getSelector();
20956 // self = [<foo> init...]
20957 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20958 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20960 // <foo> = [<bar> nextObject]
20961 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20962 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20965 Loc = Op->getOperatorLoc();
20966 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20967 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20968 return;
20970 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20971 Loc = Op->getOperatorLoc();
20972 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20973 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20974 else {
20975 // Not an assignment.
20976 return;
20979 Diag(Loc, diagnostic) << E->getSourceRange();
20981 SourceLocation Open = E->getBeginLoc();
20982 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
20983 Diag(Loc, diag::note_condition_assign_silence)
20984 << FixItHint::CreateInsertion(Open, "(")
20985 << FixItHint::CreateInsertion(Close, ")");
20987 if (IsOrAssign)
20988 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20989 << FixItHint::CreateReplacement(Loc, "!=");
20990 else
20991 Diag(Loc, diag::note_condition_assign_to_comparison)
20992 << FixItHint::CreateReplacement(Loc, "==");
20995 /// Redundant parentheses over an equality comparison can indicate
20996 /// that the user intended an assignment used as condition.
20997 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
20998 // Don't warn if the parens came from a macro.
20999 SourceLocation parenLoc = ParenE->getBeginLoc();
21000 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21001 return;
21002 // Don't warn for dependent expressions.
21003 if (ParenE->isTypeDependent())
21004 return;
21006 Expr *E = ParenE->IgnoreParens();
21008 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21009 if (opE->getOpcode() == BO_EQ &&
21010 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21011 == Expr::MLV_Valid) {
21012 SourceLocation Loc = opE->getOperatorLoc();
21014 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21015 SourceRange ParenERange = ParenE->getSourceRange();
21016 Diag(Loc, diag::note_equality_comparison_silence)
21017 << FixItHint::CreateRemoval(ParenERange.getBegin())
21018 << FixItHint::CreateRemoval(ParenERange.getEnd());
21019 Diag(Loc, diag::note_equality_comparison_to_assign)
21020 << FixItHint::CreateReplacement(Loc, "=");
21024 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21025 bool IsConstexpr) {
21026 DiagnoseAssignmentAsCondition(E);
21027 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21028 DiagnoseEqualityWithExtraParens(parenE);
21030 ExprResult result = CheckPlaceholderExpr(E);
21031 if (result.isInvalid()) return ExprError();
21032 E = result.get();
21034 if (!E->isTypeDependent()) {
21035 if (getLangOpts().CPlusPlus)
21036 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21038 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21039 if (ERes.isInvalid())
21040 return ExprError();
21041 E = ERes.get();
21043 QualType T = E->getType();
21044 if (!T->isScalarType()) { // C99 6.8.4.1p1
21045 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21046 << T << E->getSourceRange();
21047 return ExprError();
21049 CheckBoolLikeConversion(E, Loc);
21052 return E;
21055 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21056 Expr *SubExpr, ConditionKind CK,
21057 bool MissingOK) {
21058 // MissingOK indicates whether having no condition expression is valid
21059 // (for loop) or invalid (e.g. while loop).
21060 if (!SubExpr)
21061 return MissingOK ? ConditionResult() : ConditionError();
21063 ExprResult Cond;
21064 switch (CK) {
21065 case ConditionKind::Boolean:
21066 Cond = CheckBooleanCondition(Loc, SubExpr);
21067 break;
21069 case ConditionKind::ConstexprIf:
21070 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21071 break;
21073 case ConditionKind::Switch:
21074 Cond = CheckSwitchCondition(Loc, SubExpr);
21075 break;
21077 if (Cond.isInvalid()) {
21078 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21079 {SubExpr}, PreferredConditionType(CK));
21080 if (!Cond.get())
21081 return ConditionError();
21083 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
21084 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
21085 if (!FullExpr.get())
21086 return ConditionError();
21088 return ConditionResult(*this, nullptr, FullExpr,
21089 CK == ConditionKind::ConstexprIf);
21092 namespace {
21093 /// A visitor for rebuilding a call to an __unknown_any expression
21094 /// to have an appropriate type.
21095 struct RebuildUnknownAnyFunction
21096 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21098 Sema &S;
21100 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21102 ExprResult VisitStmt(Stmt *S) {
21103 llvm_unreachable("unexpected statement!");
21106 ExprResult VisitExpr(Expr *E) {
21107 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21108 << E->getSourceRange();
21109 return ExprError();
21112 /// Rebuild an expression which simply semantically wraps another
21113 /// expression which it shares the type and value kind of.
21114 template <class T> ExprResult rebuildSugarExpr(T *E) {
21115 ExprResult SubResult = Visit(E->getSubExpr());
21116 if (SubResult.isInvalid()) return ExprError();
21118 Expr *SubExpr = SubResult.get();
21119 E->setSubExpr(SubExpr);
21120 E->setType(SubExpr->getType());
21121 E->setValueKind(SubExpr->getValueKind());
21122 assert(E->getObjectKind() == OK_Ordinary);
21123 return E;
21126 ExprResult VisitParenExpr(ParenExpr *E) {
21127 return rebuildSugarExpr(E);
21130 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21131 return rebuildSugarExpr(E);
21134 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21135 ExprResult SubResult = Visit(E->getSubExpr());
21136 if (SubResult.isInvalid()) return ExprError();
21138 Expr *SubExpr = SubResult.get();
21139 E->setSubExpr(SubExpr);
21140 E->setType(S.Context.getPointerType(SubExpr->getType()));
21141 assert(E->isPRValue());
21142 assert(E->getObjectKind() == OK_Ordinary);
21143 return E;
21146 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21147 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21149 E->setType(VD->getType());
21151 assert(E->isPRValue());
21152 if (S.getLangOpts().CPlusPlus &&
21153 !(isa<CXXMethodDecl>(VD) &&
21154 cast<CXXMethodDecl>(VD)->isInstance()))
21155 E->setValueKind(VK_LValue);
21157 return E;
21160 ExprResult VisitMemberExpr(MemberExpr *E) {
21161 return resolveDecl(E, E->getMemberDecl());
21164 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21165 return resolveDecl(E, E->getDecl());
21170 /// Given a function expression of unknown-any type, try to rebuild it
21171 /// to have a function type.
21172 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21173 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21174 if (Result.isInvalid()) return ExprError();
21175 return S.DefaultFunctionArrayConversion(Result.get());
21178 namespace {
21179 /// A visitor for rebuilding an expression of type __unknown_anytype
21180 /// into one which resolves the type directly on the referring
21181 /// expression. Strict preservation of the original source
21182 /// structure is not a goal.
21183 struct RebuildUnknownAnyExpr
21184 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21186 Sema &S;
21188 /// The current destination type.
21189 QualType DestType;
21191 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21192 : S(S), DestType(CastType) {}
21194 ExprResult VisitStmt(Stmt *S) {
21195 llvm_unreachable("unexpected statement!");
21198 ExprResult VisitExpr(Expr *E) {
21199 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21200 << E->getSourceRange();
21201 return ExprError();
21204 ExprResult VisitCallExpr(CallExpr *E);
21205 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21207 /// Rebuild an expression which simply semantically wraps another
21208 /// expression which it shares the type and value kind of.
21209 template <class T> ExprResult rebuildSugarExpr(T *E) {
21210 ExprResult SubResult = Visit(E->getSubExpr());
21211 if (SubResult.isInvalid()) return ExprError();
21212 Expr *SubExpr = SubResult.get();
21213 E->setSubExpr(SubExpr);
21214 E->setType(SubExpr->getType());
21215 E->setValueKind(SubExpr->getValueKind());
21216 assert(E->getObjectKind() == OK_Ordinary);
21217 return E;
21220 ExprResult VisitParenExpr(ParenExpr *E) {
21221 return rebuildSugarExpr(E);
21224 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21225 return rebuildSugarExpr(E);
21228 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21229 const PointerType *Ptr = DestType->getAs<PointerType>();
21230 if (!Ptr) {
21231 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21232 << E->getSourceRange();
21233 return ExprError();
21236 if (isa<CallExpr>(E->getSubExpr())) {
21237 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21238 << E->getSourceRange();
21239 return ExprError();
21242 assert(E->isPRValue());
21243 assert(E->getObjectKind() == OK_Ordinary);
21244 E->setType(DestType);
21246 // Build the sub-expression as if it were an object of the pointee type.
21247 DestType = Ptr->getPointeeType();
21248 ExprResult SubResult = Visit(E->getSubExpr());
21249 if (SubResult.isInvalid()) return ExprError();
21250 E->setSubExpr(SubResult.get());
21251 return E;
21254 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21256 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21258 ExprResult VisitMemberExpr(MemberExpr *E) {
21259 return resolveDecl(E, E->getMemberDecl());
21262 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21263 return resolveDecl(E, E->getDecl());
21268 /// Rebuilds a call expression which yielded __unknown_anytype.
21269 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21270 Expr *CalleeExpr = E->getCallee();
21272 enum FnKind {
21273 FK_MemberFunction,
21274 FK_FunctionPointer,
21275 FK_BlockPointer
21278 FnKind Kind;
21279 QualType CalleeType = CalleeExpr->getType();
21280 if (CalleeType == S.Context.BoundMemberTy) {
21281 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21282 Kind = FK_MemberFunction;
21283 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21284 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21285 CalleeType = Ptr->getPointeeType();
21286 Kind = FK_FunctionPointer;
21287 } else {
21288 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21289 Kind = FK_BlockPointer;
21291 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21293 // Verify that this is a legal result type of a function.
21294 if (DestType->isArrayType() || DestType->isFunctionType()) {
21295 unsigned diagID = diag::err_func_returning_array_function;
21296 if (Kind == FK_BlockPointer)
21297 diagID = diag::err_block_returning_array_function;
21299 S.Diag(E->getExprLoc(), diagID)
21300 << DestType->isFunctionType() << DestType;
21301 return ExprError();
21304 // Otherwise, go ahead and set DestType as the call's result.
21305 E->setType(DestType.getNonLValueExprType(S.Context));
21306 E->setValueKind(Expr::getValueKindForType(DestType));
21307 assert(E->getObjectKind() == OK_Ordinary);
21309 // Rebuild the function type, replacing the result type with DestType.
21310 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21311 if (Proto) {
21312 // __unknown_anytype(...) is a special case used by the debugger when
21313 // it has no idea what a function's signature is.
21315 // We want to build this call essentially under the K&R
21316 // unprototyped rules, but making a FunctionNoProtoType in C++
21317 // would foul up all sorts of assumptions. However, we cannot
21318 // simply pass all arguments as variadic arguments, nor can we
21319 // portably just call the function under a non-variadic type; see
21320 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21321 // However, it turns out that in practice it is generally safe to
21322 // call a function declared as "A foo(B,C,D);" under the prototype
21323 // "A foo(B,C,D,...);". The only known exception is with the
21324 // Windows ABI, where any variadic function is implicitly cdecl
21325 // regardless of its normal CC. Therefore we change the parameter
21326 // types to match the types of the arguments.
21328 // This is a hack, but it is far superior to moving the
21329 // corresponding target-specific code from IR-gen to Sema/AST.
21331 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21332 SmallVector<QualType, 8> ArgTypes;
21333 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21334 ArgTypes.reserve(E->getNumArgs());
21335 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21336 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21338 ParamTypes = ArgTypes;
21340 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21341 Proto->getExtProtoInfo());
21342 } else {
21343 DestType = S.Context.getFunctionNoProtoType(DestType,
21344 FnType->getExtInfo());
21347 // Rebuild the appropriate pointer-to-function type.
21348 switch (Kind) {
21349 case FK_MemberFunction:
21350 // Nothing to do.
21351 break;
21353 case FK_FunctionPointer:
21354 DestType = S.Context.getPointerType(DestType);
21355 break;
21357 case FK_BlockPointer:
21358 DestType = S.Context.getBlockPointerType(DestType);
21359 break;
21362 // Finally, we can recurse.
21363 ExprResult CalleeResult = Visit(CalleeExpr);
21364 if (!CalleeResult.isUsable()) return ExprError();
21365 E->setCallee(CalleeResult.get());
21367 // Bind a temporary if necessary.
21368 return S.MaybeBindToTemporary(E);
21371 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21372 // Verify that this is a legal result type of a call.
21373 if (DestType->isArrayType() || DestType->isFunctionType()) {
21374 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21375 << DestType->isFunctionType() << DestType;
21376 return ExprError();
21379 // Rewrite the method result type if available.
21380 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21381 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21382 Method->setReturnType(DestType);
21385 // Change the type of the message.
21386 E->setType(DestType.getNonReferenceType());
21387 E->setValueKind(Expr::getValueKindForType(DestType));
21389 return S.MaybeBindToTemporary(E);
21392 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21393 // The only case we should ever see here is a function-to-pointer decay.
21394 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21395 assert(E->isPRValue());
21396 assert(E->getObjectKind() == OK_Ordinary);
21398 E->setType(DestType);
21400 // Rebuild the sub-expression as the pointee (function) type.
21401 DestType = DestType->castAs<PointerType>()->getPointeeType();
21403 ExprResult Result = Visit(E->getSubExpr());
21404 if (!Result.isUsable()) return ExprError();
21406 E->setSubExpr(Result.get());
21407 return E;
21408 } else if (E->getCastKind() == CK_LValueToRValue) {
21409 assert(E->isPRValue());
21410 assert(E->getObjectKind() == OK_Ordinary);
21412 assert(isa<BlockPointerType>(E->getType()));
21414 E->setType(DestType);
21416 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21417 DestType = S.Context.getLValueReferenceType(DestType);
21419 ExprResult Result = Visit(E->getSubExpr());
21420 if (!Result.isUsable()) return ExprError();
21422 E->setSubExpr(Result.get());
21423 return E;
21424 } else {
21425 llvm_unreachable("Unhandled cast type!");
21429 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21430 ExprValueKind ValueKind = VK_LValue;
21431 QualType Type = DestType;
21433 // We know how to make this work for certain kinds of decls:
21435 // - functions
21436 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21437 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21438 DestType = Ptr->getPointeeType();
21439 ExprResult Result = resolveDecl(E, VD);
21440 if (Result.isInvalid()) return ExprError();
21441 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21442 VK_PRValue);
21445 if (!Type->isFunctionType()) {
21446 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21447 << VD << E->getSourceRange();
21448 return ExprError();
21450 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21451 // We must match the FunctionDecl's type to the hack introduced in
21452 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21453 // type. See the lengthy commentary in that routine.
21454 QualType FDT = FD->getType();
21455 const FunctionType *FnType = FDT->castAs<FunctionType>();
21456 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21457 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21458 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21459 SourceLocation Loc = FD->getLocation();
21460 FunctionDecl *NewFD = FunctionDecl::Create(
21461 S.Context, FD->getDeclContext(), Loc, Loc,
21462 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21463 SC_None, S.getCurFPFeatures().isFPConstrained(),
21464 false /*isInlineSpecified*/, FD->hasPrototype(),
21465 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21467 if (FD->getQualifier())
21468 NewFD->setQualifierInfo(FD->getQualifierLoc());
21470 SmallVector<ParmVarDecl*, 16> Params;
21471 for (const auto &AI : FT->param_types()) {
21472 ParmVarDecl *Param =
21473 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21474 Param->setScopeInfo(0, Params.size());
21475 Params.push_back(Param);
21477 NewFD->setParams(Params);
21478 DRE->setDecl(NewFD);
21479 VD = DRE->getDecl();
21483 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21484 if (MD->isInstance()) {
21485 ValueKind = VK_PRValue;
21486 Type = S.Context.BoundMemberTy;
21489 // Function references aren't l-values in C.
21490 if (!S.getLangOpts().CPlusPlus)
21491 ValueKind = VK_PRValue;
21493 // - variables
21494 } else if (isa<VarDecl>(VD)) {
21495 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21496 Type = RefTy->getPointeeType();
21497 } else if (Type->isFunctionType()) {
21498 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21499 << VD << E->getSourceRange();
21500 return ExprError();
21503 // - nothing else
21504 } else {
21505 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21506 << VD << E->getSourceRange();
21507 return ExprError();
21510 // Modifying the declaration like this is friendly to IR-gen but
21511 // also really dangerous.
21512 VD->setType(DestType);
21513 E->setType(Type);
21514 E->setValueKind(ValueKind);
21515 return E;
21518 /// Check a cast of an unknown-any type. We intentionally only
21519 /// trigger this for C-style casts.
21520 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21521 Expr *CastExpr, CastKind &CastKind,
21522 ExprValueKind &VK, CXXCastPath &Path) {
21523 // The type we're casting to must be either void or complete.
21524 if (!CastType->isVoidType() &&
21525 RequireCompleteType(TypeRange.getBegin(), CastType,
21526 diag::err_typecheck_cast_to_incomplete))
21527 return ExprError();
21529 // Rewrite the casted expression from scratch.
21530 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21531 if (!result.isUsable()) return ExprError();
21533 CastExpr = result.get();
21534 VK = CastExpr->getValueKind();
21535 CastKind = CK_NoOp;
21537 return CastExpr;
21540 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21541 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21544 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21545 Expr *arg, QualType &paramType) {
21546 // If the syntactic form of the argument is not an explicit cast of
21547 // any sort, just do default argument promotion.
21548 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21549 if (!castArg) {
21550 ExprResult result = DefaultArgumentPromotion(arg);
21551 if (result.isInvalid()) return ExprError();
21552 paramType = result.get()->getType();
21553 return result;
21556 // Otherwise, use the type that was written in the explicit cast.
21557 assert(!arg->hasPlaceholderType());
21558 paramType = castArg->getTypeAsWritten();
21560 // Copy-initialize a parameter of that type.
21561 InitializedEntity entity =
21562 InitializedEntity::InitializeParameter(Context, paramType,
21563 /*consumed*/ false);
21564 return PerformCopyInitialization(entity, callLoc, arg);
21567 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21568 Expr *orig = E;
21569 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21570 while (true) {
21571 E = E->IgnoreParenImpCasts();
21572 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21573 E = call->getCallee();
21574 diagID = diag::err_uncasted_call_of_unknown_any;
21575 } else {
21576 break;
21580 SourceLocation loc;
21581 NamedDecl *d;
21582 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21583 loc = ref->getLocation();
21584 d = ref->getDecl();
21585 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21586 loc = mem->getMemberLoc();
21587 d = mem->getMemberDecl();
21588 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21589 diagID = diag::err_uncasted_call_of_unknown_any;
21590 loc = msg->getSelectorStartLoc();
21591 d = msg->getMethodDecl();
21592 if (!d) {
21593 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21594 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21595 << orig->getSourceRange();
21596 return ExprError();
21598 } else {
21599 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21600 << E->getSourceRange();
21601 return ExprError();
21604 S.Diag(loc, diagID) << d << orig->getSourceRange();
21606 // Never recoverable.
21607 return ExprError();
21610 /// Check for operands with placeholder types and complain if found.
21611 /// Returns ExprError() if there was an error and no recovery was possible.
21612 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21613 if (!Context.isDependenceAllowed()) {
21614 // C cannot handle TypoExpr nodes on either side of a binop because it
21615 // doesn't handle dependent types properly, so make sure any TypoExprs have
21616 // been dealt with before checking the operands.
21617 ExprResult Result = CorrectDelayedTyposInExpr(E);
21618 if (!Result.isUsable()) return ExprError();
21619 E = Result.get();
21622 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21623 if (!placeholderType) return E;
21625 switch (placeholderType->getKind()) {
21627 // Overloaded expressions.
21628 case BuiltinType::Overload: {
21629 // Try to resolve a single function template specialization.
21630 // This is obligatory.
21631 ExprResult Result = E;
21632 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
21633 return Result;
21635 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21636 // leaves Result unchanged on failure.
21637 Result = E;
21638 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
21639 return Result;
21641 // If that failed, try to recover with a call.
21642 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21643 /*complain*/ true);
21644 return Result;
21647 // Bound member functions.
21648 case BuiltinType::BoundMember: {
21649 ExprResult result = E;
21650 const Expr *BME = E->IgnoreParens();
21651 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21652 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21653 if (isa<CXXPseudoDestructorExpr>(BME)) {
21654 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21655 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21656 if (ME->getMemberNameInfo().getName().getNameKind() ==
21657 DeclarationName::CXXDestructorName)
21658 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21660 tryToRecoverWithCall(result, PD,
21661 /*complain*/ true);
21662 return result;
21665 // ARC unbridged casts.
21666 case BuiltinType::ARCUnbridgedCast: {
21667 Expr *realCast = stripARCUnbridgedCast(E);
21668 diagnoseARCUnbridgedCast(realCast);
21669 return realCast;
21672 // Expressions of unknown type.
21673 case BuiltinType::UnknownAny:
21674 return diagnoseUnknownAnyExpr(*this, E);
21676 // Pseudo-objects.
21677 case BuiltinType::PseudoObject:
21678 return checkPseudoObjectRValue(E);
21680 case BuiltinType::BuiltinFn: {
21681 // Accept __noop without parens by implicitly converting it to a call expr.
21682 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21683 if (DRE) {
21684 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21685 unsigned BuiltinID = FD->getBuiltinID();
21686 if (BuiltinID == Builtin::BI__noop) {
21687 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21688 CK_BuiltinFnToFnPtr)
21689 .get();
21690 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21691 VK_PRValue, SourceLocation(),
21692 FPOptionsOverride());
21695 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21696 // Any use of these other than a direct call is ill-formed as of C++20,
21697 // because they are not addressable functions. In earlier language
21698 // modes, warn and force an instantiation of the real body.
21699 Diag(E->getBeginLoc(),
21700 getLangOpts().CPlusPlus20
21701 ? diag::err_use_of_unaddressable_function
21702 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21703 if (FD->isImplicitlyInstantiable()) {
21704 // Require a definition here because a normal attempt at
21705 // instantiation for a builtin will be ignored, and we won't try
21706 // again later. We assume that the definition of the template
21707 // precedes this use.
21708 InstantiateFunctionDefinition(E->getBeginLoc(), FD,
21709 /*Recursive=*/false,
21710 /*DefinitionRequired=*/true,
21711 /*AtEndOfTU=*/false);
21713 // Produce a properly-typed reference to the function.
21714 CXXScopeSpec SS;
21715 SS.Adopt(DRE->getQualifierLoc());
21716 TemplateArgumentListInfo TemplateArgs;
21717 DRE->copyTemplateArgumentsInto(TemplateArgs);
21718 return BuildDeclRefExpr(
21719 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21720 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21721 DRE->getTemplateKeywordLoc(),
21722 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21726 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21727 return ExprError();
21730 case BuiltinType::IncompleteMatrixIdx:
21731 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21732 ->getRowIdx()
21733 ->getBeginLoc(),
21734 diag::err_matrix_incomplete_index);
21735 return ExprError();
21737 // Expressions of unknown type.
21738 case BuiltinType::OMPArraySection:
21739 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
21740 return ExprError();
21742 // Expressions of unknown type.
21743 case BuiltinType::OMPArrayShaping:
21744 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21746 case BuiltinType::OMPIterator:
21747 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21749 // Everything else should be impossible.
21750 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21751 case BuiltinType::Id:
21752 #include "clang/Basic/OpenCLImageTypes.def"
21753 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21754 case BuiltinType::Id:
21755 #include "clang/Basic/OpenCLExtensionTypes.def"
21756 #define SVE_TYPE(Name, Id, SingletonId) \
21757 case BuiltinType::Id:
21758 #include "clang/Basic/AArch64SVEACLETypes.def"
21759 #define PPC_VECTOR_TYPE(Name, Id, Size) \
21760 case BuiltinType::Id:
21761 #include "clang/Basic/PPCTypes.def"
21762 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21763 #include "clang/Basic/RISCVVTypes.def"
21764 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21765 #include "clang/Basic/WebAssemblyReferenceTypes.def"
21766 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21767 #define PLACEHOLDER_TYPE(Id, SingletonId)
21768 #include "clang/AST/BuiltinTypes.def"
21769 break;
21772 llvm_unreachable("invalid placeholder type!");
21775 bool Sema::CheckCaseExpression(Expr *E) {
21776 if (E->isTypeDependent())
21777 return true;
21778 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
21779 return E->getType()->isIntegralOrEnumerationType();
21780 return false;
21783 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21784 ExprResult
21785 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
21786 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
21787 "Unknown Objective-C Boolean value!");
21788 QualType BoolT = Context.ObjCBuiltinBoolTy;
21789 if (!Context.getBOOLDecl()) {
21790 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
21791 Sema::LookupOrdinaryName);
21792 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
21793 NamedDecl *ND = Result.getFoundDecl();
21794 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
21795 Context.setBOOLDecl(TD);
21798 if (Context.getBOOLDecl())
21799 BoolT = Context.getBOOLType();
21800 return new (Context)
21801 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
21804 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
21805 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
21806 SourceLocation RParen) {
21807 auto FindSpecVersion =
21808 [&](StringRef Platform) -> std::optional<VersionTuple> {
21809 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21810 return Spec.getPlatform() == Platform;
21812 // Transcribe the "ios" availability check to "maccatalyst" when compiling
21813 // for "maccatalyst" if "maccatalyst" is not specified.
21814 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
21815 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21816 return Spec.getPlatform() == "ios";
21819 if (Spec == AvailSpecs.end())
21820 return std::nullopt;
21821 return Spec->getVersion();
21824 VersionTuple Version;
21825 if (auto MaybeVersion =
21826 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
21827 Version = *MaybeVersion;
21829 // The use of `@available` in the enclosing context should be analyzed to
21830 // warn when it's used inappropriately (i.e. not if(@available)).
21831 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
21832 Context->HasPotentialAvailabilityViolations = true;
21834 return new (Context)
21835 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
21838 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
21839 ArrayRef<Expr *> SubExprs, QualType T) {
21840 if (!Context.getLangOpts().RecoveryAST)
21841 return ExprError();
21843 if (isSFINAEContext())
21844 return ExprError();
21846 if (T.isNull() || T->isUndeducedType() ||
21847 !Context.getLangOpts().RecoveryASTType)
21848 // We don't know the concrete type, fallback to dependent type.
21849 T = Context.DependentTy;
21851 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);