1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
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
7 //===----------------------------------------------------------------------===//
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/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/FixedPoint.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
53 using llvm::RoundingMode;
55 /// Determine whether the use of this declaration is valid, without
56 /// emitting diagnostics.
57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58 // See if this is an auto-typed variable whose initializer we are parsing.
59 if (ParsingInitForAutoVars.count(D))
62 // See if this is a deleted function.
63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
67 // If the function has a deduced return type, and we can't deduce it,
68 // then we can't use it either.
69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
73 // See if this is an aligned allocation/deallocation function that is
75 if (TreatUnavailableAsInvalid &&
76 isUnavailableAlignedAllocationFunction(*FD))
80 // See if this function is unavailable.
81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89 // Warn if this is used but marked unused.
90 if (const auto *A = D->getAttr<UnusedAttr>()) {
91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92 // should diagnose them.
93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96 if (DC && !DC->hasAttr<UnusedAttr>())
97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
102 /// Emit a note explaining that this function is deleted.
103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104 assert(Decl && Decl->isDeleted());
106 if (Decl->isDefaulted()) {
107 // If the method was explicitly defaulted, point at that declaration.
108 if (!Decl->isImplicit())
109 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
111 // Try to diagnose why this special member function was implicitly
112 // deleted. This might fail, if that reason no longer applies.
113 DiagnoseDeletedDefaultedFunction(Decl);
117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118 if (Ctor && Ctor->isInheritingConstructor())
119 return NoteDeletedInheritingConstructor(Ctor);
121 Diag(Decl->getLocation(), diag::note_availability_specified_here)
125 /// Determine whether a FunctionDecl was ever declared with an
126 /// explicit storage class.
127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128 for (auto I : D->redecls()) {
129 if (I->getStorageClass() != SC_None)
135 /// Check whether we're in an extern inline function and referring to a
136 /// variable or function with internal linkage (C11 6.7.4p3).
138 /// This is only a warning because we used to silently accept this code, but
139 /// in many cases it will not behave correctly. This is not enabled in C++ mode
140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141 /// and so while there may still be user mistakes, most of the time we can't
142 /// prove that there are errors.
143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
145 SourceLocation Loc) {
146 // This is disabled under C++; there are too many ways for this to fire in
147 // contexts where the warning is a false positive, or where it is technically
148 // correct but benign.
149 if (S.getLangOpts().CPlusPlus)
152 // Check if this is an inlined function or method.
153 FunctionDecl *Current = S.getCurFunctionDecl();
156 if (!Current->isInlined())
158 if (!Current->isExternallyVisible())
161 // Check if the decl has internal linkage.
162 if (D->getFormalLinkage() != InternalLinkage)
165 // Downgrade from ExtWarn to Extension if
166 // (1) the supposedly external inline function is in the main file,
167 // and probably won't be included anywhere else.
168 // (2) the thing we're referencing is a pure function.
169 // (3) the thing we're referencing is another inline function.
170 // This last can give us false negatives, but it's better than warning on
171 // wrappers for simple C library functions.
172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174 if (!DowngradeWarning && UsedFn)
175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178 : diag::ext_internal_in_extern_inline)
179 << /*IsVar=*/!UsedFn << D;
181 S.MaybeSuggestAddingStaticToDecl(Current);
183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188 const FunctionDecl *First = Cur->getFirstDecl();
190 // Suggest "static" on the function, if possible.
191 if (!hasAnyExplicitStorageClass(First)) {
192 SourceLocation DeclBegin = First->getSourceRange().getBegin();
193 Diag(DeclBegin, diag::note_convert_inline_to_static)
194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
198 /// Determine whether the use of this declaration is valid, and
199 /// emit any corresponding diagnostics.
201 /// This routine diagnoses various problems with referencing
202 /// declarations that can occur when using a declaration. For example,
203 /// it might warn if a deprecated or unavailable declaration is being
204 /// used, or produce an error (and return true) if a C++0x deleted
205 /// function is being used.
207 /// \returns true if there was an error (this declaration cannot be
208 /// referenced), false otherwise.
210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211 const ObjCInterfaceDecl *UnknownObjCClass,
212 bool ObjCPropertyAccess,
213 bool AvoidPartialAvailabilityChecks,
214 ObjCInterfaceDecl *ClassReceiver) {
215 SourceLocation Loc = Locs.front();
216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217 // If there were any diagnostics suppressed by template argument deduction,
219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220 if (Pos != SuppressedDiagnostics.end()) {
221 for (const PartialDiagnosticAt &Suppressed : Pos->second)
222 Diag(Suppressed.first, Suppressed.second);
224 // Clear out the list of suppressed diagnostics, so that we don't emit
225 // them again for this specialization. However, we don't obsolete this
226 // entry from the table, because we want to avoid ever emitting these
227 // diagnostics again.
231 // C++ [basic.start.main]p3:
232 // The function 'main' shall not be used within a program.
233 if (cast<FunctionDecl>(D)->isMain())
234 Diag(Loc, diag::ext_main_used);
236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
239 // See if this is an auto-typed variable whose initializer we are parsing.
240 if (ParsingInitForAutoVars.count(D)) {
241 if (isa<BindingDecl>(D)) {
242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246 << D->getDeclName() << cast<VarDecl>(D)->getType();
251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252 // See if this is a deleted function.
253 if (FD->isDeleted()) {
254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255 if (Ctor && Ctor->isInheritingConstructor())
256 Diag(Loc, diag::err_deleted_inherited_ctor_use)
258 << Ctor->getInheritedConstructor().getConstructor()->getParent();
260 Diag(Loc, diag::err_deleted_function_use);
261 NoteDeletedFunction(FD);
266 // A program that refers explicitly or implicitly to a function with a
267 // trailing requires-clause whose constraint-expression is not satisfied,
268 // other than to declare it, is ill-formed. [...]
270 // See if this is a function with constraints that need to be satisfied.
271 // Check this before deducing the return type, as it might instantiate the
273 if (FD->getTrailingRequiresClause()) {
274 ConstraintSatisfaction Satisfaction;
275 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276 // A diagnostic will have already been generated (non-constant
277 // constraint expression, for example)
279 if (!Satisfaction.IsSatisfied) {
281 diag::err_reference_to_function_with_unsatisfied_constraints)
283 DiagnoseUnsatisfiedConstraint(Satisfaction);
288 // If the function has a deduced return type, and we can't deduce it,
289 // then we can't use it either.
290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291 DeduceReturnType(FD, Loc))
294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
297 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
301 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302 // Lambdas are only default-constructible or assignable in C++2a onwards.
303 if (MD->getParent()->isLambda() &&
304 ((isa<CXXConstructorDecl>(MD) &&
305 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
307 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308 << !isa<CXXConstructorDecl>(MD);
312 auto getReferencedObjCProp = [](const NamedDecl *D) ->
313 const ObjCPropertyDecl * {
314 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315 return MD->findPropertyDecl();
318 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
321 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
325 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326 // Only the variables omp_in and omp_out are allowed in the combiner.
327 // Only the variables omp_priv and omp_orig are allowed in the
328 // initializer-clause.
329 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
332 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333 << getCurFunction()->HasOMPDeclareReductionCombiner;
334 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
338 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339 // List-items in map clauses on this construct may only refer to the declared
340 // variable var and entities that could be referenced by a procedure defined
341 // at the same location
342 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
343 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
345 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
346 << DMD->getVarName().getAsString();
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
351 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
352 AvoidPartialAvailabilityChecks, ClassReceiver);
354 DiagnoseUnusedOfDecl(*this, D, Loc);
356 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
358 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
359 if (const auto *VD = dyn_cast<ValueDecl>(D))
360 checkDeviceDecl(VD, Loc);
362 if (!Context.getTargetInfo().isTLSSupported())
363 if (const auto *VD = dyn_cast<VarDecl>(D))
364 if (VD->getTLSKind() != VarDecl::TLS_None)
365 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
368 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
369 !isUnevaluatedContext()) {
370 // C++ [expr.prim.req.nested] p3
371 // A local parameter shall only appear as an unevaluated operand
372 // (Clause 8) within the constraint-expression.
373 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
375 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
382 /// DiagnoseSentinelCalls - This routine checks whether a call or
383 /// message-send is to a declaration with the sentinel attribute, and
384 /// if so, it checks that the requirements of the sentinel are
386 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
387 ArrayRef<Expr *> Args) {
388 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
392 // The number of formal parameters of the declaration.
393 unsigned numFormalParams;
395 // The kind of declaration. This is also an index into a %select in
397 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
399 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
400 numFormalParams = MD->param_size();
401 calleeType = CT_Method;
402 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
403 numFormalParams = FD->param_size();
404 calleeType = CT_Function;
405 } else if (isa<VarDecl>(D)) {
406 QualType type = cast<ValueDecl>(D)->getType();
407 const FunctionType *fn = nullptr;
408 if (const PointerType *ptr = type->getAs<PointerType>()) {
409 fn = ptr->getPointeeType()->getAs<FunctionType>();
411 calleeType = CT_Function;
412 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
413 fn = ptr->getPointeeType()->castAs<FunctionType>();
414 calleeType = CT_Block;
419 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
420 numFormalParams = proto->getNumParams();
428 // "nullPos" is the number of formal parameters at the end which
429 // effectively count as part of the variadic arguments. This is
430 // useful if you would prefer to not have *any* formal parameters,
431 // but the language forces you to have at least one.
432 unsigned nullPos = attr->getNullPos();
433 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
434 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
436 // The number of arguments which should follow the sentinel.
437 unsigned numArgsAfterSentinel = attr->getSentinel();
439 // If there aren't enough arguments for all the formal parameters,
440 // the sentinel, and the args after the sentinel, complain.
441 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
442 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
443 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
447 // Otherwise, find the sentinel expression.
448 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
449 if (!sentinelExpr) return;
450 if (sentinelExpr->isValueDependent()) return;
451 if (Context.isSentinelNullExpr(sentinelExpr)) return;
453 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
454 // or 'NULL' if those are actually defined in the context. Only use
455 // 'nil' for ObjC methods, where it's much more likely that the
456 // variadic arguments form a list of object pointers.
457 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
458 std::string NullValue;
459 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
461 else if (getLangOpts().CPlusPlus11)
462 NullValue = "nullptr";
463 else if (PP.isMacroDefined("NULL"))
466 NullValue = "(void*) 0";
468 if (MissingNilLoc.isInvalid())
469 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
471 Diag(MissingNilLoc, diag::warn_missing_sentinel)
473 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
474 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
477 SourceRange Sema::getExprRange(Expr *E) const {
478 return E ? E->getSourceRange() : SourceRange();
481 //===----------------------------------------------------------------------===//
482 // Standard Promotions and Conversions
483 //===----------------------------------------------------------------------===//
485 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
486 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
487 // Handle any placeholder expressions which made it here.
488 if (E->getType()->isPlaceholderType()) {
489 ExprResult result = CheckPlaceholderExpr(E);
490 if (result.isInvalid()) return ExprError();
494 QualType Ty = E->getType();
495 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
497 if (Ty->isFunctionType()) {
498 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
499 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
500 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
503 E = ImpCastExprToType(E, Context.getPointerType(Ty),
504 CK_FunctionToPointerDecay).get();
505 } else if (Ty->isArrayType()) {
506 // In C90 mode, arrays only promote to pointers if the array expression is
507 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
508 // type 'array of type' is converted to an expression that has type 'pointer
509 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
510 // that has type 'array of type' ...". The relevant change is "an lvalue"
511 // (C90) to "an expression" (C99).
514 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
515 // T" can be converted to an rvalue of type "pointer to T".
517 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
518 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
519 CK_ArrayToPointerDecay).get();
524 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
525 // Check to see if we are dereferencing a null pointer. If so,
526 // and if not volatile-qualified, this is undefined behavior that the
527 // optimizer will delete, so warn about it. People sometimes try to use this
528 // to get a deterministic trap and are surprised by clang's behavior. This
529 // only handles the pattern "*null", which is a very syntactic check.
530 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
531 if (UO && UO->getOpcode() == UO_Deref &&
532 UO->getSubExpr()->getType()->isPointerType()) {
534 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
535 if ((!isTargetAddressSpace(AS) ||
536 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
537 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
538 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
539 !UO->getType().isVolatileQualified()) {
540 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
541 S.PDiag(diag::warn_indirection_through_null)
542 << UO->getSubExpr()->getSourceRange());
543 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
544 S.PDiag(diag::note_indirection_through_null));
549 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
550 SourceLocation AssignLoc,
552 const ObjCIvarDecl *IV = OIRE->getDecl();
556 DeclarationName MemberName = IV->getDeclName();
557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
558 if (!Member || !Member->isStr("isa"))
561 const Expr *Base = OIRE->getBase();
562 QualType BaseType = Base->getType();
564 BaseType = BaseType->getPointeeType();
565 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
566 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
567 ObjCInterfaceDecl *ClassDeclared = nullptr;
568 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
569 if (!ClassDeclared->getSuperClass()
570 && (*ClassDeclared->ivar_begin()) == IV) {
572 NamedDecl *ObjectSetClass =
573 S.LookupSingleName(S.TUScope,
574 &S.Context.Idents.get("object_setClass"),
575 SourceLocation(), S.LookupOrdinaryName);
576 if (ObjectSetClass) {
577 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
578 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
579 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
581 << FixItHint::CreateReplacement(
582 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
583 << FixItHint::CreateInsertion(RHSLocEnd, ")");
586 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
588 NamedDecl *ObjectGetClass =
589 S.LookupSingleName(S.TUScope,
590 &S.Context.Idents.get("object_getClass"),
591 SourceLocation(), S.LookupOrdinaryName);
593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
596 << FixItHint::CreateReplacement(
597 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
599 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
601 S.Diag(IV->getLocation(), diag::note_ivar_decl);
606 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
607 // Handle any placeholder expressions which made it here.
608 if (E->getType()->isPlaceholderType()) {
609 ExprResult result = CheckPlaceholderExpr(E);
610 if (result.isInvalid()) return ExprError();
614 // C++ [conv.lval]p1:
615 // A glvalue of a non-function, non-array type T can be
616 // converted to a prvalue.
617 if (!E->isGLValue()) return E;
619 QualType T = E->getType();
620 assert(!T.isNull() && "r-value conversion on typeless expression?");
622 // lvalue-to-rvalue conversion cannot be applied to function or array types.
623 if (T->isFunctionType() || T->isArrayType())
626 // We don't want to throw lvalue-to-rvalue casts on top of
627 // expressions of certain types in C++.
628 if (getLangOpts().CPlusPlus &&
629 (E->getType() == Context.OverloadTy ||
630 T->isDependentType() ||
634 // The C standard is actually really unclear on this point, and
635 // DR106 tells us what the result should be but not why. It's
636 // generally best to say that void types just doesn't undergo
637 // lvalue-to-rvalue at all. Note that expressions of unqualified
638 // 'void' type are never l-values, but qualified void can be.
642 // OpenCL usually rejects direct accesses to values of 'half' type.
643 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
645 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
650 CheckForNullPointerDereference(*this, E);
651 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
652 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
653 &Context.Idents.get("object_getClass"),
654 SourceLocation(), LookupOrdinaryName);
656 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
657 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
658 << FixItHint::CreateReplacement(
659 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
661 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
663 else if (const ObjCIvarRefExpr *OIRE =
664 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
665 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
667 // C++ [conv.lval]p1:
668 // [...] If T is a non-class type, the type of the prvalue is the
669 // cv-unqualified version of T. Otherwise, the type of the
673 // If the lvalue has qualified type, the value has the unqualified
674 // version of the type of the lvalue; otherwise, the value has the
675 // type of the lvalue.
676 if (T.hasQualifiers())
677 T = T.getUnqualifiedType();
679 // Under the MS ABI, lock down the inheritance model now.
680 if (T->isMemberPointerType() &&
681 Context.getTargetInfo().getCXXABI().isMicrosoft())
682 (void)isCompleteType(E->getExprLoc(), T);
684 ExprResult Res = CheckLValueToRValueConversionOperand(E);
689 // Loading a __weak object implicitly retains the value, so we need a cleanup to
691 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
692 Cleanup.setExprNeedsCleanups(true);
694 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
695 Cleanup.setExprNeedsCleanups(true);
697 // C++ [conv.lval]p3:
698 // If T is cv std::nullptr_t, the result is a null pointer constant.
699 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
700 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
703 // ... if the lvalue has atomic type, the value has the non-atomic version
704 // of the type of the lvalue ...
705 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
706 T = Atomic->getValueType().getUnqualifiedType();
707 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
714 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
715 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
718 Res = DefaultLvalueConversion(Res.get());
724 /// CallExprUnaryConversions - a special case of an unary conversion
725 /// performed on a function designator of a call expression.
726 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
727 QualType Ty = E->getType();
729 // Only do implicit cast for a function type, but not for a pointer
731 if (Ty->isFunctionType()) {
732 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
733 CK_FunctionToPointerDecay);
737 Res = DefaultLvalueConversion(Res.get());
743 /// UsualUnaryConversions - Performs various conversions that are common to most
744 /// operators (C99 6.3). The conversions of array and function types are
745 /// sometimes suppressed. For example, the array->pointer conversion doesn't
746 /// apply if the array is an argument to the sizeof or address (&) operators.
747 /// In these instances, this routine should *not* be called.
748 ExprResult Sema::UsualUnaryConversions(Expr *E) {
749 // First, convert to an r-value.
750 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
755 QualType Ty = E->getType();
756 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
758 // Half FP have to be promoted to float unless it is natively supported
759 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
760 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
762 // Try to perform integral promotions if the object has a theoretically
764 if (Ty->isIntegralOrUnscopedEnumerationType()) {
767 // The following may be used in an expression wherever an int or
768 // unsigned int may be used:
769 // - an object or expression with an integer type whose integer
770 // conversion rank is less than or equal to the rank of int
772 // - A bit-field of type _Bool, int, signed int, or unsigned int.
774 // If an int can represent all values of the original type, the
775 // value is converted to an int; otherwise, it is converted to an
776 // unsigned int. These are called the integer promotions. All
777 // other types are unchanged by the integer promotions.
779 QualType PTy = Context.isPromotableBitField(E);
781 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
784 if (Ty->isPromotableIntegerType()) {
785 QualType PT = Context.getPromotedIntegerType(Ty);
786 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
793 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
794 /// do not have a prototype. Arguments that have type float or __fp16
795 /// are promoted to double. All other argument types are converted by
796 /// UsualUnaryConversions().
797 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
798 QualType Ty = E->getType();
799 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
801 ExprResult Res = UsualUnaryConversions(E);
806 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
807 // promote to double.
808 // Note that default argument promotion applies only to float (and
809 // half/fp16); it does not apply to _Float16.
810 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
811 if (BTy && (BTy->getKind() == BuiltinType::Half ||
812 BTy->getKind() == BuiltinType::Float)) {
813 if (getLangOpts().OpenCL &&
814 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
815 if (BTy->getKind() == BuiltinType::Half) {
816 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
819 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
823 // C++ performs lvalue-to-rvalue conversion as a default argument
824 // promotion, even on class types, but note:
825 // C++11 [conv.lval]p2:
826 // When an lvalue-to-rvalue conversion occurs in an unevaluated
827 // operand or a subexpression thereof the value contained in the
828 // referenced object is not accessed. Otherwise, if the glvalue
829 // has a class type, the conversion copy-initializes a temporary
830 // of type T from the glvalue and the result of the conversion
831 // is a prvalue for the temporary.
832 // FIXME: add some way to gate this entire thing for correctness in
833 // potentially potentially evaluated contexts.
834 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
835 ExprResult Temp = PerformCopyInitialization(
836 InitializedEntity::InitializeTemporary(E->getType()),
838 if (Temp.isInvalid())
846 /// Determine the degree of POD-ness for an expression.
847 /// Incomplete types are considered POD, since this check can be performed
848 /// when we're in an unevaluated context.
849 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
850 if (Ty->isIncompleteType()) {
851 // C++11 [expr.call]p7:
852 // After these conversions, if the argument does not have arithmetic,
853 // enumeration, pointer, pointer to member, or class type, the program
856 // Since we've already performed array-to-pointer and function-to-pointer
857 // decay, the only such type in C++ is cv void. This also handles
858 // initializer lists as variadic arguments.
859 if (Ty->isVoidType())
862 if (Ty->isObjCObjectType())
867 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
870 if (Ty.isCXX98PODType(Context))
873 // C++11 [expr.call]p7:
874 // Passing a potentially-evaluated argument of class type (Clause 9)
875 // having a non-trivial copy constructor, a non-trivial move constructor,
876 // or a non-trivial destructor, with no corresponding parameter,
877 // is conditionally-supported with implementation-defined semantics.
878 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
879 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
880 if (!Record->hasNonTrivialCopyConstructor() &&
881 !Record->hasNonTrivialMoveConstructor() &&
882 !Record->hasNonTrivialDestructor())
883 return VAK_ValidInCXX11;
885 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
888 if (Ty->isObjCObjectType())
891 if (getLangOpts().MSVCCompat)
892 return VAK_MSVCUndefined;
894 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
895 // permitted to reject them. We should consider doing so.
896 return VAK_Undefined;
899 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
900 // Don't allow one to pass an Objective-C interface to a vararg.
901 const QualType &Ty = E->getType();
902 VarArgKind VAK = isValidVarArgType(Ty);
904 // Complain about passing non-POD types through varargs.
906 case VAK_ValidInCXX11:
908 E->getBeginLoc(), nullptr,
909 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
912 if (Ty->isRecordType()) {
913 // This is unlikely to be what the user intended. If the class has a
914 // 'c_str' member function, the user probably meant to call that.
915 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
916 PDiag(diag::warn_pass_class_arg_to_vararg)
917 << Ty << CT << hasCStrMethod(E) << ".c_str()");
922 case VAK_MSVCUndefined:
923 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
924 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
925 << getLangOpts().CPlusPlus11 << Ty << CT);
929 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
930 Diag(E->getBeginLoc(),
931 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
933 else if (Ty->isObjCObjectType())
934 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
935 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
938 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
939 << isa<InitListExpr>(E) << Ty << CT;
944 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
945 /// will create a trap if the resulting type is not a POD type.
946 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
947 FunctionDecl *FDecl) {
948 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
949 // Strip the unbridged-cast placeholder expression off, if applicable.
950 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
951 (CT == VariadicMethod ||
952 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
953 E = stripARCUnbridgedCast(E);
955 // Otherwise, do normal placeholder checking.
957 ExprResult ExprRes = CheckPlaceholderExpr(E);
958 if (ExprRes.isInvalid())
964 ExprResult ExprRes = DefaultArgumentPromotion(E);
965 if (ExprRes.isInvalid())
968 // Copy blocks to the heap.
969 if (ExprRes.get()->getType()->isBlockPointerType())
970 maybeExtendBlockObject(ExprRes);
974 // Diagnostics regarding non-POD argument types are
975 // emitted along with format string checking in Sema::CheckFunctionCall().
976 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
977 // Turn this into a trap.
979 SourceLocation TemplateKWLoc;
981 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
983 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
984 /*HasTrailingLParen=*/true,
985 /*IsAddressOfOperand=*/false);
986 if (TrapFn.isInvalid())
989 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
990 None, E->getEndLoc());
991 if (Call.isInvalid())
995 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
996 if (Comma.isInvalid())
1001 if (!getLangOpts().CPlusPlus &&
1002 RequireCompleteType(E->getExprLoc(), E->getType(),
1003 diag::err_call_incomplete_argument))
1009 /// Converts an integer to complex float type. Helper function of
1010 /// UsualArithmeticConversions()
1012 /// \return false if the integer expression is an integer type and is
1013 /// successfully converted to the complex type.
1014 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1015 ExprResult &ComplexExpr,
1019 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1020 if (SkipCast) return false;
1021 if (IntTy->isIntegerType()) {
1022 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1023 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1024 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1025 CK_FloatingRealToComplex);
1027 assert(IntTy->isComplexIntegerType());
1028 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1029 CK_IntegralComplexToFloatingComplex);
1034 /// Handle arithmetic conversion with complex types. Helper function of
1035 /// UsualArithmeticConversions()
1036 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1037 ExprResult &RHS, QualType LHSType,
1039 bool IsCompAssign) {
1040 // if we have an integer operand, the result is the complex type.
1041 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1044 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1045 /*skipCast*/IsCompAssign))
1048 // This handles complex/complex, complex/float, or float/complex.
1049 // When both operands are complex, the shorter operand is converted to the
1050 // type of the longer, and that is the type of the result. This corresponds
1051 // to what is done when combining two real floating-point operands.
1052 // The fun begins when size promotion occur across type domains.
1053 // From H&S 6.3.4: When one operand is complex and the other is a real
1054 // floating-point type, the less precise type is converted, within it's
1055 // real or complex domain, to the precision of the other type. For example,
1056 // when combining a "long double" with a "double _Complex", the
1057 // "double _Complex" is promoted to "long double _Complex".
1059 // Compute the rank of the two types, regardless of whether they are complex.
1060 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1062 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1063 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1064 QualType LHSElementType =
1065 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1066 QualType RHSElementType =
1067 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1069 QualType ResultType = S.Context.getComplexType(LHSElementType);
1071 // Promote the precision of the LHS if not an assignment.
1072 ResultType = S.Context.getComplexType(RHSElementType);
1073 if (!IsCompAssign) {
1076 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1078 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1080 } else if (Order > 0) {
1081 // Promote the precision of the RHS.
1083 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1085 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1090 /// Handle arithmetic conversion from integer to float. Helper function
1091 /// of UsualArithmeticConversions()
1092 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1093 ExprResult &IntExpr,
1094 QualType FloatTy, QualType IntTy,
1095 bool ConvertFloat, bool ConvertInt) {
1096 if (IntTy->isIntegerType()) {
1098 // Convert intExpr to the lhs floating point type.
1099 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1100 CK_IntegralToFloating);
1104 // Convert both sides to the appropriate complex float.
1105 assert(IntTy->isComplexIntegerType());
1106 QualType result = S.Context.getComplexType(FloatTy);
1108 // _Complex int -> _Complex float
1110 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1111 CK_IntegralComplexToFloatingComplex);
1113 // float -> _Complex float
1115 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1116 CK_FloatingRealToComplex);
1121 /// Handle arithmethic conversion with floating point types. Helper
1122 /// function of UsualArithmeticConversions()
1123 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1124 ExprResult &RHS, QualType LHSType,
1125 QualType RHSType, bool IsCompAssign) {
1126 bool LHSFloat = LHSType->isRealFloatingType();
1127 bool RHSFloat = RHSType->isRealFloatingType();
1129 // If we have two real floating types, convert the smaller operand
1130 // to the bigger result.
1131 if (LHSFloat && RHSFloat) {
1132 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1134 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1138 assert(order < 0 && "illegal float comparison");
1140 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1145 // Half FP has to be promoted to float unless it is natively supported
1146 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1147 LHSType = S.Context.FloatTy;
1149 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1150 /*ConvertFloat=*/!IsCompAssign,
1151 /*ConvertInt=*/ true);
1154 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1155 /*convertInt=*/ true,
1156 /*convertFloat=*/!IsCompAssign);
1159 /// Diagnose attempts to convert between __float128 and long double if
1160 /// there is no support for such conversion. Helper function of
1161 /// UsualArithmeticConversions().
1162 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1164 /* No issue converting if at least one of the types is not a floating point
1165 type or the two types have the same rank.
1167 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1168 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1171 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1172 "The remaining types must be floating point types.");
1174 auto *LHSComplex = LHSType->getAs<ComplexType>();
1175 auto *RHSComplex = RHSType->getAs<ComplexType>();
1177 QualType LHSElemType = LHSComplex ?
1178 LHSComplex->getElementType() : LHSType;
1179 QualType RHSElemType = RHSComplex ?
1180 RHSComplex->getElementType() : RHSType;
1182 // No issue if the two types have the same representation
1183 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1184 &S.Context.getFloatTypeSemantics(RHSElemType))
1187 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1188 RHSElemType == S.Context.LongDoubleTy);
1189 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1190 RHSElemType == S.Context.Float128Ty);
1192 // We've handled the situation where __float128 and long double have the same
1193 // representation. We allow all conversions for all possible long double types
1194 // except PPC's double double.
1195 return Float128AndLongDouble &&
1196 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1197 &llvm::APFloat::PPCDoubleDouble());
1200 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1203 /// These helper callbacks are placed in an anonymous namespace to
1204 /// permit their use as function template parameters.
1205 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1206 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1209 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1210 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1211 CK_IntegralComplexCast);
1215 /// Handle integer arithmetic conversions. Helper function of
1216 /// UsualArithmeticConversions()
1217 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1218 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1219 ExprResult &RHS, QualType LHSType,
1220 QualType RHSType, bool IsCompAssign) {
1221 // The rules for this case are in C99 6.3.1.8
1222 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1223 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1224 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1225 if (LHSSigned == RHSSigned) {
1226 // Same signedness; use the higher-ranked type
1228 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1230 } else if (!IsCompAssign)
1231 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1233 } else if (order != (LHSSigned ? 1 : -1)) {
1234 // The unsigned type has greater than or equal rank to the
1235 // signed type, so use the unsigned type
1237 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1239 } else if (!IsCompAssign)
1240 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1242 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1243 // The two types are different widths; if we are here, that
1244 // means the signed type is larger than the unsigned type, so
1245 // use the signed type.
1247 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1249 } else if (!IsCompAssign)
1250 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1253 // The signed type is higher-ranked than the unsigned type,
1254 // but isn't actually any bigger (like unsigned int and long
1255 // on most 32-bit systems). Use the unsigned type corresponding
1256 // to the signed type.
1258 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1259 RHS = (*doRHSCast)(S, RHS.get(), result);
1261 LHS = (*doLHSCast)(S, LHS.get(), result);
1266 /// Handle conversions with GCC complex int extension. Helper function
1267 /// of UsualArithmeticConversions()
1268 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1269 ExprResult &RHS, QualType LHSType,
1271 bool IsCompAssign) {
1272 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1273 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1275 if (LHSComplexInt && RHSComplexInt) {
1276 QualType LHSEltType = LHSComplexInt->getElementType();
1277 QualType RHSEltType = RHSComplexInt->getElementType();
1278 QualType ScalarType =
1279 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1280 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1282 return S.Context.getComplexType(ScalarType);
1285 if (LHSComplexInt) {
1286 QualType LHSEltType = LHSComplexInt->getElementType();
1287 QualType ScalarType =
1288 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1289 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1290 QualType ComplexType = S.Context.getComplexType(ScalarType);
1291 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1292 CK_IntegralRealToComplex);
1297 assert(RHSComplexInt);
1299 QualType RHSEltType = RHSComplexInt->getElementType();
1300 QualType ScalarType =
1301 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1302 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1303 QualType ComplexType = S.Context.getComplexType(ScalarType);
1306 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1307 CK_IntegralRealToComplex);
1311 /// Return the rank of a given fixed point or integer type. The value itself
1312 /// doesn't matter, but the values must be increasing with proper increasing
1313 /// rank as described in N1169 4.1.1.
1314 static unsigned GetFixedPointRank(QualType Ty) {
1315 const auto *BTy = Ty->getAs<BuiltinType>();
1316 assert(BTy && "Expected a builtin type.");
1318 switch (BTy->getKind()) {
1319 case BuiltinType::ShortFract:
1320 case BuiltinType::UShortFract:
1321 case BuiltinType::SatShortFract:
1322 case BuiltinType::SatUShortFract:
1324 case BuiltinType::Fract:
1325 case BuiltinType::UFract:
1326 case BuiltinType::SatFract:
1327 case BuiltinType::SatUFract:
1329 case BuiltinType::LongFract:
1330 case BuiltinType::ULongFract:
1331 case BuiltinType::SatLongFract:
1332 case BuiltinType::SatULongFract:
1334 case BuiltinType::ShortAccum:
1335 case BuiltinType::UShortAccum:
1336 case BuiltinType::SatShortAccum:
1337 case BuiltinType::SatUShortAccum:
1339 case BuiltinType::Accum:
1340 case BuiltinType::UAccum:
1341 case BuiltinType::SatAccum:
1342 case BuiltinType::SatUAccum:
1344 case BuiltinType::LongAccum:
1345 case BuiltinType::ULongAccum:
1346 case BuiltinType::SatLongAccum:
1347 case BuiltinType::SatULongAccum:
1350 if (BTy->isInteger())
1352 llvm_unreachable("Unexpected fixed point or integer type");
1356 /// handleFixedPointConversion - Fixed point operations between fixed
1357 /// point types and integers or other fixed point types do not fall under
1358 /// usual arithmetic conversion since these conversions could result in loss
1359 /// of precsision (N1169 4.1.4). These operations should be calculated with
1360 /// the full precision of their result type (N1169 4.1.6.2.1).
1361 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1363 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1364 "Expected at least one of the operands to be a fixed point type");
1365 assert((LHSTy->isFixedPointOrIntegerType() ||
1366 RHSTy->isFixedPointOrIntegerType()) &&
1367 "Special fixed point arithmetic operation conversions are only "
1368 "applied to ints or other fixed point types");
1370 // If one operand has signed fixed-point type and the other operand has
1371 // unsigned fixed-point type, then the unsigned fixed-point operand is
1372 // converted to its corresponding signed fixed-point type and the resulting
1373 // type is the type of the converted operand.
1374 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1375 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1376 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1377 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1379 // The result type is the type with the highest rank, whereby a fixed-point
1380 // conversion rank is always greater than an integer conversion rank; if the
1381 // type of either of the operands is a saturating fixedpoint type, the result
1382 // type shall be the saturating fixed-point type corresponding to the type
1383 // with the highest rank; the resulting value is converted (taking into
1384 // account rounding and overflow) to the precision of the resulting type.
1385 // Same ranks between signed and unsigned types are resolved earlier, so both
1386 // types are either signed or both unsigned at this point.
1387 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1388 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1390 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1392 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1393 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1398 /// Check that the usual arithmetic conversions can be performed on this pair of
1399 /// expressions that might be of enumeration type.
1400 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1402 Sema::ArithConvKind ACK) {
1403 // C++2a [expr.arith.conv]p1:
1404 // If one operand is of enumeration type and the other operand is of a
1405 // different enumeration type or a floating-point type, this behavior is
1406 // deprecated ([depr.arith.conv.enum]).
1408 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1409 // Eventually we will presumably reject these cases (in C++23 onwards?).
1410 QualType L = LHS->getType(), R = RHS->getType();
1411 bool LEnum = L->isUnscopedEnumerationType(),
1412 REnum = R->isUnscopedEnumerationType();
1413 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1414 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1415 (REnum && L->isFloatingType())) {
1416 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1417 ? diag::warn_arith_conv_enum_float_cxx20
1418 : diag::warn_arith_conv_enum_float)
1419 << LHS->getSourceRange() << RHS->getSourceRange()
1420 << (int)ACK << LEnum << L << R;
1421 } else if (!IsCompAssign && LEnum && REnum &&
1422 !S.Context.hasSameUnqualifiedType(L, R)) {
1424 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1425 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1426 // If either enumeration type is unnamed, it's less likely that the
1427 // user cares about this, but this situation is still deprecated in
1428 // C++2a. Use a different warning group.
1429 DiagID = S.getLangOpts().CPlusPlus20
1430 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1431 : diag::warn_arith_conv_mixed_anon_enum_types;
1432 } else if (ACK == Sema::ACK_Conditional) {
1433 // Conditional expressions are separated out because they have
1434 // historically had a different warning flag.
1435 DiagID = S.getLangOpts().CPlusPlus20
1436 ? diag::warn_conditional_mixed_enum_types_cxx20
1437 : diag::warn_conditional_mixed_enum_types;
1438 } else if (ACK == Sema::ACK_Comparison) {
1439 // Comparison expressions are separated out because they have
1440 // historically had a different warning flag.
1441 DiagID = S.getLangOpts().CPlusPlus20
1442 ? diag::warn_comparison_mixed_enum_types_cxx20
1443 : diag::warn_comparison_mixed_enum_types;
1445 DiagID = S.getLangOpts().CPlusPlus20
1446 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1447 : diag::warn_arith_conv_mixed_enum_types;
1449 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1450 << (int)ACK << L << R;
1454 /// UsualArithmeticConversions - Performs various conversions that are common to
1455 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1456 /// routine returns the first non-arithmetic type found. The client is
1457 /// responsible for emitting appropriate error diagnostics.
1458 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1460 ArithConvKind ACK) {
1461 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1463 if (ACK != ACK_CompAssign) {
1464 LHS = UsualUnaryConversions(LHS.get());
1465 if (LHS.isInvalid())
1469 RHS = UsualUnaryConversions(RHS.get());
1470 if (RHS.isInvalid())
1473 // For conversion purposes, we ignore any qualifiers.
1474 // For example, "const float" and "float" are equivalent.
1476 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1478 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1480 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1481 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1482 LHSType = AtomicLHS->getValueType();
1484 // If both types are identical, no conversion is needed.
1485 if (LHSType == RHSType)
1488 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1489 // The caller can deal with this (e.g. pointer + int).
1490 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1493 // Apply unary and bitfield promotions to the LHS's type.
1494 QualType LHSUnpromotedType = LHSType;
1495 if (LHSType->isPromotableIntegerType())
1496 LHSType = Context.getPromotedIntegerType(LHSType);
1497 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1498 if (!LHSBitfieldPromoteTy.isNull())
1499 LHSType = LHSBitfieldPromoteTy;
1500 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1501 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1503 // If both types are identical, no conversion is needed.
1504 if (LHSType == RHSType)
1507 // ExtInt types aren't subject to conversions between them or normal integers,
1509 if(LHSType->isExtIntType() || RHSType->isExtIntType())
1512 // At this point, we have two different arithmetic types.
1514 // Diagnose attempts to convert between __float128 and long double where
1515 // such conversions currently can't be handled.
1516 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1519 // Handle complex types first (C99 6.3.1.8p1).
1520 if (LHSType->isComplexType() || RHSType->isComplexType())
1521 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1522 ACK == ACK_CompAssign);
1524 // Now handle "real" floating types (i.e. float, double, long double).
1525 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1526 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1527 ACK == ACK_CompAssign);
1529 // Handle GCC complex int extension.
1530 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1531 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1532 ACK == ACK_CompAssign);
1534 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1535 return handleFixedPointConversion(*this, LHSType, RHSType);
1537 // Finally, we have two differing integer types.
1538 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1539 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1542 //===----------------------------------------------------------------------===//
1543 // Semantic Analysis for various Expression Types
1544 //===----------------------------------------------------------------------===//
1548 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1549 SourceLocation DefaultLoc,
1550 SourceLocation RParenLoc,
1551 Expr *ControllingExpr,
1552 ArrayRef<ParsedType> ArgTypes,
1553 ArrayRef<Expr *> ArgExprs) {
1554 unsigned NumAssocs = ArgTypes.size();
1555 assert(NumAssocs == ArgExprs.size());
1557 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1558 for (unsigned i = 0; i < NumAssocs; ++i) {
1560 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1565 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1567 llvm::makeArrayRef(Types, NumAssocs),
1574 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1575 SourceLocation DefaultLoc,
1576 SourceLocation RParenLoc,
1577 Expr *ControllingExpr,
1578 ArrayRef<TypeSourceInfo *> Types,
1579 ArrayRef<Expr *> Exprs) {
1580 unsigned NumAssocs = Types.size();
1581 assert(NumAssocs == Exprs.size());
1583 // Decay and strip qualifiers for the controlling expression type, and handle
1584 // placeholder type replacement. See committee discussion from WG14 DR423.
1586 EnterExpressionEvaluationContext Unevaluated(
1587 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1588 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1591 ControllingExpr = R.get();
1594 // The controlling expression is an unevaluated operand, so side effects are
1595 // likely unintended.
1596 if (!inTemplateInstantiation() &&
1597 ControllingExpr->HasSideEffects(Context, false))
1598 Diag(ControllingExpr->getExprLoc(),
1599 diag::warn_side_effects_unevaluated_context);
1601 bool TypeErrorFound = false,
1602 IsResultDependent = ControllingExpr->isTypeDependent(),
1603 ContainsUnexpandedParameterPack
1604 = ControllingExpr->containsUnexpandedParameterPack();
1606 for (unsigned i = 0; i < NumAssocs; ++i) {
1607 if (Exprs[i]->containsUnexpandedParameterPack())
1608 ContainsUnexpandedParameterPack = true;
1611 if (Types[i]->getType()->containsUnexpandedParameterPack())
1612 ContainsUnexpandedParameterPack = true;
1614 if (Types[i]->getType()->isDependentType()) {
1615 IsResultDependent = true;
1617 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1618 // complete object type other than a variably modified type."
1620 if (Types[i]->getType()->isIncompleteType())
1621 D = diag::err_assoc_type_incomplete;
1622 else if (!Types[i]->getType()->isObjectType())
1623 D = diag::err_assoc_type_nonobject;
1624 else if (Types[i]->getType()->isVariablyModifiedType())
1625 D = diag::err_assoc_type_variably_modified;
1628 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1629 << Types[i]->getTypeLoc().getSourceRange()
1630 << Types[i]->getType();
1631 TypeErrorFound = true;
1634 // C11 6.5.1.1p2 "No two generic associations in the same generic
1635 // selection shall specify compatible types."
1636 for (unsigned j = i+1; j < NumAssocs; ++j)
1637 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1638 Context.typesAreCompatible(Types[i]->getType(),
1639 Types[j]->getType())) {
1640 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1641 diag::err_assoc_compatible_types)
1642 << Types[j]->getTypeLoc().getSourceRange()
1643 << Types[j]->getType()
1644 << Types[i]->getType();
1645 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1646 diag::note_compat_assoc)
1647 << Types[i]->getTypeLoc().getSourceRange()
1648 << Types[i]->getType();
1649 TypeErrorFound = true;
1657 // If we determined that the generic selection is result-dependent, don't
1658 // try to compute the result expression.
1659 if (IsResultDependent)
1660 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1661 Exprs, DefaultLoc, RParenLoc,
1662 ContainsUnexpandedParameterPack);
1664 SmallVector<unsigned, 1> CompatIndices;
1665 unsigned DefaultIndex = -1U;
1666 for (unsigned i = 0; i < NumAssocs; ++i) {
1669 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1670 Types[i]->getType()))
1671 CompatIndices.push_back(i);
1674 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1675 // type compatible with at most one of the types named in its generic
1676 // association list."
1677 if (CompatIndices.size() > 1) {
1678 // We strip parens here because the controlling expression is typically
1679 // parenthesized in macro definitions.
1680 ControllingExpr = ControllingExpr->IgnoreParens();
1681 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1682 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1683 << (unsigned)CompatIndices.size();
1684 for (unsigned I : CompatIndices) {
1685 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1686 diag::note_compat_assoc)
1687 << Types[I]->getTypeLoc().getSourceRange()
1688 << Types[I]->getType();
1693 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1694 // its controlling expression shall have type compatible with exactly one of
1695 // the types named in its generic association list."
1696 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1697 // We strip parens here because the controlling expression is typically
1698 // parenthesized in macro definitions.
1699 ControllingExpr = ControllingExpr->IgnoreParens();
1700 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1701 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1705 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1706 // type name that is compatible with the type of the controlling expression,
1707 // then the result expression of the generic selection is the expression
1708 // in that generic association. Otherwise, the result expression of the
1709 // generic selection is the expression in the default generic association."
1710 unsigned ResultIndex =
1711 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1713 return GenericSelectionExpr::Create(
1714 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1715 ContainsUnexpandedParameterPack, ResultIndex);
1718 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1719 /// location of the token and the offset of the ud-suffix within it.
1720 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1722 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1726 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1727 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1728 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1729 IdentifierInfo *UDSuffix,
1730 SourceLocation UDSuffixLoc,
1731 ArrayRef<Expr*> Args,
1732 SourceLocation LitEndLoc) {
1733 assert(Args.size() <= 2 && "too many arguments for literal operator");
1736 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1737 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1738 if (ArgTy[ArgIdx]->isArrayType())
1739 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1742 DeclarationName OpName =
1743 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1744 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1745 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1747 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1748 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1749 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1750 /*AllowStringTemplate*/ false,
1751 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1754 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1757 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1758 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1759 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1760 /// multiple tokens. However, the common case is that StringToks points to one
1764 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1765 assert(!StringToks.empty() && "Must have at least one string!");
1767 StringLiteralParser Literal(StringToks, PP);
1768 if (Literal.hadError)
1771 SmallVector<SourceLocation, 4> StringTokLocs;
1772 for (const Token &Tok : StringToks)
1773 StringTokLocs.push_back(Tok.getLocation());
1775 QualType CharTy = Context.CharTy;
1776 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1777 if (Literal.isWide()) {
1778 CharTy = Context.getWideCharType();
1779 Kind = StringLiteral::Wide;
1780 } else if (Literal.isUTF8()) {
1781 if (getLangOpts().Char8)
1782 CharTy = Context.Char8Ty;
1783 Kind = StringLiteral::UTF8;
1784 } else if (Literal.isUTF16()) {
1785 CharTy = Context.Char16Ty;
1786 Kind = StringLiteral::UTF16;
1787 } else if (Literal.isUTF32()) {
1788 CharTy = Context.Char32Ty;
1789 Kind = StringLiteral::UTF32;
1790 } else if (Literal.isPascal()) {
1791 CharTy = Context.UnsignedCharTy;
1794 // Warn on initializing an array of char from a u8 string literal; this
1795 // becomes ill-formed in C++2a.
1796 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1797 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1798 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1800 // Create removals for all 'u8' prefixes in the string literal(s). This
1801 // ensures C++2a compatibility (but may change the program behavior when
1802 // built by non-Clang compilers for which the execution character set is
1803 // not always UTF-8).
1804 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1805 SourceLocation RemovalDiagLoc;
1806 for (const Token &Tok : StringToks) {
1807 if (Tok.getKind() == tok::utf8_string_literal) {
1808 if (RemovalDiagLoc.isInvalid())
1809 RemovalDiagLoc = Tok.getLocation();
1810 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1812 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1813 getSourceManager(), getLangOpts())));
1816 Diag(RemovalDiagLoc, RemovalDiag);
1820 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1822 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1823 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1824 Kind, Literal.Pascal, StrTy,
1826 StringTokLocs.size());
1827 if (Literal.getUDSuffix().empty())
1830 // We're building a user-defined literal.
1831 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1832 SourceLocation UDSuffixLoc =
1833 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1834 Literal.getUDSuffixOffset());
1836 // Make sure we're allowed user-defined literals here.
1838 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1840 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1841 // operator "" X (str, len)
1842 QualType SizeType = Context.getSizeType();
1844 DeclarationName OpName =
1845 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1846 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1847 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1849 QualType ArgTy[] = {
1850 Context.getArrayDecayedType(StrTy), SizeType
1853 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1854 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1855 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1856 /*AllowStringTemplate*/ true,
1857 /*DiagnoseMissing*/ true)) {
1860 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1861 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1863 Expr *Args[] = { Lit, LenArg };
1865 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1868 case LOLR_StringTemplate: {
1869 TemplateArgumentListInfo ExplicitArgs;
1871 unsigned CharBits = Context.getIntWidth(CharTy);
1872 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1873 llvm::APSInt Value(CharBits, CharIsUnsigned);
1875 TemplateArgument TypeArg(CharTy);
1876 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1877 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1879 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1880 Value = Lit->getCodeUnit(I);
1881 TemplateArgument Arg(Context, Value, CharTy);
1882 TemplateArgumentLocInfo ArgInfo;
1883 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1885 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1890 case LOLR_ErrorNoDiagnostic:
1891 llvm_unreachable("unexpected literal operator lookup result");
1895 llvm_unreachable("unexpected literal operator lookup result");
1899 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1901 const CXXScopeSpec *SS) {
1902 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1903 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1907 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1908 const DeclarationNameInfo &NameInfo,
1909 const CXXScopeSpec *SS, NamedDecl *FoundD,
1910 SourceLocation TemplateKWLoc,
1911 const TemplateArgumentListInfo *TemplateArgs) {
1912 NestedNameSpecifierLoc NNS =
1913 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1914 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1918 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1919 // A declaration named in an unevaluated operand never constitutes an odr-use.
1920 if (isUnevaluatedContext())
1921 return NOUR_Unevaluated;
1923 // C++2a [basic.def.odr]p4:
1924 // A variable x whose name appears as a potentially-evaluated expression e
1925 // is odr-used by e unless [...] x is a reference that is usable in
1926 // constant expressions.
1927 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1928 if (VD->getType()->isReferenceType() &&
1929 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1930 VD->isUsableInConstantExpressions(Context))
1931 return NOUR_Constant;
1934 // All remaining non-variable cases constitute an odr-use. For variables, we
1935 // need to wait and see how the expression is used.
1939 /// BuildDeclRefExpr - Build an expression that references a
1940 /// declaration that does not require a closure capture.
1942 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1943 const DeclarationNameInfo &NameInfo,
1944 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1945 SourceLocation TemplateKWLoc,
1946 const TemplateArgumentListInfo *TemplateArgs) {
1947 bool RefersToCapturedVariable =
1949 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1951 DeclRefExpr *E = DeclRefExpr::Create(
1952 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1953 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1954 MarkDeclRefReferenced(E);
1956 // C++ [except.spec]p17:
1957 // An exception-specification is considered to be needed when:
1958 // - in an expression, the function is the unique lookup result or
1959 // the selected member of a set of overloaded functions.
1961 // We delay doing this until after we've built the function reference and
1962 // marked it as used so that:
1963 // a) if the function is defaulted, we get errors from defining it before /
1964 // instead of errors from computing its exception specification, and
1965 // b) if the function is a defaulted comparison, we can use the body we
1966 // build when defining it as input to the exception specification
1967 // computation rather than computing a new body.
1968 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1969 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1970 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1971 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1975 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1976 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1977 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1978 getCurFunction()->recordUseOfWeak(E);
1980 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1981 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1982 FD = IFD->getAnonField();
1984 UnusedPrivateFields.remove(FD);
1985 // Just in case we're building an illegal pointer-to-member.
1986 if (FD->isBitField())
1987 E->setObjectKind(OK_BitField);
1990 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1991 // designates a bit-field.
1992 if (auto *BD = dyn_cast<BindingDecl>(D))
1993 if (auto *BE = BD->getBinding())
1994 E->setObjectKind(BE->getObjectKind());
1999 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2000 /// possibly a list of template arguments.
2002 /// If this produces template arguments, it is permitted to call
2003 /// DecomposeTemplateName.
2005 /// This actually loses a lot of source location information for
2006 /// non-standard name kinds; we should consider preserving that in
2009 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2010 TemplateArgumentListInfo &Buffer,
2011 DeclarationNameInfo &NameInfo,
2012 const TemplateArgumentListInfo *&TemplateArgs) {
2013 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2014 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2015 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2017 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2018 Id.TemplateId->NumArgs);
2019 translateTemplateArguments(TemplateArgsPtr, Buffer);
2021 TemplateName TName = Id.TemplateId->Template.get();
2022 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2023 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2024 TemplateArgs = &Buffer;
2026 NameInfo = GetNameFromUnqualifiedId(Id);
2027 TemplateArgs = nullptr;
2031 static void emitEmptyLookupTypoDiagnostic(
2032 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2033 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2034 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2036 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2038 // Emit a special diagnostic for failed member lookups.
2039 // FIXME: computing the declaration context might fail here (?)
2041 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2044 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2048 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2049 bool DroppedSpecifier =
2050 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2051 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2052 ? diag::note_implicit_param_decl
2053 : diag::note_previous_decl;
2055 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2056 SemaRef.PDiag(NoteID));
2058 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2059 << Typo << Ctx << DroppedSpecifier
2061 SemaRef.PDiag(NoteID));
2064 /// Diagnose an empty lookup.
2066 /// \return false if new lookup candidates were found
2067 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2068 CorrectionCandidateCallback &CCC,
2069 TemplateArgumentListInfo *ExplicitTemplateArgs,
2070 ArrayRef<Expr *> Args, TypoExpr **Out) {
2071 DeclarationName Name = R.getLookupName();
2073 unsigned diagnostic = diag::err_undeclared_var_use;
2074 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2075 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2076 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2077 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2078 diagnostic = diag::err_undeclared_use;
2079 diagnostic_suggest = diag::err_undeclared_use_suggest;
2082 // If the original lookup was an unqualified lookup, fake an
2083 // unqualified lookup. This is useful when (for example) the
2084 // original lookup would not have found something because it was a
2086 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2088 if (isa<CXXRecordDecl>(DC)) {
2089 LookupQualifiedName(R, DC);
2092 // Don't give errors about ambiguities in this lookup.
2093 R.suppressDiagnostics();
2095 // During a default argument instantiation the CurContext points
2096 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2097 // function parameter list, hence add an explicit check.
2098 bool isDefaultArgument =
2099 !CodeSynthesisContexts.empty() &&
2100 CodeSynthesisContexts.back().Kind ==
2101 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2102 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2103 bool isInstance = CurMethod &&
2104 CurMethod->isInstance() &&
2105 DC == CurMethod->getParent() && !isDefaultArgument;
2107 // Give a code modification hint to insert 'this->'.
2108 // TODO: fixit for inserting 'Base<T>::' in the other cases.
2109 // Actually quite difficult!
2110 if (getLangOpts().MSVCCompat)
2111 diagnostic = diag::ext_found_via_dependent_bases_lookup;
2113 Diag(R.getNameLoc(), diagnostic) << Name
2114 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2115 CheckCXXThisCapture(R.getNameLoc());
2117 Diag(R.getNameLoc(), diagnostic) << Name;
2120 // Do we really want to note all of these?
2121 for (NamedDecl *D : R)
2122 Diag(D->getLocation(), diag::note_dependent_var_use);
2124 // Return true if we are inside a default argument instantiation
2125 // and the found name refers to an instance member function, otherwise
2126 // the function calling DiagnoseEmptyLookup will try to create an
2127 // implicit member call and this is wrong for default argument.
2128 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2129 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2133 // Tell the callee to try to recover.
2140 DC = DC->getLookupParent();
2143 // We didn't find anything, so try to correct for a typo.
2144 TypoCorrection Corrected;
2146 SourceLocation TypoLoc = R.getNameLoc();
2147 assert(!ExplicitTemplateArgs &&
2148 "Diagnosing an empty lookup with explicit template args!");
2149 *Out = CorrectTypoDelayed(
2150 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2151 [=](const TypoCorrection &TC) {
2152 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2153 diagnostic, diagnostic_suggest);
2155 nullptr, CTK_ErrorRecovery);
2159 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2160 S, &SS, CCC, CTK_ErrorRecovery))) {
2161 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2162 bool DroppedSpecifier =
2163 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2164 R.setLookupName(Corrected.getCorrection());
2166 bool AcceptableWithRecovery = false;
2167 bool AcceptableWithoutRecovery = false;
2168 NamedDecl *ND = Corrected.getFoundDecl();
2170 if (Corrected.isOverloaded()) {
2171 OverloadCandidateSet OCS(R.getNameLoc(),
2172 OverloadCandidateSet::CSK_Normal);
2173 OverloadCandidateSet::iterator Best;
2174 for (NamedDecl *CD : Corrected) {
2175 if (FunctionTemplateDecl *FTD =
2176 dyn_cast<FunctionTemplateDecl>(CD))
2177 AddTemplateOverloadCandidate(
2178 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2180 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2181 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2182 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2185 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2187 ND = Best->FoundDecl;
2188 Corrected.setCorrectionDecl(ND);
2191 // FIXME: Arbitrarily pick the first declaration for the note.
2192 Corrected.setCorrectionDecl(ND);
2197 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2198 CXXRecordDecl *Record = nullptr;
2199 if (Corrected.getCorrectionSpecifier()) {
2200 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2201 Record = Ty->getAsCXXRecordDecl();
2204 Record = cast<CXXRecordDecl>(
2205 ND->getDeclContext()->getRedeclContext());
2206 R.setNamingClass(Record);
2209 auto *UnderlyingND = ND->getUnderlyingDecl();
2210 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2211 isa<FunctionTemplateDecl>(UnderlyingND);
2212 // FIXME: If we ended up with a typo for a type name or
2213 // Objective-C class name, we're in trouble because the parser
2214 // is in the wrong place to recover. Suggest the typo
2215 // correction, but don't make it a fix-it since we're not going
2216 // to recover well anyway.
2217 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2218 getAsTypeTemplateDecl(UnderlyingND) ||
2219 isa<ObjCInterfaceDecl>(UnderlyingND);
2221 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2222 // because we aren't able to recover.
2223 AcceptableWithoutRecovery = true;
2226 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2227 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2228 ? diag::note_implicit_param_decl
2229 : diag::note_previous_decl;
2231 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2232 PDiag(NoteID), AcceptableWithRecovery);
2234 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2235 << Name << computeDeclContext(SS, false)
2236 << DroppedSpecifier << SS.getRange(),
2237 PDiag(NoteID), AcceptableWithRecovery);
2239 // Tell the callee whether to try to recover.
2240 return !AcceptableWithRecovery;
2245 // Emit a special diagnostic for failed member lookups.
2246 // FIXME: computing the declaration context might fail here (?)
2247 if (!SS.isEmpty()) {
2248 Diag(R.getNameLoc(), diag::err_no_member)
2249 << Name << computeDeclContext(SS, false)
2254 // Give up, we can't recover.
2255 Diag(R.getNameLoc(), diagnostic) << Name;
2259 /// In Microsoft mode, if we are inside a template class whose parent class has
2260 /// dependent base classes, and we can't resolve an unqualified identifier, then
2261 /// assume the identifier is a member of a dependent base class. We can only
2262 /// recover successfully in static methods, instance methods, and other contexts
2263 /// where 'this' is available. This doesn't precisely match MSVC's
2264 /// instantiation model, but it's close enough.
2266 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2267 DeclarationNameInfo &NameInfo,
2268 SourceLocation TemplateKWLoc,
2269 const TemplateArgumentListInfo *TemplateArgs) {
2270 // Only try to recover from lookup into dependent bases in static methods or
2271 // contexts where 'this' is available.
2272 QualType ThisType = S.getCurrentThisType();
2273 const CXXRecordDecl *RD = nullptr;
2274 if (!ThisType.isNull())
2275 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2276 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2277 RD = MD->getParent();
2278 if (!RD || !RD->hasAnyDependentBases())
2281 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2282 // is available, suggest inserting 'this->' as a fixit.
2283 SourceLocation Loc = NameInfo.getLoc();
2284 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2285 DB << NameInfo.getName() << RD;
2287 if (!ThisType.isNull()) {
2288 DB << FixItHint::CreateInsertion(Loc, "this->");
2289 return CXXDependentScopeMemberExpr::Create(
2290 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2291 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2292 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2295 // Synthesize a fake NNS that points to the derived class. This will
2296 // perform name lookup during template instantiation.
2299 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2300 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2301 return DependentScopeDeclRefExpr::Create(
2302 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2307 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2308 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2309 bool HasTrailingLParen, bool IsAddressOfOperand,
2310 CorrectionCandidateCallback *CCC,
2311 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2312 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2313 "cannot be direct & operand and have a trailing lparen");
2317 TemplateArgumentListInfo TemplateArgsBuffer;
2319 // Decompose the UnqualifiedId into the following data.
2320 DeclarationNameInfo NameInfo;
2321 const TemplateArgumentListInfo *TemplateArgs;
2322 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2324 DeclarationName Name = NameInfo.getName();
2325 IdentifierInfo *II = Name.getAsIdentifierInfo();
2326 SourceLocation NameLoc = NameInfo.getLoc();
2328 if (II && II->isEditorPlaceholder()) {
2329 // FIXME: When typed placeholders are supported we can create a typed
2330 // placeholder expression node.
2334 // C++ [temp.dep.expr]p3:
2335 // An id-expression is type-dependent if it contains:
2336 // -- an identifier that was declared with a dependent type,
2337 // (note: handled after lookup)
2338 // -- a template-id that is dependent,
2339 // (note: handled in BuildTemplateIdExpr)
2340 // -- a conversion-function-id that specifies a dependent type,
2341 // -- a nested-name-specifier that contains a class-name that
2342 // names a dependent type.
2343 // Determine whether this is a member of an unknown specialization;
2344 // we need to handle these differently.
2345 bool DependentID = false;
2346 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2347 Name.getCXXNameType()->isDependentType()) {
2349 } else if (SS.isSet()) {
2350 if (DeclContext *DC = computeDeclContext(SS, false)) {
2351 if (RequireCompleteDeclContext(SS, DC))
2359 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2360 IsAddressOfOperand, TemplateArgs);
2362 // Perform the required lookup.
2363 LookupResult R(*this, NameInfo,
2364 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2365 ? LookupObjCImplicitSelfParam
2366 : LookupOrdinaryName);
2367 if (TemplateKWLoc.isValid() || TemplateArgs) {
2368 // Lookup the template name again to correctly establish the context in
2369 // which it was found. This is really unfortunate as we already did the
2370 // lookup to determine that it was a template name in the first place. If
2371 // this becomes a performance hit, we can work harder to preserve those
2372 // results until we get here but it's likely not worth it.
2373 bool MemberOfUnknownSpecialization;
2374 AssumedTemplateKind AssumedTemplate;
2375 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2376 MemberOfUnknownSpecialization, TemplateKWLoc,
2380 if (MemberOfUnknownSpecialization ||
2381 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2382 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2383 IsAddressOfOperand, TemplateArgs);
2385 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2386 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2388 // If the result might be in a dependent base class, this is a dependent
2390 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2391 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2392 IsAddressOfOperand, TemplateArgs);
2394 // If this reference is in an Objective-C method, then we need to do
2395 // some special Objective-C lookup, too.
2396 if (IvarLookupFollowUp) {
2397 ExprResult E(LookupInObjCMethod(R, S, II, true));
2401 if (Expr *Ex = E.getAs<Expr>())
2406 if (R.isAmbiguous())
2409 // This could be an implicitly declared function reference (legal in C90,
2410 // extension in C99, forbidden in C++).
2411 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2412 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2413 if (D) R.addDecl(D);
2416 // Determine whether this name might be a candidate for
2417 // argument-dependent lookup.
2418 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2420 if (R.empty() && !ADL) {
2421 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2422 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2423 TemplateKWLoc, TemplateArgs))
2427 // Don't diagnose an empty lookup for inline assembly.
2428 if (IsInlineAsmIdentifier)
2431 // If this name wasn't predeclared and if this is not a function
2432 // call, diagnose the problem.
2433 TypoExpr *TE = nullptr;
2434 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2436 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2437 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2438 "Typo correction callback misconfigured");
2440 // Make sure the callback knows what the typo being diagnosed is.
2441 CCC->setTypoName(II);
2443 CCC->setTypoNNS(SS.getScopeRep());
2445 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2446 // a template name, but we happen to have always already looked up the name
2447 // before we get here if it must be a template name.
2448 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2450 if (TE && KeywordReplacement) {
2451 auto &State = getTypoExprState(TE);
2452 auto BestTC = State.Consumer->getNextCorrection();
2453 if (BestTC.isKeyword()) {
2454 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2455 if (State.DiagHandler)
2456 State.DiagHandler(BestTC);
2457 KeywordReplacement->startToken();
2458 KeywordReplacement->setKind(II->getTokenID());
2459 KeywordReplacement->setIdentifierInfo(II);
2460 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2461 // Clean up the state associated with the TypoExpr, since it has
2462 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2463 clearDelayedTypo(TE);
2464 // Signal that a correction to a keyword was performed by returning a
2465 // valid-but-null ExprResult.
2466 return (Expr*)nullptr;
2468 State.Consumer->resetCorrectionStream();
2470 return TE ? TE : ExprError();
2473 assert(!R.empty() &&
2474 "DiagnoseEmptyLookup returned false but added no results");
2476 // If we found an Objective-C instance variable, let
2477 // LookupInObjCMethod build the appropriate expression to
2478 // reference the ivar.
2479 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2481 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2482 // In a hopelessly buggy code, Objective-C instance variable
2483 // lookup fails and no expression will be built to reference it.
2484 if (!E.isInvalid() && !E.get())
2490 // This is guaranteed from this point on.
2491 assert(!R.empty() || ADL);
2493 // Check whether this might be a C++ implicit instance member access.
2494 // C++ [class.mfct.non-static]p3:
2495 // When an id-expression that is not part of a class member access
2496 // syntax and not used to form a pointer to member is used in the
2497 // body of a non-static member function of class X, if name lookup
2498 // resolves the name in the id-expression to a non-static non-type
2499 // member of some class C, the id-expression is transformed into a
2500 // class member access expression using (*this) as the
2501 // postfix-expression to the left of the . operator.
2503 // But we don't actually need to do this for '&' operands if R
2504 // resolved to a function or overloaded function set, because the
2505 // expression is ill-formed if it actually works out to be a
2506 // non-static member function:
2508 // C++ [expr.ref]p4:
2509 // Otherwise, if E1.E2 refers to a non-static member function. . .
2510 // [t]he expression can be used only as the left-hand operand of a
2511 // member function call.
2513 // There are other safeguards against such uses, but it's important
2514 // to get this right here so that we don't end up making a
2515 // spuriously dependent expression if we're inside a dependent
2517 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2518 bool MightBeImplicitMember;
2519 if (!IsAddressOfOperand)
2520 MightBeImplicitMember = true;
2521 else if (!SS.isEmpty())
2522 MightBeImplicitMember = false;
2523 else if (R.isOverloadedResult())
2524 MightBeImplicitMember = false;
2525 else if (R.isUnresolvableResult())
2526 MightBeImplicitMember = true;
2528 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2529 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2530 isa<MSPropertyDecl>(R.getFoundDecl());
2532 if (MightBeImplicitMember)
2533 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2534 R, TemplateArgs, S);
2537 if (TemplateArgs || TemplateKWLoc.isValid()) {
2539 // In C++1y, if this is a variable template id, then check it
2540 // in BuildTemplateIdExpr().
2541 // The single lookup result must be a variable template declaration.
2542 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2543 Id.TemplateId->Kind == TNK_Var_template) {
2544 assert(R.getAsSingle<VarTemplateDecl>() &&
2545 "There should only be one declaration found.");
2548 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2551 return BuildDeclarationNameExpr(SS, R, ADL);
2554 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2555 /// declaration name, generally during template instantiation.
2556 /// There's a large number of things which don't need to be done along
2558 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2559 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2560 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2561 DeclContext *DC = computeDeclContext(SS, false);
2563 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2564 NameInfo, /*TemplateArgs=*/nullptr);
2566 if (RequireCompleteDeclContext(SS, DC))
2569 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2570 LookupQualifiedName(R, DC);
2572 if (R.isAmbiguous())
2575 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2576 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2577 NameInfo, /*TemplateArgs=*/nullptr);
2580 Diag(NameInfo.getLoc(), diag::err_no_member)
2581 << NameInfo.getName() << DC << SS.getRange();
2585 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2586 // Diagnose a missing typename if this resolved unambiguously to a type in
2587 // a dependent context. If we can recover with a type, downgrade this to
2588 // a warning in Microsoft compatibility mode.
2589 unsigned DiagID = diag::err_typename_missing;
2590 if (RecoveryTSI && getLangOpts().MSVCCompat)
2591 DiagID = diag::ext_typename_missing;
2592 SourceLocation Loc = SS.getBeginLoc();
2593 auto D = Diag(Loc, DiagID);
2594 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2595 << SourceRange(Loc, NameInfo.getEndLoc());
2597 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2602 // Only issue the fixit if we're prepared to recover.
2603 D << FixItHint::CreateInsertion(Loc, "typename ");
2605 // Recover by pretending this was an elaborated type.
2606 QualType Ty = Context.getTypeDeclType(TD);
2608 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2610 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2611 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2612 QTL.setElaboratedKeywordLoc(SourceLocation());
2613 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2615 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2620 // Defend against this resolving to an implicit member access. We usually
2621 // won't get here if this might be a legitimate a class member (we end up in
2622 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2623 // a pointer-to-member or in an unevaluated context in C++11.
2624 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2625 return BuildPossibleImplicitMemberExpr(SS,
2626 /*TemplateKWLoc=*/SourceLocation(),
2627 R, /*TemplateArgs=*/nullptr, S);
2629 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2632 /// The parser has read a name in, and Sema has detected that we're currently
2633 /// inside an ObjC method. Perform some additional checks and determine if we
2634 /// should form a reference to an ivar.
2636 /// Ideally, most of this would be done by lookup, but there's
2637 /// actually quite a lot of extra work involved.
2638 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2639 IdentifierInfo *II) {
2640 SourceLocation Loc = Lookup.getNameLoc();
2641 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2643 // Check for error condition which is already reported.
2645 return DeclResult(true);
2647 // There are two cases to handle here. 1) scoped lookup could have failed,
2648 // in which case we should look for an ivar. 2) scoped lookup could have
2649 // found a decl, but that decl is outside the current instance method (i.e.
2650 // a global variable). In these two cases, we do a lookup for an ivar with
2651 // this name, if the lookup sucedes, we replace it our current decl.
2653 // If we're in a class method, we don't normally want to look for
2654 // ivars. But if we don't find anything else, and there's an
2655 // ivar, that's an error.
2656 bool IsClassMethod = CurMethod->isClassMethod();
2660 LookForIvars = true;
2661 else if (IsClassMethod)
2662 LookForIvars = false;
2664 LookForIvars = (Lookup.isSingleResult() &&
2665 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2666 ObjCInterfaceDecl *IFace = nullptr;
2668 IFace = CurMethod->getClassInterface();
2669 ObjCInterfaceDecl *ClassDeclared;
2670 ObjCIvarDecl *IV = nullptr;
2671 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2672 // Diagnose using an ivar in a class method.
2673 if (IsClassMethod) {
2674 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2675 return DeclResult(true);
2678 // Diagnose the use of an ivar outside of the declaring class.
2679 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2680 !declaresSameEntity(ClassDeclared, IFace) &&
2681 !getLangOpts().DebuggerSupport)
2682 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2687 } else if (CurMethod->isInstanceMethod()) {
2688 // We should warn if a local variable hides an ivar.
2689 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2690 ObjCInterfaceDecl *ClassDeclared;
2691 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2692 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2693 declaresSameEntity(IFace, ClassDeclared))
2694 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2697 } else if (Lookup.isSingleResult() &&
2698 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2699 // If accessing a stand-alone ivar in a class method, this is an error.
2700 if (const ObjCIvarDecl *IV =
2701 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2702 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2703 return DeclResult(true);
2707 // Didn't encounter an error, didn't find an ivar.
2708 return DeclResult(false);
2711 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2713 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2714 assert(CurMethod && CurMethod->isInstanceMethod() &&
2715 "should not reference ivar from this context");
2717 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2718 assert(IFace && "should not reference ivar from this context");
2720 // If we're referencing an invalid decl, just return this as a silent
2721 // error node. The error diagnostic was already emitted on the decl.
2722 if (IV->isInvalidDecl())
2725 // Check if referencing a field with __attribute__((deprecated)).
2726 if (DiagnoseUseOfDecl(IV, Loc))
2729 // FIXME: This should use a new expr for a direct reference, don't
2730 // turn this into Self->ivar, just return a BareIVarExpr or something.
2731 IdentifierInfo &II = Context.Idents.get("self");
2732 UnqualifiedId SelfName;
2733 SelfName.setIdentifier(&II, SourceLocation());
2734 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2735 CXXScopeSpec SelfScopeSpec;
2736 SourceLocation TemplateKWLoc;
2737 ExprResult SelfExpr =
2738 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2739 /*HasTrailingLParen=*/false,
2740 /*IsAddressOfOperand=*/false);
2741 if (SelfExpr.isInvalid())
2744 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2745 if (SelfExpr.isInvalid())
2748 MarkAnyDeclReferenced(Loc, IV, true);
2750 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2751 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2752 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2753 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2755 ObjCIvarRefExpr *Result = new (Context)
2756 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2757 IV->getLocation(), SelfExpr.get(), true, true);
2759 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2760 if (!isUnevaluatedContext() &&
2761 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2762 getCurFunction()->recordUseOfWeak(Result);
2764 if (getLangOpts().ObjCAutoRefCount)
2765 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2766 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2771 /// The parser has read a name in, and Sema has detected that we're currently
2772 /// inside an ObjC method. Perform some additional checks and determine if we
2773 /// should form a reference to an ivar. If so, build an expression referencing
2776 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2777 IdentifierInfo *II, bool AllowBuiltinCreation) {
2778 // FIXME: Integrate this lookup step into LookupParsedName.
2779 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2780 if (Ivar.isInvalid())
2782 if (Ivar.isUsable())
2783 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2784 cast<ObjCIvarDecl>(Ivar.get()));
2786 if (Lookup.empty() && II && AllowBuiltinCreation)
2787 LookupBuiltin(Lookup);
2789 // Sentinel value saying that we didn't do anything special.
2790 return ExprResult(false);
2793 /// Cast a base object to a member's actual type.
2795 /// Logically this happens in three phases:
2797 /// * First we cast from the base type to the naming class.
2798 /// The naming class is the class into which we were looking
2799 /// when we found the member; it's the qualifier type if a
2800 /// qualifier was provided, and otherwise it's the base type.
2802 /// * Next we cast from the naming class to the declaring class.
2803 /// If the member we found was brought into a class's scope by
2804 /// a using declaration, this is that class; otherwise it's
2805 /// the class declaring the member.
2807 /// * Finally we cast from the declaring class to the "true"
2808 /// declaring class of the member. This conversion does not
2809 /// obey access control.
2811 Sema::PerformObjectMemberConversion(Expr *From,
2812 NestedNameSpecifier *Qualifier,
2813 NamedDecl *FoundDecl,
2814 NamedDecl *Member) {
2815 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2819 QualType DestRecordType;
2821 QualType FromRecordType;
2822 QualType FromType = From->getType();
2823 bool PointerConversions = false;
2824 if (isa<FieldDecl>(Member)) {
2825 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2826 auto FromPtrType = FromType->getAs<PointerType>();
2827 DestRecordType = Context.getAddrSpaceQualType(
2828 DestRecordType, FromPtrType
2829 ? FromType->getPointeeType().getAddressSpace()
2830 : FromType.getAddressSpace());
2833 DestType = Context.getPointerType(DestRecordType);
2834 FromRecordType = FromPtrType->getPointeeType();
2835 PointerConversions = true;
2837 DestType = DestRecordType;
2838 FromRecordType = FromType;
2840 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2841 if (Method->isStatic())
2844 DestType = Method->getThisType();
2845 DestRecordType = DestType->getPointeeType();
2847 if (FromType->getAs<PointerType>()) {
2848 FromRecordType = FromType->getPointeeType();
2849 PointerConversions = true;
2851 FromRecordType = FromType;
2852 DestType = DestRecordType;
2855 LangAS FromAS = FromRecordType.getAddressSpace();
2856 LangAS DestAS = DestRecordType.getAddressSpace();
2857 if (FromAS != DestAS) {
2858 QualType FromRecordTypeWithoutAS =
2859 Context.removeAddrSpaceQualType(FromRecordType);
2860 QualType FromTypeWithDestAS =
2861 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2862 if (PointerConversions)
2863 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2864 From = ImpCastExprToType(From, FromTypeWithDestAS,
2865 CK_AddressSpaceConversion, From->getValueKind())
2869 // No conversion necessary.
2873 if (DestType->isDependentType() || FromType->isDependentType())
2876 // If the unqualified types are the same, no conversion is necessary.
2877 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2880 SourceRange FromRange = From->getSourceRange();
2881 SourceLocation FromLoc = FromRange.getBegin();
2883 ExprValueKind VK = From->getValueKind();
2885 // C++ [class.member.lookup]p8:
2886 // [...] Ambiguities can often be resolved by qualifying a name with its
2889 // If the member was a qualified name and the qualified referred to a
2890 // specific base subobject type, we'll cast to that intermediate type
2891 // first and then to the object in which the member is declared. That allows
2892 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2894 // class Base { public: int x; };
2895 // class Derived1 : public Base { };
2896 // class Derived2 : public Base { };
2897 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2899 // void VeryDerived::f() {
2900 // x = 17; // error: ambiguous base subobjects
2901 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2903 if (Qualifier && Qualifier->getAsType()) {
2904 QualType QType = QualType(Qualifier->getAsType(), 0);
2905 assert(QType->isRecordType() && "lookup done with non-record type");
2907 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2909 // In C++98, the qualifier type doesn't actually have to be a base
2910 // type of the object type, in which case we just ignore it.
2911 // Otherwise build the appropriate casts.
2912 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2913 CXXCastPath BasePath;
2914 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2915 FromLoc, FromRange, &BasePath))
2918 if (PointerConversions)
2919 QType = Context.getPointerType(QType);
2920 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2921 VK, &BasePath).get();
2924 FromRecordType = QRecordType;
2926 // If the qualifier type was the same as the destination type,
2928 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2933 bool IgnoreAccess = false;
2935 // If we actually found the member through a using declaration, cast
2936 // down to the using declaration's type.
2938 // Pointer equality is fine here because only one declaration of a
2939 // class ever has member declarations.
2940 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2941 assert(isa<UsingShadowDecl>(FoundDecl));
2942 QualType URecordType = Context.getTypeDeclType(
2943 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2945 // We only need to do this if the naming-class to declaring-class
2946 // conversion is non-trivial.
2947 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2948 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2949 CXXCastPath BasePath;
2950 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2951 FromLoc, FromRange, &BasePath))
2954 QualType UType = URecordType;
2955 if (PointerConversions)
2956 UType = Context.getPointerType(UType);
2957 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2958 VK, &BasePath).get();
2960 FromRecordType = URecordType;
2963 // We don't do access control for the conversion from the
2964 // declaring class to the true declaring class.
2965 IgnoreAccess = true;
2968 CXXCastPath BasePath;
2969 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2970 FromLoc, FromRange, &BasePath,
2974 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2978 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2979 const LookupResult &R,
2980 bool HasTrailingLParen) {
2981 // Only when used directly as the postfix-expression of a call.
2982 if (!HasTrailingLParen)
2985 // Never if a scope specifier was provided.
2989 // Only in C++ or ObjC++.
2990 if (!getLangOpts().CPlusPlus)
2993 // Turn off ADL when we find certain kinds of declarations during
2995 for (NamedDecl *D : R) {
2996 // C++0x [basic.lookup.argdep]p3:
2997 // -- a declaration of a class member
2998 // Since using decls preserve this property, we check this on the
3000 if (D->isCXXClassMember())
3003 // C++0x [basic.lookup.argdep]p3:
3004 // -- a block-scope function declaration that is not a
3005 // using-declaration
3006 // NOTE: we also trigger this for function templates (in fact, we
3007 // don't check the decl type at all, since all other decl types
3008 // turn off ADL anyway).
3009 if (isa<UsingShadowDecl>(D))
3010 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3011 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3014 // C++0x [basic.lookup.argdep]p3:
3015 // -- a declaration that is neither a function or a function
3017 // And also for builtin functions.
3018 if (isa<FunctionDecl>(D)) {
3019 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3021 // But also builtin functions.
3022 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3024 } else if (!isa<FunctionTemplateDecl>(D))
3032 /// Diagnoses obvious problems with the use of the given declaration
3033 /// as an expression. This is only actually called for lookups that
3034 /// were not overloaded, and it doesn't promise that the declaration
3035 /// will in fact be used.
3036 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3037 if (D->isInvalidDecl())
3040 if (isa<TypedefNameDecl>(D)) {
3041 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3045 if (isa<ObjCInterfaceDecl>(D)) {
3046 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3050 if (isa<NamespaceDecl>(D)) {
3051 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3058 // Certain multiversion types should be treated as overloaded even when there is
3060 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3061 assert(R.isSingleResult() && "Expected only a single result");
3062 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3064 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3067 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3068 LookupResult &R, bool NeedsADL,
3069 bool AcceptInvalidDecl) {
3070 // If this is a single, fully-resolved result and we don't need ADL,
3071 // just build an ordinary singleton decl ref.
3072 if (!NeedsADL && R.isSingleResult() &&
3073 !R.getAsSingle<FunctionTemplateDecl>() &&
3074 !ShouldLookupResultBeMultiVersionOverload(R))
3075 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3076 R.getRepresentativeDecl(), nullptr,
3079 // We only need to check the declaration if there's exactly one
3080 // result, because in the overloaded case the results can only be
3081 // functions and function templates.
3082 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3083 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3086 // Otherwise, just build an unresolved lookup expression. Suppress
3087 // any lookup-related diagnostics; we'll hash these out later, when
3088 // we've picked a target.
3089 R.suppressDiagnostics();
3091 UnresolvedLookupExpr *ULE
3092 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3093 SS.getWithLocInContext(Context),
3094 R.getLookupNameInfo(),
3095 NeedsADL, R.isOverloadedResult(),
3096 R.begin(), R.end());
3102 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3103 ValueDecl *var, DeclContext *DC);
3105 /// Complete semantic analysis for a reference to the given declaration.
3106 ExprResult Sema::BuildDeclarationNameExpr(
3107 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3108 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3109 bool AcceptInvalidDecl) {
3110 assert(D && "Cannot refer to a NULL declaration");
3111 assert(!isa<FunctionTemplateDecl>(D) &&
3112 "Cannot refer unambiguously to a function template");
3114 SourceLocation Loc = NameInfo.getLoc();
3115 if (CheckDeclInExpr(*this, Loc, D))
3118 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3119 // Specifically diagnose references to class templates that are missing
3120 // a template argument list.
3121 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3125 // Make sure that we're referring to a value.
3126 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3128 Diag(Loc, diag::err_ref_non_value)
3129 << D << SS.getRange();
3130 Diag(D->getLocation(), diag::note_declared_at);
3134 // Check whether this declaration can be used. Note that we suppress
3135 // this check when we're going to perform argument-dependent lookup
3136 // on this function name, because this might not be the function
3137 // that overload resolution actually selects.
3138 if (DiagnoseUseOfDecl(VD, Loc))
3141 // Only create DeclRefExpr's for valid Decl's.
3142 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3145 // Handle members of anonymous structs and unions. If we got here,
3146 // and the reference is to a class member indirect field, then this
3147 // must be the subject of a pointer-to-member expression.
3148 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3149 if (!indirectField->isCXXClassMember())
3150 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3154 QualType type = VD->getType();
3157 ExprValueKind valueKind = VK_RValue;
3159 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3160 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3161 // is expanded by some outer '...' in the context of the use.
3162 type = type.getNonPackExpansionType();
3164 switch (D->getKind()) {
3165 // Ignore all the non-ValueDecl kinds.
3166 #define ABSTRACT_DECL(kind)
3167 #define VALUE(type, base)
3168 #define DECL(type, base) \
3170 #include "clang/AST/DeclNodes.inc"
3171 llvm_unreachable("invalid value decl kind");
3173 // These shouldn't make it here.
3174 case Decl::ObjCAtDefsField:
3175 llvm_unreachable("forming non-member reference to ivar?");
3177 // Enum constants are always r-values and never references.
3178 // Unresolved using declarations are dependent.
3179 case Decl::EnumConstant:
3180 case Decl::UnresolvedUsingValue:
3181 case Decl::OMPDeclareReduction:
3182 case Decl::OMPDeclareMapper:
3183 valueKind = VK_RValue;
3186 // Fields and indirect fields that got here must be for
3187 // pointer-to-member expressions; we just call them l-values for
3188 // internal consistency, because this subexpression doesn't really
3189 // exist in the high-level semantics.
3191 case Decl::IndirectField:
3192 case Decl::ObjCIvar:
3193 assert(getLangOpts().CPlusPlus &&
3194 "building reference to field in C?");
3196 // These can't have reference type in well-formed programs, but
3197 // for internal consistency we do this anyway.
3198 type = type.getNonReferenceType();
3199 valueKind = VK_LValue;
3202 // Non-type template parameters are either l-values or r-values
3203 // depending on the type.
3204 case Decl::NonTypeTemplateParm: {
3205 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3206 type = reftype->getPointeeType();
3207 valueKind = VK_LValue; // even if the parameter is an r-value reference
3211 // For non-references, we need to strip qualifiers just in case
3212 // the template parameter was declared as 'const int' or whatever.
3213 valueKind = VK_RValue;
3214 type = type.getUnqualifiedType();
3219 case Decl::VarTemplateSpecialization:
3220 case Decl::VarTemplatePartialSpecialization:
3221 case Decl::Decomposition:
3222 case Decl::OMPCapturedExpr:
3223 // In C, "extern void blah;" is valid and is an r-value.
3224 if (!getLangOpts().CPlusPlus &&
3225 !type.hasQualifiers() &&
3226 type->isVoidType()) {
3227 valueKind = VK_RValue;
3232 case Decl::ImplicitParam:
3233 case Decl::ParmVar: {
3234 // These are always l-values.
3235 valueKind = VK_LValue;
3236 type = type.getNonReferenceType();
3238 // FIXME: Does the addition of const really only apply in
3239 // potentially-evaluated contexts? Since the variable isn't actually
3240 // captured in an unevaluated context, it seems that the answer is no.
3241 if (!isUnevaluatedContext()) {
3242 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3243 if (!CapturedType.isNull())
3244 type = CapturedType;
3250 case Decl::Binding: {
3251 // These are always lvalues.
3252 valueKind = VK_LValue;
3253 type = type.getNonReferenceType();
3254 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3255 // decides how that's supposed to work.
3256 auto *BD = cast<BindingDecl>(VD);
3257 if (BD->getDeclContext() != CurContext) {
3258 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3259 if (DD && DD->hasLocalStorage())
3260 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3265 case Decl::Function: {
3266 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3267 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3268 type = Context.BuiltinFnTy;
3269 valueKind = VK_RValue;
3274 const FunctionType *fty = type->castAs<FunctionType>();
3276 // If we're referring to a function with an __unknown_anytype
3277 // result type, make the entire expression __unknown_anytype.
3278 if (fty->getReturnType() == Context.UnknownAnyTy) {
3279 type = Context.UnknownAnyTy;
3280 valueKind = VK_RValue;
3284 // Functions are l-values in C++.
3285 if (getLangOpts().CPlusPlus) {
3286 valueKind = VK_LValue;
3290 // C99 DR 316 says that, if a function type comes from a
3291 // function definition (without a prototype), that type is only
3292 // used for checking compatibility. Therefore, when referencing
3293 // the function, we pretend that we don't have the full function
3295 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3296 isa<FunctionProtoType>(fty))
3297 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3300 // Functions are r-values in C.
3301 valueKind = VK_RValue;
3305 case Decl::CXXDeductionGuide:
3306 llvm_unreachable("building reference to deduction guide");
3308 case Decl::MSProperty:
3310 // FIXME: Should MSGuidDecl be subject to capture in OpenMP,
3311 // or duplicated between host and device?
3312 valueKind = VK_LValue;
3315 case Decl::CXXMethod:
3316 // If we're referring to a method with an __unknown_anytype
3317 // result type, make the entire expression __unknown_anytype.
3318 // This should only be possible with a type written directly.
3319 if (const FunctionProtoType *proto
3320 = dyn_cast<FunctionProtoType>(VD->getType()))
3321 if (proto->getReturnType() == Context.UnknownAnyTy) {
3322 type = Context.UnknownAnyTy;
3323 valueKind = VK_RValue;
3327 // C++ methods are l-values if static, r-values if non-static.
3328 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3329 valueKind = VK_LValue;
3334 case Decl::CXXConversion:
3335 case Decl::CXXDestructor:
3336 case Decl::CXXConstructor:
3337 valueKind = VK_RValue;
3341 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3342 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3347 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3348 SmallString<32> &Target) {
3349 Target.resize(CharByteWidth * (Source.size() + 1));
3350 char *ResultPtr = &Target[0];
3351 const llvm::UTF8 *ErrorPtr;
3353 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3356 Target.resize(ResultPtr - &Target[0]);
3359 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3360 PredefinedExpr::IdentKind IK) {
3361 // Pick the current block, lambda, captured statement or function.
3362 Decl *currentDecl = nullptr;
3363 if (const BlockScopeInfo *BSI = getCurBlock())
3364 currentDecl = BSI->TheDecl;
3365 else if (const LambdaScopeInfo *LSI = getCurLambda())
3366 currentDecl = LSI->CallOperator;
3367 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3368 currentDecl = CSI->TheCapturedDecl;
3370 currentDecl = getCurFunctionOrMethodDecl();
3373 Diag(Loc, diag::ext_predef_outside_function);
3374 currentDecl = Context.getTranslationUnitDecl();
3378 StringLiteral *SL = nullptr;
3379 if (cast<DeclContext>(currentDecl)->isDependentContext())
3380 ResTy = Context.DependentTy;
3382 // Pre-defined identifiers are of type char[x], where x is the length of
3384 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3385 unsigned Length = Str.length();
3387 llvm::APInt LengthI(32, Length + 1);
3388 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3390 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3391 SmallString<32> RawChars;
3392 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3394 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3396 /*IndexTypeQuals*/ 0);
3397 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3398 /*Pascal*/ false, ResTy, Loc);
3400 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3401 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3403 /*IndexTypeQuals*/ 0);
3404 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3405 /*Pascal*/ false, ResTy, Loc);
3409 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3412 static std::pair<QualType, StringLiteral *>
3413 GetUniqueStableNameInfo(ASTContext &Context, QualType OpType,
3414 SourceLocation OpLoc, PredefinedExpr::IdentKind K) {
3415 std::pair<QualType, StringLiteral*> Result{{}, nullptr};
3417 if (OpType->isDependentType()) {
3418 Result.first = Context.DependentTy;
3422 std::string Str = PredefinedExpr::ComputeName(Context, K, OpType);
3423 llvm::APInt Length(32, Str.length() + 1);
3425 Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3426 Result.first = Context.getConstantArrayType(
3427 Result.first, Length, nullptr, ArrayType::Normal, /*IndexTypeQuals*/ 0);
3428 Result.second = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3429 /*Pascal*/ false, Result.first, OpLoc);
3433 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3434 TypeSourceInfo *Operand) {
3437 std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3438 Context, Operand->getType(), OpLoc, PredefinedExpr::UniqueStableNameType);
3440 return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3441 PredefinedExpr::UniqueStableNameType, SL,
3445 ExprResult Sema::BuildUniqueStableName(SourceLocation OpLoc,
3449 std::tie(ResultTy, SL) = GetUniqueStableNameInfo(
3450 Context, E->getType(), OpLoc, PredefinedExpr::UniqueStableNameExpr);
3452 return PredefinedExpr::Create(Context, OpLoc, ResultTy,
3453 PredefinedExpr::UniqueStableNameExpr, SL, E);
3456 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3457 SourceLocation L, SourceLocation R,
3459 TypeSourceInfo *TInfo = nullptr;
3460 QualType T = GetTypeFromParser(Ty, &TInfo);
3465 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
3467 return BuildUniqueStableName(OpLoc, TInfo);
3470 ExprResult Sema::ActOnUniqueStableNameExpr(SourceLocation OpLoc,
3471 SourceLocation L, SourceLocation R,
3473 return BuildUniqueStableName(OpLoc, E);
3476 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3477 PredefinedExpr::IdentKind IK;
3480 default: llvm_unreachable("Unknown simple primary expr!");
3481 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3482 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3483 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3484 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3485 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3486 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3487 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3490 return BuildPredefinedExpr(Loc, IK);
3493 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3494 SmallString<16> CharBuffer;
3495 bool Invalid = false;
3496 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3500 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3502 if (Literal.hadError())
3506 if (Literal.isWide())
3507 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3508 else if (Literal.isUTF8() && getLangOpts().Char8)
3509 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3510 else if (Literal.isUTF16())
3511 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3512 else if (Literal.isUTF32())
3513 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3514 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3515 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3517 Ty = Context.CharTy; // 'x' -> char in C++
3519 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3520 if (Literal.isWide())
3521 Kind = CharacterLiteral::Wide;
3522 else if (Literal.isUTF16())
3523 Kind = CharacterLiteral::UTF16;
3524 else if (Literal.isUTF32())
3525 Kind = CharacterLiteral::UTF32;
3526 else if (Literal.isUTF8())
3527 Kind = CharacterLiteral::UTF8;
3529 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3532 if (Literal.getUDSuffix().empty())
3535 // We're building a user-defined literal.
3536 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3537 SourceLocation UDSuffixLoc =
3538 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3540 // Make sure we're allowed user-defined literals here.
3542 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3544 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3545 // operator "" X (ch)
3546 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3547 Lit, Tok.getLocation());
3550 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3551 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3552 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3553 Context.IntTy, Loc);
3556 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3557 QualType Ty, SourceLocation Loc) {
3558 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3560 using llvm::APFloat;
3561 APFloat Val(Format);
3563 APFloat::opStatus result = Literal.GetFloatValue(Val);
3565 // Overflow is always an error, but underflow is only an error if
3566 // we underflowed to zero (APFloat reports denormals as underflow).
3567 if ((result & APFloat::opOverflow) ||
3568 ((result & APFloat::opUnderflow) && Val.isZero())) {
3569 unsigned diagnostic;
3570 SmallString<20> buffer;
3571 if (result & APFloat::opOverflow) {
3572 diagnostic = diag::warn_float_overflow;
3573 APFloat::getLargest(Format).toString(buffer);
3575 diagnostic = diag::warn_float_underflow;
3576 APFloat::getSmallest(Format).toString(buffer);
3579 S.Diag(Loc, diagnostic)
3581 << StringRef(buffer.data(), buffer.size());
3584 bool isExact = (result == APFloat::opOK);
3585 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3588 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3589 assert(E && "Invalid expression");
3591 if (E->isValueDependent())
3594 QualType QT = E->getType();
3595 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3596 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3600 llvm::APSInt ValueAPS;
3601 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3606 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3607 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3608 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3609 << ValueAPS.toString(10) << ValueIsPositive;
3616 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3617 // Fast path for a single digit (which is quite common). A single digit
3618 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3619 if (Tok.getLength() == 1) {
3620 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3621 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3624 SmallString<128> SpellingBuffer;
3625 // NumericLiteralParser wants to overread by one character. Add padding to
3626 // the buffer in case the token is copied to the buffer. If getSpelling()
3627 // returns a StringRef to the memory buffer, it should have a null char at
3628 // the EOF, so it is also safe.
3629 SpellingBuffer.resize(Tok.getLength() + 1);
3631 // Get the spelling of the token, which eliminates trigraphs, etc.
3632 bool Invalid = false;
3633 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3637 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3638 PP.getSourceManager(), PP.getLangOpts(),
3639 PP.getTargetInfo(), PP.getDiagnostics());
3640 if (Literal.hadError)
3643 if (Literal.hasUDSuffix()) {
3644 // We're building a user-defined literal.
3645 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3646 SourceLocation UDSuffixLoc =
3647 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3649 // Make sure we're allowed user-defined literals here.
3651 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3654 if (Literal.isFloatingLiteral()) {
3655 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3656 // long double, the literal is treated as a call of the form
3657 // operator "" X (f L)
3658 CookedTy = Context.LongDoubleTy;
3660 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3661 // unsigned long long, the literal is treated as a call of the form
3662 // operator "" X (n ULL)
3663 CookedTy = Context.UnsignedLongLongTy;
3666 DeclarationName OpName =
3667 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3668 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3669 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3671 SourceLocation TokLoc = Tok.getLocation();
3673 // Perform literal operator lookup to determine if we're building a raw
3674 // literal or a cooked one.
3675 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3676 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3677 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3678 /*AllowStringTemplate*/ false,
3679 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3680 case LOLR_ErrorNoDiagnostic:
3681 // Lookup failure for imaginary constants isn't fatal, there's still the
3682 // GNU extension producing _Complex types.
3688 if (Literal.isFloatingLiteral()) {
3689 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3691 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3692 if (Literal.GetIntegerValue(ResultVal))
3693 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3694 << /* Unsigned */ 1;
3695 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3698 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3702 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3703 // literal is treated as a call of the form
3704 // operator "" X ("n")
3705 unsigned Length = Literal.getUDSuffixOffset();
3706 QualType StrTy = Context.getConstantArrayType(
3707 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3708 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3709 Expr *Lit = StringLiteral::Create(
3710 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3711 /*Pascal*/false, StrTy, &TokLoc, 1);
3712 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3715 case LOLR_Template: {
3716 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3717 // template), L is treated as a call fo the form
3718 // operator "" X <'c1', 'c2', ... 'ck'>()
3719 // where n is the source character sequence c1 c2 ... ck.
3720 TemplateArgumentListInfo ExplicitArgs;
3721 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3722 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3723 llvm::APSInt Value(CharBits, CharIsUnsigned);
3724 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3725 Value = TokSpelling[I];
3726 TemplateArgument Arg(Context, Value, Context.CharTy);
3727 TemplateArgumentLocInfo ArgInfo;
3728 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3730 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3733 case LOLR_StringTemplate:
3734 llvm_unreachable("unexpected literal operator lookup result");
3740 if (Literal.isFixedPointLiteral()) {
3743 if (Literal.isAccum) {
3744 if (Literal.isHalf) {
3745 Ty = Context.ShortAccumTy;
3746 } else if (Literal.isLong) {
3747 Ty = Context.LongAccumTy;
3749 Ty = Context.AccumTy;
3751 } else if (Literal.isFract) {
3752 if (Literal.isHalf) {
3753 Ty = Context.ShortFractTy;
3754 } else if (Literal.isLong) {
3755 Ty = Context.LongFractTy;
3757 Ty = Context.FractTy;
3761 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3763 bool isSigned = !Literal.isUnsigned;
3764 unsigned scale = Context.getFixedPointScale(Ty);
3765 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3767 llvm::APInt Val(bit_width, 0, isSigned);
3768 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3769 bool ValIsZero = Val.isNullValue() && !Overflowed;
3771 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3772 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3773 // Clause 6.4.4 - The value of a constant shall be in the range of
3774 // representable values for its type, with exception for constants of a
3775 // fract type with a value of exactly 1; such a constant shall denote
3776 // the maximal value for the type.
3778 else if (Val.ugt(MaxVal) || Overflowed)
3779 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3781 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3782 Tok.getLocation(), scale);
3783 } else if (Literal.isFloatingLiteral()) {
3785 if (Literal.isHalf){
3786 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3787 Ty = Context.HalfTy;
3789 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3792 } else if (Literal.isFloat)
3793 Ty = Context.FloatTy;
3794 else if (Literal.isLong)
3795 Ty = Context.LongDoubleTy;
3796 else if (Literal.isFloat16)
3797 Ty = Context.Float16Ty;
3798 else if (Literal.isFloat128)
3799 Ty = Context.Float128Ty;
3801 Ty = Context.DoubleTy;
3803 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3805 if (Ty == Context.DoubleTy) {
3806 if (getLangOpts().SinglePrecisionConstants) {
3807 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3808 if (BTy->getKind() != BuiltinType::Float) {
3809 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3811 } else if (getLangOpts().OpenCL &&
3812 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3813 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3814 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3815 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3818 } else if (!Literal.isIntegerLiteral()) {
3823 // 'long long' is a C99 or C++11 feature.
3824 if (!getLangOpts().C99 && Literal.isLongLong) {
3825 if (getLangOpts().CPlusPlus)
3826 Diag(Tok.getLocation(),
3827 getLangOpts().CPlusPlus11 ?
3828 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3830 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3833 // Get the value in the widest-possible width.
3834 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3835 llvm::APInt ResultVal(MaxWidth, 0);
3837 if (Literal.GetIntegerValue(ResultVal)) {
3838 // If this value didn't fit into uintmax_t, error and force to ull.
3839 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3840 << /* Unsigned */ 1;
3841 Ty = Context.UnsignedLongLongTy;
3842 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3843 "long long is not intmax_t?");
3845 // If this value fits into a ULL, try to figure out what else it fits into
3846 // according to the rules of C99 6.4.4.1p5.
3848 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3849 // be an unsigned int.
3850 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3852 // Check from smallest to largest, picking the smallest type we can.
3855 // Microsoft specific integer suffixes are explicitly sized.
3856 if (Literal.MicrosoftInteger) {
3857 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3859 Ty = Context.CharTy;
3861 Width = Literal.MicrosoftInteger;
3862 Ty = Context.getIntTypeForBitwidth(Width,
3863 /*Signed=*/!Literal.isUnsigned);
3867 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3868 // Are int/unsigned possibilities?
3869 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3871 // Does it fit in a unsigned int?
3872 if (ResultVal.isIntN(IntSize)) {
3873 // Does it fit in a signed int?
3874 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3876 else if (AllowUnsigned)
3877 Ty = Context.UnsignedIntTy;
3882 // Are long/unsigned long possibilities?
3883 if (Ty.isNull() && !Literal.isLongLong) {
3884 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3886 // Does it fit in a unsigned long?
3887 if (ResultVal.isIntN(LongSize)) {
3888 // Does it fit in a signed long?
3889 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3890 Ty = Context.LongTy;
3891 else if (AllowUnsigned)
3892 Ty = Context.UnsignedLongTy;
3893 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3895 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3896 const unsigned LongLongSize =
3897 Context.getTargetInfo().getLongLongWidth();
3898 Diag(Tok.getLocation(),
3899 getLangOpts().CPlusPlus
3901 ? diag::warn_old_implicitly_unsigned_long_cxx
3902 : /*C++98 UB*/ diag::
3903 ext_old_implicitly_unsigned_long_cxx
3904 : diag::warn_old_implicitly_unsigned_long)
3905 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3906 : /*will be ill-formed*/ 1);
3907 Ty = Context.UnsignedLongTy;
3913 // Check long long if needed.
3915 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3917 // Does it fit in a unsigned long long?
3918 if (ResultVal.isIntN(LongLongSize)) {
3919 // Does it fit in a signed long long?
3920 // To be compatible with MSVC, hex integer literals ending with the
3921 // LL or i64 suffix are always signed in Microsoft mode.
3922 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3923 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3924 Ty = Context.LongLongTy;
3925 else if (AllowUnsigned)
3926 Ty = Context.UnsignedLongLongTy;
3927 Width = LongLongSize;
3931 // If we still couldn't decide a type, we probably have something that
3932 // does not fit in a signed long long, but has no U suffix.
3934 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3935 Ty = Context.UnsignedLongLongTy;
3936 Width = Context.getTargetInfo().getLongLongWidth();
3939 if (ResultVal.getBitWidth() != Width)
3940 ResultVal = ResultVal.trunc(Width);
3942 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3945 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3946 if (Literal.isImaginary) {
3947 Res = new (Context) ImaginaryLiteral(Res,
3948 Context.getComplexType(Res->getType()));
3950 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3955 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3956 assert(E && "ActOnParenExpr() missing expr");
3957 return new (Context) ParenExpr(L, R, E);
3960 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3962 SourceRange ArgRange) {
3963 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3964 // scalar or vector data type argument..."
3965 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3966 // type (C99 6.2.5p18) or void.
3967 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3968 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3973 assert((T->isVoidType() || !T->isIncompleteType()) &&
3974 "Scalar types should always be complete");
3978 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3980 SourceRange ArgRange,
3981 UnaryExprOrTypeTrait TraitKind) {
3982 // Invalid types must be hard errors for SFINAE in C++.
3983 if (S.LangOpts.CPlusPlus)
3987 if (T->isFunctionType() &&
3988 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3989 TraitKind == UETT_PreferredAlignOf)) {
3990 // sizeof(function)/alignof(function) is allowed as an extension.
3991 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3992 << getTraitSpelling(TraitKind) << ArgRange;
3996 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3997 // this is an error (OpenCL v1.1 s6.3.k)
3998 if (T->isVoidType()) {
3999 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4000 : diag::ext_sizeof_alignof_void_type;
4001 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4008 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4010 SourceRange ArgRange,
4011 UnaryExprOrTypeTrait TraitKind) {
4012 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4013 // runtime doesn't allow it.
4014 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4015 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4016 << T << (TraitKind == UETT_SizeOf)
4024 /// Check whether E is a pointer from a decayed array type (the decayed
4025 /// pointer type is equal to T) and emit a warning if it is.
4026 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4028 // Don't warn if the operation changed the type.
4029 if (T != E->getType())
4032 // Now look for array decays.
4033 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4034 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4037 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4039 << ICE->getSubExpr()->getType();
4042 /// Check the constraints on expression operands to unary type expression
4043 /// and type traits.
4045 /// Completes any types necessary and validates the constraints on the operand
4046 /// expression. The logic mostly mirrors the type-based overload, but may modify
4047 /// the expression as it completes the type for that expression through template
4048 /// instantiation, etc.
4049 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4050 UnaryExprOrTypeTrait ExprKind) {
4051 QualType ExprTy = E->getType();
4052 assert(!ExprTy->isReferenceType());
4054 bool IsUnevaluatedOperand =
4055 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4056 ExprKind == UETT_PreferredAlignOf);
4057 if (IsUnevaluatedOperand) {
4058 ExprResult Result = CheckUnevaluatedOperand(E);
4059 if (Result.isInvalid())
4064 if (ExprKind == UETT_VecStep)
4065 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4066 E->getSourceRange());
4068 // Explicitly list some types as extensions.
4069 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4070 E->getSourceRange(), ExprKind))
4073 // 'alignof' applied to an expression only requires the base element type of
4074 // the expression to be complete. 'sizeof' requires the expression's type to
4075 // be complete (and will attempt to complete it if it's an array of unknown
4077 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4078 if (RequireCompleteSizedType(
4079 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4080 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4081 getTraitSpelling(ExprKind), E->getSourceRange()))
4084 if (RequireCompleteSizedExprType(
4085 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4086 getTraitSpelling(ExprKind), E->getSourceRange()))
4090 // Completing the expression's type may have changed it.
4091 ExprTy = E->getType();
4092 assert(!ExprTy->isReferenceType());
4094 if (ExprTy->isFunctionType()) {
4095 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4096 << getTraitSpelling(ExprKind) << E->getSourceRange();
4100 // The operand for sizeof and alignof is in an unevaluated expression context,
4101 // so side effects could result in unintended consequences.
4102 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4103 E->HasSideEffects(Context, false))
4104 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4106 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4107 E->getSourceRange(), ExprKind))
4110 if (ExprKind == UETT_SizeOf) {
4111 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4112 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4113 QualType OType = PVD->getOriginalType();
4114 QualType Type = PVD->getType();
4115 if (Type->isPointerType() && OType->isArrayType()) {
4116 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4118 Diag(PVD->getLocation(), diag::note_declared_at);
4123 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4124 // decays into a pointer and returns an unintended result. This is most
4125 // likely a typo for "sizeof(array) op x".
4126 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4127 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4129 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4137 /// Check the constraints on operands to unary expression and type
4140 /// This will complete any types necessary, and validate the various constraints
4141 /// on those operands.
4143 /// The UsualUnaryConversions() function is *not* called by this routine.
4144 /// C99 6.3.2.1p[2-4] all state:
4145 /// Except when it is the operand of the sizeof operator ...
4147 /// C++ [expr.sizeof]p4
4148 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4149 /// standard conversions are not applied to the operand of sizeof.
4151 /// This policy is followed for all of the unary trait expressions.
4152 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4153 SourceLocation OpLoc,
4154 SourceRange ExprRange,
4155 UnaryExprOrTypeTrait ExprKind) {
4156 if (ExprType->isDependentType())
4159 // C++ [expr.sizeof]p2:
4160 // When applied to a reference or a reference type, the result
4161 // is the size of the referenced type.
4162 // C++11 [expr.alignof]p3:
4163 // When alignof is applied to a reference type, the result
4164 // shall be the alignment of the referenced type.
4165 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4166 ExprType = Ref->getPointeeType();
4168 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4169 // When alignof or _Alignof is applied to an array type, the result
4170 // is the alignment of the element type.
4171 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4172 ExprKind == UETT_OpenMPRequiredSimdAlign)
4173 ExprType = Context.getBaseElementType(ExprType);
4175 if (ExprKind == UETT_VecStep)
4176 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4178 // Explicitly list some types as extensions.
4179 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4183 if (RequireCompleteSizedType(
4184 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4185 getTraitSpelling(ExprKind), ExprRange))
4188 if (ExprType->isFunctionType()) {
4189 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4190 << getTraitSpelling(ExprKind) << ExprRange;
4194 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4201 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4202 // Cannot know anything else if the expression is dependent.
4203 if (E->isTypeDependent())
4206 if (E->getObjectKind() == OK_BitField) {
4207 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4208 << 1 << E->getSourceRange();
4212 ValueDecl *D = nullptr;
4213 Expr *Inner = E->IgnoreParens();
4214 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4216 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4217 D = ME->getMemberDecl();
4220 // If it's a field, require the containing struct to have a
4221 // complete definition so that we can compute the layout.
4223 // This can happen in C++11 onwards, either by naming the member
4224 // in a way that is not transformed into a member access expression
4225 // (in an unevaluated operand, for instance), or by naming the member
4226 // in a trailing-return-type.
4228 // For the record, since __alignof__ on expressions is a GCC
4229 // extension, GCC seems to permit this but always gives the
4230 // nonsensical answer 0.
4232 // We don't really need the layout here --- we could instead just
4233 // directly check for all the appropriate alignment-lowing
4234 // attributes --- but that would require duplicating a lot of
4235 // logic that just isn't worth duplicating for such a marginal
4237 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4238 // Fast path this check, since we at least know the record has a
4239 // definition if we can find a member of it.
4240 if (!FD->getParent()->isCompleteDefinition()) {
4241 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4242 << E->getSourceRange();
4246 // Otherwise, if it's a field, and the field doesn't have
4247 // reference type, then it must have a complete type (or be a
4248 // flexible array member, which we explicitly want to
4249 // white-list anyway), which makes the following checks trivial.
4250 if (!FD->getType()->isReferenceType())
4254 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4257 bool Sema::CheckVecStepExpr(Expr *E) {
4258 E = E->IgnoreParens();
4260 // Cannot know anything else if the expression is dependent.
4261 if (E->isTypeDependent())
4264 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4267 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4268 CapturingScopeInfo *CSI) {
4269 assert(T->isVariablyModifiedType());
4270 assert(CSI != nullptr);
4272 // We're going to walk down into the type and look for VLA expressions.
4274 const Type *Ty = T.getTypePtr();
4275 switch (Ty->getTypeClass()) {
4276 #define TYPE(Class, Base)
4277 #define ABSTRACT_TYPE(Class, Base)
4278 #define NON_CANONICAL_TYPE(Class, Base)
4279 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4280 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4281 #include "clang/AST/TypeNodes.inc"
4284 // These types are never variably-modified.
4288 case Type::ExtVector:
4289 case Type::ConstantMatrix:
4292 case Type::Elaborated:
4293 case Type::TemplateSpecialization:
4294 case Type::ObjCObject:
4295 case Type::ObjCInterface:
4296 case Type::ObjCObjectPointer:
4297 case Type::ObjCTypeParam:
4300 llvm_unreachable("type class is never variably-modified!");
4301 case Type::Adjusted:
4302 T = cast<AdjustedType>(Ty)->getOriginalType();
4305 T = cast<DecayedType>(Ty)->getPointeeType();
4308 T = cast<PointerType>(Ty)->getPointeeType();
4310 case Type::BlockPointer:
4311 T = cast<BlockPointerType>(Ty)->getPointeeType();
4313 case Type::LValueReference:
4314 case Type::RValueReference:
4315 T = cast<ReferenceType>(Ty)->getPointeeType();
4317 case Type::MemberPointer:
4318 T = cast<MemberPointerType>(Ty)->getPointeeType();
4320 case Type::ConstantArray:
4321 case Type::IncompleteArray:
4322 // Losing element qualification here is fine.
4323 T = cast<ArrayType>(Ty)->getElementType();
4325 case Type::VariableArray: {
4326 // Losing element qualification here is fine.
4327 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4329 // Unknown size indication requires no size computation.
4330 // Otherwise, evaluate and record it.
4331 auto Size = VAT->getSizeExpr();
4332 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4333 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4334 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4336 T = VAT->getElementType();
4339 case Type::FunctionProto:
4340 case Type::FunctionNoProto:
4341 T = cast<FunctionType>(Ty)->getReturnType();
4345 case Type::UnaryTransform:
4346 case Type::Attributed:
4347 case Type::SubstTemplateTypeParm:
4348 case Type::PackExpansion:
4349 case Type::MacroQualified:
4350 // Keep walking after single level desugaring.
4351 T = T.getSingleStepDesugaredType(Context);
4354 T = cast<TypedefType>(Ty)->desugar();
4356 case Type::Decltype:
4357 T = cast<DecltypeType>(Ty)->desugar();
4360 case Type::DeducedTemplateSpecialization:
4361 T = cast<DeducedType>(Ty)->getDeducedType();
4363 case Type::TypeOfExpr:
4364 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4367 T = cast<AtomicType>(Ty)->getValueType();
4370 } while (!T.isNull() && T->isVariablyModifiedType());
4373 /// Build a sizeof or alignof expression given a type operand.
4375 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4376 SourceLocation OpLoc,
4377 UnaryExprOrTypeTrait ExprKind,
4382 QualType T = TInfo->getType();
4384 if (!T->isDependentType() &&
4385 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4388 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4389 if (auto *TT = T->getAs<TypedefType>()) {
4390 for (auto I = FunctionScopes.rbegin(),
4391 E = std::prev(FunctionScopes.rend());
4393 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4396 DeclContext *DC = nullptr;
4397 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4398 DC = LSI->CallOperator;
4399 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4400 DC = CRSI->TheCapturedDecl;
4401 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4404 if (DC->containsDecl(TT->getDecl()))
4406 captureVariablyModifiedType(Context, T, CSI);
4412 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4413 return new (Context) UnaryExprOrTypeTraitExpr(
4414 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4417 /// Build a sizeof or alignof expression given an expression
4420 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4421 UnaryExprOrTypeTrait ExprKind) {
4422 ExprResult PE = CheckPlaceholderExpr(E);
4428 // Verify that the operand is valid.
4429 bool isInvalid = false;
4430 if (E->isTypeDependent()) {
4431 // Delay type-checking for type-dependent expressions.
4432 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4433 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4434 } else if (ExprKind == UETT_VecStep) {
4435 isInvalid = CheckVecStepExpr(E);
4436 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4437 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4439 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4440 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4443 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4449 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4450 PE = TransformToPotentiallyEvaluated(E);
4451 if (PE.isInvalid()) return ExprError();
4455 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4456 return new (Context) UnaryExprOrTypeTraitExpr(
4457 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4460 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4461 /// expr and the same for @c alignof and @c __alignof
4462 /// Note that the ArgRange is invalid if isType is false.
4464 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4465 UnaryExprOrTypeTrait ExprKind, bool IsType,
4466 void *TyOrEx, SourceRange ArgRange) {
4467 // If error parsing type, ignore.
4468 if (!TyOrEx) return ExprError();
4471 TypeSourceInfo *TInfo;
4472 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4473 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4476 Expr *ArgEx = (Expr *)TyOrEx;
4477 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4481 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4483 if (V.get()->isTypeDependent())
4484 return S.Context.DependentTy;
4486 // _Real and _Imag are only l-values for normal l-values.
4487 if (V.get()->getObjectKind() != OK_Ordinary) {
4488 V = S.DefaultLvalueConversion(V.get());
4493 // These operators return the element type of a complex type.
4494 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4495 return CT->getElementType();
4497 // Otherwise they pass through real integer and floating point types here.
4498 if (V.get()->getType()->isArithmeticType())
4499 return V.get()->getType();
4501 // Test for placeholders.
4502 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4503 if (PR.isInvalid()) return QualType();
4504 if (PR.get() != V.get()) {
4506 return CheckRealImagOperand(S, V, Loc, IsReal);
4509 // Reject anything else.
4510 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4511 << (IsReal ? "__real" : "__imag");
4518 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4519 tok::TokenKind Kind, Expr *Input) {
4520 UnaryOperatorKind Opc;
4522 default: llvm_unreachable("Unknown unary op!");
4523 case tok::plusplus: Opc = UO_PostInc; break;
4524 case tok::minusminus: Opc = UO_PostDec; break;
4527 // Since this might is a postfix expression, get rid of ParenListExprs.
4528 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4529 if (Result.isInvalid()) return ExprError();
4530 Input = Result.get();
4532 return BuildUnaryOp(S, OpLoc, Opc, Input);
4535 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4537 /// \return true on error
4538 static bool checkArithmeticOnObjCPointer(Sema &S,
4539 SourceLocation opLoc,
4541 assert(op->getType()->isObjCObjectPointerType());
4542 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4543 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4546 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4547 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4548 << op->getSourceRange();
4552 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4553 auto *BaseNoParens = Base->IgnoreParens();
4554 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4555 return MSProp->getPropertyDecl()->getType()->isArrayType();
4556 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4560 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4561 Expr *idx, SourceLocation rbLoc) {
4562 if (base && !base->getType().isNull() &&
4563 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4564 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4565 SourceLocation(), /*Length*/ nullptr,
4566 /*Stride=*/nullptr, rbLoc);
4568 // Since this might be a postfix expression, get rid of ParenListExprs.
4569 if (isa<ParenListExpr>(base)) {
4570 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4571 if (result.isInvalid()) return ExprError();
4572 base = result.get();
4575 // Check if base and idx form a MatrixSubscriptExpr.
4577 // Helper to check for comma expressions, which are not allowed as indices for
4578 // matrix subscript expressions.
4579 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4580 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4581 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4582 << SourceRange(base->getBeginLoc(), rbLoc);
4587 // The matrix subscript operator ([][])is considered a single operator.
4588 // Separating the index expressions by parenthesis is not allowed.
4589 if (base->getType()->isSpecificPlaceholderType(
4590 BuiltinType::IncompleteMatrixIdx) &&
4591 !isa<MatrixSubscriptExpr>(base)) {
4592 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4593 << SourceRange(base->getBeginLoc(), rbLoc);
4596 // If the base is either a MatrixSubscriptExpr or a matrix type, try to create
4597 // a new MatrixSubscriptExpr.
4598 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4599 if (matSubscriptE) {
4600 if (CheckAndReportCommaError(idx))
4603 assert(matSubscriptE->isIncomplete() &&
4604 "base has to be an incomplete matrix subscript");
4605 return CreateBuiltinMatrixSubscriptExpr(
4606 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4608 Expr *matrixBase = base;
4609 bool IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4610 if (!IsMSPropertySubscript) {
4611 ExprResult result = CheckPlaceholderExpr(base);
4612 if (!result.isInvalid())
4613 matrixBase = result.get();
4615 if (matrixBase->getType()->isMatrixType()) {
4616 if (CheckAndReportCommaError(idx))
4619 return CreateBuiltinMatrixSubscriptExpr(matrixBase, idx, nullptr, rbLoc);
4622 // A comma-expression as the index is deprecated in C++2a onwards.
4623 if (getLangOpts().CPlusPlus20 &&
4624 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4625 (isa<CXXOperatorCallExpr>(idx) &&
4626 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4627 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4628 << SourceRange(base->getBeginLoc(), rbLoc);
4631 // Handle any non-overload placeholder types in the base and index
4632 // expressions. We can't handle overloads here because the other
4633 // operand might be an overloadable type, in which case the overload
4634 // resolution for the operator overload should get the first crack
4636 if (base->getType()->isNonOverloadPlaceholderType()) {
4637 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4638 if (!IsMSPropertySubscript) {
4639 ExprResult result = CheckPlaceholderExpr(base);
4640 if (result.isInvalid())
4642 base = result.get();
4645 if (idx->getType()->isNonOverloadPlaceholderType()) {
4646 ExprResult result = CheckPlaceholderExpr(idx);
4647 if (result.isInvalid()) return ExprError();
4651 // Build an unanalyzed expression if either operand is type-dependent.
4652 if (getLangOpts().CPlusPlus &&
4653 (base->isTypeDependent() || idx->isTypeDependent())) {
4654 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4655 VK_LValue, OK_Ordinary, rbLoc);
4658 // MSDN, property (C++)
4659 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4660 // This attribute can also be used in the declaration of an empty array in a
4661 // class or structure definition. For example:
4662 // __declspec(property(get=GetX, put=PutX)) int x[];
4663 // The above statement indicates that x[] can be used with one or more array
4664 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4665 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4666 if (IsMSPropertySubscript) {
4667 // Build MS property subscript expression if base is MS property reference
4668 // or MS property subscript.
4669 return new (Context) MSPropertySubscriptExpr(
4670 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4673 // Use C++ overloaded-operator rules if either operand has record
4674 // type. The spec says to do this if either type is *overloadable*,
4675 // but enum types can't declare subscript operators or conversion
4676 // operators, so there's nothing interesting for overload resolution
4677 // to do if there aren't any record types involved.
4679 // ObjC pointers have their own subscripting logic that is not tied
4680 // to overload resolution and so should not take this path.
4681 if (getLangOpts().CPlusPlus &&
4682 (base->getType()->isRecordType() ||
4683 (!base->getType()->isObjCObjectPointerType() &&
4684 idx->getType()->isRecordType()))) {
4685 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4688 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4690 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4691 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4696 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4697 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4698 InitializationKind Kind =
4699 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4700 InitializationSequence InitSeq(*this, Entity, Kind, E);
4701 return InitSeq.Perform(*this, Entity, Kind, E);
4704 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4706 SourceLocation RBLoc) {
4707 ExprResult BaseR = CheckPlaceholderExpr(Base);
4708 if (BaseR.isInvalid())
4712 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4713 if (RowR.isInvalid())
4715 RowIdx = RowR.get();
4718 return new (Context) MatrixSubscriptExpr(
4719 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4721 // Build an unanalyzed expression if any of the operands is type-dependent.
4722 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4723 ColumnIdx->isTypeDependent())
4724 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4725 Context.DependentTy, RBLoc);
4727 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4728 if (ColumnR.isInvalid())
4730 ColumnIdx = ColumnR.get();
4732 // Check that IndexExpr is an integer expression. If it is a constant
4733 // expression, check that it is less than Dim (= the number of elements in the
4734 // corresponding dimension).
4735 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4736 bool IsColumnIdx) -> Expr * {
4737 if (!IndexExpr->getType()->isIntegerType() &&
4738 !IndexExpr->isTypeDependent()) {
4739 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4745 if (IndexExpr->isIntegerConstantExpr(Idx, Context) &&
4746 (Idx < 0 || Idx >= Dim)) {
4747 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4748 << IsColumnIdx << Dim;
4752 ExprResult ConvExpr =
4753 tryConvertExprToType(IndexExpr, Context.getSizeType());
4754 assert(!ConvExpr.isInvalid() &&
4755 "should be able to convert any integer type to size type");
4756 return ConvExpr.get();
4759 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4760 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4761 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4762 if (!RowIdx || !ColumnIdx)
4765 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4766 MTy->getElementType(), RBLoc);
4769 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4770 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4771 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4773 // For expressions like `&(*s).b`, the base is recorded and what should be
4775 const MemberExpr *Member = nullptr;
4776 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4777 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4779 LastRecord.PossibleDerefs.erase(StrippedExpr);
4782 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4783 QualType ResultTy = E->getType();
4784 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4786 // Bail if the element is an array since it is not memory access.
4787 if (isa<ArrayType>(ResultTy))
4790 if (ResultTy->hasAttr(attr::NoDeref)) {
4791 LastRecord.PossibleDerefs.insert(E);
4795 // Check if the base type is a pointer to a member access of a struct
4796 // marked with noderef.
4797 const Expr *Base = E->getBase();
4798 QualType BaseTy = Base->getType();
4799 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4800 // Not a pointer access
4803 const MemberExpr *Member = nullptr;
4804 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4806 Base = Member->getBase();
4808 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4809 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4810 LastRecord.PossibleDerefs.insert(E);
4814 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4816 SourceLocation ColonLocFirst,
4817 SourceLocation ColonLocSecond,
4818 Expr *Length, Expr *Stride,
4819 SourceLocation RBLoc) {
4820 if (Base->getType()->isPlaceholderType() &&
4821 !Base->getType()->isSpecificPlaceholderType(
4822 BuiltinType::OMPArraySection)) {
4823 ExprResult Result = CheckPlaceholderExpr(Base);
4824 if (Result.isInvalid())
4826 Base = Result.get();
4828 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4829 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4830 if (Result.isInvalid())
4832 Result = DefaultLvalueConversion(Result.get());
4833 if (Result.isInvalid())
4835 LowerBound = Result.get();
4837 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4838 ExprResult Result = CheckPlaceholderExpr(Length);
4839 if (Result.isInvalid())
4841 Result = DefaultLvalueConversion(Result.get());
4842 if (Result.isInvalid())
4844 Length = Result.get();
4846 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4847 ExprResult Result = CheckPlaceholderExpr(Stride);
4848 if (Result.isInvalid())
4850 Result = DefaultLvalueConversion(Result.get());
4851 if (Result.isInvalid())
4853 Stride = Result.get();
4856 // Build an unanalyzed expression if either operand is type-dependent.
4857 if (Base->isTypeDependent() ||
4859 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4860 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4861 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4862 return new (Context) OMPArraySectionExpr(
4863 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4864 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4867 // Perform default conversions.
4868 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4870 if (OriginalTy->isAnyPointerType()) {
4871 ResultTy = OriginalTy->getPointeeType();
4872 } else if (OriginalTy->isArrayType()) {
4873 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4876 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4877 << Base->getSourceRange());
4881 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4883 if (Res.isInvalid())
4884 return ExprError(Diag(LowerBound->getExprLoc(),
4885 diag::err_omp_typecheck_section_not_integer)
4886 << 0 << LowerBound->getSourceRange());
4887 LowerBound = Res.get();
4889 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4890 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4891 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4892 << 0 << LowerBound->getSourceRange();
4896 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4897 if (Res.isInvalid())
4898 return ExprError(Diag(Length->getExprLoc(),
4899 diag::err_omp_typecheck_section_not_integer)
4900 << 1 << Length->getSourceRange());
4903 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4904 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4905 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4906 << 1 << Length->getSourceRange();
4910 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4911 if (Res.isInvalid())
4912 return ExprError(Diag(Stride->getExprLoc(),
4913 diag::err_omp_typecheck_section_not_integer)
4914 << 1 << Stride->getSourceRange());
4917 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4918 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4919 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4920 << 1 << Stride->getSourceRange();
4923 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4924 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4925 // type. Note that functions are not objects, and that (in C99 parlance)
4926 // incomplete types are not object types.
4927 if (ResultTy->isFunctionType()) {
4928 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4929 << ResultTy << Base->getSourceRange();
4933 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4934 diag::err_omp_section_incomplete_type, Base))
4937 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4938 Expr::EvalResult Result;
4939 if (LowerBound->EvaluateAsInt(Result, Context)) {
4940 // OpenMP 5.0, [2.1.5 Array Sections]
4941 // The array section must be a subset of the original array.
4942 llvm::APSInt LowerBoundValue = Result.Val.getInt();
4943 if (LowerBoundValue.isNegative()) {
4944 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4945 << LowerBound->getSourceRange();
4952 Expr::EvalResult Result;
4953 if (Length->EvaluateAsInt(Result, Context)) {
4954 // OpenMP 5.0, [2.1.5 Array Sections]
4955 // The length must evaluate to non-negative integers.
4956 llvm::APSInt LengthValue = Result.Val.getInt();
4957 if (LengthValue.isNegative()) {
4958 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4959 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4960 << Length->getSourceRange();
4964 } else if (ColonLocFirst.isValid() &&
4965 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4966 !OriginalTy->isVariableArrayType()))) {
4967 // OpenMP 5.0, [2.1.5 Array Sections]
4968 // When the size of the array dimension is not known, the length must be
4969 // specified explicitly.
4970 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
4971 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4976 Expr::EvalResult Result;
4977 if (Stride->EvaluateAsInt(Result, Context)) {
4978 // OpenMP 5.0, [2.1.5 Array Sections]
4979 // The stride must evaluate to a positive integer.
4980 llvm::APSInt StrideValue = Result.Val.getInt();
4981 if (!StrideValue.isStrictlyPositive()) {
4982 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
4983 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
4984 << Stride->getSourceRange();
4990 if (!Base->getType()->isSpecificPlaceholderType(
4991 BuiltinType::OMPArraySection)) {
4992 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4993 if (Result.isInvalid())
4995 Base = Result.get();
4997 return new (Context) OMPArraySectionExpr(
4998 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
4999 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5002 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5003 SourceLocation RParenLoc,
5004 ArrayRef<Expr *> Dims,
5005 ArrayRef<SourceRange> Brackets) {
5006 if (Base->getType()->isPlaceholderType()) {
5007 ExprResult Result = CheckPlaceholderExpr(Base);
5008 if (Result.isInvalid())
5010 Result = DefaultLvalueConversion(Result.get());
5011 if (Result.isInvalid())
5013 Base = Result.get();
5015 QualType BaseTy = Base->getType();
5016 // Delay analysis of the types/expressions if instantiation/specialization is
5018 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5019 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5020 LParenLoc, RParenLoc, Dims, Brackets);
5021 if (!BaseTy->isPointerType() ||
5022 (!Base->isTypeDependent() &&
5023 BaseTy->getPointeeType()->isIncompleteType()))
5024 return ExprError(Diag(Base->getExprLoc(),
5025 diag::err_omp_non_pointer_type_array_shaping_base)
5026 << Base->getSourceRange());
5028 SmallVector<Expr *, 4> NewDims;
5029 bool ErrorFound = false;
5030 for (Expr *Dim : Dims) {
5031 if (Dim->getType()->isPlaceholderType()) {
5032 ExprResult Result = CheckPlaceholderExpr(Dim);
5033 if (Result.isInvalid()) {
5037 Result = DefaultLvalueConversion(Result.get());
5038 if (Result.isInvalid()) {
5044 if (!Dim->isTypeDependent()) {
5046 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5047 if (Result.isInvalid()) {
5049 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5050 << Dim->getSourceRange();
5054 Expr::EvalResult EvResult;
5055 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5056 // OpenMP 5.0, [2.1.4 Array Shaping]
5057 // Each si is an integral type expression that must evaluate to a
5058 // positive integer.
5059 llvm::APSInt Value = EvResult.Val.getInt();
5060 if (!Value.isStrictlyPositive()) {
5061 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5062 << Value.toString(/*Radix=*/10, /*Signed=*/true)
5063 << Dim->getSourceRange();
5069 NewDims.push_back(Dim);
5073 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5074 LParenLoc, RParenLoc, NewDims, Brackets);
5077 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5078 SourceLocation LLoc, SourceLocation RLoc,
5079 ArrayRef<OMPIteratorData> Data) {
5080 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5081 bool IsCorrect = true;
5082 for (const OMPIteratorData &D : Data) {
5083 TypeSourceInfo *TInfo = nullptr;
5084 SourceLocation StartLoc;
5086 if (!D.Type.getAsOpaquePtr()) {
5087 // OpenMP 5.0, 2.1.6 Iterators
5088 // In an iterator-specifier, if the iterator-type is not specified then
5089 // the type of that iterator is of int type.
5090 DeclTy = Context.IntTy;
5091 StartLoc = D.DeclIdentLoc;
5093 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5094 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5097 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5098 DeclTy->containsUnexpandedParameterPack() ||
5099 DeclTy->isInstantiationDependentType();
5100 if (!IsDeclTyDependent) {
5101 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5102 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5103 // The iterator-type must be an integral or pointer type.
5104 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5109 if (DeclTy.isConstant(Context)) {
5110 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5111 // The iterator-type must not be const qualified.
5112 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5119 // Iterator declaration.
5120 assert(D.DeclIdent && "Identifier expected.");
5121 // Always try to create iterator declarator to avoid extra error messages
5122 // about unknown declarations use.
5123 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5124 D.DeclIdent, DeclTy, TInfo, SC_None);
5127 // Check for conflicting previous declaration.
5128 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5129 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5130 ForVisibleRedeclaration);
5131 Previous.suppressDiagnostics();
5132 LookupName(Previous, S);
5134 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5135 /*AllowInlineNamespace=*/false);
5136 if (!Previous.empty()) {
5137 NamedDecl *Old = Previous.getRepresentativeDecl();
5138 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5139 Diag(Old->getLocation(), diag::note_previous_definition);
5141 PushOnScopeChains(VD, S);
5144 CurContext->addDecl(VD);
5146 Expr *Begin = D.Range.Begin;
5147 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5148 ExprResult BeginRes =
5149 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5150 Begin = BeginRes.get();
5152 Expr *End = D.Range.End;
5153 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5154 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5157 Expr *Step = D.Range.Step;
5158 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5159 if (!Step->getType()->isIntegralType(Context)) {
5160 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5161 << Step << Step->getSourceRange();
5165 llvm::APSInt Result;
5166 bool IsConstant = Step->isIntegerConstantExpr(Result, Context);
5167 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5168 // If the step expression of a range-specification equals zero, the
5169 // behavior is unspecified.
5170 if (IsConstant && Result.isNullValue()) {
5171 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5172 << Step << Step->getSourceRange();
5177 if (!Begin || !End || !IsCorrect) {
5181 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5182 IDElem.IteratorDecl = VD;
5183 IDElem.AssignmentLoc = D.AssignLoc;
5184 IDElem.Range.Begin = Begin;
5185 IDElem.Range.End = End;
5186 IDElem.Range.Step = Step;
5187 IDElem.ColonLoc = D.ColonLoc;
5188 IDElem.SecondColonLoc = D.SecColonLoc;
5191 // Invalidate all created iterator declarations if error is found.
5192 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5193 if (Decl *ID = D.IteratorDecl)
5194 ID->setInvalidDecl();
5198 SmallVector<OMPIteratorHelperData, 4> Helpers;
5199 if (!CurContext->isDependentContext()) {
5200 // Build number of ityeration for each iteration range.
5201 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5202 // ((Begini-Stepi-1-Endi) / -Stepi);
5203 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5205 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5207 if(!Res.isUsable()) {
5214 // (Endi - Begini) + Stepi
5215 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5216 if (!Res.isUsable()) {
5220 // (Endi - Begini) + Stepi - 1
5222 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5223 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5224 if (!Res.isUsable()) {
5228 // ((Endi - Begini) + Stepi - 1) / Stepi
5229 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5230 if (!Res.isUsable()) {
5234 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5236 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5237 D.Range.Begin, D.Range.End);
5238 if (!Res1.isUsable()) {
5242 // (Begini - Endi) - Stepi
5244 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5245 if (!Res1.isUsable()) {
5249 // (Begini - Endi) - Stepi - 1
5251 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5252 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5253 if (!Res1.isUsable()) {
5257 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5259 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5260 if (!Res1.isUsable()) {
5266 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5267 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5268 if (!CmpRes.isUsable()) {
5272 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5273 Res.get(), Res1.get());
5274 if (!Res.isUsable()) {
5279 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5280 if (!Res.isUsable()) {
5285 // Build counter update.
5288 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5289 D.IteratorDecl->getBeginLoc(), nullptr,
5290 Res.get()->getType(), nullptr, SC_None);
5291 CounterVD->setImplicit();
5293 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5294 D.IteratorDecl->getBeginLoc());
5295 // Build counter update.
5296 // I = Begini + counter * Stepi;
5297 ExprResult UpdateRes;
5299 UpdateRes = CreateBuiltinBinOp(
5300 D.AssignmentLoc, BO_Mul,
5301 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5303 UpdateRes = DefaultLvalueConversion(RefRes.get());
5305 if (!UpdateRes.isUsable()) {
5309 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5311 if (!UpdateRes.isUsable()) {
5316 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5317 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5318 D.IteratorDecl->getBeginLoc());
5319 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5321 if (!UpdateRes.isUsable()) {
5326 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5327 if (!UpdateRes.isUsable()) {
5331 ExprResult CounterUpdateRes =
5332 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5333 if (!CounterUpdateRes.isUsable()) {
5338 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5339 if (!CounterUpdateRes.isUsable()) {
5343 OMPIteratorHelperData &HD = Helpers.emplace_back();
5344 HD.CounterVD = CounterVD;
5345 HD.Upper = Res.get();
5346 HD.Update = UpdateRes.get();
5347 HD.CounterUpdate = CounterUpdateRes.get();
5350 Helpers.assign(ID.size(), {});
5353 // Invalidate all created iterator declarations if error is found.
5354 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5355 if (Decl *ID = D.IteratorDecl)
5356 ID->setInvalidDecl();
5360 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5361 LLoc, RLoc, ID, Helpers);
5365 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5366 Expr *Idx, SourceLocation RLoc) {
5367 Expr *LHSExp = Base;
5370 ExprValueKind VK = VK_LValue;
5371 ExprObjectKind OK = OK_Ordinary;
5373 // Per C++ core issue 1213, the result is an xvalue if either operand is
5374 // a non-lvalue array, and an lvalue otherwise.
5375 if (getLangOpts().CPlusPlus11) {
5376 for (auto *Op : {LHSExp, RHSExp}) {
5377 Op = Op->IgnoreImplicit();
5378 if (Op->getType()->isArrayType() && !Op->isLValue())
5383 // Perform default conversions.
5384 if (!LHSExp->getType()->getAs<VectorType>()) {
5385 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5386 if (Result.isInvalid())
5388 LHSExp = Result.get();
5390 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5391 if (Result.isInvalid())
5393 RHSExp = Result.get();
5395 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5397 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5398 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5399 // in the subscript position. As a result, we need to derive the array base
5400 // and index from the expression types.
5401 Expr *BaseExpr, *IndexExpr;
5402 QualType ResultType;
5403 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5406 ResultType = Context.DependentTy;
5407 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5410 ResultType = PTy->getPointeeType();
5411 } else if (const ObjCObjectPointerType *PTy =
5412 LHSTy->getAs<ObjCObjectPointerType>()) {
5416 // Use custom logic if this should be the pseudo-object subscript
5418 if (!LangOpts.isSubscriptPointerArithmetic())
5419 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5422 ResultType = PTy->getPointeeType();
5423 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5424 // Handle the uncommon case of "123[Ptr]".
5427 ResultType = PTy->getPointeeType();
5428 } else if (const ObjCObjectPointerType *PTy =
5429 RHSTy->getAs<ObjCObjectPointerType>()) {
5430 // Handle the uncommon case of "123[Ptr]".
5433 ResultType = PTy->getPointeeType();
5434 if (!LangOpts.isSubscriptPointerArithmetic()) {
5435 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5436 << ResultType << BaseExpr->getSourceRange();
5439 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5440 BaseExpr = LHSExp; // vectors: V[123]
5442 // We apply C++ DR1213 to vector subscripting too.
5443 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5444 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5445 if (Materialized.isInvalid())
5447 LHSExp = Materialized.get();
5449 VK = LHSExp->getValueKind();
5450 if (VK != VK_RValue)
5451 OK = OK_VectorComponent;
5453 ResultType = VTy->getElementType();
5454 QualType BaseType = BaseExpr->getType();
5455 Qualifiers BaseQuals = BaseType.getQualifiers();
5456 Qualifiers MemberQuals = ResultType.getQualifiers();
5457 Qualifiers Combined = BaseQuals + MemberQuals;
5458 if (Combined != MemberQuals)
5459 ResultType = Context.getQualifiedType(ResultType, Combined);
5460 } else if (LHSTy->isArrayType()) {
5461 // If we see an array that wasn't promoted by
5462 // DefaultFunctionArrayLvalueConversion, it must be an array that
5463 // wasn't promoted because of the C90 rule that doesn't
5464 // allow promoting non-lvalue arrays. Warn, then
5465 // force the promotion here.
5466 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5467 << LHSExp->getSourceRange();
5468 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5469 CK_ArrayToPointerDecay).get();
5470 LHSTy = LHSExp->getType();
5474 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5475 } else if (RHSTy->isArrayType()) {
5476 // Same as previous, except for 123[f().a] case
5477 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5478 << RHSExp->getSourceRange();
5479 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5480 CK_ArrayToPointerDecay).get();
5481 RHSTy = RHSExp->getType();
5485 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5487 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5488 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5491 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5492 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5493 << IndexExpr->getSourceRange());
5495 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5496 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5497 && !IndexExpr->isTypeDependent())
5498 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5500 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5501 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5502 // type. Note that Functions are not objects, and that (in C99 parlance)
5503 // incomplete types are not object types.
5504 if (ResultType->isFunctionType()) {
5505 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5506 << ResultType << BaseExpr->getSourceRange();
5510 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5511 // GNU extension: subscripting on pointer to void
5512 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5513 << BaseExpr->getSourceRange();
5515 // C forbids expressions of unqualified void type from being l-values.
5516 // See IsCForbiddenLValueType.
5517 if (!ResultType.hasQualifiers()) VK = VK_RValue;
5518 } else if (!ResultType->isDependentType() &&
5519 RequireCompleteSizedType(
5521 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5524 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5525 !ResultType.isCForbiddenLValueType());
5527 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5528 FunctionScopes.size() > 1) {
5530 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5531 for (auto I = FunctionScopes.rbegin(),
5532 E = std::prev(FunctionScopes.rend());
5534 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5537 DeclContext *DC = nullptr;
5538 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5539 DC = LSI->CallOperator;
5540 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5541 DC = CRSI->TheCapturedDecl;
5542 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5545 if (DC->containsDecl(TT->getDecl()))
5547 captureVariablyModifiedType(
5548 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5554 return new (Context)
5555 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5558 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5559 ParmVarDecl *Param) {
5560 if (Param->hasUnparsedDefaultArg()) {
5561 // If we've already cleared out the location for the default argument,
5562 // that means we're parsing it right now.
5563 if (!UnparsedDefaultArgLocs.count(Param)) {
5564 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5565 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5566 Param->setInvalidDecl();
5571 diag::err_use_of_default_argument_to_function_declared_later) <<
5572 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
5573 Diag(UnparsedDefaultArgLocs[Param],
5574 diag::note_default_argument_declared_here);
5578 if (Param->hasUninstantiatedDefaultArg() &&
5579 InstantiateDefaultArgument(CallLoc, FD, Param))
5582 assert(Param->hasInit() && "default argument but no initializer?");
5584 // If the default expression creates temporaries, we need to
5585 // push them to the current stack of expression temporaries so they'll
5586 // be properly destroyed.
5587 // FIXME: We should really be rebuilding the default argument with new
5588 // bound temporaries; see the comment in PR5810.
5589 // We don't need to do that with block decls, though, because
5590 // blocks in default argument expression can never capture anything.
5591 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5592 // Set the "needs cleanups" bit regardless of whether there are
5593 // any explicit objects.
5594 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5596 // Append all the objects to the cleanup list. Right now, this
5597 // should always be a no-op, because blocks in default argument
5598 // expressions should never be able to capture anything.
5599 assert(!Init->getNumObjects() &&
5600 "default argument expression has capturing blocks?");
5603 // We already type-checked the argument, so we know it works.
5604 // Just mark all of the declarations in this potentially-evaluated expression
5605 // as being "referenced".
5606 EnterExpressionEvaluationContext EvalContext(
5607 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5608 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5609 /*SkipLocalVariables=*/true);
5613 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5614 FunctionDecl *FD, ParmVarDecl *Param) {
5615 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5616 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5618 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5621 Sema::VariadicCallType
5622 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5624 if (Proto && Proto->isVariadic()) {
5625 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5626 return VariadicConstructor;
5627 else if (Fn && Fn->getType()->isBlockPointerType())
5628 return VariadicBlock;
5630 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5631 if (Method->isInstance())
5632 return VariadicMethod;
5633 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5634 return VariadicMethod;
5635 return VariadicFunction;
5637 return VariadicDoesNotApply;
5641 class FunctionCallCCC final : public FunctionCallFilterCCC {
5643 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5644 unsigned NumArgs, MemberExpr *ME)
5645 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5646 FunctionName(FuncName) {}
5648 bool ValidateCandidate(const TypoCorrection &candidate) override {
5649 if (!candidate.getCorrectionSpecifier() ||
5650 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5654 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5657 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5658 return std::make_unique<FunctionCallCCC>(*this);
5662 const IdentifierInfo *const FunctionName;
5666 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5667 FunctionDecl *FDecl,
5668 ArrayRef<Expr *> Args) {
5669 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5670 DeclarationName FuncName = FDecl->getDeclName();
5671 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5673 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5674 if (TypoCorrection Corrected = S.CorrectTypo(
5675 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5676 S.getScopeForContext(S.CurContext), nullptr, CCC,
5677 Sema::CTK_ErrorRecovery)) {
5678 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5679 if (Corrected.isOverloaded()) {
5680 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5681 OverloadCandidateSet::iterator Best;
5682 for (NamedDecl *CD : Corrected) {
5683 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5684 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5687 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5689 ND = Best->FoundDecl;
5690 Corrected.setCorrectionDecl(ND);
5696 ND = ND->getUnderlyingDecl();
5697 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5701 return TypoCorrection();
5704 /// ConvertArgumentsForCall - Converts the arguments specified in
5705 /// Args/NumArgs to the parameter types of the function FDecl with
5706 /// function prototype Proto. Call is the call expression itself, and
5707 /// Fn is the function expression. For a C++ member function, this
5708 /// routine does not attempt to convert the object argument. Returns
5709 /// true if the call is ill-formed.
5711 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5712 FunctionDecl *FDecl,
5713 const FunctionProtoType *Proto,
5714 ArrayRef<Expr *> Args,
5715 SourceLocation RParenLoc,
5716 bool IsExecConfig) {
5717 // Bail out early if calling a builtin with custom typechecking.
5719 if (unsigned ID = FDecl->getBuiltinID())
5720 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5723 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5724 // assignment, to the types of the corresponding parameter, ...
5725 unsigned NumParams = Proto->getNumParams();
5726 bool Invalid = false;
5727 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5728 unsigned FnKind = Fn->getType()->isBlockPointerType()
5730 : (IsExecConfig ? 3 /* kernel function (exec config) */
5731 : 0 /* function */);
5733 // If too few arguments are available (and we don't have default
5734 // arguments for the remaining parameters), don't make the call.
5735 if (Args.size() < NumParams) {
5736 if (Args.size() < MinArgs) {
5738 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5740 MinArgs == NumParams && !Proto->isVariadic()
5741 ? diag::err_typecheck_call_too_few_args_suggest
5742 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5743 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5744 << static_cast<unsigned>(Args.size())
5745 << TC.getCorrectionRange());
5746 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5748 MinArgs == NumParams && !Proto->isVariadic()
5749 ? diag::err_typecheck_call_too_few_args_one
5750 : diag::err_typecheck_call_too_few_args_at_least_one)
5751 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5753 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5754 ? diag::err_typecheck_call_too_few_args
5755 : diag::err_typecheck_call_too_few_args_at_least)
5756 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5757 << Fn->getSourceRange();
5759 // Emit the location of the prototype.
5760 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5761 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5765 // We reserve space for the default arguments when we create
5766 // the call expression, before calling ConvertArgumentsForCall.
5767 assert((Call->getNumArgs() == NumParams) &&
5768 "We should have reserved space for the default arguments before!");
5771 // If too many are passed and not variadic, error on the extras and drop
5773 if (Args.size() > NumParams) {
5774 if (!Proto->isVariadic()) {
5776 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5778 MinArgs == NumParams && !Proto->isVariadic()
5779 ? diag::err_typecheck_call_too_many_args_suggest
5780 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5781 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5782 << static_cast<unsigned>(Args.size())
5783 << TC.getCorrectionRange());
5784 } else if (NumParams == 1 && FDecl &&
5785 FDecl->getParamDecl(0)->getDeclName())
5786 Diag(Args[NumParams]->getBeginLoc(),
5787 MinArgs == NumParams
5788 ? diag::err_typecheck_call_too_many_args_one
5789 : diag::err_typecheck_call_too_many_args_at_most_one)
5790 << FnKind << FDecl->getParamDecl(0)
5791 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5792 << SourceRange(Args[NumParams]->getBeginLoc(),
5793 Args.back()->getEndLoc());
5795 Diag(Args[NumParams]->getBeginLoc(),
5796 MinArgs == NumParams
5797 ? diag::err_typecheck_call_too_many_args
5798 : diag::err_typecheck_call_too_many_args_at_most)
5799 << FnKind << NumParams << static_cast<unsigned>(Args.size())
5800 << Fn->getSourceRange()
5801 << SourceRange(Args[NumParams]->getBeginLoc(),
5802 Args.back()->getEndLoc());
5804 // Emit the location of the prototype.
5805 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5806 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5808 // This deletes the extra arguments.
5809 Call->shrinkNumArgs(NumParams);
5813 SmallVector<Expr *, 8> AllArgs;
5814 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5816 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5820 unsigned TotalNumArgs = AllArgs.size();
5821 for (unsigned i = 0; i < TotalNumArgs; ++i)
5822 Call->setArg(i, AllArgs[i]);
5827 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5828 const FunctionProtoType *Proto,
5829 unsigned FirstParam, ArrayRef<Expr *> Args,
5830 SmallVectorImpl<Expr *> &AllArgs,
5831 VariadicCallType CallType, bool AllowExplicit,
5832 bool IsListInitialization) {
5833 unsigned NumParams = Proto->getNumParams();
5834 bool Invalid = false;
5836 // Continue to check argument types (even if we have too few/many args).
5837 for (unsigned i = FirstParam; i < NumParams; i++) {
5838 QualType ProtoArgType = Proto->getParamType(i);
5841 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5842 if (ArgIx < Args.size()) {
5843 Arg = Args[ArgIx++];
5845 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5846 diag::err_call_incomplete_argument, Arg))
5849 // Strip the unbridged-cast placeholder expression off, if applicable.
5850 bool CFAudited = false;
5851 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5852 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5853 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5854 Arg = stripARCUnbridgedCast(Arg);
5855 else if (getLangOpts().ObjCAutoRefCount &&
5856 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5857 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5860 if (Proto->getExtParameterInfo(i).isNoEscape())
5861 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5862 BE->getBlockDecl()->setDoesNotEscape();
5864 InitializedEntity Entity =
5865 Param ? InitializedEntity::InitializeParameter(Context, Param,
5867 : InitializedEntity::InitializeParameter(
5868 Context, ProtoArgType, Proto->isParamConsumed(i));
5870 // Remember that parameter belongs to a CF audited API.
5872 Entity.setParameterCFAudited();
5874 ExprResult ArgE = PerformCopyInitialization(
5875 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5876 if (ArgE.isInvalid())
5879 Arg = ArgE.getAs<Expr>();
5881 assert(Param && "can't use default arguments without a known callee");
5883 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5884 if (ArgExpr.isInvalid())
5887 Arg = ArgExpr.getAs<Expr>();
5890 // Check for array bounds violations for each argument to the call. This
5891 // check only triggers warnings when the argument isn't a more complex Expr
5892 // with its own checking, such as a BinaryOperator.
5893 CheckArrayAccess(Arg);
5895 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5896 CheckStaticArrayArgument(CallLoc, Param, Arg);
5898 AllArgs.push_back(Arg);
5901 // If this is a variadic call, handle args passed through "...".
5902 if (CallType != VariadicDoesNotApply) {
5903 // Assume that extern "C" functions with variadic arguments that
5904 // return __unknown_anytype aren't *really* variadic.
5905 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5906 FDecl->isExternC()) {
5907 for (Expr *A : Args.slice(ArgIx)) {
5908 QualType paramType; // ignored
5909 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5910 Invalid |= arg.isInvalid();
5911 AllArgs.push_back(arg.get());
5914 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5916 for (Expr *A : Args.slice(ArgIx)) {
5917 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5918 Invalid |= Arg.isInvalid();
5919 AllArgs.push_back(Arg.get());
5923 // Check for array bounds violations.
5924 for (Expr *A : Args.slice(ArgIx))
5925 CheckArrayAccess(A);
5930 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5931 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5932 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5933 TL = DTL.getOriginalLoc();
5934 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5935 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5936 << ATL.getLocalSourceRange();
5939 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5940 /// array parameter, check that it is non-null, and that if it is formed by
5941 /// array-to-pointer decay, the underlying array is sufficiently large.
5943 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5944 /// array type derivation, then for each call to the function, the value of the
5945 /// corresponding actual argument shall provide access to the first element of
5946 /// an array with at least as many elements as specified by the size expression.
5948 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5950 const Expr *ArgExpr) {
5951 // Static array parameters are not supported in C++.
5952 if (!Param || getLangOpts().CPlusPlus)
5955 QualType OrigTy = Param->getOriginalType();
5957 const ArrayType *AT = Context.getAsArrayType(OrigTy);
5958 if (!AT || AT->getSizeModifier() != ArrayType::Static)
5961 if (ArgExpr->isNullPointerConstant(Context,
5962 Expr::NPC_NeverValueDependent)) {
5963 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5964 DiagnoseCalleeStaticArrayParam(*this, Param);
5968 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5972 const ConstantArrayType *ArgCAT =
5973 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5977 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5978 ArgCAT->getElementType())) {
5979 if (ArgCAT->getSize().ult(CAT->getSize())) {
5980 Diag(CallLoc, diag::warn_static_array_too_small)
5981 << ArgExpr->getSourceRange()
5982 << (unsigned)ArgCAT->getSize().getZExtValue()
5983 << (unsigned)CAT->getSize().getZExtValue() << 0;
5984 DiagnoseCalleeStaticArrayParam(*this, Param);
5989 Optional<CharUnits> ArgSize =
5990 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5991 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5992 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5993 Diag(CallLoc, diag::warn_static_array_too_small)
5994 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5995 << (unsigned)ParmSize->getQuantity() << 1;
5996 DiagnoseCalleeStaticArrayParam(*this, Param);
6000 /// Given a function expression of unknown-any type, try to rebuild it
6001 /// to have a function type.
6002 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6004 /// Is the given type a placeholder that we need to lower out
6005 /// immediately during argument processing?
6006 static bool isPlaceholderToRemoveAsArg(QualType type) {
6007 // Placeholders are never sugared.
6008 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6009 if (!placeholder) return false;
6011 switch (placeholder->getKind()) {
6012 // Ignore all the non-placeholder types.
6013 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6014 case BuiltinType::Id:
6015 #include "clang/Basic/OpenCLImageTypes.def"
6016 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6017 case BuiltinType::Id:
6018 #include "clang/Basic/OpenCLExtensionTypes.def"
6019 // In practice we'll never use this, since all SVE types are sugared
6020 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6021 #define SVE_TYPE(Name, Id, SingletonId) \
6022 case BuiltinType::Id:
6023 #include "clang/Basic/AArch64SVEACLETypes.def"
6024 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6025 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6026 #include "clang/AST/BuiltinTypes.def"
6029 // We cannot lower out overload sets; they might validly be resolved
6030 // by the call machinery.
6031 case BuiltinType::Overload:
6034 // Unbridged casts in ARC can be handled in some call positions and
6035 // should be left in place.
6036 case BuiltinType::ARCUnbridgedCast:
6039 // Pseudo-objects should be converted as soon as possible.
6040 case BuiltinType::PseudoObject:
6043 // The debugger mode could theoretically but currently does not try
6044 // to resolve unknown-typed arguments based on known parameter types.
6045 case BuiltinType::UnknownAny:
6048 // These are always invalid as call arguments and should be reported.
6049 case BuiltinType::BoundMember:
6050 case BuiltinType::BuiltinFn:
6051 case BuiltinType::IncompleteMatrixIdx:
6052 case BuiltinType::OMPArraySection:
6053 case BuiltinType::OMPArrayShaping:
6054 case BuiltinType::OMPIterator:
6058 llvm_unreachable("bad builtin type kind");
6061 /// Check an argument list for placeholders that we won't try to
6063 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6064 // Apply this processing to all the arguments at once instead of
6065 // dying at the first failure.
6066 bool hasInvalid = false;
6067 for (size_t i = 0, e = args.size(); i != e; i++) {
6068 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6069 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6070 if (result.isInvalid()) hasInvalid = true;
6071 else args[i] = result.get();
6072 } else if (hasInvalid) {
6073 (void)S.CorrectDelayedTyposInExpr(args[i]);
6079 /// If a builtin function has a pointer argument with no explicit address
6080 /// space, then it should be able to accept a pointer to any address
6081 /// space as input. In order to do this, we need to replace the
6082 /// standard builtin declaration with one that uses the same address space
6085 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6086 /// it does not contain any pointer arguments without
6087 /// an address space qualifer. Otherwise the rewritten
6088 /// FunctionDecl is returned.
6089 /// TODO: Handle pointer return types.
6090 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6091 FunctionDecl *FDecl,
6092 MultiExprArg ArgExprs) {
6094 QualType DeclType = FDecl->getType();
6095 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6097 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6098 ArgExprs.size() < FT->getNumParams())
6101 bool NeedsNewDecl = false;
6103 SmallVector<QualType, 8> OverloadParams;
6105 for (QualType ParamType : FT->param_types()) {
6107 // Convert array arguments to pointer to simplify type lookup.
6109 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6110 if (ArgRes.isInvalid())
6112 Expr *Arg = ArgRes.get();
6113 QualType ArgType = Arg->getType();
6114 if (!ParamType->isPointerType() ||
6115 ParamType.hasAddressSpace() ||
6116 !ArgType->isPointerType() ||
6117 !ArgType->getPointeeType().hasAddressSpace()) {
6118 OverloadParams.push_back(ParamType);
6122 QualType PointeeType = ParamType->getPointeeType();
6123 if (PointeeType.hasAddressSpace())
6126 NeedsNewDecl = true;
6127 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6129 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6130 OverloadParams.push_back(Context.getPointerType(PointeeType));
6136 FunctionProtoType::ExtProtoInfo EPI;
6137 EPI.Variadic = FT->isVariadic();
6138 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6139 OverloadParams, EPI);
6140 DeclContext *Parent = FDecl->getParent();
6141 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6142 FDecl->getLocation(),
6143 FDecl->getLocation(),
6144 FDecl->getIdentifier(),
6148 /*hasPrototype=*/true);
6149 SmallVector<ParmVarDecl*, 16> Params;
6150 FT = cast<FunctionProtoType>(OverloadTy);
6151 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6152 QualType ParamType = FT->getParamType(i);
6154 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6155 SourceLocation(), nullptr, ParamType,
6156 /*TInfo=*/nullptr, SC_None, nullptr);
6157 Parm->setScopeInfo(0, i);
6158 Params.push_back(Parm);
6160 OverloadDecl->setParams(Params);
6161 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6162 return OverloadDecl;
6165 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6166 FunctionDecl *Callee,
6167 MultiExprArg ArgExprs) {
6168 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6169 // similar attributes) really don't like it when functions are called with an
6170 // invalid number of args.
6171 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6172 /*PartialOverloading=*/false) &&
6173 !Callee->isVariadic())
6175 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6178 if (const EnableIfAttr *Attr =
6179 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6180 S.Diag(Fn->getBeginLoc(),
6181 isa<CXXMethodDecl>(Callee)
6182 ? diag::err_ovl_no_viable_member_function_in_call
6183 : diag::err_ovl_no_viable_function_in_call)
6184 << Callee << Callee->getSourceRange();
6185 S.Diag(Callee->getLocation(),
6186 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6187 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6192 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6193 const UnresolvedMemberExpr *const UME, Sema &S) {
6195 const auto GetFunctionLevelDCIfCXXClass =
6196 [](Sema &S) -> const CXXRecordDecl * {
6197 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6198 if (!DC || !DC->getParent())
6201 // If the call to some member function was made from within a member
6202 // function body 'M' return return 'M's parent.
6203 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6204 return MD->getParent()->getCanonicalDecl();
6205 // else the call was made from within a default member initializer of a
6206 // class, so return the class.
6207 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6208 return RD->getCanonicalDecl();
6211 // If our DeclContext is neither a member function nor a class (in the
6212 // case of a lambda in a default member initializer), we can't have an
6213 // enclosing 'this'.
6215 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6216 if (!CurParentClass)
6219 // The naming class for implicit member functions call is the class in which
6220 // name lookup starts.
6221 const CXXRecordDecl *const NamingClass =
6222 UME->getNamingClass()->getCanonicalDecl();
6223 assert(NamingClass && "Must have naming class even for implicit access");
6225 // If the unresolved member functions were found in a 'naming class' that is
6226 // related (either the same or derived from) to the class that contains the
6227 // member function that itself contained the implicit member access.
6229 return CurParentClass == NamingClass ||
6230 CurParentClass->isDerivedFrom(NamingClass);
6234 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6235 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6240 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6241 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6242 // already been captured, or if this is an implicit member function call (if
6243 // it isn't, an attempt to capture 'this' should already have been made).
6244 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6245 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6248 // Check if the naming class in which the unresolved members were found is
6249 // related (same as or is a base of) to the enclosing class.
6251 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6255 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6256 // If the enclosing function is not dependent, then this lambda is
6257 // capture ready, so if we can capture this, do so.
6258 if (!EnclosingFunctionCtx->isDependentContext()) {
6259 // If the current lambda and all enclosing lambdas can capture 'this' -
6260 // then go ahead and capture 'this' (since our unresolved overload set
6261 // contains at least one non-static member function).
6262 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6263 S.CheckCXXThisCapture(CallLoc);
6264 } else if (S.CurContext->isDependentContext()) {
6265 // ... since this is an implicit member reference, that might potentially
6266 // involve a 'this' capture, mark 'this' for potential capture in
6267 // enclosing lambdas.
6268 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6269 CurLSI->addPotentialThisCapture(CallLoc);
6273 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6274 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6277 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6278 if (Call.isInvalid())
6281 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6283 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6284 if (ULE->hasExplicitTemplateArgs() &&
6285 ULE->decls_begin() == ULE->decls_end()) {
6286 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6287 ? diag::warn_cxx17_compat_adl_only_template_id
6288 : diag::ext_adl_only_template_id)
6293 if (LangOpts.OpenMP)
6294 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6300 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6301 /// This provides the location of the left/right parens and a list of comma
6303 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6304 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6305 Expr *ExecConfig, bool IsExecConfig) {
6306 // Since this might be a postfix expression, get rid of ParenListExprs.
6307 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6308 if (Result.isInvalid()) return ExprError();
6311 if (checkArgsForPlaceholders(*this, ArgExprs))
6314 if (getLangOpts().CPlusPlus) {
6315 // If this is a pseudo-destructor expression, build the call immediately.
6316 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6317 if (!ArgExprs.empty()) {
6318 // Pseudo-destructor calls should not have any arguments.
6319 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6320 << FixItHint::CreateRemoval(
6321 SourceRange(ArgExprs.front()->getBeginLoc(),
6322 ArgExprs.back()->getEndLoc()));
6325 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6326 VK_RValue, RParenLoc);
6328 if (Fn->getType() == Context.PseudoObjectTy) {
6329 ExprResult result = CheckPlaceholderExpr(Fn);
6330 if (result.isInvalid()) return ExprError();
6334 // Determine whether this is a dependent call inside a C++ template,
6335 // in which case we won't do any semantic analysis now.
6336 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6338 return CUDAKernelCallExpr::Create(
6339 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6340 Context.DependentTy, VK_RValue, RParenLoc);
6343 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6344 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6347 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6348 VK_RValue, RParenLoc);
6352 // Determine whether this is a call to an object (C++ [over.call.object]).
6353 if (Fn->getType()->isRecordType())
6354 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6357 if (Fn->getType() == Context.UnknownAnyTy) {
6358 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6359 if (result.isInvalid()) return ExprError();
6363 if (Fn->getType() == Context.BoundMemberTy) {
6364 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6369 // Check for overloaded calls. This can happen even in C due to extensions.
6370 if (Fn->getType() == Context.OverloadTy) {
6371 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6373 // We aren't supposed to apply this logic if there's an '&' involved.
6374 if (!find.HasFormOfMemberPointer) {
6375 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6376 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6377 VK_RValue, RParenLoc);
6378 OverloadExpr *ovl = find.Expression;
6379 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6380 return BuildOverloadedCallExpr(
6381 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6382 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6383 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6388 // If we're directly calling a function, get the appropriate declaration.
6389 if (Fn->getType() == Context.UnknownAnyTy) {
6390 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6391 if (result.isInvalid()) return ExprError();
6395 Expr *NakedFn = Fn->IgnoreParens();
6397 bool CallingNDeclIndirectly = false;
6398 NamedDecl *NDecl = nullptr;
6399 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6400 if (UnOp->getOpcode() == UO_AddrOf) {
6401 CallingNDeclIndirectly = true;
6402 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6406 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6407 NDecl = DRE->getDecl();
6409 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6410 if (FDecl && FDecl->getBuiltinID()) {
6411 // Rewrite the function decl for this builtin by replacing parameters
6412 // with no explicit address space with the address space of the arguments
6415 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6417 Fn = DeclRefExpr::Create(
6418 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6419 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6420 nullptr, DRE->isNonOdrUse());
6423 } else if (isa<MemberExpr>(NakedFn))
6424 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6426 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6427 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6428 FD, /*Complain=*/true, Fn->getBeginLoc()))
6431 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6434 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6437 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6438 ExecConfig, IsExecConfig);
6441 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6443 /// __builtin_astype( value, dst type )
6445 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6446 SourceLocation BuiltinLoc,
6447 SourceLocation RParenLoc) {
6448 ExprValueKind VK = VK_RValue;
6449 ExprObjectKind OK = OK_Ordinary;
6450 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6451 QualType SrcTy = E->getType();
6452 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6453 return ExprError(Diag(BuiltinLoc,
6454 diag::err_invalid_astype_of_different_size)
6457 << E->getSourceRange());
6458 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6461 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6462 /// provided arguments.
6464 /// __builtin_convertvector( value, dst type )
6466 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6467 SourceLocation BuiltinLoc,
6468 SourceLocation RParenLoc) {
6469 TypeSourceInfo *TInfo;
6470 GetTypeFromParser(ParsedDestTy, &TInfo);
6471 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6474 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6475 /// i.e. an expression not of \p OverloadTy. The expression should
6476 /// unary-convert to an expression of function-pointer or
6477 /// block-pointer type.
6479 /// \param NDecl the declaration being called, if available
6480 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6481 SourceLocation LParenLoc,
6482 ArrayRef<Expr *> Args,
6483 SourceLocation RParenLoc, Expr *Config,
6484 bool IsExecConfig, ADLCallKind UsesADL) {
6485 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6486 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6488 // Functions with 'interrupt' attribute cannot be called directly.
6489 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6490 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6494 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6495 // so there's some risk when calling out to non-interrupt handler functions
6496 // that the callee might not preserve them. This is easy to diagnose here,
6497 // but can be very challenging to debug.
6498 if (auto *Caller = getCurFunctionDecl())
6499 if (Caller->hasAttr<ARMInterruptAttr>()) {
6500 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6501 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6502 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6505 // Promote the function operand.
6506 // We special-case function promotion here because we only allow promoting
6507 // builtin functions to function pointers in the callee of a call.
6511 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6512 // Extract the return type from the (builtin) function pointer type.
6513 // FIXME Several builtins still have setType in
6514 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6515 // Builtins.def to ensure they are correct before removing setType calls.
6516 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6517 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6518 ResultTy = FDecl->getCallResultType();
6520 Result = CallExprUnaryConversions(Fn);
6521 ResultTy = Context.BoolTy;
6523 if (Result.isInvalid())
6527 // Check for a valid function type, but only if it is not a builtin which
6528 // requires custom type checking. These will be handled by
6529 // CheckBuiltinFunctionCall below just after creation of the call expression.
6530 const FunctionType *FuncT = nullptr;
6531 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6533 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6534 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6535 // have type pointer to function".
6536 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6538 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6539 << Fn->getType() << Fn->getSourceRange());
6540 } else if (const BlockPointerType *BPT =
6541 Fn->getType()->getAs<BlockPointerType>()) {
6542 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6544 // Handle calls to expressions of unknown-any type.
6545 if (Fn->getType() == Context.UnknownAnyTy) {
6546 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6547 if (rewrite.isInvalid())
6553 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6554 << Fn->getType() << Fn->getSourceRange());
6558 // Get the number of parameters in the function prototype, if any.
6559 // We will allocate space for max(Args.size(), NumParams) arguments
6560 // in the call expression.
6561 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6562 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6566 assert(UsesADL == ADLCallKind::NotADL &&
6567 "CUDAKernelCallExpr should not use ADL");
6569 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6570 ResultTy, VK_RValue, RParenLoc, NumParams);
6572 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6573 RParenLoc, NumParams, UsesADL);
6576 if (!getLangOpts().CPlusPlus) {
6577 // Forget about the nulled arguments since typo correction
6578 // do not handle them well.
6579 TheCall->shrinkNumArgs(Args.size());
6580 // C cannot always handle TypoExpr nodes in builtin calls and direct
6581 // function calls as their argument checking don't necessarily handle
6582 // dependent types properly, so make sure any TypoExprs have been
6584 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6585 if (!Result.isUsable()) return ExprError();
6586 CallExpr *TheOldCall = TheCall;
6587 TheCall = dyn_cast<CallExpr>(Result.get());
6588 bool CorrectedTypos = TheCall != TheOldCall;
6589 if (!TheCall) return Result;
6590 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6592 // A new call expression node was created if some typos were corrected.
6593 // However it may not have been constructed with enough storage. In this
6594 // case, rebuild the node with enough storage. The waste of space is
6595 // immaterial since this only happens when some typos were corrected.
6596 if (CorrectedTypos && Args.size() < NumParams) {
6598 TheCall = CUDAKernelCallExpr::Create(
6599 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6600 RParenLoc, NumParams);
6602 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6603 RParenLoc, NumParams, UsesADL);
6605 // We can now handle the nulled arguments for the default arguments.
6606 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6609 // Bail out early if calling a builtin with custom type checking.
6610 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6611 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6613 if (getLangOpts().CUDA) {
6615 // CUDA: Kernel calls must be to global functions
6616 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6617 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6618 << FDecl << Fn->getSourceRange());
6620 // CUDA: Kernel function must have 'void' return type
6621 if (!FuncT->getReturnType()->isVoidType() &&
6622 !FuncT->getReturnType()->getAs<AutoType>() &&
6623 !FuncT->getReturnType()->isInstantiationDependentType())
6624 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6625 << Fn->getType() << Fn->getSourceRange());
6627 // CUDA: Calls to global functions must be configured
6628 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6629 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6630 << FDecl << Fn->getSourceRange());
6634 // Check for a valid return type
6635 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6639 // We know the result type of the call, set it.
6640 TheCall->setType(FuncT->getCallResultType(Context));
6641 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6644 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6648 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6651 // Check if we have too few/too many template arguments, based
6652 // on our knowledge of the function definition.
6653 const FunctionDecl *Def = nullptr;
6654 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6655 Proto = Def->getType()->getAs<FunctionProtoType>();
6656 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6657 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6658 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6661 // If the function we're calling isn't a function prototype, but we have
6662 // a function prototype from a prior declaratiom, use that prototype.
6663 if (!FDecl->hasPrototype())
6664 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6667 // Promote the arguments (C99 6.5.2.2p6).
6668 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6669 Expr *Arg = Args[i];
6671 if (Proto && i < Proto->getNumParams()) {
6672 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6673 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6675 PerformCopyInitialization(Entity, SourceLocation(), Arg);
6676 if (ArgE.isInvalid())
6679 Arg = ArgE.getAs<Expr>();
6682 ExprResult ArgE = DefaultArgumentPromotion(Arg);
6684 if (ArgE.isInvalid())
6687 Arg = ArgE.getAs<Expr>();
6690 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6691 diag::err_call_incomplete_argument, Arg))
6694 TheCall->setArg(i, Arg);
6698 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6699 if (!Method->isStatic())
6700 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6701 << Fn->getSourceRange());
6703 // Check for sentinels
6705 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6707 // Warn for unions passing across security boundary (CMSE).
6708 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6709 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6710 if (const auto *RT =
6711 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6712 if (RT->getDecl()->isOrContainsUnion())
6713 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6719 // Do special checking on direct calls to functions.
6721 if (CheckFunctionCall(FDecl, TheCall, Proto))
6724 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6727 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6729 if (CheckPointerCall(NDecl, TheCall, Proto))
6732 if (CheckOtherCall(TheCall, Proto))
6736 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6740 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6741 SourceLocation RParenLoc, Expr *InitExpr) {
6742 assert(Ty && "ActOnCompoundLiteral(): missing type");
6743 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6745 TypeSourceInfo *TInfo;
6746 QualType literalType = GetTypeFromParser(Ty, &TInfo);
6748 TInfo = Context.getTrivialTypeSourceInfo(literalType);
6750 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6754 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6755 SourceLocation RParenLoc, Expr *LiteralExpr) {
6756 QualType literalType = TInfo->getType();
6758 if (literalType->isArrayType()) {
6759 if (RequireCompleteSizedType(
6760 LParenLoc, Context.getBaseElementType(literalType),
6761 diag::err_array_incomplete_or_sizeless_type,
6762 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6764 if (literalType->isVariableArrayType())
6765 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6766 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6767 } else if (!literalType->isDependentType() &&
6768 RequireCompleteType(LParenLoc, literalType,
6769 diag::err_typecheck_decl_incomplete_type,
6770 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6773 InitializedEntity Entity
6774 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6775 InitializationKind Kind
6776 = InitializationKind::CreateCStyleCast(LParenLoc,
6777 SourceRange(LParenLoc, RParenLoc),
6779 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6780 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6782 if (Result.isInvalid())
6784 LiteralExpr = Result.get();
6786 bool isFileScope = !CurContext->isFunctionOrMethod();
6788 // In C, compound literals are l-values for some reason.
6789 // For GCC compatibility, in C++, file-scope array compound literals with
6790 // constant initializers are also l-values, and compound literals are
6791 // otherwise prvalues.
6793 // (GCC also treats C++ list-initialized file-scope array prvalues with
6794 // constant initializers as l-values, but that's non-conforming, so we don't
6795 // follow it there.)
6797 // FIXME: It would be better to handle the lvalue cases as materializing and
6798 // lifetime-extending a temporary object, but our materialized temporaries
6799 // representation only supports lifetime extension from a variable, not "out
6801 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6802 // is bound to the result of applying array-to-pointer decay to the compound
6804 // FIXME: GCC supports compound literals of reference type, which should
6805 // obviously have a value kind derived from the kind of reference involved.
6807 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6812 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6813 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6814 Expr *Init = ILE->getInit(i);
6815 ILE->setInit(i, ConstantExpr::Create(Context, Init));
6818 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6819 VK, LiteralExpr, isFileScope);
6821 if (!LiteralExpr->isTypeDependent() &&
6822 !LiteralExpr->isValueDependent() &&
6823 !literalType->isDependentType()) // C99 6.5.2.5p3
6824 if (CheckForConstantInitializer(LiteralExpr, literalType))
6826 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6827 literalType.getAddressSpace() != LangAS::Default) {
6828 // Embedded-C extensions to C99 6.5.2.5:
6829 // "If the compound literal occurs inside the body of a function, the
6830 // type name shall not be qualified by an address-space qualifier."
6831 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6832 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6836 if (!isFileScope && !getLangOpts().CPlusPlus) {
6837 // Compound literals that have automatic storage duration are destroyed at
6838 // the end of the scope in C; in C++, they're just temporaries.
6840 // Emit diagnostics if it is or contains a C union type that is non-trivial
6842 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6843 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6844 NTCUC_CompoundLiteral, NTCUK_Destruct);
6846 // Diagnose jumps that enter or exit the lifetime of the compound literal.
6847 if (literalType.isDestructedType()) {
6848 Cleanup.setExprNeedsCleanups(true);
6849 ExprCleanupObjects.push_back(E);
6850 getCurFunction()->setHasBranchProtectedScope();
6854 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6855 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6856 checkNonTrivialCUnionInInitializer(E->getInitializer(),
6857 E->getInitializer()->getExprLoc());
6859 return MaybeBindToTemporary(E);
6863 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6864 SourceLocation RBraceLoc) {
6865 // Only produce each kind of designated initialization diagnostic once.
6866 SourceLocation FirstDesignator;
6867 bool DiagnosedArrayDesignator = false;
6868 bool DiagnosedNestedDesignator = false;
6869 bool DiagnosedMixedDesignator = false;
6871 // Check that any designated initializers are syntactically valid in the
6872 // current language mode.
6873 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6874 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6875 if (FirstDesignator.isInvalid())
6876 FirstDesignator = DIE->getBeginLoc();
6878 if (!getLangOpts().CPlusPlus)
6881 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6882 DiagnosedNestedDesignator = true;
6883 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6884 << DIE->getDesignatorsSourceRange();
6887 for (auto &Desig : DIE->designators()) {
6888 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6889 DiagnosedArrayDesignator = true;
6890 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6891 << Desig.getSourceRange();
6895 if (!DiagnosedMixedDesignator &&
6896 !isa<DesignatedInitExpr>(InitArgList[0])) {
6897 DiagnosedMixedDesignator = true;
6898 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6899 << DIE->getSourceRange();
6900 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6901 << InitArgList[0]->getSourceRange();
6903 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6904 isa<DesignatedInitExpr>(InitArgList[0])) {
6905 DiagnosedMixedDesignator = true;
6906 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6907 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6908 << DIE->getSourceRange();
6909 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6910 << InitArgList[I]->getSourceRange();
6914 if (FirstDesignator.isValid()) {
6915 // Only diagnose designated initiaization as a C++20 extension if we didn't
6916 // already diagnose use of (non-C++20) C99 designator syntax.
6917 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6918 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6919 Diag(FirstDesignator, getLangOpts().CPlusPlus20
6920 ? diag::warn_cxx17_compat_designated_init
6921 : diag::ext_cxx_designated_init);
6922 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6923 Diag(FirstDesignator, diag::ext_designated_init);
6927 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6931 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6932 SourceLocation RBraceLoc) {
6933 // Semantic analysis for initializers is done by ActOnDeclarator() and
6934 // CheckInitializer() - it requires knowledge of the object being initialized.
6936 // Immediately handle non-overload placeholders. Overloads can be
6937 // resolved contextually, but everything else here can't.
6938 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6939 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6940 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6942 // Ignore failures; dropping the entire initializer list because
6943 // of one failure would be terrible for indexing/etc.
6944 if (result.isInvalid()) continue;
6946 InitArgList[I] = result.get();
6950 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6952 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6956 /// Do an explicit extend of the given block pointer if we're in ARC.
6957 void Sema::maybeExtendBlockObject(ExprResult &E) {
6958 assert(E.get()->getType()->isBlockPointerType());
6959 assert(E.get()->isRValue());
6961 // Only do this in an r-value context.
6962 if (!getLangOpts().ObjCAutoRefCount) return;
6964 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6965 CK_ARCExtendBlockObject, E.get(),
6966 /*base path*/ nullptr, VK_RValue);
6967 Cleanup.setExprNeedsCleanups(true);
6970 /// Prepare a conversion of the given expression to an ObjC object
6972 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6973 QualType type = E.get()->getType();
6974 if (type->isObjCObjectPointerType()) {
6976 } else if (type->isBlockPointerType()) {
6977 maybeExtendBlockObject(E);
6978 return CK_BlockPointerToObjCPointerCast;
6980 assert(type->isPointerType());
6981 return CK_CPointerToObjCPointerCast;
6985 /// Prepares for a scalar cast, performing all the necessary stages
6986 /// except the final cast and returning the kind required.
6987 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6988 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6989 // Also, callers should have filtered out the invalid cases with
6990 // pointers. Everything else should be possible.
6992 QualType SrcTy = Src.get()->getType();
6993 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6996 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6997 case Type::STK_MemberPointer:
6998 llvm_unreachable("member pointer type in C");
7000 case Type::STK_CPointer:
7001 case Type::STK_BlockPointer:
7002 case Type::STK_ObjCObjectPointer:
7003 switch (DestTy->getScalarTypeKind()) {
7004 case Type::STK_CPointer: {
7005 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7006 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7007 if (SrcAS != DestAS)
7008 return CK_AddressSpaceConversion;
7009 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7013 case Type::STK_BlockPointer:
7014 return (SrcKind == Type::STK_BlockPointer
7015 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7016 case Type::STK_ObjCObjectPointer:
7017 if (SrcKind == Type::STK_ObjCObjectPointer)
7019 if (SrcKind == Type::STK_CPointer)
7020 return CK_CPointerToObjCPointerCast;
7021 maybeExtendBlockObject(Src);
7022 return CK_BlockPointerToObjCPointerCast;
7023 case Type::STK_Bool:
7024 return CK_PointerToBoolean;
7025 case Type::STK_Integral:
7026 return CK_PointerToIntegral;
7027 case Type::STK_Floating:
7028 case Type::STK_FloatingComplex:
7029 case Type::STK_IntegralComplex:
7030 case Type::STK_MemberPointer:
7031 case Type::STK_FixedPoint:
7032 llvm_unreachable("illegal cast from pointer");
7034 llvm_unreachable("Should have returned before this");
7036 case Type::STK_FixedPoint:
7037 switch (DestTy->getScalarTypeKind()) {
7038 case Type::STK_FixedPoint:
7039 return CK_FixedPointCast;
7040 case Type::STK_Bool:
7041 return CK_FixedPointToBoolean;
7042 case Type::STK_Integral:
7043 return CK_FixedPointToIntegral;
7044 case Type::STK_Floating:
7045 case Type::STK_IntegralComplex:
7046 case Type::STK_FloatingComplex:
7047 Diag(Src.get()->getExprLoc(),
7048 diag::err_unimplemented_conversion_with_fixed_point_type)
7050 return CK_IntegralCast;
7051 case Type::STK_CPointer:
7052 case Type::STK_ObjCObjectPointer:
7053 case Type::STK_BlockPointer:
7054 case Type::STK_MemberPointer:
7055 llvm_unreachable("illegal cast to pointer type");
7057 llvm_unreachable("Should have returned before this");
7059 case Type::STK_Bool: // casting from bool is like casting from an integer
7060 case Type::STK_Integral:
7061 switch (DestTy->getScalarTypeKind()) {
7062 case Type::STK_CPointer:
7063 case Type::STK_ObjCObjectPointer:
7064 case Type::STK_BlockPointer:
7065 if (Src.get()->isNullPointerConstant(Context,
7066 Expr::NPC_ValueDependentIsNull))
7067 return CK_NullToPointer;
7068 return CK_IntegralToPointer;
7069 case Type::STK_Bool:
7070 return CK_IntegralToBoolean;
7071 case Type::STK_Integral:
7072 return CK_IntegralCast;
7073 case Type::STK_Floating:
7074 return CK_IntegralToFloating;
7075 case Type::STK_IntegralComplex:
7076 Src = ImpCastExprToType(Src.get(),
7077 DestTy->castAs<ComplexType>()->getElementType(),
7079 return CK_IntegralRealToComplex;
7080 case Type::STK_FloatingComplex:
7081 Src = ImpCastExprToType(Src.get(),
7082 DestTy->castAs<ComplexType>()->getElementType(),
7083 CK_IntegralToFloating);
7084 return CK_FloatingRealToComplex;
7085 case Type::STK_MemberPointer:
7086 llvm_unreachable("member pointer type in C");
7087 case Type::STK_FixedPoint:
7088 return CK_IntegralToFixedPoint;
7090 llvm_unreachable("Should have returned before this");
7092 case Type::STK_Floating:
7093 switch (DestTy->getScalarTypeKind()) {
7094 case Type::STK_Floating:
7095 return CK_FloatingCast;
7096 case Type::STK_Bool:
7097 return CK_FloatingToBoolean;
7098 case Type::STK_Integral:
7099 return CK_FloatingToIntegral;
7100 case Type::STK_FloatingComplex:
7101 Src = ImpCastExprToType(Src.get(),
7102 DestTy->castAs<ComplexType>()->getElementType(),
7104 return CK_FloatingRealToComplex;
7105 case Type::STK_IntegralComplex:
7106 Src = ImpCastExprToType(Src.get(),
7107 DestTy->castAs<ComplexType>()->getElementType(),
7108 CK_FloatingToIntegral);
7109 return CK_IntegralRealToComplex;
7110 case Type::STK_CPointer:
7111 case Type::STK_ObjCObjectPointer:
7112 case Type::STK_BlockPointer:
7113 llvm_unreachable("valid float->pointer cast?");
7114 case Type::STK_MemberPointer:
7115 llvm_unreachable("member pointer type in C");
7116 case Type::STK_FixedPoint:
7117 Diag(Src.get()->getExprLoc(),
7118 diag::err_unimplemented_conversion_with_fixed_point_type)
7120 return CK_IntegralCast;
7122 llvm_unreachable("Should have returned before this");
7124 case Type::STK_FloatingComplex:
7125 switch (DestTy->getScalarTypeKind()) {
7126 case Type::STK_FloatingComplex:
7127 return CK_FloatingComplexCast;
7128 case Type::STK_IntegralComplex:
7129 return CK_FloatingComplexToIntegralComplex;
7130 case Type::STK_Floating: {
7131 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7132 if (Context.hasSameType(ET, DestTy))
7133 return CK_FloatingComplexToReal;
7134 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7135 return CK_FloatingCast;
7137 case Type::STK_Bool:
7138 return CK_FloatingComplexToBoolean;
7139 case Type::STK_Integral:
7140 Src = ImpCastExprToType(Src.get(),
7141 SrcTy->castAs<ComplexType>()->getElementType(),
7142 CK_FloatingComplexToReal);
7143 return CK_FloatingToIntegral;
7144 case Type::STK_CPointer:
7145 case Type::STK_ObjCObjectPointer:
7146 case Type::STK_BlockPointer:
7147 llvm_unreachable("valid complex float->pointer cast?");
7148 case Type::STK_MemberPointer:
7149 llvm_unreachable("member pointer type in C");
7150 case Type::STK_FixedPoint:
7151 Diag(Src.get()->getExprLoc(),
7152 diag::err_unimplemented_conversion_with_fixed_point_type)
7154 return CK_IntegralCast;
7156 llvm_unreachable("Should have returned before this");
7158 case Type::STK_IntegralComplex:
7159 switch (DestTy->getScalarTypeKind()) {
7160 case Type::STK_FloatingComplex:
7161 return CK_IntegralComplexToFloatingComplex;
7162 case Type::STK_IntegralComplex:
7163 return CK_IntegralComplexCast;
7164 case Type::STK_Integral: {
7165 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7166 if (Context.hasSameType(ET, DestTy))
7167 return CK_IntegralComplexToReal;
7168 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7169 return CK_IntegralCast;
7171 case Type::STK_Bool:
7172 return CK_IntegralComplexToBoolean;
7173 case Type::STK_Floating:
7174 Src = ImpCastExprToType(Src.get(),
7175 SrcTy->castAs<ComplexType>()->getElementType(),
7176 CK_IntegralComplexToReal);
7177 return CK_IntegralToFloating;
7178 case Type::STK_CPointer:
7179 case Type::STK_ObjCObjectPointer:
7180 case Type::STK_BlockPointer:
7181 llvm_unreachable("valid complex int->pointer cast?");
7182 case Type::STK_MemberPointer:
7183 llvm_unreachable("member pointer type in C");
7184 case Type::STK_FixedPoint:
7185 Diag(Src.get()->getExprLoc(),
7186 diag::err_unimplemented_conversion_with_fixed_point_type)
7188 return CK_IntegralCast;
7190 llvm_unreachable("Should have returned before this");
7193 llvm_unreachable("Unhandled scalar cast");
7196 static bool breakDownVectorType(QualType type, uint64_t &len,
7197 QualType &eltType) {
7198 // Vectors are simple.
7199 if (const VectorType *vecType = type->getAs<VectorType>()) {
7200 len = vecType->getNumElements();
7201 eltType = vecType->getElementType();
7202 assert(eltType->isScalarType());
7206 // We allow lax conversion to and from non-vector types, but only if
7207 // they're real types (i.e. non-complex, non-pointer scalar types).
7208 if (!type->isRealType()) return false;
7215 /// Are the two types lax-compatible vector types? That is, given
7216 /// that one of them is a vector, do they have equal storage sizes,
7217 /// where the storage size is the number of elements times the element
7220 /// This will also return false if either of the types is neither a
7221 /// vector nor a real type.
7222 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7223 assert(destTy->isVectorType() || srcTy->isVectorType());
7225 // Disallow lax conversions between scalars and ExtVectors (these
7226 // conversions are allowed for other vector types because common headers
7227 // depend on them). Most scalar OP ExtVector cases are handled by the
7228 // splat path anyway, which does what we want (convert, not bitcast).
7229 // What this rules out for ExtVectors is crazy things like char4*float.
7230 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7231 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7233 uint64_t srcLen, destLen;
7234 QualType srcEltTy, destEltTy;
7235 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7236 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7238 // ASTContext::getTypeSize will return the size rounded up to a
7239 // power of 2, so instead of using that, we need to use the raw
7240 // element size multiplied by the element count.
7241 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7242 uint64_t destEltSize = Context.getTypeSize(destEltTy);
7244 return (srcLen * srcEltSize == destLen * destEltSize);
7247 /// Is this a legal conversion between two types, one of which is
7248 /// known to be a vector type?
7249 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7250 assert(destTy->isVectorType() || srcTy->isVectorType());
7252 switch (Context.getLangOpts().getLaxVectorConversions()) {
7253 case LangOptions::LaxVectorConversionKind::None:
7256 case LangOptions::LaxVectorConversionKind::Integer:
7257 if (!srcTy->isIntegralOrEnumerationType()) {
7258 auto *Vec = srcTy->getAs<VectorType>();
7259 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7262 if (!destTy->isIntegralOrEnumerationType()) {
7263 auto *Vec = destTy->getAs<VectorType>();
7264 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7267 // OK, integer (vector) -> integer (vector) bitcast.
7270 case LangOptions::LaxVectorConversionKind::All:
7274 return areLaxCompatibleVectorTypes(srcTy, destTy);
7277 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7279 assert(VectorTy->isVectorType() && "Not a vector type!");
7281 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7282 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7283 return Diag(R.getBegin(),
7284 Ty->isVectorType() ?
7285 diag::err_invalid_conversion_between_vectors :
7286 diag::err_invalid_conversion_between_vector_and_integer)
7287 << VectorTy << Ty << R;
7289 return Diag(R.getBegin(),
7290 diag::err_invalid_conversion_between_vector_and_scalar)
7291 << VectorTy << Ty << R;
7297 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7298 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7300 if (DestElemTy == SplattedExpr->getType())
7301 return SplattedExpr;
7303 assert(DestElemTy->isFloatingType() ||
7304 DestElemTy->isIntegralOrEnumerationType());
7307 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7308 // OpenCL requires that we convert `true` boolean expressions to -1, but
7309 // only when splatting vectors.
7310 if (DestElemTy->isFloatingType()) {
7311 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7312 // in two steps: boolean to signed integral, then to floating.
7313 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7314 CK_BooleanToSignedIntegral);
7315 SplattedExpr = CastExprRes.get();
7316 CK = CK_IntegralToFloating;
7318 CK = CK_BooleanToSignedIntegral;
7321 ExprResult CastExprRes = SplattedExpr;
7322 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7323 if (CastExprRes.isInvalid())
7325 SplattedExpr = CastExprRes.get();
7327 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7330 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7331 Expr *CastExpr, CastKind &Kind) {
7332 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7334 QualType SrcTy = CastExpr->getType();
7336 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7337 // an ExtVectorType.
7338 // In OpenCL, casts between vectors of different types are not allowed.
7339 // (See OpenCL 6.2).
7340 if (SrcTy->isVectorType()) {
7341 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7342 (getLangOpts().OpenCL &&
7343 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7344 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7345 << DestTy << SrcTy << R;
7352 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7353 // conversion will take place first from scalar to elt type, and then
7354 // splat from elt type to vector.
7355 if (SrcTy->isPointerType())
7356 return Diag(R.getBegin(),
7357 diag::err_invalid_conversion_between_vector_and_scalar)
7358 << DestTy << SrcTy << R;
7360 Kind = CK_VectorSplat;
7361 return prepareVectorSplat(DestTy, CastExpr);
7365 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7366 Declarator &D, ParsedType &Ty,
7367 SourceLocation RParenLoc, Expr *CastExpr) {
7368 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7369 "ActOnCastExpr(): missing type or expr");
7371 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7372 if (D.isInvalidType())
7375 if (getLangOpts().CPlusPlus) {
7376 // Check that there are no default arguments (C++ only).
7377 CheckExtraCXXDefaultArguments(D);
7379 // Make sure any TypoExprs have been dealt with.
7380 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7381 if (!Res.isUsable())
7383 CastExpr = Res.get();
7386 checkUnusedDeclAttributes(D);
7388 QualType castType = castTInfo->getType();
7389 Ty = CreateParsedType(castType, castTInfo);
7391 bool isVectorLiteral = false;
7393 // Check for an altivec or OpenCL literal,
7394 // i.e. all the elements are integer constants.
7395 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7396 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7397 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7398 && castType->isVectorType() && (PE || PLE)) {
7399 if (PLE && PLE->getNumExprs() == 0) {
7400 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7403 if (PE || PLE->getNumExprs() == 1) {
7404 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7405 if (!E->getType()->isVectorType())
7406 isVectorLiteral = true;
7409 isVectorLiteral = true;
7412 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7413 // then handle it as such.
7414 if (isVectorLiteral)
7415 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7417 // If the Expr being casted is a ParenListExpr, handle it specially.
7418 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7419 // sequence of BinOp comma operators.
7420 if (isa<ParenListExpr>(CastExpr)) {
7421 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7422 if (Result.isInvalid()) return ExprError();
7423 CastExpr = Result.get();
7426 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7427 !getSourceManager().isInSystemMacro(LParenLoc))
7428 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7430 CheckTollFreeBridgeCast(castType, CastExpr);
7432 CheckObjCBridgeRelatedCast(castType, CastExpr);
7434 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7436 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7439 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7440 SourceLocation RParenLoc, Expr *E,
7441 TypeSourceInfo *TInfo) {
7442 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7443 "Expected paren or paren list expression");
7448 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7449 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7450 LiteralLParenLoc = PE->getLParenLoc();
7451 LiteralRParenLoc = PE->getRParenLoc();
7452 exprs = PE->getExprs();
7453 numExprs = PE->getNumExprs();
7454 } else { // isa<ParenExpr> by assertion at function entrance
7455 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7456 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7457 subExpr = cast<ParenExpr>(E)->getSubExpr();
7462 QualType Ty = TInfo->getType();
7463 assert(Ty->isVectorType() && "Expected vector type");
7465 SmallVector<Expr *, 8> initExprs;
7466 const VectorType *VTy = Ty->castAs<VectorType>();
7467 unsigned numElems = VTy->getNumElements();
7469 // '(...)' form of vector initialization in AltiVec: the number of
7470 // initializers must be one or must match the size of the vector.
7471 // If a single value is specified in the initializer then it will be
7472 // replicated to all the components of the vector
7473 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7474 // The number of initializers must be one or must match the size of the
7475 // vector. If a single value is specified in the initializer then it will
7476 // be replicated to all the components of the vector
7477 if (numExprs == 1) {
7478 QualType ElemTy = VTy->getElementType();
7479 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7480 if (Literal.isInvalid())
7482 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7483 PrepareScalarCast(Literal, ElemTy));
7484 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7486 else if (numExprs < numElems) {
7487 Diag(E->getExprLoc(),
7488 diag::err_incorrect_number_of_vector_initializers);
7492 initExprs.append(exprs, exprs + numExprs);
7495 // For OpenCL, when the number of initializers is a single value,
7496 // it will be replicated to all components of the vector.
7497 if (getLangOpts().OpenCL &&
7498 VTy->getVectorKind() == VectorType::GenericVector &&
7500 QualType ElemTy = VTy->getElementType();
7501 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7502 if (Literal.isInvalid())
7504 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7505 PrepareScalarCast(Literal, ElemTy));
7506 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7509 initExprs.append(exprs, exprs + numExprs);
7511 // FIXME: This means that pretty-printing the final AST will produce curly
7512 // braces instead of the original commas.
7513 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7514 initExprs, LiteralRParenLoc);
7516 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7519 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7520 /// the ParenListExpr into a sequence of comma binary operators.
7522 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7523 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7527 ExprResult Result(E->getExpr(0));
7529 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7530 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7533 if (Result.isInvalid()) return ExprError();
7535 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7538 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7541 return ParenListExpr::Create(Context, L, Val, R);
7544 /// Emit a specialized diagnostic when one expression is a null pointer
7545 /// constant and the other is not a pointer. Returns true if a diagnostic is
7547 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7548 SourceLocation QuestionLoc) {
7549 Expr *NullExpr = LHSExpr;
7550 Expr *NonPointerExpr = RHSExpr;
7551 Expr::NullPointerConstantKind NullKind =
7552 NullExpr->isNullPointerConstant(Context,
7553 Expr::NPC_ValueDependentIsNotNull);
7555 if (NullKind == Expr::NPCK_NotNull) {
7557 NonPointerExpr = LHSExpr;
7559 NullExpr->isNullPointerConstant(Context,
7560 Expr::NPC_ValueDependentIsNotNull);
7563 if (NullKind == Expr::NPCK_NotNull)
7566 if (NullKind == Expr::NPCK_ZeroExpression)
7569 if (NullKind == Expr::NPCK_ZeroLiteral) {
7570 // In this case, check to make sure that we got here from a "NULL"
7571 // string in the source code.
7572 NullExpr = NullExpr->IgnoreParenImpCasts();
7573 SourceLocation loc = NullExpr->getExprLoc();
7574 if (!findMacroSpelling(loc, "NULL"))
7578 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7579 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7580 << NonPointerExpr->getType() << DiagType
7581 << NonPointerExpr->getSourceRange();
7585 /// Return false if the condition expression is valid, true otherwise.
7586 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7587 QualType CondTy = Cond->getType();
7589 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7590 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7591 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7592 << CondTy << Cond->getSourceRange();
7597 if (CondTy->isScalarType()) return false;
7599 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7600 << CondTy << Cond->getSourceRange();
7604 /// Handle when one or both operands are void type.
7605 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7607 Expr *LHSExpr = LHS.get();
7608 Expr *RHSExpr = RHS.get();
7610 if (!LHSExpr->getType()->isVoidType())
7611 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7612 << RHSExpr->getSourceRange();
7613 if (!RHSExpr->getType()->isVoidType())
7614 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7615 << LHSExpr->getSourceRange();
7616 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7617 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7618 return S.Context.VoidTy;
7621 /// Return false if the NullExpr can be promoted to PointerTy,
7623 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7624 QualType PointerTy) {
7625 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7626 !NullExpr.get()->isNullPointerConstant(S.Context,
7627 Expr::NPC_ValueDependentIsNull))
7630 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7634 /// Checks compatibility between two pointers and return the resulting
7636 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7638 SourceLocation Loc) {
7639 QualType LHSTy = LHS.get()->getType();
7640 QualType RHSTy = RHS.get()->getType();
7642 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7643 // Two identical pointers types are always compatible.
7647 QualType lhptee, rhptee;
7649 // Get the pointee types.
7650 bool IsBlockPointer = false;
7651 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7652 lhptee = LHSBTy->getPointeeType();
7653 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7654 IsBlockPointer = true;
7656 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7657 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7660 // C99 6.5.15p6: If both operands are pointers to compatible types or to
7661 // differently qualified versions of compatible types, the result type is
7662 // a pointer to an appropriately qualified version of the composite
7665 // Only CVR-qualifiers exist in the standard, and the differently-qualified
7666 // clause doesn't make sense for our extensions. E.g. address space 2 should
7667 // be incompatible with address space 3: they may live on different devices or
7669 Qualifiers lhQual = lhptee.getQualifiers();
7670 Qualifiers rhQual = rhptee.getQualifiers();
7672 LangAS ResultAddrSpace = LangAS::Default;
7673 LangAS LAddrSpace = lhQual.getAddressSpace();
7674 LangAS RAddrSpace = rhQual.getAddressSpace();
7676 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7677 // spaces is disallowed.
7678 if (lhQual.isAddressSpaceSupersetOf(rhQual))
7679 ResultAddrSpace = LAddrSpace;
7680 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7681 ResultAddrSpace = RAddrSpace;
7683 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7684 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7685 << RHS.get()->getSourceRange();
7689 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7690 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7691 lhQual.removeCVRQualifiers();
7692 rhQual.removeCVRQualifiers();
7694 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7695 // (C99 6.7.3) for address spaces. We assume that the check should behave in
7696 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7697 // qual types are compatible iff
7698 // * corresponded types are compatible
7699 // * CVR qualifiers are equal
7700 // * address spaces are equal
7701 // Thus for conditional operator we merge CVR and address space unqualified
7702 // pointees and if there is a composite type we return a pointer to it with
7703 // merged qualifiers.
7705 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7707 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7708 lhQual.removeAddressSpace();
7709 rhQual.removeAddressSpace();
7711 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7712 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7714 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7716 if (CompositeTy.isNull()) {
7717 // In this situation, we assume void* type. No especially good
7718 // reason, but this is what gcc does, and we do have to pick
7719 // to get a consistent AST.
7720 QualType incompatTy;
7721 incompatTy = S.Context.getPointerType(
7722 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7723 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7724 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7726 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7727 // for casts between types with incompatible address space qualifiers.
7728 // For the following code the compiler produces casts between global and
7729 // local address spaces of the corresponded innermost pointees:
7730 // local int *global *a;
7731 // global int *global *b;
7732 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7733 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7734 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7735 << RHS.get()->getSourceRange();
7740 // The pointer types are compatible.
7741 // In case of OpenCL ResultTy should have the address space qualifier
7742 // which is a superset of address spaces of both the 2nd and the 3rd
7743 // operands of the conditional operator.
7744 QualType ResultTy = [&, ResultAddrSpace]() {
7745 if (S.getLangOpts().OpenCL) {
7746 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7747 CompositeQuals.setAddressSpace(ResultAddrSpace);
7749 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7750 .withCVRQualifiers(MergedCVRQual);
7752 return CompositeTy.withCVRQualifiers(MergedCVRQual);
7755 ResultTy = S.Context.getBlockPointerType(ResultTy);
7757 ResultTy = S.Context.getPointerType(ResultTy);
7759 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7760 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7764 /// Return the resulting type when the operands are both block pointers.
7765 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7768 SourceLocation Loc) {
7769 QualType LHSTy = LHS.get()->getType();
7770 QualType RHSTy = RHS.get()->getType();
7772 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7773 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7774 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7775 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7776 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7779 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7780 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7781 << RHS.get()->getSourceRange();
7785 // We have 2 block pointer types.
7786 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7789 /// Return the resulting type when the operands are both pointers.
7791 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7793 SourceLocation Loc) {
7794 // get the pointer types
7795 QualType LHSTy = LHS.get()->getType();
7796 QualType RHSTy = RHS.get()->getType();
7798 // get the "pointed to" types
7799 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7800 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7802 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7803 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7804 // Figure out necessary qualifiers (C99 6.5.15p6)
7805 QualType destPointee
7806 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7807 QualType destType = S.Context.getPointerType(destPointee);
7808 // Add qualifiers if necessary.
7809 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7810 // Promote to void*.
7811 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7814 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7815 QualType destPointee
7816 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7817 QualType destType = S.Context.getPointerType(destPointee);
7818 // Add qualifiers if necessary.
7819 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7820 // Promote to void*.
7821 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7825 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7828 /// Return false if the first expression is not an integer and the second
7829 /// expression is not a pointer, true otherwise.
7830 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7831 Expr* PointerExpr, SourceLocation Loc,
7832 bool IsIntFirstExpr) {
7833 if (!PointerExpr->getType()->isPointerType() ||
7834 !Int.get()->getType()->isIntegerType())
7837 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7838 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7840 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7841 << Expr1->getType() << Expr2->getType()
7842 << Expr1->getSourceRange() << Expr2->getSourceRange();
7843 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7844 CK_IntegralToPointer);
7848 /// Simple conversion between integer and floating point types.
7850 /// Used when handling the OpenCL conditional operator where the
7851 /// condition is a vector while the other operands are scalar.
7853 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7854 /// types are either integer or floating type. Between the two
7855 /// operands, the type with the higher rank is defined as the "result
7856 /// type". The other operand needs to be promoted to the same type. No
7857 /// other type promotion is allowed. We cannot use
7858 /// UsualArithmeticConversions() for this purpose, since it always
7859 /// promotes promotable types.
7860 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7862 SourceLocation QuestionLoc) {
7863 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7864 if (LHS.isInvalid())
7866 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7867 if (RHS.isInvalid())
7870 // For conversion purposes, we ignore any qualifiers.
7871 // For example, "const float" and "float" are equivalent.
7873 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7875 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7877 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7878 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7879 << LHSType << LHS.get()->getSourceRange();
7883 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7884 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7885 << RHSType << RHS.get()->getSourceRange();
7889 // If both types are identical, no conversion is needed.
7890 if (LHSType == RHSType)
7893 // Now handle "real" floating types (i.e. float, double, long double).
7894 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7895 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7896 /*IsCompAssign = */ false);
7898 // Finally, we have two differing integer types.
7899 return handleIntegerConversion<doIntegralCast, doIntegralCast>
7900 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7903 /// Convert scalar operands to a vector that matches the
7904 /// condition in length.
7906 /// Used when handling the OpenCL conditional operator where the
7907 /// condition is a vector while the other operands are scalar.
7909 /// We first compute the "result type" for the scalar operands
7910 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7911 /// into a vector of that type where the length matches the condition
7912 /// vector type. s6.11.6 requires that the element types of the result
7913 /// and the condition must have the same number of bits.
7915 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7916 QualType CondTy, SourceLocation QuestionLoc) {
7917 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7918 if (ResTy.isNull()) return QualType();
7920 const VectorType *CV = CondTy->getAs<VectorType>();
7923 // Determine the vector result type
7924 unsigned NumElements = CV->getNumElements();
7925 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7927 // Ensure that all types have the same number of bits
7928 if (S.Context.getTypeSize(CV->getElementType())
7929 != S.Context.getTypeSize(ResTy)) {
7930 // Since VectorTy is created internally, it does not pretty print
7931 // with an OpenCL name. Instead, we just print a description.
7932 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7933 SmallString<64> Str;
7934 llvm::raw_svector_ostream OS(Str);
7935 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7936 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7937 << CondTy << OS.str();
7941 // Convert operands to the vector result type
7942 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7943 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7948 /// Return false if this is a valid OpenCL condition vector
7949 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7950 SourceLocation QuestionLoc) {
7951 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7953 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7955 QualType EleTy = CondTy->getElementType();
7956 if (EleTy->isIntegerType()) return false;
7958 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7959 << Cond->getType() << Cond->getSourceRange();
7963 /// Return false if the vector condition type and the vector
7964 /// result type are compatible.
7966 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7967 /// number of elements, and their element types have the same number
7969 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7970 SourceLocation QuestionLoc) {
7971 const VectorType *CV = CondTy->getAs<VectorType>();
7972 const VectorType *RV = VecResTy->getAs<VectorType>();
7975 if (CV->getNumElements() != RV->getNumElements()) {
7976 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7977 << CondTy << VecResTy;
7981 QualType CVE = CV->getElementType();
7982 QualType RVE = RV->getElementType();
7984 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7985 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7986 << CondTy << VecResTy;
7993 /// Return the resulting type for the conditional operator in
7994 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
7995 /// s6.3.i) when the condition is a vector type.
7997 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7998 ExprResult &LHS, ExprResult &RHS,
7999 SourceLocation QuestionLoc) {
8000 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8001 if (Cond.isInvalid())
8003 QualType CondTy = Cond.get()->getType();
8005 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8008 // If either operand is a vector then find the vector type of the
8009 // result as specified in OpenCL v1.1 s6.3.i.
8010 if (LHS.get()->getType()->isVectorType() ||
8011 RHS.get()->getType()->isVectorType()) {
8012 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8013 /*isCompAssign*/false,
8014 /*AllowBothBool*/true,
8015 /*AllowBoolConversions*/false);
8016 if (VecResTy.isNull()) return QualType();
8017 // The result type must match the condition type as specified in
8018 // OpenCL v1.1 s6.11.6.
8019 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8024 // Both operands are scalar.
8025 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8028 /// Return true if the Expr is block type
8029 static bool checkBlockType(Sema &S, const Expr *E) {
8030 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8031 QualType Ty = CE->getCallee()->getType();
8032 if (Ty->isBlockPointerType()) {
8033 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8040 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8041 /// In that case, LHS = cond.
8043 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8044 ExprResult &RHS, ExprValueKind &VK,
8046 SourceLocation QuestionLoc) {
8048 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8049 if (!LHSResult.isUsable()) return QualType();
8052 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8053 if (!RHSResult.isUsable()) return QualType();
8056 // C++ is sufficiently different to merit its own checker.
8057 if (getLangOpts().CPlusPlus)
8058 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8063 // The OpenCL operator with a vector condition is sufficiently
8064 // different to merit its own checker.
8065 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8066 Cond.get()->getType()->isExtVectorType())
8067 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8069 // First, check the condition.
8070 Cond = UsualUnaryConversions(Cond.get());
8071 if (Cond.isInvalid())
8073 if (checkCondition(*this, Cond.get(), QuestionLoc))
8076 // Now check the two expressions.
8077 if (LHS.get()->getType()->isVectorType() ||
8078 RHS.get()->getType()->isVectorType())
8079 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8080 /*AllowBothBool*/true,
8081 /*AllowBoolConversions*/false);
8084 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8085 if (LHS.isInvalid() || RHS.isInvalid())
8088 QualType LHSTy = LHS.get()->getType();
8089 QualType RHSTy = RHS.get()->getType();
8091 // Diagnose attempts to convert between __float128 and long double where
8092 // such conversions currently can't be handled.
8093 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8095 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8096 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8100 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8101 // selection operator (?:).
8102 if (getLangOpts().OpenCL &&
8103 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8107 // If both operands have arithmetic type, do the usual arithmetic conversions
8108 // to find a common type: C99 6.5.15p3,5.
8109 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8110 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8111 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8116 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8117 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8121 // If both operands are the same structure or union type, the result is that
8123 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8124 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8125 if (LHSRT->getDecl() == RHSRT->getDecl())
8126 // "If both the operands have structure or union type, the result has
8127 // that type." This implies that CV qualifiers are dropped.
8128 return LHSTy.getUnqualifiedType();
8129 // FIXME: Type of conditional expression must be complete in C mode.
8132 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8133 // The following || allows only one side to be void (a GCC-ism).
8134 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8135 return checkConditionalVoidType(*this, LHS, RHS);
8138 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8139 // the type of the other operand."
8140 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8141 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8143 // All objective-c pointer type analysis is done here.
8144 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8146 if (LHS.isInvalid() || RHS.isInvalid())
8148 if (!compositeType.isNull())
8149 return compositeType;
8152 // Handle block pointer types.
8153 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8154 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8157 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8158 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8159 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8162 // GCC compatibility: soften pointer/integer mismatch. Note that
8163 // null pointers have been filtered out by this point.
8164 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8165 /*IsIntFirstExpr=*/true))
8167 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8168 /*IsIntFirstExpr=*/false))
8171 // Allow ?: operations in which both operands have the same
8172 // built-in sizeless type.
8173 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8176 // Emit a better diagnostic if one of the expressions is a null pointer
8177 // constant and the other is not a pointer type. In this case, the user most
8178 // likely forgot to take the address of the other expression.
8179 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8182 // Otherwise, the operands are not compatible.
8183 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8184 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8185 << RHS.get()->getSourceRange();
8189 /// FindCompositeObjCPointerType - Helper method to find composite type of
8190 /// two objective-c pointer types of the two input expressions.
8191 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8192 SourceLocation QuestionLoc) {
8193 QualType LHSTy = LHS.get()->getType();
8194 QualType RHSTy = RHS.get()->getType();
8196 // Handle things like Class and struct objc_class*. Here we case the result
8197 // to the pseudo-builtin, because that will be implicitly cast back to the
8198 // redefinition type if an attempt is made to access its fields.
8199 if (LHSTy->isObjCClassType() &&
8200 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8201 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8204 if (RHSTy->isObjCClassType() &&
8205 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8206 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8209 // And the same for struct objc_object* / id
8210 if (LHSTy->isObjCIdType() &&
8211 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8212 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8215 if (RHSTy->isObjCIdType() &&
8216 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8217 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8220 // And the same for struct objc_selector* / SEL
8221 if (Context.isObjCSelType(LHSTy) &&
8222 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8223 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8226 if (Context.isObjCSelType(RHSTy) &&
8227 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8228 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8231 // Check constraints for Objective-C object pointers types.
8232 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8234 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8235 // Two identical object pointer types are always compatible.
8238 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8239 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8240 QualType compositeType = LHSTy;
8242 // If both operands are interfaces and either operand can be
8243 // assigned to the other, use that type as the composite
8244 // type. This allows
8245 // xxx ? (A*) a : (B*) b
8246 // where B is a subclass of A.
8248 // Additionally, as for assignment, if either type is 'id'
8249 // allow silent coercion. Finally, if the types are
8250 // incompatible then make sure to use 'id' as the composite
8251 // type so the result is acceptable for sending messages to.
8253 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8254 // It could return the composite type.
8255 if (!(compositeType =
8256 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8257 // Nothing more to do.
8258 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8259 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8260 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8261 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8262 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8263 RHSOPT->isObjCQualifiedIdType()) &&
8264 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8266 // Need to handle "id<xx>" explicitly.
8267 // GCC allows qualified id and any Objective-C type to devolve to
8268 // id. Currently localizing to here until clear this should be
8269 // part of ObjCQualifiedIdTypesAreCompatible.
8270 compositeType = Context.getObjCIdType();
8271 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8272 compositeType = Context.getObjCIdType();
8274 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8276 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8277 QualType incompatTy = Context.getObjCIdType();
8278 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8279 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8282 // The object pointer types are compatible.
8283 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8284 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8285 return compositeType;
8287 // Check Objective-C object pointer types and 'void *'
8288 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8289 if (getLangOpts().ObjCAutoRefCount) {
8290 // ARC forbids the implicit conversion of object pointers to 'void *',
8291 // so these types are not compatible.
8292 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8293 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8297 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8298 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8299 QualType destPointee
8300 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8301 QualType destType = Context.getPointerType(destPointee);
8302 // Add qualifiers if necessary.
8303 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8304 // Promote to void*.
8305 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8308 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8309 if (getLangOpts().ObjCAutoRefCount) {
8310 // ARC forbids the implicit conversion of object pointers to 'void *',
8311 // so these types are not compatible.
8312 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8313 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8317 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8318 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8319 QualType destPointee
8320 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8321 QualType destType = Context.getPointerType(destPointee);
8322 // Add qualifiers if necessary.
8323 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8324 // Promote to void*.
8325 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8331 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8332 /// ParenRange in parentheses.
8333 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8334 const PartialDiagnostic &Note,
8335 SourceRange ParenRange) {
8336 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8337 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8339 Self.Diag(Loc, Note)
8340 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8341 << FixItHint::CreateInsertion(EndLoc, ")");
8343 // We can't display the parentheses, so just show the bare note.
8344 Self.Diag(Loc, Note) << ParenRange;
8348 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8349 return BinaryOperator::isAdditiveOp(Opc) ||
8350 BinaryOperator::isMultiplicativeOp(Opc) ||
8351 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8352 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8353 // not any of the logical operators. Bitwise-xor is commonly used as a
8354 // logical-xor because there is no logical-xor operator. The logical
8355 // operators, including uses of xor, have a high false positive rate for
8356 // precedence warnings.
8359 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8360 /// expression, either using a built-in or overloaded operator,
8361 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8363 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8365 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8366 E = E->IgnoreImpCasts();
8367 E = E->IgnoreConversionOperator();
8368 E = E->IgnoreImpCasts();
8369 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8370 E = MTE->getSubExpr();
8371 E = E->IgnoreImpCasts();
8374 // Built-in binary operator.
8375 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8376 if (IsArithmeticOp(OP->getOpcode())) {
8377 *Opcode = OP->getOpcode();
8378 *RHSExprs = OP->getRHS();
8383 // Overloaded operator.
8384 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8385 if (Call->getNumArgs() != 2)
8388 // Make sure this is really a binary operator that is safe to pass into
8389 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8390 OverloadedOperatorKind OO = Call->getOperator();
8391 if (OO < OO_Plus || OO > OO_Arrow ||
8392 OO == OO_PlusPlus || OO == OO_MinusMinus)
8395 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8396 if (IsArithmeticOp(OpKind)) {
8398 *RHSExprs = Call->getArg(1);
8406 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8407 /// or is a logical expression such as (x==y) which has int type, but is
8408 /// commonly interpreted as boolean.
8409 static bool ExprLooksBoolean(Expr *E) {
8410 E = E->IgnoreParenImpCasts();
8412 if (E->getType()->isBooleanType())
8414 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8415 return OP->isComparisonOp() || OP->isLogicalOp();
8416 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8417 return OP->getOpcode() == UO_LNot;
8418 if (E->getType()->isPointerType())
8420 // FIXME: What about overloaded operator calls returning "unspecified boolean
8421 // type"s (commonly pointer-to-members)?
8426 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8427 /// and binary operator are mixed in a way that suggests the programmer assumed
8428 /// the conditional operator has higher precedence, for example:
8429 /// "int x = a + someBinaryCondition ? 1 : 2".
8430 static void DiagnoseConditionalPrecedence(Sema &Self,
8431 SourceLocation OpLoc,
8435 BinaryOperatorKind CondOpcode;
8438 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8440 if (!ExprLooksBoolean(CondRHS))
8443 // The condition is an arithmetic binary expression, with a right-
8444 // hand side that looks boolean, so warn.
8446 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8447 ? diag::warn_precedence_bitwise_conditional
8448 : diag::warn_precedence_conditional;
8450 Self.Diag(OpLoc, DiagID)
8451 << Condition->getSourceRange()
8452 << BinaryOperator::getOpcodeStr(CondOpcode);
8456 Self.PDiag(diag::note_precedence_silence)
8457 << BinaryOperator::getOpcodeStr(CondOpcode),
8458 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8460 SuggestParentheses(Self, OpLoc,
8461 Self.PDiag(diag::note_precedence_conditional_first),
8462 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8465 /// Compute the nullability of a conditional expression.
8466 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8467 QualType LHSTy, QualType RHSTy,
8469 if (!ResTy->isAnyPointerType())
8472 auto GetNullability = [&Ctx](QualType Ty) {
8473 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8476 return NullabilityKind::Unspecified;
8479 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8480 NullabilityKind MergedKind;
8482 // Compute nullability of a binary conditional expression.
8484 if (LHSKind == NullabilityKind::NonNull)
8485 MergedKind = NullabilityKind::NonNull;
8487 MergedKind = RHSKind;
8488 // Compute nullability of a normal conditional expression.
8490 if (LHSKind == NullabilityKind::Nullable ||
8491 RHSKind == NullabilityKind::Nullable)
8492 MergedKind = NullabilityKind::Nullable;
8493 else if (LHSKind == NullabilityKind::NonNull)
8494 MergedKind = RHSKind;
8495 else if (RHSKind == NullabilityKind::NonNull)
8496 MergedKind = LHSKind;
8498 MergedKind = NullabilityKind::Unspecified;
8501 // Return if ResTy already has the correct nullability.
8502 if (GetNullability(ResTy) == MergedKind)
8505 // Strip all nullability from ResTy.
8506 while (ResTy->getNullability(Ctx))
8507 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8509 // Create a new AttributedType with the new nullability kind.
8510 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8511 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8514 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
8515 /// in the case of a the GNU conditional expr extension.
8516 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8517 SourceLocation ColonLoc,
8518 Expr *CondExpr, Expr *LHSExpr,
8520 if (!getLangOpts().CPlusPlus) {
8521 // C cannot handle TypoExpr nodes in the condition because it
8522 // doesn't handle dependent types properly, so make sure any TypoExprs have
8523 // been dealt with before checking the operands.
8524 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8525 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8526 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8528 if (!CondResult.isUsable())
8532 if (!LHSResult.isUsable())
8536 if (!RHSResult.isUsable())
8539 CondExpr = CondResult.get();
8540 LHSExpr = LHSResult.get();
8541 RHSExpr = RHSResult.get();
8544 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8545 // was the condition.
8546 OpaqueValueExpr *opaqueValue = nullptr;
8547 Expr *commonExpr = nullptr;
8549 commonExpr = CondExpr;
8550 // Lower out placeholder types first. This is important so that we don't
8551 // try to capture a placeholder. This happens in few cases in C++; such
8552 // as Objective-C++'s dictionary subscripting syntax.
8553 if (commonExpr->hasPlaceholderType()) {
8554 ExprResult result = CheckPlaceholderExpr(commonExpr);
8555 if (!result.isUsable()) return ExprError();
8556 commonExpr = result.get();
8558 // We usually want to apply unary conversions *before* saving, except
8559 // in the special case of a C++ l-value conditional.
8560 if (!(getLangOpts().CPlusPlus
8561 && !commonExpr->isTypeDependent()
8562 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8563 && commonExpr->isGLValue()
8564 && commonExpr->isOrdinaryOrBitFieldObject()
8565 && RHSExpr->isOrdinaryOrBitFieldObject()
8566 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8567 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8568 if (commonRes.isInvalid())
8570 commonExpr = commonRes.get();
8573 // If the common expression is a class or array prvalue, materialize it
8574 // so that we can safely refer to it multiple times.
8575 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8576 commonExpr->getType()->isArrayType())) {
8577 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8578 if (MatExpr.isInvalid())
8580 commonExpr = MatExpr.get();
8583 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8584 commonExpr->getType(),
8585 commonExpr->getValueKind(),
8586 commonExpr->getObjectKind(),
8588 LHSExpr = CondExpr = opaqueValue;
8591 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8592 ExprValueKind VK = VK_RValue;
8593 ExprObjectKind OK = OK_Ordinary;
8594 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8595 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8596 VK, OK, QuestionLoc);
8597 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8601 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8604 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8606 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8610 return new (Context)
8611 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8612 RHS.get(), result, VK, OK);
8614 return new (Context) BinaryConditionalOperator(
8615 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8616 ColonLoc, result, VK, OK);
8619 // Check if we have a conversion between incompatible cmse function pointer
8620 // types, that is, a conversion between a function pointer with the
8621 // cmse_nonsecure_call attribute and one without.
8622 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8624 if (const auto *ToFn =
8625 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8626 if (const auto *FromFn =
8627 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8628 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8629 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8631 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8637 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8638 // being closely modeled after the C99 spec:-). The odd characteristic of this
8639 // routine is it effectively iqnores the qualifiers on the top level pointee.
8640 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8641 // FIXME: add a couple examples in this comment.
8642 static Sema::AssignConvertType
8643 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8644 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8645 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8647 // get the "pointed to" type (ignoring qualifiers at the top level)
8648 const Type *lhptee, *rhptee;
8649 Qualifiers lhq, rhq;
8650 std::tie(lhptee, lhq) =
8651 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8652 std::tie(rhptee, rhq) =
8653 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8655 Sema::AssignConvertType ConvTy = Sema::Compatible;
8657 // C99 6.5.16.1p1: This following citation is common to constraints
8658 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8659 // qualifiers of the type *pointed to* by the right;
8661 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8662 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8663 lhq.compatiblyIncludesObjCLifetime(rhq)) {
8664 // Ignore lifetime for further calculation.
8665 lhq.removeObjCLifetime();
8666 rhq.removeObjCLifetime();
8669 if (!lhq.compatiblyIncludes(rhq)) {
8670 // Treat address-space mismatches as fatal.
8671 if (!lhq.isAddressSpaceSupersetOf(rhq))
8672 return Sema::IncompatiblePointerDiscardsQualifiers;
8674 // It's okay to add or remove GC or lifetime qualifiers when converting to
8676 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8677 .compatiblyIncludes(
8678 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8679 && (lhptee->isVoidType() || rhptee->isVoidType()))
8682 // Treat lifetime mismatches as fatal.
8683 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8684 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8686 // For GCC/MS compatibility, other qualifier mismatches are treated
8687 // as still compatible in C.
8688 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8691 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8692 // incomplete type and the other is a pointer to a qualified or unqualified
8693 // version of void...
8694 if (lhptee->isVoidType()) {
8695 if (rhptee->isIncompleteOrObjectType())
8698 // As an extension, we allow cast to/from void* to function pointer.
8699 assert(rhptee->isFunctionType());
8700 return Sema::FunctionVoidPointer;
8703 if (rhptee->isVoidType()) {
8704 if (lhptee->isIncompleteOrObjectType())
8707 // As an extension, we allow cast to/from void* to function pointer.
8708 assert(lhptee->isFunctionType());
8709 return Sema::FunctionVoidPointer;
8712 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8713 // unqualified versions of compatible types, ...
8714 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8715 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8716 // Check if the pointee types are compatible ignoring the sign.
8717 // We explicitly check for char so that we catch "char" vs
8718 // "unsigned char" on systems where "char" is unsigned.
8719 if (lhptee->isCharType())
8720 ltrans = S.Context.UnsignedCharTy;
8721 else if (lhptee->hasSignedIntegerRepresentation())
8722 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8724 if (rhptee->isCharType())
8725 rtrans = S.Context.UnsignedCharTy;
8726 else if (rhptee->hasSignedIntegerRepresentation())
8727 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8729 if (ltrans == rtrans) {
8730 // Types are compatible ignoring the sign. Qualifier incompatibility
8731 // takes priority over sign incompatibility because the sign
8732 // warning can be disabled.
8733 if (ConvTy != Sema::Compatible)
8736 return Sema::IncompatiblePointerSign;
8739 // If we are a multi-level pointer, it's possible that our issue is simply
8740 // one of qualification - e.g. char ** -> const char ** is not allowed. If
8741 // the eventual target type is the same and the pointers have the same
8742 // level of indirection, this must be the issue.
8743 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8745 std::tie(lhptee, lhq) =
8746 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8747 std::tie(rhptee, rhq) =
8748 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8750 // Inconsistent address spaces at this point is invalid, even if the
8751 // address spaces would be compatible.
8752 // FIXME: This doesn't catch address space mismatches for pointers of
8753 // different nesting levels, like:
8754 // __local int *** a;
8756 // It's not clear how to actually determine when such pointers are
8757 // invalidly incompatible.
8758 if (lhq.getAddressSpace() != rhq.getAddressSpace())
8759 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8761 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8763 if (lhptee == rhptee)
8764 return Sema::IncompatibleNestedPointerQualifiers;
8767 // General pointer incompatibility takes priority over qualifiers.
8768 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8769 return Sema::IncompatibleFunctionPointer;
8770 return Sema::IncompatiblePointer;
8772 if (!S.getLangOpts().CPlusPlus &&
8773 S.IsFunctionConversion(ltrans, rtrans, ltrans))
8774 return Sema::IncompatibleFunctionPointer;
8775 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8776 return Sema::IncompatibleFunctionPointer;
8780 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8781 /// block pointer types are compatible or whether a block and normal pointer
8782 /// are compatible. It is more restrict than comparing two function pointer
8784 static Sema::AssignConvertType
8785 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8787 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8788 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8790 QualType lhptee, rhptee;
8792 // get the "pointed to" type (ignoring qualifiers at the top level)
8793 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8794 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8796 // In C++, the types have to match exactly.
8797 if (S.getLangOpts().CPlusPlus)
8798 return Sema::IncompatibleBlockPointer;
8800 Sema::AssignConvertType ConvTy = Sema::Compatible;
8802 // For blocks we enforce that qualifiers are identical.
8803 Qualifiers LQuals = lhptee.getLocalQualifiers();
8804 Qualifiers RQuals = rhptee.getLocalQualifiers();
8805 if (S.getLangOpts().OpenCL) {
8806 LQuals.removeAddressSpace();
8807 RQuals.removeAddressSpace();
8809 if (LQuals != RQuals)
8810 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8812 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8814 // The current behavior is similar to C++ lambdas. A block might be
8815 // assigned to a variable iff its return type and parameters are compatible
8816 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8817 // an assignment. Presumably it should behave in way that a function pointer
8818 // assignment does in C, so for each parameter and return type:
8819 // * CVR and address space of LHS should be a superset of CVR and address
8821 // * unqualified types should be compatible.
8822 if (S.getLangOpts().OpenCL) {
8823 if (!S.Context.typesAreBlockPointerCompatible(
8824 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8825 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8826 return Sema::IncompatibleBlockPointer;
8827 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8828 return Sema::IncompatibleBlockPointer;
8833 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8834 /// for assignment compatibility.
8835 static Sema::AssignConvertType
8836 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8838 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8839 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8841 if (LHSType->isObjCBuiltinType()) {
8842 // Class is not compatible with ObjC object pointers.
8843 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8844 !RHSType->isObjCQualifiedClassType())
8845 return Sema::IncompatiblePointer;
8846 return Sema::Compatible;
8848 if (RHSType->isObjCBuiltinType()) {
8849 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8850 !LHSType->isObjCQualifiedClassType())
8851 return Sema::IncompatiblePointer;
8852 return Sema::Compatible;
8854 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8855 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8857 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8858 // make an exception for id<P>
8859 !LHSType->isObjCQualifiedIdType())
8860 return Sema::CompatiblePointerDiscardsQualifiers;
8862 if (S.Context.typesAreCompatible(LHSType, RHSType))
8863 return Sema::Compatible;
8864 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8865 return Sema::IncompatibleObjCQualifiedId;
8866 return Sema::IncompatiblePointer;
8869 Sema::AssignConvertType
8870 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8871 QualType LHSType, QualType RHSType) {
8872 // Fake up an opaque expression. We don't actually care about what
8873 // cast operations are required, so if CheckAssignmentConstraints
8874 // adds casts to this they'll be wasted, but fortunately that doesn't
8875 // usually happen on valid code.
8876 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8877 ExprResult RHSPtr = &RHSExpr;
8880 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8883 /// This helper function returns true if QT is a vector type that has element
8884 /// type ElementType.
8885 static bool isVector(QualType QT, QualType ElementType) {
8886 if (const VectorType *VT = QT->getAs<VectorType>())
8887 return VT->getElementType().getCanonicalType() == ElementType;
8891 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8892 /// has code to accommodate several GCC extensions when type checking
8893 /// pointers. Here are some objectionable examples that GCC considers warnings:
8897 /// struct foo *pfoo;
8899 /// pint = pshort; // warning: assignment from incompatible pointer type
8900 /// a = pint; // warning: assignment makes integer from pointer without a cast
8901 /// pint = a; // warning: assignment makes pointer from integer without a cast
8902 /// pint = pfoo; // warning: assignment from incompatible pointer type
8904 /// As a result, the code for dealing with pointers is more complex than the
8905 /// C99 spec dictates.
8907 /// Sets 'Kind' for any result kind except Incompatible.
8908 Sema::AssignConvertType
8909 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8910 CastKind &Kind, bool ConvertRHS) {
8911 QualType RHSType = RHS.get()->getType();
8912 QualType OrigLHSType = LHSType;
8914 // Get canonical types. We're not formatting these types, just comparing
8916 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8917 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8919 // Common case: no conversion required.
8920 if (LHSType == RHSType) {
8925 // If we have an atomic type, try a non-atomic assignment, then just add an
8926 // atomic qualification step.
8927 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8928 Sema::AssignConvertType result =
8929 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8930 if (result != Compatible)
8932 if (Kind != CK_NoOp && ConvertRHS)
8933 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8934 Kind = CK_NonAtomicToAtomic;
8938 // If the left-hand side is a reference type, then we are in a
8939 // (rare!) case where we've allowed the use of references in C,
8940 // e.g., as a parameter type in a built-in function. In this case,
8941 // just make sure that the type referenced is compatible with the
8942 // right-hand side type. The caller is responsible for adjusting
8943 // LHSType so that the resulting expression does not have reference
8945 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8946 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8947 Kind = CK_LValueBitCast;
8950 return Incompatible;
8953 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8954 // to the same ExtVector type.
8955 if (LHSType->isExtVectorType()) {
8956 if (RHSType->isExtVectorType())
8957 return Incompatible;
8958 if (RHSType->isArithmeticType()) {
8959 // CK_VectorSplat does T -> vector T, so first cast to the element type.
8961 RHS = prepareVectorSplat(LHSType, RHS.get());
8962 Kind = CK_VectorSplat;
8967 // Conversions to or from vector type.
8968 if (LHSType->isVectorType() || RHSType->isVectorType()) {
8969 if (LHSType->isVectorType() && RHSType->isVectorType()) {
8970 // Allow assignments of an AltiVec vector type to an equivalent GCC
8971 // vector type and vice versa
8972 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8977 // If we are allowing lax vector conversions, and LHS and RHS are both
8978 // vectors, the total size only needs to be the same. This is a bitcast;
8979 // no bits are changed but the result type is different.
8980 if (isLaxVectorConversion(RHSType, LHSType)) {
8982 return IncompatibleVectors;
8986 // When the RHS comes from another lax conversion (e.g. binops between
8987 // scalars and vectors) the result is canonicalized as a vector. When the
8988 // LHS is also a vector, the lax is allowed by the condition above. Handle
8989 // the case where LHS is a scalar.
8990 if (LHSType->isScalarType()) {
8991 const VectorType *VecType = RHSType->getAs<VectorType>();
8992 if (VecType && VecType->getNumElements() == 1 &&
8993 isLaxVectorConversion(RHSType, LHSType)) {
8994 ExprResult *VecExpr = &RHS;
8995 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9001 return Incompatible;
9004 // Diagnose attempts to convert between __float128 and long double where
9005 // such conversions currently can't be handled.
9006 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9007 return Incompatible;
9009 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9010 // discards the imaginary part.
9011 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9012 !LHSType->getAs<ComplexType>())
9013 return Incompatible;
9015 // Arithmetic conversions.
9016 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9017 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9019 Kind = PrepareScalarCast(RHS, LHSType);
9023 // Conversions to normal pointers.
9024 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9026 if (isa<PointerType>(RHSType)) {
9027 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9028 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9029 if (AddrSpaceL != AddrSpaceR)
9030 Kind = CK_AddressSpaceConversion;
9031 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9035 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9039 if (RHSType->isIntegerType()) {
9040 Kind = CK_IntegralToPointer; // FIXME: null?
9041 return IntToPointer;
9044 // C pointers are not compatible with ObjC object pointers,
9045 // with two exceptions:
9046 if (isa<ObjCObjectPointerType>(RHSType)) {
9047 // - conversions to void*
9048 if (LHSPointer->getPointeeType()->isVoidType()) {
9053 // - conversions from 'Class' to the redefinition type
9054 if (RHSType->isObjCClassType() &&
9055 Context.hasSameType(LHSType,
9056 Context.getObjCClassRedefinitionType())) {
9062 return IncompatiblePointer;
9066 if (RHSType->getAs<BlockPointerType>()) {
9067 if (LHSPointer->getPointeeType()->isVoidType()) {
9068 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9069 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9073 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9078 return Incompatible;
9081 // Conversions to block pointers.
9082 if (isa<BlockPointerType>(LHSType)) {
9084 if (RHSType->isBlockPointerType()) {
9085 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9088 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9091 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9092 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9095 // int or null -> T^
9096 if (RHSType->isIntegerType()) {
9097 Kind = CK_IntegralToPointer; // FIXME: null
9098 return IntToBlockPointer;
9102 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9103 Kind = CK_AnyPointerToBlockPointerCast;
9108 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9109 if (RHSPT->getPointeeType()->isVoidType()) {
9110 Kind = CK_AnyPointerToBlockPointerCast;
9114 return Incompatible;
9117 // Conversions to Objective-C pointers.
9118 if (isa<ObjCObjectPointerType>(LHSType)) {
9120 if (RHSType->isObjCObjectPointerType()) {
9122 Sema::AssignConvertType result =
9123 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9124 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9125 result == Compatible &&
9126 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9127 result = IncompatibleObjCWeakRef;
9131 // int or null -> A*
9132 if (RHSType->isIntegerType()) {
9133 Kind = CK_IntegralToPointer; // FIXME: null
9134 return IntToPointer;
9137 // In general, C pointers are not compatible with ObjC object pointers,
9138 // with two exceptions:
9139 if (isa<PointerType>(RHSType)) {
9140 Kind = CK_CPointerToObjCPointerCast;
9142 // - conversions from 'void*'
9143 if (RHSType->isVoidPointerType()) {
9147 // - conversions to 'Class' from its redefinition type
9148 if (LHSType->isObjCClassType() &&
9149 Context.hasSameType(RHSType,
9150 Context.getObjCClassRedefinitionType())) {
9154 return IncompatiblePointer;
9157 // Only under strict condition T^ is compatible with an Objective-C pointer.
9158 if (RHSType->isBlockPointerType() &&
9159 LHSType->isBlockCompatibleObjCPointerType(Context)) {
9161 maybeExtendBlockObject(RHS);
9162 Kind = CK_BlockPointerToObjCPointerCast;
9166 return Incompatible;
9169 // Conversions from pointers that are not covered by the above.
9170 if (isa<PointerType>(RHSType)) {
9172 if (LHSType == Context.BoolTy) {
9173 Kind = CK_PointerToBoolean;
9178 if (LHSType->isIntegerType()) {
9179 Kind = CK_PointerToIntegral;
9180 return PointerToInt;
9183 return Incompatible;
9186 // Conversions from Objective-C pointers that are not covered by the above.
9187 if (isa<ObjCObjectPointerType>(RHSType)) {
9189 if (LHSType == Context.BoolTy) {
9190 Kind = CK_PointerToBoolean;
9195 if (LHSType->isIntegerType()) {
9196 Kind = CK_PointerToIntegral;
9197 return PointerToInt;
9200 return Incompatible;
9203 // struct A -> struct B
9204 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9205 if (Context.typesAreCompatible(LHSType, RHSType)) {
9211 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9212 Kind = CK_IntToOCLSampler;
9216 return Incompatible;
9219 /// Constructs a transparent union from an expression that is
9220 /// used to initialize the transparent union.
9221 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9222 ExprResult &EResult, QualType UnionType,
9224 // Build an initializer list that designates the appropriate member
9225 // of the transparent union.
9226 Expr *E = EResult.get();
9227 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9228 E, SourceLocation());
9229 Initializer->setType(UnionType);
9230 Initializer->setInitializedFieldInUnion(Field);
9232 // Build a compound literal constructing a value of the transparent
9233 // union type from this initializer list.
9234 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9235 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9236 VK_RValue, Initializer, false);
9239 Sema::AssignConvertType
9240 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9242 QualType RHSType = RHS.get()->getType();
9244 // If the ArgType is a Union type, we want to handle a potential
9245 // transparent_union GCC extension.
9246 const RecordType *UT = ArgType->getAsUnionType();
9247 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9248 return Incompatible;
9250 // The field to initialize within the transparent union.
9251 RecordDecl *UD = UT->getDecl();
9252 FieldDecl *InitField = nullptr;
9253 // It's compatible if the expression matches any of the fields.
9254 for (auto *it : UD->fields()) {
9255 if (it->getType()->isPointerType()) {
9256 // If the transparent union contains a pointer type, we allow:
9258 // 2) null pointer constant
9259 if (RHSType->isPointerType())
9260 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9261 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9266 if (RHS.get()->isNullPointerConstant(Context,
9267 Expr::NPC_ValueDependentIsNull)) {
9268 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9276 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9278 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9285 return Incompatible;
9287 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9291 Sema::AssignConvertType
9292 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9294 bool DiagnoseCFAudited,
9296 // We need to be able to tell the caller whether we diagnosed a problem, if
9297 // they ask us to issue diagnostics.
9298 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9300 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9301 // we can't avoid *all* modifications at the moment, so we need some somewhere
9302 // to put the updated value.
9303 ExprResult LocalRHS = CallerRHS;
9304 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9306 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9307 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9308 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9309 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9310 Diag(RHS.get()->getExprLoc(),
9311 diag::warn_noderef_to_dereferenceable_pointer)
9312 << RHS.get()->getSourceRange();
9317 if (getLangOpts().CPlusPlus) {
9318 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9319 // C++ 5.17p3: If the left operand is not of class type, the
9320 // expression is implicitly converted (C++ 4) to the
9321 // cv-unqualified type of the left operand.
9322 QualType RHSType = RHS.get()->getType();
9324 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9327 ImplicitConversionSequence ICS =
9328 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9329 /*SuppressUserConversions=*/false,
9330 AllowedExplicit::None,
9331 /*InOverloadResolution=*/false,
9333 /*AllowObjCWritebackConversion=*/false);
9334 if (ICS.isFailure())
9335 return Incompatible;
9336 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9339 if (RHS.isInvalid())
9340 return Incompatible;
9341 Sema::AssignConvertType result = Compatible;
9342 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9343 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9344 result = IncompatibleObjCWeakRef;
9348 // FIXME: Currently, we fall through and treat C++ classes like C
9350 // FIXME: We also fall through for atomics; not sure what should
9351 // happen there, though.
9352 } else if (RHS.get()->getType() == Context.OverloadTy) {
9353 // As a set of extensions to C, we support overloading on functions. These
9354 // functions need to be resolved here.
9356 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9357 RHS.get(), LHSType, /*Complain=*/false, DAP))
9358 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9360 return Incompatible;
9363 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9364 // a null pointer constant.
9365 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9366 LHSType->isBlockPointerType()) &&
9367 RHS.get()->isNullPointerConstant(Context,
9368 Expr::NPC_ValueDependentIsNull)) {
9369 if (Diagnose || ConvertRHS) {
9372 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9373 /*IgnoreBaseAccess=*/false, Diagnose);
9375 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9380 // OpenCL queue_t type assignment.
9381 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9382 Context, Expr::NPC_ValueDependentIsNull)) {
9383 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9387 // This check seems unnatural, however it is necessary to ensure the proper
9388 // conversion of functions/arrays. If the conversion were done for all
9389 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9390 // expressions that suppress this implicit conversion (&, sizeof).
9392 // Suppress this for references: C++ 8.5.3p5.
9393 if (!LHSType->isReferenceType()) {
9394 // FIXME: We potentially allocate here even if ConvertRHS is false.
9395 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9396 if (RHS.isInvalid())
9397 return Incompatible;
9400 Sema::AssignConvertType result =
9401 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9403 // C99 6.5.16.1p2: The value of the right operand is converted to the
9404 // type of the assignment expression.
9405 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9406 // so that we can use references in built-in functions even in C.
9407 // The getNonReferenceType() call makes sure that the resulting expression
9408 // does not have reference type.
9409 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9410 QualType Ty = LHSType.getNonLValueExprType(Context);
9411 Expr *E = RHS.get();
9413 // Check for various Objective-C errors. If we are not reporting
9414 // diagnostics and just checking for errors, e.g., during overload
9415 // resolution, return Incompatible to indicate the failure.
9416 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9417 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9418 Diagnose, DiagnoseCFAudited) != ACR_okay) {
9420 return Incompatible;
9422 if (getLangOpts().ObjC &&
9423 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9424 E->getType(), E, Diagnose) ||
9425 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9427 return Incompatible;
9428 // Replace the expression with a corrected version and continue so we
9429 // can find further errors.
9435 RHS = ImpCastExprToType(E, Ty, Kind);
9442 /// The original operand to an operator, prior to the application of the usual
9443 /// arithmetic conversions and converting the arguments of a builtin operator
9445 struct OriginalOperand {
9446 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9447 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9448 Op = MTE->getSubExpr();
9449 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9450 Op = BTE->getSubExpr();
9451 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9452 Orig = ICE->getSubExprAsWritten();
9453 Conversion = ICE->getConversionFunction();
9457 QualType getType() const { return Orig->getType(); }
9460 NamedDecl *Conversion;
9464 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9466 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9468 Diag(Loc, diag::err_typecheck_invalid_operands)
9469 << OrigLHS.getType() << OrigRHS.getType()
9470 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9472 // If a user-defined conversion was applied to either of the operands prior
9473 // to applying the built-in operator rules, tell the user about it.
9474 if (OrigLHS.Conversion) {
9475 Diag(OrigLHS.Conversion->getLocation(),
9476 diag::note_typecheck_invalid_operands_converted)
9477 << 0 << LHS.get()->getType();
9479 if (OrigRHS.Conversion) {
9480 Diag(OrigRHS.Conversion->getLocation(),
9481 diag::note_typecheck_invalid_operands_converted)
9482 << 1 << RHS.get()->getType();
9488 // Diagnose cases where a scalar was implicitly converted to a vector and
9489 // diagnose the underlying types. Otherwise, diagnose the error
9490 // as invalid vector logical operands for non-C++ cases.
9491 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9493 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9494 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9496 bool LHSNatVec = LHSType->isVectorType();
9497 bool RHSNatVec = RHSType->isVectorType();
9499 if (!(LHSNatVec && RHSNatVec)) {
9500 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9501 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9502 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9503 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9504 << Vector->getSourceRange();
9508 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9509 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9510 << RHS.get()->getSourceRange();
9515 /// Try to convert a value of non-vector type to a vector type by converting
9516 /// the type to the element type of the vector and then performing a splat.
9517 /// If the language is OpenCL, we only use conversions that promote scalar
9518 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9521 /// OpenCL V2.0 6.2.6.p2:
9522 /// An error shall occur if any scalar operand type has greater rank
9523 /// than the type of the vector element.
9525 /// \param scalar - if non-null, actually perform the conversions
9526 /// \return true if the operation fails (but without diagnosing the failure)
9527 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9529 QualType vectorEltTy,
9532 // The conversion to apply to the scalar before splatting it,
9534 CastKind scalarCast = CK_NoOp;
9536 if (vectorEltTy->isIntegralType(S.Context)) {
9537 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9538 (scalarTy->isIntegerType() &&
9539 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9540 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9543 if (!scalarTy->isIntegralType(S.Context))
9545 scalarCast = CK_IntegralCast;
9546 } else if (vectorEltTy->isRealFloatingType()) {
9547 if (scalarTy->isRealFloatingType()) {
9548 if (S.getLangOpts().OpenCL &&
9549 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9550 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9553 scalarCast = CK_FloatingCast;
9555 else if (scalarTy->isIntegralType(S.Context))
9556 scalarCast = CK_IntegralToFloating;
9563 // Adjust scalar if desired.
9565 if (scalarCast != CK_NoOp)
9566 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9567 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9572 /// Convert vector E to a vector with the same number of elements but different
9574 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9575 const auto *VecTy = E->getType()->getAs<VectorType>();
9576 assert(VecTy && "Expression E must be a vector");
9577 QualType NewVecTy = S.Context.getVectorType(ElementType,
9578 VecTy->getNumElements(),
9579 VecTy->getVectorKind());
9581 // Look through the implicit cast. Return the subexpression if its type is
9583 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9584 if (ICE->getSubExpr()->getType() == NewVecTy)
9585 return ICE->getSubExpr();
9587 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9588 return S.ImpCastExprToType(E, NewVecTy, Cast);
9591 /// Test if a (constant) integer Int can be casted to another integer type
9592 /// IntTy without losing precision.
9593 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9594 QualType OtherIntTy) {
9595 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9597 // Reject cases where the value of the Int is unknown as that would
9598 // possibly cause truncation, but accept cases where the scalar can be
9599 // demoted without loss of precision.
9600 Expr::EvalResult EVResult;
9601 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9602 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9603 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9604 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9607 // If the scalar is constant and is of a higher order and has more active
9608 // bits that the vector element type, reject it.
9609 llvm::APSInt Result = EVResult.Val.getInt();
9610 unsigned NumBits = IntSigned
9611 ? (Result.isNegative() ? Result.getMinSignedBits()
9612 : Result.getActiveBits())
9613 : Result.getActiveBits();
9614 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9617 // If the signedness of the scalar type and the vector element type
9618 // differs and the number of bits is greater than that of the vector
9619 // element reject it.
9620 return (IntSigned != OtherIntSigned &&
9621 NumBits > S.Context.getIntWidth(OtherIntTy));
9624 // Reject cases where the value of the scalar is not constant and it's
9625 // order is greater than that of the vector element type.
9629 /// Test if a (constant) integer Int can be casted to floating point type
9630 /// FloatTy without losing precision.
9631 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9633 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9635 // Determine if the integer constant can be expressed as a floating point
9636 // number of the appropriate type.
9637 Expr::EvalResult EVResult;
9638 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9642 // Reject constants that would be truncated if they were converted to
9643 // the floating point type. Test by simple to/from conversion.
9644 // FIXME: Ideally the conversion to an APFloat and from an APFloat
9645 // could be avoided if there was a convertFromAPInt method
9646 // which could signal back if implicit truncation occurred.
9647 llvm::APSInt Result = EVResult.Val.getInt();
9648 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9649 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9650 llvm::APFloat::rmTowardZero);
9651 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9652 !IntTy->hasSignedIntegerRepresentation());
9653 bool Ignored = false;
9654 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9656 if (Result != ConvertBack)
9659 // Reject types that cannot be fully encoded into the mantissa of
9661 Bits = S.Context.getTypeSize(IntTy);
9662 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9663 S.Context.getFloatTypeSemantics(FloatTy));
9664 if (Bits > FloatPrec)
9671 /// Attempt to convert and splat Scalar into a vector whose types matches
9672 /// Vector following GCC conversion rules. The rule is that implicit
9673 /// conversion can occur when Scalar can be casted to match Vector's element
9674 /// type without causing truncation of Scalar.
9675 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9676 ExprResult *Vector) {
9677 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9678 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9679 const VectorType *VT = VectorTy->getAs<VectorType>();
9681 assert(!isa<ExtVectorType>(VT) &&
9682 "ExtVectorTypes should not be handled here!");
9684 QualType VectorEltTy = VT->getElementType();
9686 // Reject cases where the vector element type or the scalar element type are
9687 // not integral or floating point types.
9688 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9691 // The conversion to apply to the scalar before splatting it,
9693 CastKind ScalarCast = CK_NoOp;
9695 // Accept cases where the vector elements are integers and the scalar is
9697 // FIXME: Notionally if the scalar was a floating point value with a precise
9698 // integral representation, we could cast it to an appropriate integer
9699 // type and then perform the rest of the checks here. GCC will perform
9700 // this conversion in some cases as determined by the input language.
9701 // We should accept it on a language independent basis.
9702 if (VectorEltTy->isIntegralType(S.Context) &&
9703 ScalarTy->isIntegralType(S.Context) &&
9704 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9706 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9709 ScalarCast = CK_IntegralCast;
9710 } else if (VectorEltTy->isIntegralType(S.Context) &&
9711 ScalarTy->isRealFloatingType()) {
9712 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9713 ScalarCast = CK_FloatingToIntegral;
9716 } else if (VectorEltTy->isRealFloatingType()) {
9717 if (ScalarTy->isRealFloatingType()) {
9719 // Reject cases where the scalar type is not a constant and has a higher
9720 // Order than the vector element type.
9721 llvm::APFloat Result(0.0);
9723 // Determine whether this is a constant scalar. In the event that the
9724 // value is dependent (and thus cannot be evaluated by the constant
9725 // evaluator), skip the evaluation. This will then diagnose once the
9726 // expression is instantiated.
9727 bool CstScalar = Scalar->get()->isValueDependent() ||
9728 Scalar->get()->EvaluateAsFloat(Result, S.Context);
9729 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9730 if (!CstScalar && Order < 0)
9733 // If the scalar cannot be safely casted to the vector element type,
9736 bool Truncated = false;
9737 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9738 llvm::APFloat::rmNearestTiesToEven, &Truncated);
9743 ScalarCast = CK_FloatingCast;
9744 } else if (ScalarTy->isIntegralType(S.Context)) {
9745 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9748 ScalarCast = CK_IntegralToFloating;
9751 } else if (ScalarTy->isEnumeralType())
9754 // Adjust scalar if desired.
9756 if (ScalarCast != CK_NoOp)
9757 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9758 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9763 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9764 SourceLocation Loc, bool IsCompAssign,
9766 bool AllowBoolConversions) {
9767 if (!IsCompAssign) {
9768 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9769 if (LHS.isInvalid())
9772 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9773 if (RHS.isInvalid())
9776 // For conversion purposes, we ignore any qualifiers.
9777 // For example, "const float" and "float" are equivalent.
9778 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9779 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9781 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9782 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9783 assert(LHSVecType || RHSVecType);
9785 // AltiVec-style "vector bool op vector bool" combinations are allowed
9786 // for some operators but not others.
9787 if (!AllowBothBool &&
9788 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9789 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9790 return InvalidOperands(Loc, LHS, RHS);
9792 // If the vector types are identical, return.
9793 if (Context.hasSameType(LHSType, RHSType))
9796 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9797 if (LHSVecType && RHSVecType &&
9798 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9799 if (isa<ExtVectorType>(LHSVecType)) {
9800 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9805 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9809 // AllowBoolConversions says that bool and non-bool AltiVec vectors
9810 // can be mixed, with the result being the non-bool type. The non-bool
9811 // operand must have integer element type.
9812 if (AllowBoolConversions && LHSVecType && RHSVecType &&
9813 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9814 (Context.getTypeSize(LHSVecType->getElementType()) ==
9815 Context.getTypeSize(RHSVecType->getElementType()))) {
9816 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9817 LHSVecType->getElementType()->isIntegerType() &&
9818 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9819 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9822 if (!IsCompAssign &&
9823 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9824 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9825 RHSVecType->getElementType()->isIntegerType()) {
9826 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9831 // If there's a vector type and a scalar, try to convert the scalar to
9832 // the vector element type and splat.
9833 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9835 if (isa<ExtVectorType>(LHSVecType)) {
9836 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9837 LHSVecType->getElementType(), LHSType,
9841 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9846 if (isa<ExtVectorType>(RHSVecType)) {
9847 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9848 LHSType, RHSVecType->getElementType(),
9852 if (LHS.get()->getValueKind() == VK_LValue ||
9853 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9858 // FIXME: The code below also handles conversion between vectors and
9859 // non-scalars, we should break this down into fine grained specific checks
9860 // and emit proper diagnostics.
9861 QualType VecType = LHSVecType ? LHSType : RHSType;
9862 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9863 QualType OtherType = LHSVecType ? RHSType : LHSType;
9864 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9865 if (isLaxVectorConversion(OtherType, VecType)) {
9866 // If we're allowing lax vector conversions, only the total (data) size
9867 // needs to be the same. For non compound assignment, if one of the types is
9868 // scalar, the result is always the vector type.
9869 if (!IsCompAssign) {
9870 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9872 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9873 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9874 // type. Note that this is already done by non-compound assignments in
9875 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9876 // <1 x T> -> T. The result is also a vector type.
9877 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9878 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9879 ExprResult *RHSExpr = &RHS;
9880 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9885 // Okay, the expression is invalid.
9887 // If there's a non-vector, non-real operand, diagnose that.
9888 if ((!RHSVecType && !RHSType->isRealType()) ||
9889 (!LHSVecType && !LHSType->isRealType())) {
9890 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9891 << LHSType << RHSType
9892 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9896 // OpenCL V1.1 6.2.6.p1:
9897 // If the operands are of more than one vector type, then an error shall
9898 // occur. Implicit conversions between vector types are not permitted, per
9900 if (getLangOpts().OpenCL &&
9901 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9902 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9903 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9909 // If there is a vector type that is not a ExtVector and a scalar, we reach
9910 // this point if scalar could not be converted to the vector's element type
9911 // without truncation.
9912 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9913 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9914 QualType Scalar = LHSVecType ? RHSType : LHSType;
9915 QualType Vector = LHSVecType ? LHSType : RHSType;
9916 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9918 diag::err_typecheck_vector_not_convertable_implict_truncation)
9919 << ScalarOrVector << Scalar << Vector;
9924 // Otherwise, use the generic diagnostic.
9926 << LHSType << RHSType
9927 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9931 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9932 // expression. These are mainly cases where the null pointer is used as an
9933 // integer instead of a pointer.
9934 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9935 SourceLocation Loc, bool IsCompare) {
9936 // The canonical way to check for a GNU null is with isNullPointerConstant,
9937 // but we use a bit of a hack here for speed; this is a relatively
9938 // hot path, and isNullPointerConstant is slow.
9939 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9940 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9942 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9944 // Avoid analyzing cases where the result will either be invalid (and
9945 // diagnosed as such) or entirely valid and not something to warn about.
9946 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9947 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9950 // Comparison operations would not make sense with a null pointer no matter
9951 // what the other expression is.
9953 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9954 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9955 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9959 // The rest of the operations only make sense with a null pointer
9960 // if the other expression is a pointer.
9961 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9962 NonNullType->canDecayToPointerType())
9965 S.Diag(Loc, diag::warn_null_in_comparison_operation)
9966 << LHSNull /* LHS is NULL */ << NonNullType
9967 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9970 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9971 SourceLocation Loc) {
9972 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9973 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9976 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9977 RUE->getKind() != UETT_SizeOf)
9980 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9981 QualType LHSTy = LHSArg->getType();
9984 if (RUE->isArgumentType())
9985 RHSTy = RUE->getArgumentType();
9987 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9989 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9990 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9993 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9994 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9995 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9996 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9999 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10000 QualType ArrayElemTy = ArrayTy->getElementType();
10001 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10002 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10003 ArrayElemTy->isCharType() ||
10004 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10006 S.Diag(Loc, diag::warn_division_sizeof_array)
10007 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10008 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10009 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10010 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10014 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10018 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10020 SourceLocation Loc, bool IsDiv) {
10021 // Check for division/remainder by zero.
10022 Expr::EvalResult RHSValue;
10023 if (!RHS.get()->isValueDependent() &&
10024 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10025 RHSValue.Val.getInt() == 0)
10026 S.DiagRuntimeBehavior(Loc, RHS.get(),
10027 S.PDiag(diag::warn_remainder_division_by_zero)
10028 << IsDiv << RHS.get()->getSourceRange());
10031 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10032 SourceLocation Loc,
10033 bool IsCompAssign, bool IsDiv) {
10034 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10036 if (LHS.get()->getType()->isVectorType() ||
10037 RHS.get()->getType()->isVectorType())
10038 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10039 /*AllowBothBool*/getLangOpts().AltiVec,
10040 /*AllowBoolConversions*/false);
10041 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10042 RHS.get()->getType()->isConstantMatrixType()))
10043 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10045 QualType compType = UsualArithmeticConversions(
10046 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10047 if (LHS.isInvalid() || RHS.isInvalid())
10051 if (compType.isNull() || !compType->isArithmeticType())
10052 return InvalidOperands(Loc, LHS, RHS);
10054 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10055 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10060 QualType Sema::CheckRemainderOperands(
10061 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10062 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10064 if (LHS.get()->getType()->isVectorType() ||
10065 RHS.get()->getType()->isVectorType()) {
10066 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10067 RHS.get()->getType()->hasIntegerRepresentation())
10068 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10069 /*AllowBothBool*/getLangOpts().AltiVec,
10070 /*AllowBoolConversions*/false);
10071 return InvalidOperands(Loc, LHS, RHS);
10074 QualType compType = UsualArithmeticConversions(
10075 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10076 if (LHS.isInvalid() || RHS.isInvalid())
10079 if (compType.isNull() || !compType->isIntegerType())
10080 return InvalidOperands(Loc, LHS, RHS);
10081 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10085 /// Diagnose invalid arithmetic on two void pointers.
10086 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10087 Expr *LHSExpr, Expr *RHSExpr) {
10088 S.Diag(Loc, S.getLangOpts().CPlusPlus
10089 ? diag::err_typecheck_pointer_arith_void_type
10090 : diag::ext_gnu_void_ptr)
10091 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10092 << RHSExpr->getSourceRange();
10095 /// Diagnose invalid arithmetic on a void pointer.
10096 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10098 S.Diag(Loc, S.getLangOpts().CPlusPlus
10099 ? diag::err_typecheck_pointer_arith_void_type
10100 : diag::ext_gnu_void_ptr)
10101 << 0 /* one pointer */ << Pointer->getSourceRange();
10104 /// Diagnose invalid arithmetic on a null pointer.
10106 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10107 /// idiom, which we recognize as a GNU extension.
10109 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10110 Expr *Pointer, bool IsGNUIdiom) {
10112 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10113 << Pointer->getSourceRange();
10115 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10116 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10119 /// Diagnose invalid arithmetic on two function pointers.
10120 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10121 Expr *LHS, Expr *RHS) {
10122 assert(LHS->getType()->isAnyPointerType());
10123 assert(RHS->getType()->isAnyPointerType());
10124 S.Diag(Loc, S.getLangOpts().CPlusPlus
10125 ? diag::err_typecheck_pointer_arith_function_type
10126 : diag::ext_gnu_ptr_func_arith)
10127 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10128 // We only show the second type if it differs from the first.
10129 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10131 << RHS->getType()->getPointeeType()
10132 << LHS->getSourceRange() << RHS->getSourceRange();
10135 /// Diagnose invalid arithmetic on a function pointer.
10136 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10138 assert(Pointer->getType()->isAnyPointerType());
10139 S.Diag(Loc, S.getLangOpts().CPlusPlus
10140 ? diag::err_typecheck_pointer_arith_function_type
10141 : diag::ext_gnu_ptr_func_arith)
10142 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10143 << 0 /* one pointer, so only one type */
10144 << Pointer->getSourceRange();
10147 /// Emit error if Operand is incomplete pointer type
10149 /// \returns True if pointer has incomplete type
10150 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10152 QualType ResType = Operand->getType();
10153 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10154 ResType = ResAtomicType->getValueType();
10156 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10157 QualType PointeeTy = ResType->getPointeeType();
10158 return S.RequireCompleteSizedType(
10160 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10161 Operand->getSourceRange());
10164 /// Check the validity of an arithmetic pointer operand.
10166 /// If the operand has pointer type, this code will check for pointer types
10167 /// which are invalid in arithmetic operations. These will be diagnosed
10168 /// appropriately, including whether or not the use is supported as an
10171 /// \returns True when the operand is valid to use (even if as an extension).
10172 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10174 QualType ResType = Operand->getType();
10175 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10176 ResType = ResAtomicType->getValueType();
10178 if (!ResType->isAnyPointerType()) return true;
10180 QualType PointeeTy = ResType->getPointeeType();
10181 if (PointeeTy->isVoidType()) {
10182 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10183 return !S.getLangOpts().CPlusPlus;
10185 if (PointeeTy->isFunctionType()) {
10186 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10187 return !S.getLangOpts().CPlusPlus;
10190 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10195 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10198 /// This routine will diagnose any invalid arithmetic on pointer operands much
10199 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10200 /// for emitting a single diagnostic even for operations where both LHS and RHS
10201 /// are (potentially problematic) pointers.
10203 /// \returns True when the operand is valid to use (even if as an extension).
10204 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10205 Expr *LHSExpr, Expr *RHSExpr) {
10206 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10207 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10208 if (!isLHSPointer && !isRHSPointer) return true;
10210 QualType LHSPointeeTy, RHSPointeeTy;
10211 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10212 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10214 // if both are pointers check if operation is valid wrt address spaces
10215 if (isLHSPointer && isRHSPointer) {
10216 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10218 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10219 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10220 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10225 // Check for arithmetic on pointers to incomplete types.
10226 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10227 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10228 if (isLHSVoidPtr || isRHSVoidPtr) {
10229 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10230 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10231 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10233 return !S.getLangOpts().CPlusPlus;
10236 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10237 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10238 if (isLHSFuncPtr || isRHSFuncPtr) {
10239 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10240 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10242 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10244 return !S.getLangOpts().CPlusPlus;
10247 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10249 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10255 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10257 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10258 Expr *LHSExpr, Expr *RHSExpr) {
10259 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10260 Expr* IndexExpr = RHSExpr;
10262 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10263 IndexExpr = LHSExpr;
10266 bool IsStringPlusInt = StrExpr &&
10267 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10268 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10271 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10272 Self.Diag(OpLoc, diag::warn_string_plus_int)
10273 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10275 // Only print a fixit for "str" + int, not for int + "str".
10276 if (IndexExpr == RHSExpr) {
10277 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10278 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10279 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10280 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10281 << FixItHint::CreateInsertion(EndLoc, "]");
10283 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10286 /// Emit a warning when adding a char literal to a string.
10287 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10288 Expr *LHSExpr, Expr *RHSExpr) {
10289 const Expr *StringRefExpr = LHSExpr;
10290 const CharacterLiteral *CharExpr =
10291 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10294 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10295 StringRefExpr = RHSExpr;
10298 if (!CharExpr || !StringRefExpr)
10301 const QualType StringType = StringRefExpr->getType();
10303 // Return if not a PointerType.
10304 if (!StringType->isAnyPointerType())
10307 // Return if not a CharacterType.
10308 if (!StringType->getPointeeType()->isAnyCharacterType())
10311 ASTContext &Ctx = Self.getASTContext();
10312 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10314 const QualType CharType = CharExpr->getType();
10315 if (!CharType->isAnyCharacterType() &&
10316 CharType->isIntegerType() &&
10317 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10318 Self.Diag(OpLoc, diag::warn_string_plus_char)
10319 << DiagRange << Ctx.CharTy;
10321 Self.Diag(OpLoc, diag::warn_string_plus_char)
10322 << DiagRange << CharExpr->getType();
10325 // Only print a fixit for str + char, not for char + str.
10326 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10327 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10328 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10329 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10330 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10331 << FixItHint::CreateInsertion(EndLoc, "]");
10333 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10337 /// Emit error when two pointers are incompatible.
10338 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10339 Expr *LHSExpr, Expr *RHSExpr) {
10340 assert(LHSExpr->getType()->isAnyPointerType());
10341 assert(RHSExpr->getType()->isAnyPointerType());
10342 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10343 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10344 << RHSExpr->getSourceRange();
10348 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10349 SourceLocation Loc, BinaryOperatorKind Opc,
10350 QualType* CompLHSTy) {
10351 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10353 if (LHS.get()->getType()->isVectorType() ||
10354 RHS.get()->getType()->isVectorType()) {
10355 QualType compType = CheckVectorOperands(
10356 LHS, RHS, Loc, CompLHSTy,
10357 /*AllowBothBool*/getLangOpts().AltiVec,
10358 /*AllowBoolConversions*/getLangOpts().ZVector);
10359 if (CompLHSTy) *CompLHSTy = compType;
10363 if (LHS.get()->getType()->isConstantMatrixType() ||
10364 RHS.get()->getType()->isConstantMatrixType()) {
10365 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10368 QualType compType = UsualArithmeticConversions(
10369 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10370 if (LHS.isInvalid() || RHS.isInvalid())
10373 // Diagnose "string literal" '+' int and string '+' "char literal".
10374 if (Opc == BO_Add) {
10375 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10376 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10379 // handle the common case first (both operands are arithmetic).
10380 if (!compType.isNull() && compType->isArithmeticType()) {
10381 if (CompLHSTy) *CompLHSTy = compType;
10385 // Type-checking. Ultimately the pointer's going to be in PExp;
10386 // note that we bias towards the LHS being the pointer.
10387 Expr *PExp = LHS.get(), *IExp = RHS.get();
10389 bool isObjCPointer;
10390 if (PExp->getType()->isPointerType()) {
10391 isObjCPointer = false;
10392 } else if (PExp->getType()->isObjCObjectPointerType()) {
10393 isObjCPointer = true;
10395 std::swap(PExp, IExp);
10396 if (PExp->getType()->isPointerType()) {
10397 isObjCPointer = false;
10398 } else if (PExp->getType()->isObjCObjectPointerType()) {
10399 isObjCPointer = true;
10401 return InvalidOperands(Loc, LHS, RHS);
10404 assert(PExp->getType()->isAnyPointerType());
10406 if (!IExp->getType()->isIntegerType())
10407 return InvalidOperands(Loc, LHS, RHS);
10409 // Adding to a null pointer results in undefined behavior.
10410 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10411 Context, Expr::NPC_ValueDependentIsNotNull)) {
10412 // In C++ adding zero to a null pointer is defined.
10413 Expr::EvalResult KnownVal;
10414 if (!getLangOpts().CPlusPlus ||
10415 (!IExp->isValueDependent() &&
10416 (!IExp->EvaluateAsInt(KnownVal, Context) ||
10417 KnownVal.Val.getInt() != 0))) {
10418 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10419 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10420 Context, BO_Add, PExp, IExp);
10421 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10425 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10428 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10431 // Check array bounds for pointer arithemtic
10432 CheckArrayAccess(PExp, IExp);
10435 QualType LHSTy = Context.isPromotableBitField(LHS.get());
10436 if (LHSTy.isNull()) {
10437 LHSTy = LHS.get()->getType();
10438 if (LHSTy->isPromotableIntegerType())
10439 LHSTy = Context.getPromotedIntegerType(LHSTy);
10441 *CompLHSTy = LHSTy;
10444 return PExp->getType();
10448 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10449 SourceLocation Loc,
10450 QualType* CompLHSTy) {
10451 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10453 if (LHS.get()->getType()->isVectorType() ||
10454 RHS.get()->getType()->isVectorType()) {
10455 QualType compType = CheckVectorOperands(
10456 LHS, RHS, Loc, CompLHSTy,
10457 /*AllowBothBool*/getLangOpts().AltiVec,
10458 /*AllowBoolConversions*/getLangOpts().ZVector);
10459 if (CompLHSTy) *CompLHSTy = compType;
10463 if (LHS.get()->getType()->isConstantMatrixType() ||
10464 RHS.get()->getType()->isConstantMatrixType()) {
10465 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10468 QualType compType = UsualArithmeticConversions(
10469 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10470 if (LHS.isInvalid() || RHS.isInvalid())
10473 // Enforce type constraints: C99 6.5.6p3.
10475 // Handle the common case first (both operands are arithmetic).
10476 if (!compType.isNull() && compType->isArithmeticType()) {
10477 if (CompLHSTy) *CompLHSTy = compType;
10481 // Either ptr - int or ptr - ptr.
10482 if (LHS.get()->getType()->isAnyPointerType()) {
10483 QualType lpointee = LHS.get()->getType()->getPointeeType();
10485 // Diagnose bad cases where we step over interface counts.
10486 if (LHS.get()->getType()->isObjCObjectPointerType() &&
10487 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10490 // The result type of a pointer-int computation is the pointer type.
10491 if (RHS.get()->getType()->isIntegerType()) {
10492 // Subtracting from a null pointer should produce a warning.
10493 // The last argument to the diagnose call says this doesn't match the
10494 // GNU int-to-pointer idiom.
10495 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10496 Expr::NPC_ValueDependentIsNotNull)) {
10497 // In C++ adding zero to a null pointer is defined.
10498 Expr::EvalResult KnownVal;
10499 if (!getLangOpts().CPlusPlus ||
10500 (!RHS.get()->isValueDependent() &&
10501 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10502 KnownVal.Val.getInt() != 0))) {
10503 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10507 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10510 // Check array bounds for pointer arithemtic
10511 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10512 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10514 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10515 return LHS.get()->getType();
10518 // Handle pointer-pointer subtractions.
10519 if (const PointerType *RHSPTy
10520 = RHS.get()->getType()->getAs<PointerType>()) {
10521 QualType rpointee = RHSPTy->getPointeeType();
10523 if (getLangOpts().CPlusPlus) {
10524 // Pointee types must be the same: C++ [expr.add]
10525 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10526 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10529 // Pointee types must be compatible C99 6.5.6p3
10530 if (!Context.typesAreCompatible(
10531 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10532 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10533 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10538 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10539 LHS.get(), RHS.get()))
10542 // FIXME: Add warnings for nullptr - ptr.
10544 // The pointee type may have zero size. As an extension, a structure or
10545 // union may have zero size or an array may have zero length. In this
10546 // case subtraction does not make sense.
10547 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10548 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10549 if (ElementSize.isZero()) {
10550 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10551 << rpointee.getUnqualifiedType()
10552 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10556 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10557 return Context.getPointerDiffType();
10561 return InvalidOperands(Loc, LHS, RHS);
10564 static bool isScopedEnumerationType(QualType T) {
10565 if (const EnumType *ET = T->getAs<EnumType>())
10566 return ET->getDecl()->isScoped();
10570 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10571 SourceLocation Loc, BinaryOperatorKind Opc,
10572 QualType LHSType) {
10573 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10574 // so skip remaining warnings as we don't want to modify values within Sema.
10575 if (S.getLangOpts().OpenCL)
10578 // Check right/shifter operand
10579 Expr::EvalResult RHSResult;
10580 if (RHS.get()->isValueDependent() ||
10581 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10583 llvm::APSInt Right = RHSResult.Val.getInt();
10585 if (Right.isNegative()) {
10586 S.DiagRuntimeBehavior(Loc, RHS.get(),
10587 S.PDiag(diag::warn_shift_negative)
10588 << RHS.get()->getSourceRange());
10592 QualType LHSExprType = LHS.get()->getType();
10593 uint64_t LeftSize = LHSExprType->isExtIntType()
10594 ? S.Context.getIntWidth(LHSExprType)
10595 : S.Context.getTypeSize(LHSExprType);
10596 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10597 if (Right.uge(LeftBits)) {
10598 S.DiagRuntimeBehavior(Loc, RHS.get(),
10599 S.PDiag(diag::warn_shift_gt_typewidth)
10600 << RHS.get()->getSourceRange());
10607 // When left shifting an ICE which is signed, we can check for overflow which
10608 // according to C++ standards prior to C++2a has undefined behavior
10609 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10610 // more than the maximum value representable in the result type, so never
10611 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10612 // expression is still probably a bug.)
10613 Expr::EvalResult LHSResult;
10614 if (LHS.get()->isValueDependent() ||
10615 LHSType->hasUnsignedIntegerRepresentation() ||
10616 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10618 llvm::APSInt Left = LHSResult.Val.getInt();
10620 // If LHS does not have a signed type and non-negative value
10621 // then, the behavior is undefined before C++2a. Warn about it.
10622 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10623 !S.getLangOpts().CPlusPlus20) {
10624 S.DiagRuntimeBehavior(Loc, LHS.get(),
10625 S.PDiag(diag::warn_shift_lhs_negative)
10626 << LHS.get()->getSourceRange());
10630 llvm::APInt ResultBits =
10631 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10632 if (LeftBits.uge(ResultBits))
10634 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10635 Result = Result.shl(Right);
10637 // Print the bit representation of the signed integer as an unsigned
10638 // hexadecimal number.
10639 SmallString<40> HexResult;
10640 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10642 // If we are only missing a sign bit, this is less likely to result in actual
10643 // bugs -- if the result is cast back to an unsigned type, it will have the
10644 // expected value. Thus we place this behind a different warning that can be
10645 // turned off separately if needed.
10646 if (LeftBits == ResultBits - 1) {
10647 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10648 << HexResult << LHSType
10649 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10653 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10654 << HexResult.str() << Result.getMinSignedBits() << LHSType
10655 << Left.getBitWidth() << LHS.get()->getSourceRange()
10656 << RHS.get()->getSourceRange();
10659 /// Return the resulting type when a vector is shifted
10660 /// by a scalar or vector shift amount.
10661 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10662 SourceLocation Loc, bool IsCompAssign) {
10663 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10664 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10665 !LHS.get()->getType()->isVectorType()) {
10666 S.Diag(Loc, diag::err_shift_rhs_only_vector)
10667 << RHS.get()->getType() << LHS.get()->getType()
10668 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10672 if (!IsCompAssign) {
10673 LHS = S.UsualUnaryConversions(LHS.get());
10674 if (LHS.isInvalid()) return QualType();
10677 RHS = S.UsualUnaryConversions(RHS.get());
10678 if (RHS.isInvalid()) return QualType();
10680 QualType LHSType = LHS.get()->getType();
10681 // Note that LHS might be a scalar because the routine calls not only in
10683 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10684 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10686 // Note that RHS might not be a vector.
10687 QualType RHSType = RHS.get()->getType();
10688 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10689 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10691 // The operands need to be integers.
10692 if (!LHSEleType->isIntegerType()) {
10693 S.Diag(Loc, diag::err_typecheck_expect_int)
10694 << LHS.get()->getType() << LHS.get()->getSourceRange();
10698 if (!RHSEleType->isIntegerType()) {
10699 S.Diag(Loc, diag::err_typecheck_expect_int)
10700 << RHS.get()->getType() << RHS.get()->getSourceRange();
10708 if (LHSEleType != RHSEleType) {
10709 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10710 LHSEleType = RHSEleType;
10713 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10714 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10716 } else if (RHSVecTy) {
10717 // OpenCL v1.1 s6.3.j says that for vector types, the operators
10718 // are applied component-wise. So if RHS is a vector, then ensure
10719 // that the number of elements is the same as LHS...
10720 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10721 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10722 << LHS.get()->getType() << RHS.get()->getType()
10723 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10726 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10727 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10728 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10729 if (LHSBT != RHSBT &&
10730 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10731 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10732 << LHS.get()->getType() << RHS.get()->getType()
10733 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10737 // ...else expand RHS to match the number of elements in LHS.
10739 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10740 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10747 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10748 SourceLocation Loc, BinaryOperatorKind Opc,
10749 bool IsCompAssign) {
10750 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10752 // Vector shifts promote their scalar inputs to vector type.
10753 if (LHS.get()->getType()->isVectorType() ||
10754 RHS.get()->getType()->isVectorType()) {
10755 if (LangOpts.ZVector) {
10756 // The shift operators for the z vector extensions work basically
10757 // like general shifts, except that neither the LHS nor the RHS is
10758 // allowed to be a "vector bool".
10759 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10760 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10761 return InvalidOperands(Loc, LHS, RHS);
10762 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10763 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10764 return InvalidOperands(Loc, LHS, RHS);
10766 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10769 // Shifts don't perform usual arithmetic conversions, they just do integer
10770 // promotions on each operand. C99 6.5.7p3
10772 // For the LHS, do usual unary conversions, but then reset them away
10773 // if this is a compound assignment.
10774 ExprResult OldLHS = LHS;
10775 LHS = UsualUnaryConversions(LHS.get());
10776 if (LHS.isInvalid())
10778 QualType LHSType = LHS.get()->getType();
10779 if (IsCompAssign) LHS = OldLHS;
10781 // The RHS is simpler.
10782 RHS = UsualUnaryConversions(RHS.get());
10783 if (RHS.isInvalid())
10785 QualType RHSType = RHS.get()->getType();
10787 // C99 6.5.7p2: Each of the operands shall have integer type.
10788 if (!LHSType->hasIntegerRepresentation() ||
10789 !RHSType->hasIntegerRepresentation())
10790 return InvalidOperands(Loc, LHS, RHS);
10792 // C++0x: Don't allow scoped enums. FIXME: Use something better than
10793 // hasIntegerRepresentation() above instead of this.
10794 if (isScopedEnumerationType(LHSType) ||
10795 isScopedEnumerationType(RHSType)) {
10796 return InvalidOperands(Loc, LHS, RHS);
10798 // Sanity-check shift operands
10799 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10801 // "The type of the result is that of the promoted left operand."
10805 /// Diagnose bad pointer comparisons.
10806 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10807 ExprResult &LHS, ExprResult &RHS,
10809 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10810 : diag::ext_typecheck_comparison_of_distinct_pointers)
10811 << LHS.get()->getType() << RHS.get()->getType()
10812 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10815 /// Returns false if the pointers are converted to a composite type,
10816 /// true otherwise.
10817 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10818 ExprResult &LHS, ExprResult &RHS) {
10819 // C++ [expr.rel]p2:
10820 // [...] Pointer conversions (4.10) and qualification
10821 // conversions (4.4) are performed on pointer operands (or on
10822 // a pointer operand and a null pointer constant) to bring
10823 // them to their composite pointer type. [...]
10825 // C++ [expr.eq]p1 uses the same notion for (in)equality
10826 // comparisons of pointers.
10828 QualType LHSType = LHS.get()->getType();
10829 QualType RHSType = RHS.get()->getType();
10830 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10831 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10833 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10835 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10836 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10837 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10839 S.InvalidOperands(Loc, LHS, RHS);
10846 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10850 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10851 : diag::ext_typecheck_comparison_of_fptr_to_void)
10852 << LHS.get()->getType() << RHS.get()->getType()
10853 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10856 static bool isObjCObjectLiteral(ExprResult &E) {
10857 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10858 case Stmt::ObjCArrayLiteralClass:
10859 case Stmt::ObjCDictionaryLiteralClass:
10860 case Stmt::ObjCStringLiteralClass:
10861 case Stmt::ObjCBoxedExprClass:
10864 // Note that ObjCBoolLiteral is NOT an object literal!
10869 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10870 const ObjCObjectPointerType *Type =
10871 LHS->getType()->getAs<ObjCObjectPointerType>();
10873 // If this is not actually an Objective-C object, bail out.
10877 // Get the LHS object's interface type.
10878 QualType InterfaceType = Type->getPointeeType();
10880 // If the RHS isn't an Objective-C object, bail out.
10881 if (!RHS->getType()->isObjCObjectPointerType())
10884 // Try to find the -isEqual: method.
10885 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10886 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10888 /*IsInstance=*/true);
10890 if (Type->isObjCIdType()) {
10891 // For 'id', just check the global pool.
10892 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10893 /*receiverId=*/true);
10895 // Check protocols.
10896 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10897 /*IsInstance=*/true);
10904 QualType T = Method->parameters()[0]->getType();
10905 if (!T->isObjCObjectPointerType())
10908 QualType R = Method->getReturnType();
10909 if (!R->isScalarType())
10915 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10916 FromE = FromE->IgnoreParenImpCasts();
10917 switch (FromE->getStmtClass()) {
10920 case Stmt::ObjCStringLiteralClass:
10921 // "string literal"
10923 case Stmt::ObjCArrayLiteralClass:
10926 case Stmt::ObjCDictionaryLiteralClass:
10927 // "dictionary literal"
10928 return LK_Dictionary;
10929 case Stmt::BlockExprClass:
10931 case Stmt::ObjCBoxedExprClass: {
10932 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10933 switch (Inner->getStmtClass()) {
10934 case Stmt::IntegerLiteralClass:
10935 case Stmt::FloatingLiteralClass:
10936 case Stmt::CharacterLiteralClass:
10937 case Stmt::ObjCBoolLiteralExprClass:
10938 case Stmt::CXXBoolLiteralExprClass:
10939 // "numeric literal"
10941 case Stmt::ImplicitCastExprClass: {
10942 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10943 // Boolean literals can be represented by implicit casts.
10944 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10957 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10958 ExprResult &LHS, ExprResult &RHS,
10959 BinaryOperator::Opcode Opc){
10962 if (isObjCObjectLiteral(LHS)) {
10963 Literal = LHS.get();
10966 Literal = RHS.get();
10970 // Don't warn on comparisons against nil.
10971 Other = Other->IgnoreParenCasts();
10972 if (Other->isNullPointerConstant(S.getASTContext(),
10973 Expr::NPC_ValueDependentIsNotNull))
10976 // This should be kept in sync with warn_objc_literal_comparison.
10977 // LK_String should always be after the other literals, since it has its own
10979 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10980 assert(LiteralKind != Sema::LK_Block);
10981 if (LiteralKind == Sema::LK_None) {
10982 llvm_unreachable("Unknown Objective-C object literal kind");
10985 if (LiteralKind == Sema::LK_String)
10986 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10987 << Literal->getSourceRange();
10989 S.Diag(Loc, diag::warn_objc_literal_comparison)
10990 << LiteralKind << Literal->getSourceRange();
10992 if (BinaryOperator::isEqualityOp(Opc) &&
10993 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10994 SourceLocation Start = LHS.get()->getBeginLoc();
10995 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10996 CharSourceRange OpRange =
10997 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10999 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11000 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11001 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11002 << FixItHint::CreateInsertion(End, "]");
11006 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11007 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11008 ExprResult &RHS, SourceLocation Loc,
11009 BinaryOperatorKind Opc) {
11010 // Check that left hand side is !something.
11011 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11012 if (!UO || UO->getOpcode() != UO_LNot) return;
11014 // Only check if the right hand side is non-bool arithmetic type.
11015 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11017 // Make sure that the something in !something is not bool.
11018 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11019 if (SubExpr->isKnownToHaveBooleanValue()) return;
11022 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11023 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11024 << Loc << IsBitwiseOp;
11026 // First note suggest !(x < y)
11027 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11028 SourceLocation FirstClose = RHS.get()->getEndLoc();
11029 FirstClose = S.getLocForEndOfToken(FirstClose);
11030 if (FirstClose.isInvalid())
11031 FirstOpen = SourceLocation();
11032 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11034 << FixItHint::CreateInsertion(FirstOpen, "(")
11035 << FixItHint::CreateInsertion(FirstClose, ")");
11037 // Second note suggests (!x) < y
11038 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11039 SourceLocation SecondClose = LHS.get()->getEndLoc();
11040 SecondClose = S.getLocForEndOfToken(SecondClose);
11041 if (SecondClose.isInvalid())
11042 SecondOpen = SourceLocation();
11043 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11044 << FixItHint::CreateInsertion(SecondOpen, "(")
11045 << FixItHint::CreateInsertion(SecondClose, ")");
11048 // Returns true if E refers to a non-weak array.
11049 static bool checkForArray(const Expr *E) {
11050 const ValueDecl *D = nullptr;
11051 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11053 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11054 if (Mem->isImplicitAccess())
11055 D = Mem->getMemberDecl();
11059 return D->getType()->isArrayType() && !D->isWeak();
11062 /// Diagnose some forms of syntactically-obvious tautological comparison.
11063 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11064 Expr *LHS, Expr *RHS,
11065 BinaryOperatorKind Opc) {
11066 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11067 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11069 QualType LHSType = LHS->getType();
11070 QualType RHSType = RHS->getType();
11071 if (LHSType->hasFloatingRepresentation() ||
11072 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11073 S.inTemplateInstantiation())
11076 // Comparisons between two array types are ill-formed for operator<=>, so
11077 // we shouldn't emit any additional warnings about it.
11078 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11081 // For non-floating point types, check for self-comparisons of the form
11082 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11083 // often indicate logic errors in the program.
11085 // NOTE: Don't warn about comparison expressions resulting from macro
11086 // expansion. Also don't warn about comparisons which are only self
11087 // comparisons within a template instantiation. The warnings should catch
11088 // obvious cases in the definition of the template anyways. The idea is to
11089 // warn when the typed comparison operator will always evaluate to the same
11092 // Used for indexing into %select in warn_comparison_always
11097 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11100 // C++2a [depr.array.comp]:
11101 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11102 // operands of array type are deprecated.
11103 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11104 RHSStripped->getType()->isArrayType()) {
11105 S.Diag(Loc, diag::warn_depr_array_comparison)
11106 << LHS->getSourceRange() << RHS->getSourceRange()
11107 << LHSStripped->getType() << RHSStripped->getType();
11108 // Carry on to produce the tautological comparison warning, if this
11109 // expression is potentially-evaluated, we can resolve the array to a
11110 // non-weak declaration, and so on.
11113 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11114 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11120 Result = AlwaysTrue;
11125 Result = AlwaysFalse;
11128 Result = AlwaysEqual;
11131 Result = AlwaysConstant;
11134 S.DiagRuntimeBehavior(Loc, nullptr,
11135 S.PDiag(diag::warn_comparison_always)
11136 << 0 /*self-comparison*/
11138 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11139 // What is it always going to evaluate to?
11142 case BO_EQ: // e.g. array1 == array2
11143 Result = AlwaysFalse;
11145 case BO_NE: // e.g. array1 != array2
11146 Result = AlwaysTrue;
11148 default: // e.g. array1 <= array2
11149 // The best we can say is 'a constant'
11150 Result = AlwaysConstant;
11153 S.DiagRuntimeBehavior(Loc, nullptr,
11154 S.PDiag(diag::warn_comparison_always)
11155 << 1 /*array comparison*/
11160 if (isa<CastExpr>(LHSStripped))
11161 LHSStripped = LHSStripped->IgnoreParenCasts();
11162 if (isa<CastExpr>(RHSStripped))
11163 RHSStripped = RHSStripped->IgnoreParenCasts();
11165 // Warn about comparisons against a string constant (unless the other
11166 // operand is null); the user probably wants string comparison function.
11167 Expr *LiteralString = nullptr;
11168 Expr *LiteralStringStripped = nullptr;
11169 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11170 !RHSStripped->isNullPointerConstant(S.Context,
11171 Expr::NPC_ValueDependentIsNull)) {
11172 LiteralString = LHS;
11173 LiteralStringStripped = LHSStripped;
11174 } else if ((isa<StringLiteral>(RHSStripped) ||
11175 isa<ObjCEncodeExpr>(RHSStripped)) &&
11176 !LHSStripped->isNullPointerConstant(S.Context,
11177 Expr::NPC_ValueDependentIsNull)) {
11178 LiteralString = RHS;
11179 LiteralStringStripped = RHSStripped;
11182 if (LiteralString) {
11183 S.DiagRuntimeBehavior(Loc, nullptr,
11184 S.PDiag(diag::warn_stringcompare)
11185 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11186 << LiteralString->getSourceRange());
11190 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11194 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11197 llvm_unreachable("unhandled cast kind");
11199 case CK_UserDefinedConversion:
11200 return ICK_Identity;
11201 case CK_LValueToRValue:
11202 return ICK_Lvalue_To_Rvalue;
11203 case CK_ArrayToPointerDecay:
11204 return ICK_Array_To_Pointer;
11205 case CK_FunctionToPointerDecay:
11206 return ICK_Function_To_Pointer;
11207 case CK_IntegralCast:
11208 return ICK_Integral_Conversion;
11209 case CK_FloatingCast:
11210 return ICK_Floating_Conversion;
11211 case CK_IntegralToFloating:
11212 case CK_FloatingToIntegral:
11213 return ICK_Floating_Integral;
11214 case CK_IntegralComplexCast:
11215 case CK_FloatingComplexCast:
11216 case CK_FloatingComplexToIntegralComplex:
11217 case CK_IntegralComplexToFloatingComplex:
11218 return ICK_Complex_Conversion;
11219 case CK_FloatingComplexToReal:
11220 case CK_FloatingRealToComplex:
11221 case CK_IntegralComplexToReal:
11222 case CK_IntegralRealToComplex:
11223 return ICK_Complex_Real;
11227 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11229 SourceLocation Loc) {
11230 // Check for a narrowing implicit conversion.
11231 StandardConversionSequence SCS;
11232 SCS.setAsIdentityConversion();
11233 SCS.setToType(0, FromType);
11234 SCS.setToType(1, ToType);
11235 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11236 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11238 APValue PreNarrowingValue;
11239 QualType PreNarrowingType;
11240 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11242 /*IgnoreFloatToIntegralConversion*/ true)) {
11243 case NK_Dependent_Narrowing:
11244 // Implicit conversion to a narrower type, but the expression is
11245 // value-dependent so we can't tell whether it's actually narrowing.
11246 case NK_Not_Narrowing:
11249 case NK_Constant_Narrowing:
11250 // Implicit conversion to a narrower type, and the value is not a constant
11252 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11254 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11257 case NK_Variable_Narrowing:
11258 // Implicit conversion to a narrower type, and the value is not a constant
11260 case NK_Type_Narrowing:
11261 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11262 << /*Constant*/ 0 << FromType << ToType;
11263 // TODO: It's not a constant expression, but what if the user intended it
11264 // to be? Can we produce notes to help them figure out why it isn't?
11267 llvm_unreachable("unhandled case in switch");
11270 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11273 SourceLocation Loc) {
11274 QualType LHSType = LHS.get()->getType();
11275 QualType RHSType = RHS.get()->getType();
11276 // Dig out the original argument type and expression before implicit casts
11277 // were applied. These are the types/expressions we need to check the
11278 // [expr.spaceship] requirements against.
11279 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11280 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11281 QualType LHSStrippedType = LHSStripped.get()->getType();
11282 QualType RHSStrippedType = RHSStripped.get()->getType();
11284 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11285 // other is not, the program is ill-formed.
11286 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11287 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11291 // FIXME: Consider combining this with checkEnumArithmeticConversions.
11292 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11293 RHSStrippedType->isEnumeralType();
11294 if (NumEnumArgs == 1) {
11295 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11296 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11297 if (OtherTy->hasFloatingRepresentation()) {
11298 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11302 if (NumEnumArgs == 2) {
11303 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11304 // type E, the operator yields the result of converting the operands
11305 // to the underlying type of E and applying <=> to the converted operands.
11306 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11307 S.InvalidOperands(Loc, LHS, RHS);
11311 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11312 assert(IntType->isArithmeticType());
11314 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11315 // promote the boolean type, and all other promotable integer types, to
11317 if (IntType->isPromotableIntegerType())
11318 IntType = S.Context.getPromotedIntegerType(IntType);
11320 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11321 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11322 LHSType = RHSType = IntType;
11325 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11326 // usual arithmetic conversions are applied to the operands.
11328 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11329 if (LHS.isInvalid() || RHS.isInvalid())
11332 return S.InvalidOperands(Loc, LHS, RHS);
11334 Optional<ComparisonCategoryType> CCT =
11335 getComparisonCategoryForBuiltinCmp(Type);
11337 return S.InvalidOperands(Loc, LHS, RHS);
11339 bool HasNarrowing = checkThreeWayNarrowingConversion(
11340 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11341 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11342 RHS.get()->getBeginLoc());
11346 assert(!Type.isNull() && "composite type for <=> has not been set");
11348 return S.CheckComparisonCategoryType(
11349 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11352 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11354 SourceLocation Loc,
11355 BinaryOperatorKind Opc) {
11357 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11359 // C99 6.5.8p3 / C99 6.5.9p4
11361 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11362 if (LHS.isInvalid() || RHS.isInvalid())
11365 return S.InvalidOperands(Loc, LHS, RHS);
11366 assert(Type->isArithmeticType() || Type->isEnumeralType());
11368 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11369 return S.InvalidOperands(Loc, LHS, RHS);
11371 // Check for comparisons of floating point operands using != and ==.
11372 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11373 S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11375 // The result of comparisons is 'bool' in C++, 'int' in C.
11376 return S.Context.getLogicalOperationType();
11379 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11380 if (!NullE.get()->getType()->isAnyPointerType())
11382 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11383 if (!E.get()->getType()->isAnyPointerType() &&
11384 E.get()->isNullPointerConstant(Context,
11385 Expr::NPC_ValueDependentIsNotNull) ==
11386 Expr::NPCK_ZeroExpression) {
11387 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11388 if (CL->getValue() == 0)
11389 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11391 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11392 NullValue ? "NULL" : "(void *)0");
11393 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11394 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11395 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11396 if (T == Context.CharTy)
11397 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11399 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11400 NullValue ? "NULL" : "(void *)0");
11405 // C99 6.5.8, C++ [expr.rel]
11406 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11407 SourceLocation Loc,
11408 BinaryOperatorKind Opc) {
11409 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11410 bool IsThreeWay = Opc == BO_Cmp;
11411 bool IsOrdered = IsRelational || IsThreeWay;
11412 auto IsAnyPointerType = [](ExprResult E) {
11413 QualType Ty = E.get()->getType();
11414 return Ty->isPointerType() || Ty->isMemberPointerType();
11417 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11418 // type, array-to-pointer, ..., conversions are performed on both operands to
11419 // bring them to their composite type.
11420 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11421 // any type-related checks.
11422 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11423 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11424 if (LHS.isInvalid())
11426 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11427 if (RHS.isInvalid())
11430 LHS = DefaultLvalueConversion(LHS.get());
11431 if (LHS.isInvalid())
11433 RHS = DefaultLvalueConversion(RHS.get());
11434 if (RHS.isInvalid())
11438 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11439 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11440 CheckPtrComparisonWithNullChar(LHS, RHS);
11441 CheckPtrComparisonWithNullChar(RHS, LHS);
11444 // Handle vector comparisons separately.
11445 if (LHS.get()->getType()->isVectorType() ||
11446 RHS.get()->getType()->isVectorType())
11447 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11449 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11450 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11452 QualType LHSType = LHS.get()->getType();
11453 QualType RHSType = RHS.get()->getType();
11454 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11455 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11456 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11458 const Expr::NullPointerConstantKind LHSNullKind =
11459 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11460 const Expr::NullPointerConstantKind RHSNullKind =
11461 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11462 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11463 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11465 auto computeResultTy = [&]() {
11467 return Context.getLogicalOperationType();
11468 assert(getLangOpts().CPlusPlus);
11469 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11471 QualType CompositeTy = LHS.get()->getType();
11472 assert(!CompositeTy->isReferenceType());
11474 Optional<ComparisonCategoryType> CCT =
11475 getComparisonCategoryForBuiltinCmp(CompositeTy);
11477 return InvalidOperands(Loc, LHS, RHS);
11479 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11480 // P0946R0: Comparisons between a null pointer constant and an object
11481 // pointer result in std::strong_equality, which is ill-formed under
11483 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11484 << (LHSIsNull ? LHS.get()->getSourceRange()
11485 : RHS.get()->getSourceRange());
11489 return CheckComparisonCategoryType(
11490 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11493 if (!IsOrdered && LHSIsNull != RHSIsNull) {
11494 bool IsEquality = Opc == BO_EQ;
11496 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11497 RHS.get()->getSourceRange());
11499 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11500 LHS.get()->getSourceRange());
11503 if ((LHSType->isIntegerType() && !LHSIsNull) ||
11504 (RHSType->isIntegerType() && !RHSIsNull)) {
11505 // Skip normal pointer conversion checks in this case; we have better
11506 // diagnostics for this below.
11507 } else if (getLangOpts().CPlusPlus) {
11508 // Equality comparison of a function pointer to a void pointer is invalid,
11509 // but we allow it as an extension.
11510 // FIXME: If we really want to allow this, should it be part of composite
11511 // pointer type computation so it works in conditionals too?
11513 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11514 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11515 // This is a gcc extension compatibility comparison.
11516 // In a SFINAE context, we treat this as a hard error to maintain
11517 // conformance with the C++ standard.
11518 diagnoseFunctionPointerToVoidComparison(
11519 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11521 if (isSFINAEContext())
11524 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11525 return computeResultTy();
11528 // C++ [expr.eq]p2:
11529 // If at least one operand is a pointer [...] bring them to their
11530 // composite pointer type.
11531 // C++ [expr.spaceship]p6
11532 // If at least one of the operands is of pointer type, [...] bring them
11533 // to their composite pointer type.
11534 // C++ [expr.rel]p2:
11535 // If both operands are pointers, [...] bring them to their composite
11537 // For <=>, the only valid non-pointer types are arrays and functions, and
11538 // we already decayed those, so this is really the same as the relational
11539 // comparison rule.
11540 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11541 (IsOrdered ? 2 : 1) &&
11542 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11543 RHSType->isObjCObjectPointerType()))) {
11544 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11546 return computeResultTy();
11548 } else if (LHSType->isPointerType() &&
11549 RHSType->isPointerType()) { // C99 6.5.8p2
11550 // All of the following pointer-related warnings are GCC extensions, except
11551 // when handling null pointer constants.
11552 QualType LCanPointeeTy =
11553 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11554 QualType RCanPointeeTy =
11555 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11557 // C99 6.5.9p2 and C99 6.5.8p2
11558 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11559 RCanPointeeTy.getUnqualifiedType())) {
11560 if (IsRelational) {
11561 // Pointers both need to point to complete or incomplete types
11562 if ((LCanPointeeTy->isIncompleteType() !=
11563 RCanPointeeTy->isIncompleteType()) &&
11564 !getLangOpts().C11) {
11565 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11566 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11567 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11568 << RCanPointeeTy->isIncompleteType();
11570 if (LCanPointeeTy->isFunctionType()) {
11571 // Valid unless a relational comparison of function pointers
11572 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11573 << LHSType << RHSType << LHS.get()->getSourceRange()
11574 << RHS.get()->getSourceRange();
11577 } else if (!IsRelational &&
11578 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11579 // Valid unless comparison between non-null pointer and function pointer
11580 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11581 && !LHSIsNull && !RHSIsNull)
11582 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11586 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11588 if (LCanPointeeTy != RCanPointeeTy) {
11589 // Treat NULL constant as a special case in OpenCL.
11590 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11591 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11593 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11594 << LHSType << RHSType << 0 /* comparison */
11595 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11598 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11599 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11600 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11602 if (LHSIsNull && !RHSIsNull)
11603 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11605 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11607 return computeResultTy();
11610 if (getLangOpts().CPlusPlus) {
11611 // C++ [expr.eq]p4:
11612 // Two operands of type std::nullptr_t or one operand of type
11613 // std::nullptr_t and the other a null pointer constant compare equal.
11614 if (!IsOrdered && LHSIsNull && RHSIsNull) {
11615 if (LHSType->isNullPtrType()) {
11616 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11617 return computeResultTy();
11619 if (RHSType->isNullPtrType()) {
11620 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11621 return computeResultTy();
11625 // Comparison of Objective-C pointers and block pointers against nullptr_t.
11626 // These aren't covered by the composite pointer type rules.
11627 if (!IsOrdered && RHSType->isNullPtrType() &&
11628 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11629 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11630 return computeResultTy();
11632 if (!IsOrdered && LHSType->isNullPtrType() &&
11633 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11634 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11635 return computeResultTy();
11638 if (IsRelational &&
11639 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11640 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11641 // HACK: Relational comparison of nullptr_t against a pointer type is
11642 // invalid per DR583, but we allow it within std::less<> and friends,
11643 // since otherwise common uses of it break.
11644 // FIXME: Consider removing this hack once LWG fixes std::less<> and
11645 // friends to have std::nullptr_t overload candidates.
11646 DeclContext *DC = CurContext;
11647 if (isa<FunctionDecl>(DC))
11648 DC = DC->getParent();
11649 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11650 if (CTSD->isInStdNamespace() &&
11651 llvm::StringSwitch<bool>(CTSD->getName())
11652 .Cases("less", "less_equal", "greater", "greater_equal", true)
11654 if (RHSType->isNullPtrType())
11655 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11657 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11658 return computeResultTy();
11663 // C++ [expr.eq]p2:
11664 // If at least one operand is a pointer to member, [...] bring them to
11665 // their composite pointer type.
11667 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11668 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11671 return computeResultTy();
11675 // Handle block pointer types.
11676 if (!IsOrdered && LHSType->isBlockPointerType() &&
11677 RHSType->isBlockPointerType()) {
11678 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11679 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11681 if (!LHSIsNull && !RHSIsNull &&
11682 !Context.typesAreCompatible(lpointee, rpointee)) {
11683 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11684 << LHSType << RHSType << LHS.get()->getSourceRange()
11685 << RHS.get()->getSourceRange();
11687 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11688 return computeResultTy();
11691 // Allow block pointers to be compared with null pointer constants.
11693 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11694 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11695 if (!LHSIsNull && !RHSIsNull) {
11696 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11697 ->getPointeeType()->isVoidType())
11698 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11699 ->getPointeeType()->isVoidType())))
11700 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11701 << LHSType << RHSType << LHS.get()->getSourceRange()
11702 << RHS.get()->getSourceRange();
11704 if (LHSIsNull && !RHSIsNull)
11705 LHS = ImpCastExprToType(LHS.get(), RHSType,
11706 RHSType->isPointerType() ? CK_BitCast
11707 : CK_AnyPointerToBlockPointerCast);
11709 RHS = ImpCastExprToType(RHS.get(), LHSType,
11710 LHSType->isPointerType() ? CK_BitCast
11711 : CK_AnyPointerToBlockPointerCast);
11712 return computeResultTy();
11715 if (LHSType->isObjCObjectPointerType() ||
11716 RHSType->isObjCObjectPointerType()) {
11717 const PointerType *LPT = LHSType->getAs<PointerType>();
11718 const PointerType *RPT = RHSType->getAs<PointerType>();
11720 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11721 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11723 if (!LPtrToVoid && !RPtrToVoid &&
11724 !Context.typesAreCompatible(LHSType, RHSType)) {
11725 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11728 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11729 // the RHS, but we have test coverage for this behavior.
11730 // FIXME: Consider using convertPointersToCompositeType in C++.
11731 if (LHSIsNull && !RHSIsNull) {
11732 Expr *E = LHS.get();
11733 if (getLangOpts().ObjCAutoRefCount)
11734 CheckObjCConversion(SourceRange(), RHSType, E,
11735 CCK_ImplicitConversion);
11736 LHS = ImpCastExprToType(E, RHSType,
11737 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11740 Expr *E = RHS.get();
11741 if (getLangOpts().ObjCAutoRefCount)
11742 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11744 /*DiagnoseCFAudited=*/false, Opc);
11745 RHS = ImpCastExprToType(E, LHSType,
11746 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11748 return computeResultTy();
11750 if (LHSType->isObjCObjectPointerType() &&
11751 RHSType->isObjCObjectPointerType()) {
11752 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11753 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11755 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11756 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11758 if (LHSIsNull && !RHSIsNull)
11759 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11761 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11762 return computeResultTy();
11765 if (!IsOrdered && LHSType->isBlockPointerType() &&
11766 RHSType->isBlockCompatibleObjCPointerType(Context)) {
11767 LHS = ImpCastExprToType(LHS.get(), RHSType,
11768 CK_BlockPointerToObjCPointerCast);
11769 return computeResultTy();
11770 } else if (!IsOrdered &&
11771 LHSType->isBlockCompatibleObjCPointerType(Context) &&
11772 RHSType->isBlockPointerType()) {
11773 RHS = ImpCastExprToType(RHS.get(), LHSType,
11774 CK_BlockPointerToObjCPointerCast);
11775 return computeResultTy();
11778 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11779 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11780 unsigned DiagID = 0;
11781 bool isError = false;
11782 if (LangOpts.DebuggerSupport) {
11783 // Under a debugger, allow the comparison of pointers to integers,
11784 // since users tend to want to compare addresses.
11785 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11786 (RHSIsNull && RHSType->isIntegerType())) {
11788 isError = getLangOpts().CPlusPlus;
11790 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11791 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11793 } else if (getLangOpts().CPlusPlus) {
11794 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11796 } else if (IsOrdered)
11797 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11799 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11803 << LHSType << RHSType << LHS.get()->getSourceRange()
11804 << RHS.get()->getSourceRange();
11809 if (LHSType->isIntegerType())
11810 LHS = ImpCastExprToType(LHS.get(), RHSType,
11811 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11813 RHS = ImpCastExprToType(RHS.get(), LHSType,
11814 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11815 return computeResultTy();
11818 // Handle block pointers.
11819 if (!IsOrdered && RHSIsNull
11820 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11821 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11822 return computeResultTy();
11824 if (!IsOrdered && LHSIsNull
11825 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11826 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11827 return computeResultTy();
11830 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11831 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11832 return computeResultTy();
11835 if (LHSType->isQueueT() && RHSType->isQueueT()) {
11836 return computeResultTy();
11839 if (LHSIsNull && RHSType->isQueueT()) {
11840 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11841 return computeResultTy();
11844 if (LHSType->isQueueT() && RHSIsNull) {
11845 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11846 return computeResultTy();
11850 return InvalidOperands(Loc, LHS, RHS);
11853 // Return a signed ext_vector_type that is of identical size and number of
11854 // elements. For floating point vectors, return an integer type of identical
11855 // size and number of elements. In the non ext_vector_type case, search from
11856 // the largest type to the smallest type to avoid cases where long long == long,
11857 // where long gets picked over long long.
11858 QualType Sema::GetSignedVectorType(QualType V) {
11859 const VectorType *VTy = V->castAs<VectorType>();
11860 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11862 if (isa<ExtVectorType>(VTy)) {
11863 if (TypeSize == Context.getTypeSize(Context.CharTy))
11864 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11865 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11866 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11867 else if (TypeSize == Context.getTypeSize(Context.IntTy))
11868 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11869 else if (TypeSize == Context.getTypeSize(Context.LongTy))
11870 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11871 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11872 "Unhandled vector element size in vector compare");
11873 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11876 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11877 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11878 VectorType::GenericVector);
11879 else if (TypeSize == Context.getTypeSize(Context.LongTy))
11880 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11881 VectorType::GenericVector);
11882 else if (TypeSize == Context.getTypeSize(Context.IntTy))
11883 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11884 VectorType::GenericVector);
11885 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11886 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11887 VectorType::GenericVector);
11888 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11889 "Unhandled vector element size in vector compare");
11890 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11891 VectorType::GenericVector);
11894 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11895 /// operates on extended vector types. Instead of producing an IntTy result,
11896 /// like a scalar comparison, a vector comparison produces a vector of integer
11898 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11899 SourceLocation Loc,
11900 BinaryOperatorKind Opc) {
11901 if (Opc == BO_Cmp) {
11902 Diag(Loc, diag::err_three_way_vector_comparison);
11906 // Check to make sure we're operating on vectors of the same type and width,
11907 // Allowing one side to be a scalar of element type.
11908 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11909 /*AllowBothBool*/true,
11910 /*AllowBoolConversions*/getLangOpts().ZVector);
11911 if (vType.isNull())
11914 QualType LHSType = LHS.get()->getType();
11916 // If AltiVec, the comparison results in a numeric type, i.e.
11917 // bool for C++, int for C
11918 if (getLangOpts().AltiVec &&
11919 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11920 return Context.getLogicalOperationType();
11922 // For non-floating point types, check for self-comparisons of the form
11923 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11924 // often indicate logic errors in the program.
11925 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11927 // Check for comparisons of floating point operands using != and ==.
11928 if (BinaryOperator::isEqualityOp(Opc) &&
11929 LHSType->hasFloatingRepresentation()) {
11930 assert(RHS.get()->getType()->hasFloatingRepresentation());
11931 CheckFloatComparison(Loc, LHS.get(), RHS.get());
11934 // Return a signed type for the vector.
11935 return GetSignedVectorType(vType);
11938 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11939 const ExprResult &XorRHS,
11940 const SourceLocation Loc) {
11941 // Do not diagnose macros.
11942 if (Loc.isMacroID())
11945 bool Negative = false;
11946 bool ExplicitPlus = false;
11947 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11948 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11953 // Check negative literals.
11954 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11955 UnaryOperatorKind Opc = UO->getOpcode();
11956 if (Opc != UO_Minus && Opc != UO_Plus)
11958 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11961 Negative = (Opc == UO_Minus);
11962 ExplicitPlus = !Negative;
11968 const llvm::APInt &LeftSideValue = LHSInt->getValue();
11969 llvm::APInt RightSideValue = RHSInt->getValue();
11970 if (LeftSideValue != 2 && LeftSideValue != 10)
11973 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11976 CharSourceRange ExprRange = CharSourceRange::getCharRange(
11977 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11978 llvm::StringRef ExprStr =
11979 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11981 CharSourceRange XorRange =
11982 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11983 llvm::StringRef XorStr =
11984 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11985 // Do not diagnose if xor keyword/macro is used.
11986 if (XorStr == "xor")
11989 std::string LHSStr = std::string(Lexer::getSourceText(
11990 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11991 S.getSourceManager(), S.getLangOpts()));
11992 std::string RHSStr = std::string(Lexer::getSourceText(
11993 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11994 S.getSourceManager(), S.getLangOpts()));
11997 RightSideValue = -RightSideValue;
11998 RHSStr = "-" + RHSStr;
11999 } else if (ExplicitPlus) {
12000 RHSStr = "+" + RHSStr;
12003 StringRef LHSStrRef = LHSStr;
12004 StringRef RHSStrRef = RHSStr;
12005 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12007 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12008 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12009 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12010 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12011 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12012 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12013 LHSStrRef.find('\'') != StringRef::npos ||
12014 RHSStrRef.find('\'') != StringRef::npos)
12017 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12018 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12019 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12020 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12021 std::string SuggestedExpr = "1 << " + RHSStr;
12022 bool Overflow = false;
12023 llvm::APInt One = (LeftSideValue - 1);
12024 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12026 if (RightSideIntValue < 64)
12027 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12028 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12029 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12030 else if (RightSideIntValue == 64)
12031 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12035 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12036 << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12037 << PowValue.toString(10, true)
12038 << FixItHint::CreateReplacement(
12039 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12042 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12043 } else if (LeftSideValue == 10) {
12044 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12045 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12046 << ExprStr << XorValue.toString(10, true) << SuggestedValue
12047 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12048 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12052 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12053 SourceLocation Loc) {
12054 // Ensure that either both operands are of the same vector type, or
12055 // one operand is of a vector type and the other is of its element type.
12056 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12057 /*AllowBothBool*/true,
12058 /*AllowBoolConversions*/false);
12059 if (vType.isNull())
12060 return InvalidOperands(Loc, LHS, RHS);
12061 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12062 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12063 return InvalidOperands(Loc, LHS, RHS);
12064 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12065 // usage of the logical operators && and || with vectors in C. This
12066 // check could be notionally dropped.
12067 if (!getLangOpts().CPlusPlus &&
12068 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12069 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12071 return GetSignedVectorType(LHS.get()->getType());
12074 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12075 SourceLocation Loc,
12076 bool IsCompAssign) {
12077 if (!IsCompAssign) {
12078 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12079 if (LHS.isInvalid())
12082 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12083 if (RHS.isInvalid())
12086 // For conversion purposes, we ignore any qualifiers.
12087 // For example, "const float" and "float" are equivalent.
12088 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12089 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12091 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12092 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12093 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12095 if (Context.hasSameType(LHSType, RHSType))
12098 // Type conversion may change LHS/RHS. Keep copies to the original results, in
12099 // case we have to return InvalidOperands.
12100 ExprResult OriginalLHS = LHS;
12101 ExprResult OriginalRHS = RHS;
12102 if (LHSMatType && !RHSMatType) {
12103 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12104 if (!RHS.isInvalid())
12107 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12110 if (!LHSMatType && RHSMatType) {
12111 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12112 if (!LHS.isInvalid())
12114 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12117 return InvalidOperands(Loc, LHS, RHS);
12120 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12121 SourceLocation Loc,
12122 bool IsCompAssign) {
12123 if (!IsCompAssign) {
12124 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12125 if (LHS.isInvalid())
12128 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12129 if (RHS.isInvalid())
12132 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12133 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12134 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12136 if (LHSMatType && RHSMatType) {
12137 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12138 return InvalidOperands(Loc, LHS, RHS);
12140 if (!Context.hasSameType(LHSMatType->getElementType(),
12141 RHSMatType->getElementType()))
12142 return InvalidOperands(Loc, LHS, RHS);
12144 return Context.getConstantMatrixType(LHSMatType->getElementType(),
12145 LHSMatType->getNumRows(),
12146 RHSMatType->getNumColumns());
12148 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12151 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12152 SourceLocation Loc,
12153 BinaryOperatorKind Opc) {
12154 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12156 bool IsCompAssign =
12157 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12159 if (LHS.get()->getType()->isVectorType() ||
12160 RHS.get()->getType()->isVectorType()) {
12161 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12162 RHS.get()->getType()->hasIntegerRepresentation())
12163 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12164 /*AllowBothBool*/true,
12165 /*AllowBoolConversions*/getLangOpts().ZVector);
12166 return InvalidOperands(Loc, LHS, RHS);
12170 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12172 if (LHS.get()->getType()->hasFloatingRepresentation() ||
12173 RHS.get()->getType()->hasFloatingRepresentation())
12174 return InvalidOperands(Loc, LHS, RHS);
12176 ExprResult LHSResult = LHS, RHSResult = RHS;
12177 QualType compType = UsualArithmeticConversions(
12178 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12179 if (LHSResult.isInvalid() || RHSResult.isInvalid())
12181 LHS = LHSResult.get();
12182 RHS = RHSResult.get();
12185 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12187 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12189 return InvalidOperands(Loc, LHS, RHS);
12193 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12194 SourceLocation Loc,
12195 BinaryOperatorKind Opc) {
12196 // Check vector operands differently.
12197 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12198 return CheckVectorLogicalOperands(LHS, RHS, Loc);
12200 bool EnumConstantInBoolContext = false;
12201 for (const ExprResult &HS : {LHS, RHS}) {
12202 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12203 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12204 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12205 EnumConstantInBoolContext = true;
12209 if (EnumConstantInBoolContext)
12210 Diag(Loc, diag::warn_enum_constant_in_bool_context);
12212 // Diagnose cases where the user write a logical and/or but probably meant a
12213 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
12215 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12216 !LHS.get()->getType()->isBooleanType() &&
12217 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12218 // Don't warn in macros or template instantiations.
12219 !Loc.isMacroID() && !inTemplateInstantiation()) {
12220 // If the RHS can be constant folded, and if it constant folds to something
12221 // that isn't 0 or 1 (which indicate a potential logical operation that
12222 // happened to fold to true/false) then warn.
12223 // Parens on the RHS are ignored.
12224 Expr::EvalResult EVResult;
12225 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12226 llvm::APSInt Result = EVResult.Val.getInt();
12227 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12228 !RHS.get()->getExprLoc().isMacroID()) ||
12229 (Result != 0 && Result != 1)) {
12230 Diag(Loc, diag::warn_logical_instead_of_bitwise)
12231 << RHS.get()->getSourceRange()
12232 << (Opc == BO_LAnd ? "&&" : "||");
12233 // Suggest replacing the logical operator with the bitwise version
12234 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12235 << (Opc == BO_LAnd ? "&" : "|")
12236 << FixItHint::CreateReplacement(SourceRange(
12237 Loc, getLocForEndOfToken(Loc)),
12238 Opc == BO_LAnd ? "&" : "|");
12239 if (Opc == BO_LAnd)
12240 // Suggest replacing "Foo() && kNonZero" with "Foo()"
12241 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12242 << FixItHint::CreateRemoval(
12243 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12244 RHS.get()->getEndLoc()));
12249 if (!Context.getLangOpts().CPlusPlus) {
12250 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12251 // not operate on the built-in scalar and vector float types.
12252 if (Context.getLangOpts().OpenCL &&
12253 Context.getLangOpts().OpenCLVersion < 120) {
12254 if (LHS.get()->getType()->isFloatingType() ||
12255 RHS.get()->getType()->isFloatingType())
12256 return InvalidOperands(Loc, LHS, RHS);
12259 LHS = UsualUnaryConversions(LHS.get());
12260 if (LHS.isInvalid())
12263 RHS = UsualUnaryConversions(RHS.get());
12264 if (RHS.isInvalid())
12267 if (!LHS.get()->getType()->isScalarType() ||
12268 !RHS.get()->getType()->isScalarType())
12269 return InvalidOperands(Loc, LHS, RHS);
12271 return Context.IntTy;
12274 // The following is safe because we only use this method for
12275 // non-overloadable operands.
12277 // C++ [expr.log.and]p1
12278 // C++ [expr.log.or]p1
12279 // The operands are both contextually converted to type bool.
12280 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12281 if (LHSRes.isInvalid())
12282 return InvalidOperands(Loc, LHS, RHS);
12285 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12286 if (RHSRes.isInvalid())
12287 return InvalidOperands(Loc, LHS, RHS);
12290 // C++ [expr.log.and]p2
12291 // C++ [expr.log.or]p2
12292 // The result is a bool.
12293 return Context.BoolTy;
12296 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12297 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12298 if (!ME) return false;
12299 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12300 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12301 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12302 if (!Base) return false;
12303 return Base->getMethodDecl() != nullptr;
12306 /// Is the given expression (which must be 'const') a reference to a
12307 /// variable which was originally non-const, but which has become
12308 /// 'const' due to being captured within a block?
12309 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
12310 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12311 assert(E->isLValue() && E->getType().isConstQualified());
12312 E = E->IgnoreParens();
12314 // Must be a reference to a declaration from an enclosing scope.
12315 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12316 if (!DRE) return NCCK_None;
12317 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12319 // The declaration must be a variable which is not declared 'const'.
12320 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12321 if (!var) return NCCK_None;
12322 if (var->getType().isConstQualified()) return NCCK_None;
12323 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12325 // Decide whether the first capture was for a block or a lambda.
12326 DeclContext *DC = S.CurContext, *Prev = nullptr;
12327 // Decide whether the first capture was for a block or a lambda.
12329 // For init-capture, it is possible that the variable belongs to the
12330 // template pattern of the current context.
12331 if (auto *FD = dyn_cast<FunctionDecl>(DC))
12332 if (var->isInitCapture() &&
12333 FD->getTemplateInstantiationPattern() == var->getDeclContext())
12335 if (DC == var->getDeclContext())
12338 DC = DC->getParent();
12340 // Unless we have an init-capture, we've gone one step too far.
12341 if (!var->isInitCapture())
12343 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12346 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12347 Ty = Ty.getNonReferenceType();
12348 if (IsDereference && Ty->isPointerType())
12349 Ty = Ty->getPointeeType();
12350 return !Ty.isConstQualified();
12353 // Update err_typecheck_assign_const and note_typecheck_assign_const
12354 // when this enum is changed.
12361 ConstUnknown, // Keep as last element
12364 /// Emit the "read-only variable not assignable" error and print notes to give
12365 /// more information about why the variable is not assignable, such as pointing
12366 /// to the declaration of a const variable, showing that a method is const, or
12367 /// that the function is returning a const reference.
12368 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12369 SourceLocation Loc) {
12370 SourceRange ExprRange = E->getSourceRange();
12372 // Only emit one error on the first const found. All other consts will emit
12373 // a note to the error.
12374 bool DiagnosticEmitted = false;
12376 // Track if the current expression is the result of a dereference, and if the
12377 // next checked expression is the result of a dereference.
12378 bool IsDereference = false;
12379 bool NextIsDereference = false;
12381 // Loop to process MemberExpr chains.
12383 IsDereference = NextIsDereference;
12385 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12386 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12387 NextIsDereference = ME->isArrow();
12388 const ValueDecl *VD = ME->getMemberDecl();
12389 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12390 // Mutable fields can be modified even if the class is const.
12391 if (Field->isMutable()) {
12392 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12396 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12397 if (!DiagnosticEmitted) {
12398 S.Diag(Loc, diag::err_typecheck_assign_const)
12399 << ExprRange << ConstMember << false /*static*/ << Field
12400 << Field->getType();
12401 DiagnosticEmitted = true;
12403 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12404 << ConstMember << false /*static*/ << Field << Field->getType()
12405 << Field->getSourceRange();
12409 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12410 if (VDecl->getType().isConstQualified()) {
12411 if (!DiagnosticEmitted) {
12412 S.Diag(Loc, diag::err_typecheck_assign_const)
12413 << ExprRange << ConstMember << true /*static*/ << VDecl
12414 << VDecl->getType();
12415 DiagnosticEmitted = true;
12417 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12418 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12419 << VDecl->getSourceRange();
12421 // Static fields do not inherit constness from parents.
12424 break; // End MemberExpr
12425 } else if (const ArraySubscriptExpr *ASE =
12426 dyn_cast<ArraySubscriptExpr>(E)) {
12427 E = ASE->getBase()->IgnoreParenImpCasts();
12429 } else if (const ExtVectorElementExpr *EVE =
12430 dyn_cast<ExtVectorElementExpr>(E)) {
12431 E = EVE->getBase()->IgnoreParenImpCasts();
12437 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12439 const FunctionDecl *FD = CE->getDirectCallee();
12440 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12441 if (!DiagnosticEmitted) {
12442 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12443 << ConstFunction << FD;
12444 DiagnosticEmitted = true;
12446 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12447 diag::note_typecheck_assign_const)
12448 << ConstFunction << FD << FD->getReturnType()
12449 << FD->getReturnTypeSourceRange();
12451 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12452 // Point to variable declaration.
12453 if (const ValueDecl *VD = DRE->getDecl()) {
12454 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12455 if (!DiagnosticEmitted) {
12456 S.Diag(Loc, diag::err_typecheck_assign_const)
12457 << ExprRange << ConstVariable << VD << VD->getType();
12458 DiagnosticEmitted = true;
12460 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12461 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12464 } else if (isa<CXXThisExpr>(E)) {
12465 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12466 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12467 if (MD->isConst()) {
12468 if (!DiagnosticEmitted) {
12469 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12470 << ConstMethod << MD;
12471 DiagnosticEmitted = true;
12473 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12474 << ConstMethod << MD << MD->getSourceRange();
12480 if (DiagnosticEmitted)
12483 // Can't determine a more specific message, so display the generic error.
12484 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12487 enum OriginalExprKind {
12493 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12494 const RecordType *Ty,
12495 SourceLocation Loc, SourceRange Range,
12496 OriginalExprKind OEK,
12497 bool &DiagnosticEmitted) {
12498 std::vector<const RecordType *> RecordTypeList;
12499 RecordTypeList.push_back(Ty);
12500 unsigned NextToCheckIndex = 0;
12501 // We walk the record hierarchy breadth-first to ensure that we print
12502 // diagnostics in field nesting order.
12503 while (RecordTypeList.size() > NextToCheckIndex) {
12504 bool IsNested = NextToCheckIndex > 0;
12505 for (const FieldDecl *Field :
12506 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12507 // First, check every field for constness.
12508 QualType FieldTy = Field->getType();
12509 if (FieldTy.isConstQualified()) {
12510 if (!DiagnosticEmitted) {
12511 S.Diag(Loc, diag::err_typecheck_assign_const)
12512 << Range << NestedConstMember << OEK << VD
12513 << IsNested << Field;
12514 DiagnosticEmitted = true;
12516 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12517 << NestedConstMember << IsNested << Field
12518 << FieldTy << Field->getSourceRange();
12521 // Then we append it to the list to check next in order.
12522 FieldTy = FieldTy.getCanonicalType();
12523 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12524 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12525 RecordTypeList.push_back(FieldRecTy);
12528 ++NextToCheckIndex;
12532 /// Emit an error for the case where a record we are trying to assign to has a
12533 /// const-qualified field somewhere in its hierarchy.
12534 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12535 SourceLocation Loc) {
12536 QualType Ty = E->getType();
12537 assert(Ty->isRecordType() && "lvalue was not record?");
12538 SourceRange Range = E->getSourceRange();
12539 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12540 bool DiagEmitted = false;
12542 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12543 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12544 Range, OEK_Member, DiagEmitted);
12545 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12546 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12547 Range, OEK_Variable, DiagEmitted);
12549 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12550 Range, OEK_LValue, DiagEmitted);
12552 DiagnoseConstAssignment(S, E, Loc);
12555 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
12556 /// emit an error and return true. If so, return false.
12557 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12558 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12560 S.CheckShadowingDeclModification(E, Loc);
12562 SourceLocation OrigLoc = Loc;
12563 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12565 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12566 IsLV = Expr::MLV_InvalidMessageExpression;
12567 if (IsLV == Expr::MLV_Valid)
12570 unsigned DiagID = 0;
12571 bool NeedType = false;
12572 switch (IsLV) { // C99 6.5.16p2
12573 case Expr::MLV_ConstQualified:
12574 // Use a specialized diagnostic when we're assigning to an object
12575 // from an enclosing function or block.
12576 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12577 if (NCCK == NCCK_Block)
12578 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12580 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12584 // In ARC, use some specialized diagnostics for occasions where we
12585 // infer 'const'. These are always pseudo-strong variables.
12586 if (S.getLangOpts().ObjCAutoRefCount) {
12587 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12588 if (declRef && isa<VarDecl>(declRef->getDecl())) {
12589 VarDecl *var = cast<VarDecl>(declRef->getDecl());
12591 // Use the normal diagnostic if it's pseudo-__strong but the
12592 // user actually wrote 'const'.
12593 if (var->isARCPseudoStrong() &&
12594 (!var->getTypeSourceInfo() ||
12595 !var->getTypeSourceInfo()->getType().isConstQualified())) {
12596 // There are three pseudo-strong cases:
12598 ObjCMethodDecl *method = S.getCurMethodDecl();
12599 if (method && var == method->getSelfDecl()) {
12600 DiagID = method->isClassMethod()
12601 ? diag::err_typecheck_arc_assign_self_class_method
12602 : diag::err_typecheck_arc_assign_self;
12604 // - Objective-C externally_retained attribute.
12605 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12606 isa<ParmVarDecl>(var)) {
12607 DiagID = diag::err_typecheck_arc_assign_externally_retained;
12609 // - fast enumeration variables
12611 DiagID = diag::err_typecheck_arr_assign_enumeration;
12614 SourceRange Assign;
12615 if (Loc != OrigLoc)
12616 Assign = SourceRange(OrigLoc, OrigLoc);
12617 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12618 // We need to preserve the AST regardless, so migration tool
12625 // If none of the special cases above are triggered, then this is a
12626 // simple const assignment.
12628 DiagnoseConstAssignment(S, E, Loc);
12633 case Expr::MLV_ConstAddrSpace:
12634 DiagnoseConstAssignment(S, E, Loc);
12636 case Expr::MLV_ConstQualifiedField:
12637 DiagnoseRecursiveConstFields(S, E, Loc);
12639 case Expr::MLV_ArrayType:
12640 case Expr::MLV_ArrayTemporary:
12641 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12644 case Expr::MLV_NotObjectType:
12645 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12648 case Expr::MLV_LValueCast:
12649 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12651 case Expr::MLV_Valid:
12652 llvm_unreachable("did not take early return for MLV_Valid");
12653 case Expr::MLV_InvalidExpression:
12654 case Expr::MLV_MemberFunction:
12655 case Expr::MLV_ClassTemporary:
12656 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12658 case Expr::MLV_IncompleteType:
12659 case Expr::MLV_IncompleteVoidType:
12660 return S.RequireCompleteType(Loc, E->getType(),
12661 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12662 case Expr::MLV_DuplicateVectorComponents:
12663 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12665 case Expr::MLV_NoSetterProperty:
12666 llvm_unreachable("readonly properties should be processed differently");
12667 case Expr::MLV_InvalidMessageExpression:
12668 DiagID = diag::err_readonly_message_assignment;
12670 case Expr::MLV_SubObjCPropertySetting:
12671 DiagID = diag::err_no_subobject_property_setting;
12675 SourceRange Assign;
12676 if (Loc != OrigLoc)
12677 Assign = SourceRange(OrigLoc, OrigLoc);
12679 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12681 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12685 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12686 SourceLocation Loc,
12688 if (Sema.inTemplateInstantiation())
12690 if (Sema.isUnevaluatedContext())
12692 if (Loc.isInvalid() || Loc.isMacroID())
12694 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12698 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12699 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12701 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12703 const ValueDecl *LHSDecl =
12704 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12705 const ValueDecl *RHSDecl =
12706 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12707 if (LHSDecl != RHSDecl)
12709 if (LHSDecl->getType().isVolatileQualified())
12711 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12712 if (RefTy->getPointeeType().isVolatileQualified())
12715 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12718 // Objective-C instance variables
12719 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12720 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12721 if (OL && OR && OL->getDecl() == OR->getDecl()) {
12722 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12723 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12724 if (RL && RR && RL->getDecl() == RR->getDecl())
12725 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12730 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12731 SourceLocation Loc,
12732 QualType CompoundType) {
12733 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12735 // Verify that LHS is a modifiable lvalue, and emit error if not.
12736 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12739 QualType LHSType = LHSExpr->getType();
12740 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12742 // OpenCL v1.2 s6.1.1.1 p2:
12743 // The half data type can only be used to declare a pointer to a buffer that
12744 // contains half values
12745 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12746 LHSType->isHalfType()) {
12747 Diag(Loc, diag::err_opencl_half_load_store) << 1
12748 << LHSType.getUnqualifiedType();
12752 AssignConvertType ConvTy;
12753 if (CompoundType.isNull()) {
12754 Expr *RHSCheck = RHS.get();
12756 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12758 QualType LHSTy(LHSType);
12759 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12760 if (RHS.isInvalid())
12762 // Special case of NSObject attributes on c-style pointer types.
12763 if (ConvTy == IncompatiblePointer &&
12764 ((Context.isObjCNSObjectType(LHSType) &&
12765 RHSType->isObjCObjectPointerType()) ||
12766 (Context.isObjCNSObjectType(RHSType) &&
12767 LHSType->isObjCObjectPointerType())))
12768 ConvTy = Compatible;
12770 if (ConvTy == Compatible &&
12771 LHSType->isObjCObjectType())
12772 Diag(Loc, diag::err_objc_object_assignment)
12775 // If the RHS is a unary plus or minus, check to see if they = and + are
12776 // right next to each other. If so, the user may have typo'd "x =+ 4"
12777 // instead of "x += 4".
12778 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12779 RHSCheck = ICE->getSubExpr();
12780 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12781 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12782 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12783 // Only if the two operators are exactly adjacent.
12784 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12785 // And there is a space or other character before the subexpr of the
12786 // unary +/-. We don't want to warn on "x=-1".
12787 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12788 UO->getSubExpr()->getBeginLoc().isFileID()) {
12789 Diag(Loc, diag::warn_not_compound_assign)
12790 << (UO->getOpcode() == UO_Plus ? "+" : "-")
12791 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12795 if (ConvTy == Compatible) {
12796 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12797 // Warn about retain cycles where a block captures the LHS, but
12798 // not if the LHS is a simple variable into which the block is
12799 // being stored...unless that variable can be captured by reference!
12800 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12801 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12802 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12803 checkRetainCycles(LHSExpr, RHS.get());
12806 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12807 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12808 // It is safe to assign a weak reference into a strong variable.
12809 // Although this code can still have problems:
12810 // id x = self.weakProp;
12811 // id y = self.weakProp;
12812 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12813 // paths through the function. This should be revisited if
12814 // -Wrepeated-use-of-weak is made flow-sensitive.
12815 // For ObjCWeak only, we do not warn if the assign is to a non-weak
12816 // variable, which will be valid for the current autorelease scope.
12817 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12818 RHS.get()->getBeginLoc()))
12819 getCurFunction()->markSafeWeakUse(RHS.get());
12821 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12822 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12826 // Compound assignment "x += y"
12827 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12830 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12831 RHS.get(), AA_Assigning))
12834 CheckForNullPointerDereference(*this, LHSExpr);
12836 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12837 if (CompoundType.isNull()) {
12838 // C++2a [expr.ass]p5:
12839 // A simple-assignment whose left operand is of a volatile-qualified
12840 // type is deprecated unless the assignment is either a discarded-value
12841 // expression or an unevaluated operand
12842 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12844 // C++2a [expr.ass]p6:
12845 // [Compound-assignment] expressions are deprecated if E1 has
12846 // volatile-qualified type
12847 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12851 // C99 6.5.16p3: The type of an assignment expression is the type of the
12852 // left operand unless the left operand has qualified type, in which case
12853 // it is the unqualified version of the type of the left operand.
12854 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12855 // is converted to the type of the assignment expression (above).
12856 // C++ 5.17p1: the type of the assignment expression is that of its left
12858 return (getLangOpts().CPlusPlus
12859 ? LHSType : LHSType.getUnqualifiedType());
12862 // Only ignore explicit casts to void.
12863 static bool IgnoreCommaOperand(const Expr *E) {
12864 E = E->IgnoreParens();
12866 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12867 if (CE->getCastKind() == CK_ToVoid) {
12871 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12872 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12873 CE->getSubExpr()->getType()->isDependentType()) {
12881 // Look for instances where it is likely the comma operator is confused with
12882 // another operator. There is an explicit list of acceptable expressions for
12883 // the left hand side of the comma operator, otherwise emit a warning.
12884 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12885 // No warnings in macros
12886 if (Loc.isMacroID())
12889 // Don't warn in template instantiations.
12890 if (inTemplateInstantiation())
12893 // Scope isn't fine-grained enough to explicitly list the specific cases, so
12894 // instead, skip more than needed, then call back into here with the
12895 // CommaVisitor in SemaStmt.cpp.
12896 // The listed locations are the initialization and increment portions
12897 // of a for loop. The additional checks are on the condition of
12898 // if statements, do/while loops, and for loops.
12899 // Differences in scope flags for C89 mode requires the extra logic.
12900 const unsigned ForIncrementFlags =
12901 getLangOpts().C99 || getLangOpts().CPlusPlus
12902 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12903 : Scope::ContinueScope | Scope::BreakScope;
12904 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12905 const unsigned ScopeFlags = getCurScope()->getFlags();
12906 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12907 (ScopeFlags & ForInitFlags) == ForInitFlags)
12910 // If there are multiple comma operators used together, get the RHS of the
12911 // of the comma operator as the LHS.
12912 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12913 if (BO->getOpcode() != BO_Comma)
12915 LHS = BO->getRHS();
12918 // Only allow some expressions on LHS to not warn.
12919 if (IgnoreCommaOperand(LHS))
12922 Diag(Loc, diag::warn_comma_operator);
12923 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12924 << LHS->getSourceRange()
12925 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12926 LangOpts.CPlusPlus ? "static_cast<void>("
12928 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12933 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12934 SourceLocation Loc) {
12935 LHS = S.CheckPlaceholderExpr(LHS.get());
12936 RHS = S.CheckPlaceholderExpr(RHS.get());
12937 if (LHS.isInvalid() || RHS.isInvalid())
12940 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12941 // operands, but not unary promotions.
12942 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12944 // So we treat the LHS as a ignored value, and in C++ we allow the
12945 // containing site to determine what should be done with the RHS.
12946 LHS = S.IgnoredValueConversions(LHS.get());
12947 if (LHS.isInvalid())
12950 S.DiagnoseUnusedExprResult(LHS.get());
12952 if (!S.getLangOpts().CPlusPlus) {
12953 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12954 if (RHS.isInvalid())
12956 if (!RHS.get()->getType()->isVoidType())
12957 S.RequireCompleteType(Loc, RHS.get()->getType(),
12958 diag::err_incomplete_type);
12961 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12962 S.DiagnoseCommaOperator(LHS.get(), Loc);
12964 return RHS.get()->getType();
12967 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12968 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12969 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12971 ExprObjectKind &OK,
12972 SourceLocation OpLoc,
12973 bool IsInc, bool IsPrefix) {
12974 if (Op->isTypeDependent())
12975 return S.Context.DependentTy;
12977 QualType ResType = Op->getType();
12978 // Atomic types can be used for increment / decrement where the non-atomic
12979 // versions can, so ignore the _Atomic() specifier for the purpose of
12981 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12982 ResType = ResAtomicType->getValueType();
12984 assert(!ResType.isNull() && "no type for increment/decrement expression");
12986 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12987 // Decrement of bool is not allowed.
12989 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12992 // Increment of bool sets it to true, but is deprecated.
12993 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12994 : diag::warn_increment_bool)
12995 << Op->getSourceRange();
12996 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12997 // Error on enum increments and decrements in C++ mode
12998 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13000 } else if (ResType->isRealType()) {
13002 } else if (ResType->isPointerType()) {
13003 // C99 6.5.2.4p2, 6.5.6p2
13004 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13006 } else if (ResType->isObjCObjectPointerType()) {
13007 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13008 // Otherwise, we just need a complete type.
13009 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13010 checkArithmeticOnObjCPointer(S, OpLoc, Op))
13012 } else if (ResType->isAnyComplexType()) {
13013 // C99 does not support ++/-- on complex types, we allow as an extension.
13014 S.Diag(OpLoc, diag::ext_integer_increment_complex)
13015 << ResType << Op->getSourceRange();
13016 } else if (ResType->isPlaceholderType()) {
13017 ExprResult PR = S.CheckPlaceholderExpr(Op);
13018 if (PR.isInvalid()) return QualType();
13019 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13021 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13022 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13023 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13024 (ResType->castAs<VectorType>()->getVectorKind() !=
13025 VectorType::AltiVecBool)) {
13026 // The z vector extensions allow ++ and -- for non-bool vectors.
13027 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13028 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13029 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13031 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13032 << ResType << int(IsInc) << Op->getSourceRange();
13035 // At this point, we know we have a real, complex or pointer type.
13036 // Now make sure the operand is a modifiable lvalue.
13037 if (CheckForModifiableLvalue(Op, OpLoc, S))
13039 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13040 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13041 // An operand with volatile-qualified type is deprecated
13042 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13043 << IsInc << ResType;
13045 // In C++, a prefix increment is the same type as the operand. Otherwise
13046 // (in C or with postfix), the increment is the unqualified type of the
13048 if (IsPrefix && S.getLangOpts().CPlusPlus) {
13050 OK = Op->getObjectKind();
13054 return ResType.getUnqualifiedType();
13059 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13060 /// This routine allows us to typecheck complex/recursive expressions
13061 /// where the declaration is needed for type checking. We only need to
13062 /// handle cases when the expression references a function designator
13063 /// or is an lvalue. Here are some examples:
13065 /// - &*****f => f for f a function designator.
13067 /// - &s.zz[1].yy -> s, if zz is an array
13068 /// - *(x + 1) -> x, if x is an array
13069 /// - &"123"[2] -> 0
13070 /// - & __real__ x -> x
13072 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13074 static ValueDecl *getPrimaryDecl(Expr *E) {
13075 switch (E->getStmtClass()) {
13076 case Stmt::DeclRefExprClass:
13077 return cast<DeclRefExpr>(E)->getDecl();
13078 case Stmt::MemberExprClass:
13079 // If this is an arrow operator, the address is an offset from
13080 // the base's value, so the object the base refers to is
13082 if (cast<MemberExpr>(E)->isArrow())
13084 // Otherwise, the expression refers to a part of the base
13085 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13086 case Stmt::ArraySubscriptExprClass: {
13087 // FIXME: This code shouldn't be necessary! We should catch the implicit
13088 // promotion of register arrays earlier.
13089 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13090 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13091 if (ICE->getSubExpr()->getType()->isArrayType())
13092 return getPrimaryDecl(ICE->getSubExpr());
13096 case Stmt::UnaryOperatorClass: {
13097 UnaryOperator *UO = cast<UnaryOperator>(E);
13099 switch(UO->getOpcode()) {
13103 return getPrimaryDecl(UO->getSubExpr());
13108 case Stmt::ParenExprClass:
13109 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13110 case Stmt::ImplicitCastExprClass:
13111 // If the result of an implicit cast is an l-value, we care about
13112 // the sub-expression; otherwise, the result here doesn't matter.
13113 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13114 case Stmt::CXXUuidofExprClass:
13115 return cast<CXXUuidofExpr>(E)->getGuidDecl();
13124 AO_Vector_Element = 1,
13125 AO_Property_Expansion = 2,
13126 AO_Register_Variable = 3,
13127 AO_Matrix_Element = 4,
13131 /// Diagnose invalid operand for address of operations.
13133 /// \param Type The type of operand which cannot have its address taken.
13134 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13135 Expr *E, unsigned Type) {
13136 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13139 /// CheckAddressOfOperand - The operand of & must be either a function
13140 /// designator or an lvalue designating an object. If it is an lvalue, the
13141 /// object cannot be declared with storage class register or be a bit field.
13142 /// Note: The usual conversions are *not* applied to the operand of the &
13143 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13144 /// In C++, the operand might be an overloaded function name, in which case
13145 /// we allow the '&' but retain the overloaded-function type.
13146 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13147 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13148 if (PTy->getKind() == BuiltinType::Overload) {
13149 Expr *E = OrigOp.get()->IgnoreParens();
13150 if (!isa<OverloadExpr>(E)) {
13151 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13152 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13153 << OrigOp.get()->getSourceRange();
13157 OverloadExpr *Ovl = cast<OverloadExpr>(E);
13158 if (isa<UnresolvedMemberExpr>(Ovl))
13159 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13160 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13161 << OrigOp.get()->getSourceRange();
13165 return Context.OverloadTy;
13168 if (PTy->getKind() == BuiltinType::UnknownAny)
13169 return Context.UnknownAnyTy;
13171 if (PTy->getKind() == BuiltinType::BoundMember) {
13172 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13173 << OrigOp.get()->getSourceRange();
13177 OrigOp = CheckPlaceholderExpr(OrigOp.get());
13178 if (OrigOp.isInvalid()) return QualType();
13181 if (OrigOp.get()->isTypeDependent())
13182 return Context.DependentTy;
13184 assert(!OrigOp.get()->getType()->isPlaceholderType());
13186 // Make sure to ignore parentheses in subsequent checks
13187 Expr *op = OrigOp.get()->IgnoreParens();
13189 // In OpenCL captures for blocks called as lambda functions
13190 // are located in the private address space. Blocks used in
13191 // enqueue_kernel can be located in a different address space
13192 // depending on a vendor implementation. Thus preventing
13193 // taking an address of the capture to avoid invalid AS casts.
13194 if (LangOpts.OpenCL) {
13195 auto* VarRef = dyn_cast<DeclRefExpr>(op);
13196 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13197 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13202 if (getLangOpts().C99) {
13203 // Implement C99-only parts of addressof rules.
13204 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13205 if (uOp->getOpcode() == UO_Deref)
13206 // Per C99 6.5.3.2, the address of a deref always returns a valid result
13207 // (assuming the deref expression is valid).
13208 return uOp->getSubExpr()->getType();
13210 // Technically, there should be a check for array subscript
13211 // expressions here, but the result of one is always an lvalue anyway.
13213 ValueDecl *dcl = getPrimaryDecl(op);
13215 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13216 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13217 op->getBeginLoc()))
13220 Expr::LValueClassification lval = op->ClassifyLValue(Context);
13221 unsigned AddressOfError = AO_No_Error;
13223 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13224 bool sfinae = (bool)isSFINAEContext();
13225 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13226 : diag::ext_typecheck_addrof_temporary)
13227 << op->getType() << op->getSourceRange();
13230 // Materialize the temporary as an lvalue so that we can take its address.
13232 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13233 } else if (isa<ObjCSelectorExpr>(op)) {
13234 return Context.getPointerType(op->getType());
13235 } else if (lval == Expr::LV_MemberFunction) {
13236 // If it's an instance method, make a member pointer.
13237 // The expression must have exactly the form &A::foo.
13239 // If the underlying expression isn't a decl ref, give up.
13240 if (!isa<DeclRefExpr>(op)) {
13241 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13242 << OrigOp.get()->getSourceRange();
13245 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13246 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13248 // The id-expression was parenthesized.
13249 if (OrigOp.get() != DRE) {
13250 Diag(OpLoc, diag::err_parens_pointer_member_function)
13251 << OrigOp.get()->getSourceRange();
13253 // The method was named without a qualifier.
13254 } else if (!DRE->getQualifier()) {
13255 if (MD->getParent()->getName().empty())
13256 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13257 << op->getSourceRange();
13259 SmallString<32> Str;
13260 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13261 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13262 << op->getSourceRange()
13263 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13267 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13268 if (isa<CXXDestructorDecl>(MD))
13269 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13271 QualType MPTy = Context.getMemberPointerType(
13272 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13273 // Under the MS ABI, lock down the inheritance model now.
13274 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13275 (void)isCompleteType(OpLoc, MPTy);
13277 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13279 // The operand must be either an l-value or a function designator
13280 if (!op->getType()->isFunctionType()) {
13281 // Use a special diagnostic for loads from property references.
13282 if (isa<PseudoObjectExpr>(op)) {
13283 AddressOfError = AO_Property_Expansion;
13285 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13286 << op->getType() << op->getSourceRange();
13290 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13291 // The operand cannot be a bit-field
13292 AddressOfError = AO_Bit_Field;
13293 } else if (op->getObjectKind() == OK_VectorComponent) {
13294 // The operand cannot be an element of a vector
13295 AddressOfError = AO_Vector_Element;
13296 } else if (op->getObjectKind() == OK_MatrixComponent) {
13297 // The operand cannot be an element of a matrix.
13298 AddressOfError = AO_Matrix_Element;
13299 } else if (dcl) { // C99 6.5.3.2p1
13300 // We have an lvalue with a decl. Make sure the decl is not declared
13301 // with the register storage-class specifier.
13302 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13303 // in C++ it is not error to take address of a register
13304 // variable (c++03 7.1.1P3)
13305 if (vd->getStorageClass() == SC_Register &&
13306 !getLangOpts().CPlusPlus) {
13307 AddressOfError = AO_Register_Variable;
13309 } else if (isa<MSPropertyDecl>(dcl)) {
13310 AddressOfError = AO_Property_Expansion;
13311 } else if (isa<FunctionTemplateDecl>(dcl)) {
13312 return Context.OverloadTy;
13313 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13314 // Okay: we can take the address of a field.
13315 // Could be a pointer to member, though, if there is an explicit
13316 // scope qualifier for the class.
13317 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13318 DeclContext *Ctx = dcl->getDeclContext();
13319 if (Ctx && Ctx->isRecord()) {
13320 if (dcl->getType()->isReferenceType()) {
13322 diag::err_cannot_form_pointer_to_member_of_reference_type)
13323 << dcl->getDeclName() << dcl->getType();
13327 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13328 Ctx = Ctx->getParent();
13330 QualType MPTy = Context.getMemberPointerType(
13332 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13333 // Under the MS ABI, lock down the inheritance model now.
13334 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13335 (void)isCompleteType(OpLoc, MPTy);
13339 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13340 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13341 llvm_unreachable("Unknown/unexpected decl type");
13344 if (AddressOfError != AO_No_Error) {
13345 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13349 if (lval == Expr::LV_IncompleteVoidType) {
13350 // Taking the address of a void variable is technically illegal, but we
13351 // allow it in cases which are otherwise valid.
13352 // Example: "extern void x; void* y = &x;".
13353 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13356 // If the operand has type "type", the result has type "pointer to type".
13357 if (op->getType()->isObjCObjectType())
13358 return Context.getObjCObjectPointerType(op->getType());
13360 CheckAddressOfPackedMember(op);
13362 return Context.getPointerType(op->getType());
13365 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13366 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13369 const Decl *D = DRE->getDecl();
13372 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13375 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13376 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13378 if (FunctionScopeInfo *FD = S.getCurFunction())
13379 if (!FD->ModifiedNonNullParams.count(Param))
13380 FD->ModifiedNonNullParams.insert(Param);
13383 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
13384 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13385 SourceLocation OpLoc) {
13386 if (Op->isTypeDependent())
13387 return S.Context.DependentTy;
13389 ExprResult ConvResult = S.UsualUnaryConversions(Op);
13390 if (ConvResult.isInvalid())
13392 Op = ConvResult.get();
13393 QualType OpTy = Op->getType();
13396 if (isa<CXXReinterpretCastExpr>(Op)) {
13397 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13398 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13399 Op->getSourceRange());
13402 if (const PointerType *PT = OpTy->getAs<PointerType>())
13404 Result = PT->getPointeeType();
13406 else if (const ObjCObjectPointerType *OPT =
13407 OpTy->getAs<ObjCObjectPointerType>())
13408 Result = OPT->getPointeeType();
13410 ExprResult PR = S.CheckPlaceholderExpr(Op);
13411 if (PR.isInvalid()) return QualType();
13412 if (PR.get() != Op)
13413 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13416 if (Result.isNull()) {
13417 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13418 << OpTy << Op->getSourceRange();
13422 // Note that per both C89 and C99, indirection is always legal, even if Result
13423 // is an incomplete type or void. It would be possible to warn about
13424 // dereferencing a void pointer, but it's completely well-defined, and such a
13425 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13426 // for pointers to 'void' but is fine for any other pointer type:
13428 // C++ [expr.unary.op]p1:
13429 // [...] the expression to which [the unary * operator] is applied shall
13430 // be a pointer to an object type, or a pointer to a function type
13431 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13432 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13433 << OpTy << Op->getSourceRange();
13435 // Dereferences are usually l-values...
13438 // ...except that certain expressions are never l-values in C.
13439 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13445 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13446 BinaryOperatorKind Opc;
13448 default: llvm_unreachable("Unknown binop!");
13449 case tok::periodstar: Opc = BO_PtrMemD; break;
13450 case tok::arrowstar: Opc = BO_PtrMemI; break;
13451 case tok::star: Opc = BO_Mul; break;
13452 case tok::slash: Opc = BO_Div; break;
13453 case tok::percent: Opc = BO_Rem; break;
13454 case tok::plus: Opc = BO_Add; break;
13455 case tok::minus: Opc = BO_Sub; break;
13456 case tok::lessless: Opc = BO_Shl; break;
13457 case tok::greatergreater: Opc = BO_Shr; break;
13458 case tok::lessequal: Opc = BO_LE; break;
13459 case tok::less: Opc = BO_LT; break;
13460 case tok::greaterequal: Opc = BO_GE; break;
13461 case tok::greater: Opc = BO_GT; break;
13462 case tok::exclaimequal: Opc = BO_NE; break;
13463 case tok::equalequal: Opc = BO_EQ; break;
13464 case tok::spaceship: Opc = BO_Cmp; break;
13465 case tok::amp: Opc = BO_And; break;
13466 case tok::caret: Opc = BO_Xor; break;
13467 case tok::pipe: Opc = BO_Or; break;
13468 case tok::ampamp: Opc = BO_LAnd; break;
13469 case tok::pipepipe: Opc = BO_LOr; break;
13470 case tok::equal: Opc = BO_Assign; break;
13471 case tok::starequal: Opc = BO_MulAssign; break;
13472 case tok::slashequal: Opc = BO_DivAssign; break;
13473 case tok::percentequal: Opc = BO_RemAssign; break;
13474 case tok::plusequal: Opc = BO_AddAssign; break;
13475 case tok::minusequal: Opc = BO_SubAssign; break;
13476 case tok::lesslessequal: Opc = BO_ShlAssign; break;
13477 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
13478 case tok::ampequal: Opc = BO_AndAssign; break;
13479 case tok::caretequal: Opc = BO_XorAssign; break;
13480 case tok::pipeequal: Opc = BO_OrAssign; break;
13481 case tok::comma: Opc = BO_Comma; break;
13486 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13487 tok::TokenKind Kind) {
13488 UnaryOperatorKind Opc;
13490 default: llvm_unreachable("Unknown unary op!");
13491 case tok::plusplus: Opc = UO_PreInc; break;
13492 case tok::minusminus: Opc = UO_PreDec; break;
13493 case tok::amp: Opc = UO_AddrOf; break;
13494 case tok::star: Opc = UO_Deref; break;
13495 case tok::plus: Opc = UO_Plus; break;
13496 case tok::minus: Opc = UO_Minus; break;
13497 case tok::tilde: Opc = UO_Not; break;
13498 case tok::exclaim: Opc = UO_LNot; break;
13499 case tok::kw___real: Opc = UO_Real; break;
13500 case tok::kw___imag: Opc = UO_Imag; break;
13501 case tok::kw___extension__: Opc = UO_Extension; break;
13506 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13507 /// This warning suppressed in the event of macro expansions.
13508 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13509 SourceLocation OpLoc, bool IsBuiltin) {
13510 if (S.inTemplateInstantiation())
13512 if (S.isUnevaluatedContext())
13514 if (OpLoc.isInvalid() || OpLoc.isMacroID())
13516 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13517 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13518 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13519 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13520 if (!LHSDeclRef || !RHSDeclRef ||
13521 LHSDeclRef->getLocation().isMacroID() ||
13522 RHSDeclRef->getLocation().isMacroID())
13524 const ValueDecl *LHSDecl =
13525 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13526 const ValueDecl *RHSDecl =
13527 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13528 if (LHSDecl != RHSDecl)
13530 if (LHSDecl->getType().isVolatileQualified())
13532 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13533 if (RefTy->getPointeeType().isVolatileQualified())
13536 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13537 : diag::warn_self_assignment_overloaded)
13538 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13539 << RHSExpr->getSourceRange();
13542 /// Check if a bitwise-& is performed on an Objective-C pointer. This
13543 /// is usually indicative of introspection within the Objective-C pointer.
13544 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13545 SourceLocation OpLoc) {
13546 if (!S.getLangOpts().ObjC)
13549 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13550 const Expr *LHS = L.get();
13551 const Expr *RHS = R.get();
13553 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13554 ObjCPointerExpr = LHS;
13557 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13558 ObjCPointerExpr = RHS;
13562 // This warning is deliberately made very specific to reduce false
13563 // positives with logic that uses '&' for hashing. This logic mainly
13564 // looks for code trying to introspect into tagged pointers, which
13565 // code should generally never do.
13566 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13567 unsigned Diag = diag::warn_objc_pointer_masking;
13568 // Determine if we are introspecting the result of performSelectorXXX.
13569 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13570 // Special case messages to -performSelector and friends, which
13571 // can return non-pointer values boxed in a pointer value.
13572 // Some clients may wish to silence warnings in this subcase.
13573 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13574 Selector S = ME->getSelector();
13575 StringRef SelArg0 = S.getNameForSlot(0);
13576 if (SelArg0.startswith("performSelector"))
13577 Diag = diag::warn_objc_pointer_masking_performSelector;
13580 S.Diag(OpLoc, Diag)
13581 << ObjCPointerExpr->getSourceRange();
13585 static NamedDecl *getDeclFromExpr(Expr *E) {
13588 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13589 return DRE->getDecl();
13590 if (auto *ME = dyn_cast<MemberExpr>(E))
13591 return ME->getMemberDecl();
13592 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13593 return IRE->getDecl();
13597 // This helper function promotes a binary operator's operands (which are of a
13598 // half vector type) to a vector of floats and then truncates the result to
13599 // a vector of either half or short.
13600 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13601 BinaryOperatorKind Opc, QualType ResultTy,
13602 ExprValueKind VK, ExprObjectKind OK,
13603 bool IsCompAssign, SourceLocation OpLoc,
13604 FPOptionsOverride FPFeatures) {
13605 auto &Context = S.getASTContext();
13606 assert((isVector(ResultTy, Context.HalfTy) ||
13607 isVector(ResultTy, Context.ShortTy)) &&
13608 "Result must be a vector of half or short");
13609 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13610 isVector(RHS.get()->getType(), Context.HalfTy) &&
13611 "both operands expected to be a half vector");
13613 RHS = convertVector(RHS.get(), Context.FloatTy, S);
13614 QualType BinOpResTy = RHS.get()->getType();
13616 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13617 // change BinOpResTy to a vector of ints.
13618 if (isVector(ResultTy, Context.ShortTy))
13619 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13622 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13623 ResultTy, VK, OK, OpLoc, FPFeatures,
13624 BinOpResTy, BinOpResTy);
13626 LHS = convertVector(LHS.get(), Context.FloatTy, S);
13627 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13628 BinOpResTy, VK, OK, OpLoc, FPFeatures);
13629 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13632 static std::pair<ExprResult, ExprResult>
13633 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13635 ExprResult LHS = LHSExpr, RHS = RHSExpr;
13636 if (!S.getLangOpts().CPlusPlus) {
13637 // C cannot handle TypoExpr nodes on either side of a binop because it
13638 // doesn't handle dependent types properly, so make sure any TypoExprs have
13639 // been dealt with before checking the operands.
13640 LHS = S.CorrectDelayedTyposInExpr(LHS);
13641 RHS = S.CorrectDelayedTyposInExpr(
13642 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13643 [Opc, LHS](Expr *E) {
13644 if (Opc != BO_Assign)
13645 return ExprResult(E);
13646 // Avoid correcting the RHS to the same Expr as the LHS.
13647 Decl *D = getDeclFromExpr(E);
13648 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13651 return std::make_pair(LHS, RHS);
13654 /// Returns true if conversion between vectors of halfs and vectors of floats
13656 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13657 Expr *E0, Expr *E1 = nullptr) {
13658 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13659 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13662 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13663 QualType Ty = E->IgnoreImplicit()->getType();
13665 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13666 // to vectors of floats. Although the element type of the vectors is __fp16,
13667 // the vectors shouldn't be treated as storage-only types. See the
13668 // discussion here: https://reviews.llvm.org/rG825235c140e7
13669 if (const VectorType *VT = Ty->getAs<VectorType>()) {
13670 if (VT->getVectorKind() == VectorType::NeonVector)
13672 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13677 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13680 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13681 /// operator @p Opc at location @c TokLoc. This routine only supports
13682 /// built-in operations; ActOnBinOp handles overloaded operators.
13683 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13684 BinaryOperatorKind Opc,
13685 Expr *LHSExpr, Expr *RHSExpr) {
13686 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13687 // The syntax only allows initializer lists on the RHS of assignment,
13688 // so we don't need to worry about accepting invalid code for
13689 // non-assignment operators.
13691 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13692 // of x = {} is x = T().
13693 InitializationKind Kind = InitializationKind::CreateDirectList(
13694 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13695 InitializedEntity Entity =
13696 InitializedEntity::InitializeTemporary(LHSExpr->getType());
13697 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13698 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13699 if (Init.isInvalid())
13701 RHSExpr = Init.get();
13704 ExprResult LHS = LHSExpr, RHS = RHSExpr;
13705 QualType ResultTy; // Result type of the binary operator.
13706 // The following two variables are used for compound assignment operators
13707 QualType CompLHSTy; // Type of LHS after promotions for computation
13708 QualType CompResultTy; // Type of computation result
13709 ExprValueKind VK = VK_RValue;
13710 ExprObjectKind OK = OK_Ordinary;
13711 bool ConvertHalfVec = false;
13713 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13714 if (!LHS.isUsable() || !RHS.isUsable())
13715 return ExprError();
13717 if (getLangOpts().OpenCL) {
13718 QualType LHSTy = LHSExpr->getType();
13719 QualType RHSTy = RHSExpr->getType();
13720 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13721 // the ATOMIC_VAR_INIT macro.
13722 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13723 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13724 if (BO_Assign == Opc)
13725 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13727 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13728 return ExprError();
13731 // OpenCL special types - image, sampler, pipe, and blocks are to be used
13732 // only with a builtin functions and therefore should be disallowed here.
13733 if (LHSTy->isImageType() || RHSTy->isImageType() ||
13734 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13735 LHSTy->isPipeType() || RHSTy->isPipeType() ||
13736 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13737 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13738 return ExprError();
13744 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13745 if (getLangOpts().CPlusPlus &&
13746 LHS.get()->getObjectKind() != OK_ObjCProperty) {
13747 VK = LHS.get()->getValueKind();
13748 OK = LHS.get()->getObjectKind();
13750 if (!ResultTy.isNull()) {
13751 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13752 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13754 // Avoid copying a block to the heap if the block is assigned to a local
13755 // auto variable that is declared in the same scope as the block. This
13756 // optimization is unsafe if the local variable is declared in an outer
13757 // scope. For example:
13763 // // It is unsafe to invoke the block here if it wasn't copied to the
13767 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13768 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13769 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13770 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13771 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13773 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13774 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13775 NTCUC_Assignment, NTCUK_Copy);
13777 RecordModifiableNonNullParam(*this, LHS.get());
13781 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13782 Opc == BO_PtrMemI);
13786 ConvertHalfVec = true;
13787 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13791 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13794 ConvertHalfVec = true;
13795 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13798 ConvertHalfVec = true;
13799 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13803 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13809 ConvertHalfVec = true;
13810 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13814 ConvertHalfVec = true;
13815 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13818 ConvertHalfVec = true;
13819 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13820 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13823 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13827 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13831 ConvertHalfVec = true;
13832 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13836 ConvertHalfVec = true;
13837 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13838 Opc == BO_DivAssign);
13839 CompLHSTy = CompResultTy;
13840 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13841 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13844 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13845 CompLHSTy = CompResultTy;
13846 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13847 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13850 ConvertHalfVec = true;
13851 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13852 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13853 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13856 ConvertHalfVec = true;
13857 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13858 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13859 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13863 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13864 CompLHSTy = CompResultTy;
13865 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13866 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13869 case BO_OrAssign: // fallthrough
13870 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13873 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13874 CompLHSTy = CompResultTy;
13875 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13876 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13879 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13880 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13881 VK = RHS.get()->getValueKind();
13882 OK = RHS.get()->getObjectKind();
13886 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13887 return ExprError();
13889 // Some of the binary operations require promoting operands of half vector to
13890 // float vectors and truncating the result back to half vector. For now, we do
13891 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13893 assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13894 isVector(LHS.get()->getType(), Context.HalfTy) &&
13895 "both sides are half vectors or neither sides are");
13897 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
13899 // Check for array bounds violations for both sides of the BinaryOperator
13900 CheckArrayAccess(LHS.get());
13901 CheckArrayAccess(RHS.get());
13903 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13904 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13905 &Context.Idents.get("object_setClass"),
13906 SourceLocation(), LookupOrdinaryName);
13907 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13908 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13909 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13910 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13911 "object_setClass(")
13912 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13914 << FixItHint::CreateInsertion(RHSLocEnd, ")");
13917 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13919 else if (const ObjCIvarRefExpr *OIRE =
13920 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13921 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13923 // Opc is not a compound assignment if CompResultTy is null.
13924 if (CompResultTy.isNull()) {
13925 if (ConvertHalfVec)
13926 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13927 OpLoc, CurFPFeatureOverrides());
13928 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
13929 VK, OK, OpLoc, CurFPFeatureOverrides());
13932 // Handle compound assignments.
13933 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13936 OK = LHS.get()->getObjectKind();
13939 // The LHS is not converted to the result type for fixed-point compound
13940 // assignment as the common type is computed on demand. Reset the CompLHSTy
13941 // to the LHS type we would have gotten after unary conversions.
13942 if (CompResultTy->isFixedPointType())
13943 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
13945 if (ConvertHalfVec)
13946 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13947 OpLoc, CurFPFeatureOverrides());
13949 return CompoundAssignOperator::Create(
13950 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
13951 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
13954 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13955 /// operators are mixed in a way that suggests that the programmer forgot that
13956 /// comparison operators have higher precedence. The most typical example of
13957 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13958 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13959 SourceLocation OpLoc, Expr *LHSExpr,
13961 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13962 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13964 // Check that one of the sides is a comparison operator and the other isn't.
13965 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13966 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13967 if (isLeftComp == isRightComp)
13970 // Bitwise operations are sometimes used as eager logical ops.
13971 // Don't diagnose this.
13972 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13973 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13974 if (isLeftBitwise || isRightBitwise)
13977 SourceRange DiagRange = isLeftComp
13978 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13979 : SourceRange(OpLoc, RHSExpr->getEndLoc());
13980 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13981 SourceRange ParensRange =
13983 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13984 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13986 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13987 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13988 SuggestParentheses(Self, OpLoc,
13989 Self.PDiag(diag::note_precedence_silence) << OpStr,
13990 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13991 SuggestParentheses(Self, OpLoc,
13992 Self.PDiag(diag::note_precedence_bitwise_first)
13993 << BinaryOperator::getOpcodeStr(Opc),
13997 /// It accepts a '&&' expr that is inside a '||' one.
13998 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13999 /// in parentheses.
14001 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14002 BinaryOperator *Bop) {
14003 assert(Bop->getOpcode() == BO_LAnd);
14004 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14005 << Bop->getSourceRange() << OpLoc;
14006 SuggestParentheses(Self, Bop->getOperatorLoc(),
14007 Self.PDiag(diag::note_precedence_silence)
14008 << Bop->getOpcodeStr(),
14009 Bop->getSourceRange());
14012 /// Returns true if the given expression can be evaluated as a constant
14014 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14016 return !E->isValueDependent() &&
14017 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14020 /// Returns true if the given expression can be evaluated as a constant
14022 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14024 return !E->isValueDependent() &&
14025 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14028 /// Look for '&&' in the left hand of a '||' expr.
14029 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14030 Expr *LHSExpr, Expr *RHSExpr) {
14031 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14032 if (Bop->getOpcode() == BO_LAnd) {
14033 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14034 if (EvaluatesAsFalse(S, RHSExpr))
14036 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14037 if (!EvaluatesAsTrue(S, Bop->getLHS()))
14038 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14039 } else if (Bop->getOpcode() == BO_LOr) {
14040 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14041 // If it's "a || b && 1 || c" we didn't warn earlier for
14042 // "a || b && 1", but warn now.
14043 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14044 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14050 /// Look for '&&' in the right hand of a '||' expr.
14051 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14052 Expr *LHSExpr, Expr *RHSExpr) {
14053 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14054 if (Bop->getOpcode() == BO_LAnd) {
14055 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14056 if (EvaluatesAsFalse(S, LHSExpr))
14058 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14059 if (!EvaluatesAsTrue(S, Bop->getRHS()))
14060 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14065 /// Look for bitwise op in the left or right hand of a bitwise op with
14066 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14067 /// the '&' expression in parentheses.
14068 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14069 SourceLocation OpLoc, Expr *SubExpr) {
14070 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14071 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14072 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14073 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14074 << Bop->getSourceRange() << OpLoc;
14075 SuggestParentheses(S, Bop->getOperatorLoc(),
14076 S.PDiag(diag::note_precedence_silence)
14077 << Bop->getOpcodeStr(),
14078 Bop->getSourceRange());
14083 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14084 Expr *SubExpr, StringRef Shift) {
14085 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14086 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14087 StringRef Op = Bop->getOpcodeStr();
14088 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14089 << Bop->getSourceRange() << OpLoc << Shift << Op;
14090 SuggestParentheses(S, Bop->getOperatorLoc(),
14091 S.PDiag(diag::note_precedence_silence) << Op,
14092 Bop->getSourceRange());
14097 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14098 Expr *LHSExpr, Expr *RHSExpr) {
14099 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14103 FunctionDecl *FD = OCE->getDirectCallee();
14104 if (!FD || !FD->isOverloadedOperator())
14107 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14108 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14111 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14112 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14113 << (Kind == OO_LessLess);
14114 SuggestParentheses(S, OCE->getOperatorLoc(),
14115 S.PDiag(diag::note_precedence_silence)
14116 << (Kind == OO_LessLess ? "<<" : ">>"),
14117 OCE->getSourceRange());
14118 SuggestParentheses(
14119 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14120 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14123 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14125 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14126 SourceLocation OpLoc, Expr *LHSExpr,
14128 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14129 if (BinaryOperator::isBitwiseOp(Opc))
14130 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14132 // Diagnose "arg1 & arg2 | arg3"
14133 if ((Opc == BO_Or || Opc == BO_Xor) &&
14134 !OpLoc.isMacroID()/* Don't warn in macros. */) {
14135 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14136 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14139 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14140 // We don't warn for 'assert(a || b && "bad")' since this is safe.
14141 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14142 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14143 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14146 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14147 || Opc == BO_Shr) {
14148 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14149 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14150 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14153 // Warn on overloaded shift operators and comparisons, such as:
14155 if (BinaryOperator::isComparisonOp(Opc))
14156 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14159 // Binary Operators. 'Tok' is the token for the operator.
14160 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14161 tok::TokenKind Kind,
14162 Expr *LHSExpr, Expr *RHSExpr) {
14163 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14164 assert(LHSExpr && "ActOnBinOp(): missing left expression");
14165 assert(RHSExpr && "ActOnBinOp(): missing right expression");
14167 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14168 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14170 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14173 /// Build an overloaded binary operator expression in the given scope.
14174 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14175 BinaryOperatorKind Opc,
14176 Expr *LHS, Expr *RHS) {
14185 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14186 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14192 // Find all of the overloaded operators visible from this
14193 // point. We perform both an operator-name lookup from the local
14194 // scope and an argument-dependent lookup based on the types of
14196 UnresolvedSet<16> Functions;
14197 OverloadedOperatorKind OverOp
14198 = BinaryOperator::getOverloadedOperator(Opc);
14199 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
14200 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
14201 RHS->getType(), Functions);
14203 // In C++20 onwards, we may have a second operator to look up.
14204 if (S.getLangOpts().CPlusPlus20) {
14205 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14206 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
14207 RHS->getType(), Functions);
14210 // Build the (potentially-overloaded, potentially-dependent)
14211 // binary operation.
14212 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14215 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14216 BinaryOperatorKind Opc,
14217 Expr *LHSExpr, Expr *RHSExpr) {
14218 ExprResult LHS, RHS;
14219 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14220 if (!LHS.isUsable() || !RHS.isUsable())
14221 return ExprError();
14222 LHSExpr = LHS.get();
14223 RHSExpr = RHS.get();
14225 // We want to end up calling one of checkPseudoObjectAssignment
14226 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14227 // both expressions are overloadable or either is type-dependent),
14228 // or CreateBuiltinBinOp (in any other case). We also want to get
14229 // any placeholder types out of the way.
14231 // Handle pseudo-objects in the LHS.
14232 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14233 // Assignments with a pseudo-object l-value need special analysis.
14234 if (pty->getKind() == BuiltinType::PseudoObject &&
14235 BinaryOperator::isAssignmentOp(Opc))
14236 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14238 // Don't resolve overloads if the other type is overloadable.
14239 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14240 // We can't actually test that if we still have a placeholder,
14241 // though. Fortunately, none of the exceptions we see in that
14242 // code below are valid when the LHS is an overload set. Note
14243 // that an overload set can be dependently-typed, but it never
14244 // instantiates to having an overloadable type.
14245 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14246 if (resolvedRHS.isInvalid()) return ExprError();
14247 RHSExpr = resolvedRHS.get();
14249 if (RHSExpr->isTypeDependent() ||
14250 RHSExpr->getType()->isOverloadableType())
14251 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14254 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14255 // template, diagnose the missing 'template' keyword instead of diagnosing
14256 // an invalid use of a bound member function.
14258 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14259 // to C++1z [over.over]/1.4, but we already checked for that case above.
14260 if (Opc == BO_LT && inTemplateInstantiation() &&
14261 (pty->getKind() == BuiltinType::BoundMember ||
14262 pty->getKind() == BuiltinType::Overload)) {
14263 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14264 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14265 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14266 return isa<FunctionTemplateDecl>(ND);
14268 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14269 : OE->getNameLoc(),
14270 diag::err_template_kw_missing)
14271 << OE->getName().getAsString() << "";
14272 return ExprError();
14276 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14277 if (LHS.isInvalid()) return ExprError();
14278 LHSExpr = LHS.get();
14281 // Handle pseudo-objects in the RHS.
14282 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14283 // An overload in the RHS can potentially be resolved by the type
14284 // being assigned to.
14285 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14286 if (getLangOpts().CPlusPlus &&
14287 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14288 LHSExpr->getType()->isOverloadableType()))
14289 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14291 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14294 // Don't resolve overloads if the other type is overloadable.
14295 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14296 LHSExpr->getType()->isOverloadableType())
14297 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14299 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14300 if (!resolvedRHS.isUsable()) return ExprError();
14301 RHSExpr = resolvedRHS.get();
14304 if (getLangOpts().CPlusPlus) {
14305 // If either expression is type-dependent, always build an
14307 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14308 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14310 // Otherwise, build an overloaded op if either expression has an
14311 // overloadable type.
14312 if (LHSExpr->getType()->isOverloadableType() ||
14313 RHSExpr->getType()->isOverloadableType())
14314 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14317 // Build a built-in binary operation.
14318 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14321 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14322 if (T.isNull() || T->isDependentType())
14325 if (!T->isPromotableIntegerType())
14328 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14331 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14332 UnaryOperatorKind Opc,
14334 ExprResult Input = InputExpr;
14335 ExprValueKind VK = VK_RValue;
14336 ExprObjectKind OK = OK_Ordinary;
14337 QualType resultType;
14338 bool CanOverflow = false;
14340 bool ConvertHalfVec = false;
14341 if (getLangOpts().OpenCL) {
14342 QualType Ty = InputExpr->getType();
14343 // The only legal unary operation for atomics is '&'.
14344 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14345 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14346 // only with a builtin functions and therefore should be disallowed here.
14347 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14348 || Ty->isBlockPointerType())) {
14349 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14350 << InputExpr->getType()
14351 << Input.get()->getSourceRange());
14360 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14362 Opc == UO_PreInc ||
14364 Opc == UO_PreInc ||
14366 CanOverflow = isOverflowingIntegerType(Context, resultType);
14369 resultType = CheckAddressOfOperand(Input, OpLoc);
14370 CheckAddressOfNoDeref(InputExpr);
14371 RecordModifiableNonNullParam(*this, InputExpr);
14374 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14375 if (Input.isInvalid()) return ExprError();
14376 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14381 CanOverflow = Opc == UO_Minus &&
14382 isOverflowingIntegerType(Context, Input.get()->getType());
14383 Input = UsualUnaryConversions(Input.get());
14384 if (Input.isInvalid()) return ExprError();
14385 // Unary plus and minus require promoting an operand of half vector to a
14386 // float vector and truncating the result back to a half vector. For now, we
14387 // do this only when HalfArgsAndReturns is set (that is, when the target is
14389 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14391 // If the operand is a half vector, promote it to a float vector.
14392 if (ConvertHalfVec)
14393 Input = convertVector(Input.get(), Context.FloatTy, *this);
14394 resultType = Input.get()->getType();
14395 if (resultType->isDependentType())
14397 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14399 else if (resultType->isVectorType() &&
14400 // The z vector extensions don't allow + or - with bool vectors.
14401 (!Context.getLangOpts().ZVector ||
14402 resultType->castAs<VectorType>()->getVectorKind() !=
14403 VectorType::AltiVecBool))
14405 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14407 resultType->isPointerType())
14410 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14411 << resultType << Input.get()->getSourceRange());
14413 case UO_Not: // bitwise complement
14414 Input = UsualUnaryConversions(Input.get());
14415 if (Input.isInvalid())
14416 return ExprError();
14417 resultType = Input.get()->getType();
14418 if (resultType->isDependentType())
14420 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14421 if (resultType->isComplexType() || resultType->isComplexIntegerType())
14422 // C99 does not support '~' for complex conjugation.
14423 Diag(OpLoc, diag::ext_integer_complement_complex)
14424 << resultType << Input.get()->getSourceRange();
14425 else if (resultType->hasIntegerRepresentation())
14427 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14428 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14429 // on vector float types.
14430 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14431 if (!T->isIntegerType())
14432 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14433 << resultType << Input.get()->getSourceRange());
14435 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14436 << resultType << Input.get()->getSourceRange());
14440 case UO_LNot: // logical negation
14441 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14442 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14443 if (Input.isInvalid()) return ExprError();
14444 resultType = Input.get()->getType();
14446 // Though we still have to promote half FP to float...
14447 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14448 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14449 resultType = Context.FloatTy;
14452 if (resultType->isDependentType())
14454 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14455 // C99 6.5.3.3p1: ok, fallthrough;
14456 if (Context.getLangOpts().CPlusPlus) {
14457 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14458 // operand contextually converted to bool.
14459 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14460 ScalarTypeToBooleanCastKind(resultType));
14461 } else if (Context.getLangOpts().OpenCL &&
14462 Context.getLangOpts().OpenCLVersion < 120) {
14463 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14464 // operate on scalar float types.
14465 if (!resultType->isIntegerType() && !resultType->isPointerType())
14466 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14467 << resultType << Input.get()->getSourceRange());
14469 } else if (resultType->isExtVectorType()) {
14470 if (Context.getLangOpts().OpenCL &&
14471 Context.getLangOpts().OpenCLVersion < 120 &&
14472 !Context.getLangOpts().OpenCLCPlusPlus) {
14473 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14474 // operate on vector float types.
14475 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14476 if (!T->isIntegerType())
14477 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14478 << resultType << Input.get()->getSourceRange());
14480 // Vector logical not returns the signed variant of the operand type.
14481 resultType = GetSignedVectorType(resultType);
14483 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14484 const VectorType *VTy = resultType->castAs<VectorType>();
14485 if (VTy->getVectorKind() != VectorType::GenericVector)
14486 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14487 << resultType << Input.get()->getSourceRange());
14489 // Vector logical not returns the signed variant of the operand type.
14490 resultType = GetSignedVectorType(resultType);
14493 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14494 << resultType << Input.get()->getSourceRange());
14497 // LNot always has type int. C99 6.5.3.3p5.
14498 // In C++, it's bool. C++ 5.3.1p8
14499 resultType = Context.getLogicalOperationType();
14503 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14504 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14505 // complex l-values to ordinary l-values and all other values to r-values.
14506 if (Input.isInvalid()) return ExprError();
14507 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14508 if (Input.get()->getValueKind() != VK_RValue &&
14509 Input.get()->getObjectKind() == OK_Ordinary)
14510 VK = Input.get()->getValueKind();
14511 } else if (!getLangOpts().CPlusPlus) {
14512 // In C, a volatile scalar is read by __imag. In C++, it is not.
14513 Input = DefaultLvalueConversion(Input.get());
14517 resultType = Input.get()->getType();
14518 VK = Input.get()->getValueKind();
14519 OK = Input.get()->getObjectKind();
14522 // It's unnecessary to represent the pass-through operator co_await in the
14523 // AST; just return the input expression instead.
14524 assert(!Input.get()->getType()->isDependentType() &&
14525 "the co_await expression must be non-dependant before "
14526 "building operator co_await");
14529 if (resultType.isNull() || Input.isInvalid())
14530 return ExprError();
14532 // Check for array bounds violations in the operand of the UnaryOperator,
14533 // except for the '*' and '&' operators that have to be handled specially
14534 // by CheckArrayAccess (as there are special cases like &array[arraysize]
14535 // that are explicitly defined as valid by the standard).
14536 if (Opc != UO_AddrOf && Opc != UO_Deref)
14537 CheckArrayAccess(Input.get());
14540 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14541 OpLoc, CanOverflow, CurFPFeatureOverrides());
14543 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14544 !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
14545 ExprEvalContexts.back().PossibleDerefs.insert(UO);
14547 // Convert the result back to a half vector.
14548 if (ConvertHalfVec)
14549 return convertVector(UO, Context.HalfTy, *this);
14553 /// Determine whether the given expression is a qualified member
14554 /// access expression, of a form that could be turned into a pointer to member
14555 /// with the address-of operator.
14556 bool Sema::isQualifiedMemberAccess(Expr *E) {
14557 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14558 if (!DRE->getQualifier())
14561 ValueDecl *VD = DRE->getDecl();
14562 if (!VD->isCXXClassMember())
14565 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14567 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14568 return Method->isInstance();
14573 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14574 if (!ULE->getQualifier())
14577 for (NamedDecl *D : ULE->decls()) {
14578 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14579 if (Method->isInstance())
14582 // Overload set does not contain methods.
14593 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14594 UnaryOperatorKind Opc, Expr *Input) {
14595 // First things first: handle placeholders so that the
14596 // overloaded-operator check considers the right type.
14597 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14598 // Increment and decrement of pseudo-object references.
14599 if (pty->getKind() == BuiltinType::PseudoObject &&
14600 UnaryOperator::isIncrementDecrementOp(Opc))
14601 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14603 // extension is always a builtin operator.
14604 if (Opc == UO_Extension)
14605 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14607 // & gets special logic for several kinds of placeholder.
14608 // The builtin code knows what to do.
14609 if (Opc == UO_AddrOf &&
14610 (pty->getKind() == BuiltinType::Overload ||
14611 pty->getKind() == BuiltinType::UnknownAny ||
14612 pty->getKind() == BuiltinType::BoundMember))
14613 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14615 // Anything else needs to be handled now.
14616 ExprResult Result = CheckPlaceholderExpr(Input);
14617 if (Result.isInvalid()) return ExprError();
14618 Input = Result.get();
14621 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14622 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14623 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14624 // Find all of the overloaded operators visible from this
14625 // point. We perform both an operator-name lookup from the local
14626 // scope and an argument-dependent lookup based on the types of
14628 UnresolvedSet<16> Functions;
14629 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14630 if (S && OverOp != OO_None)
14631 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
14634 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14637 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14640 // Unary Operators. 'Tok' is the token for the operator.
14641 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14642 tok::TokenKind Op, Expr *Input) {
14643 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14646 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
14647 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14648 LabelDecl *TheDecl) {
14649 TheDecl->markUsed(Context);
14650 // Create the AST node. The address of a label always has type 'void*'.
14651 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14652 Context.getPointerType(Context.VoidTy));
14655 void Sema::ActOnStartStmtExpr() {
14656 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14659 void Sema::ActOnStmtExprError() {
14660 // Note that function is also called by TreeTransform when leaving a
14661 // StmtExpr scope without rebuilding anything.
14663 DiscardCleanupsInEvaluationContext();
14664 PopExpressionEvaluationContext();
14667 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14668 SourceLocation RPLoc) {
14669 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14672 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14673 SourceLocation RPLoc, unsigned TemplateDepth) {
14674 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14675 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14677 if (hasAnyUnrecoverableErrorsInThisFunction())
14678 DiscardCleanupsInEvaluationContext();
14679 assert(!Cleanup.exprNeedsCleanups() &&
14680 "cleanups within StmtExpr not correctly bound!");
14681 PopExpressionEvaluationContext();
14683 // FIXME: there are a variety of strange constraints to enforce here, for
14684 // example, it is not possible to goto into a stmt expression apparently.
14685 // More semantic analysis is needed.
14687 // If there are sub-stmts in the compound stmt, take the type of the last one
14688 // as the type of the stmtexpr.
14689 QualType Ty = Context.VoidTy;
14690 bool StmtExprMayBindToTemp = false;
14691 if (!Compound->body_empty()) {
14692 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14693 if (const auto *LastStmt =
14694 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14695 if (const Expr *Value = LastStmt->getExprStmt()) {
14696 StmtExprMayBindToTemp = true;
14697 Ty = Value->getType();
14702 // FIXME: Check that expression type is complete/non-abstract; statement
14703 // expressions are not lvalues.
14704 Expr *ResStmtExpr =
14705 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14706 if (StmtExprMayBindToTemp)
14707 return MaybeBindToTemporary(ResStmtExpr);
14708 return ResStmtExpr;
14711 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14712 if (ER.isInvalid())
14713 return ExprError();
14715 // Do function/array conversion on the last expression, but not
14716 // lvalue-to-rvalue. However, initialize an unqualified type.
14717 ER = DefaultFunctionArrayConversion(ER.get());
14718 if (ER.isInvalid())
14719 return ExprError();
14720 Expr *E = ER.get();
14722 if (E->isTypeDependent())
14725 // In ARC, if the final expression ends in a consume, splice
14726 // the consume out and bind it later. In the alternate case
14727 // (when dealing with a retainable type), the result
14728 // initialization will create a produce. In both cases the
14729 // result will be +1, and we'll need to balance that out with
14731 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14732 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14733 return Cast->getSubExpr();
14735 // FIXME: Provide a better location for the initialization.
14736 return PerformCopyInitialization(
14737 InitializedEntity::InitializeStmtExprResult(
14738 E->getBeginLoc(), E->getType().getUnqualifiedType()),
14739 SourceLocation(), E);
14742 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14743 TypeSourceInfo *TInfo,
14744 ArrayRef<OffsetOfComponent> Components,
14745 SourceLocation RParenLoc) {
14746 QualType ArgTy = TInfo->getType();
14747 bool Dependent = ArgTy->isDependentType();
14748 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14750 // We must have at least one component that refers to the type, and the first
14751 // one is known to be a field designator. Verify that the ArgTy represents
14752 // a struct/union/class.
14753 if (!Dependent && !ArgTy->isRecordType())
14754 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14755 << ArgTy << TypeRange);
14757 // Type must be complete per C99 7.17p3 because a declaring a variable
14758 // with an incomplete type would be ill-formed.
14760 && RequireCompleteType(BuiltinLoc, ArgTy,
14761 diag::err_offsetof_incomplete_type, TypeRange))
14762 return ExprError();
14764 bool DidWarnAboutNonPOD = false;
14765 QualType CurrentType = ArgTy;
14766 SmallVector<OffsetOfNode, 4> Comps;
14767 SmallVector<Expr*, 4> Exprs;
14768 for (const OffsetOfComponent &OC : Components) {
14769 if (OC.isBrackets) {
14770 // Offset of an array sub-field. TODO: Should we allow vector elements?
14771 if (!CurrentType->isDependentType()) {
14772 const ArrayType *AT = Context.getAsArrayType(CurrentType);
14774 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14776 CurrentType = AT->getElementType();
14778 CurrentType = Context.DependentTy;
14780 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14781 if (IdxRval.isInvalid())
14782 return ExprError();
14783 Expr *Idx = IdxRval.get();
14785 // The expression must be an integral expression.
14786 // FIXME: An integral constant expression?
14787 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14788 !Idx->getType()->isIntegerType())
14790 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14791 << Idx->getSourceRange());
14793 // Record this array index.
14794 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14795 Exprs.push_back(Idx);
14799 // Offset of a field.
14800 if (CurrentType->isDependentType()) {
14801 // We have the offset of a field, but we can't look into the dependent
14802 // type. Just record the identifier of the field.
14803 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14804 CurrentType = Context.DependentTy;
14808 // We need to have a complete type to look into.
14809 if (RequireCompleteType(OC.LocStart, CurrentType,
14810 diag::err_offsetof_incomplete_type))
14811 return ExprError();
14813 // Look for the designated field.
14814 const RecordType *RC = CurrentType->getAs<RecordType>();
14816 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14818 RecordDecl *RD = RC->getDecl();
14820 // C++ [lib.support.types]p5:
14821 // The macro offsetof accepts a restricted set of type arguments in this
14822 // International Standard. type shall be a POD structure or a POD union
14824 // C++11 [support.types]p4:
14825 // If type is not a standard-layout class (Clause 9), the results are
14827 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14828 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14830 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14831 : diag::ext_offsetof_non_pod_type;
14833 if (!IsSafe && !DidWarnAboutNonPOD &&
14834 DiagRuntimeBehavior(BuiltinLoc, nullptr,
14836 << SourceRange(Components[0].LocStart, OC.LocEnd)
14838 DidWarnAboutNonPOD = true;
14841 // Look for the field.
14842 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14843 LookupQualifiedName(R, RD);
14844 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14845 IndirectFieldDecl *IndirectMemberDecl = nullptr;
14847 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14848 MemberDecl = IndirectMemberDecl->getAnonField();
14852 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14853 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14857 // (If the specified member is a bit-field, the behavior is undefined.)
14859 // We diagnose this as an error.
14860 if (MemberDecl->isBitField()) {
14861 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14862 << MemberDecl->getDeclName()
14863 << SourceRange(BuiltinLoc, RParenLoc);
14864 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14865 return ExprError();
14868 RecordDecl *Parent = MemberDecl->getParent();
14869 if (IndirectMemberDecl)
14870 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14872 // If the member was found in a base class, introduce OffsetOfNodes for
14873 // the base class indirections.
14874 CXXBasePaths Paths;
14875 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14877 if (Paths.getDetectedVirtual()) {
14878 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14879 << MemberDecl->getDeclName()
14880 << SourceRange(BuiltinLoc, RParenLoc);
14881 return ExprError();
14884 CXXBasePath &Path = Paths.front();
14885 for (const CXXBasePathElement &B : Path)
14886 Comps.push_back(OffsetOfNode(B.Base));
14889 if (IndirectMemberDecl) {
14890 for (auto *FI : IndirectMemberDecl->chain()) {
14891 assert(isa<FieldDecl>(FI));
14892 Comps.push_back(OffsetOfNode(OC.LocStart,
14893 cast<FieldDecl>(FI), OC.LocEnd));
14896 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14898 CurrentType = MemberDecl->getType().getNonReferenceType();
14901 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14902 Comps, Exprs, RParenLoc);
14905 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14906 SourceLocation BuiltinLoc,
14907 SourceLocation TypeLoc,
14908 ParsedType ParsedArgTy,
14909 ArrayRef<OffsetOfComponent> Components,
14910 SourceLocation RParenLoc) {
14912 TypeSourceInfo *ArgTInfo;
14913 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14914 if (ArgTy.isNull())
14915 return ExprError();
14918 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14920 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14924 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14926 Expr *LHSExpr, Expr *RHSExpr,
14927 SourceLocation RPLoc) {
14928 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14930 ExprValueKind VK = VK_RValue;
14931 ExprObjectKind OK = OK_Ordinary;
14933 bool CondIsTrue = false;
14934 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14935 resType = Context.DependentTy;
14937 // The conditional expression is required to be a constant expression.
14938 llvm::APSInt condEval(32);
14940 = VerifyIntegerConstantExpression(CondExpr, &condEval,
14941 diag::err_typecheck_choose_expr_requires_constant, false);
14942 if (CondICE.isInvalid())
14943 return ExprError();
14944 CondExpr = CondICE.get();
14945 CondIsTrue = condEval.getZExtValue();
14947 // If the condition is > zero, then the AST type is the same as the LHSExpr.
14948 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14950 resType = ActiveExpr->getType();
14951 VK = ActiveExpr->getValueKind();
14952 OK = ActiveExpr->getObjectKind();
14955 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
14956 resType, VK, OK, RPLoc, CondIsTrue);
14959 //===----------------------------------------------------------------------===//
14960 // Clang Extensions.
14961 //===----------------------------------------------------------------------===//
14963 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14964 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14965 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14967 if (LangOpts.CPlusPlus) {
14968 MangleNumberingContext *MCtx;
14969 Decl *ManglingContextDecl;
14970 std::tie(MCtx, ManglingContextDecl) =
14971 getCurrentMangleNumberContext(Block->getDeclContext());
14973 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14974 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14978 PushBlockScope(CurScope, Block);
14979 CurContext->addDecl(Block);
14981 PushDeclContext(CurScope, Block);
14983 CurContext = Block;
14985 getCurBlock()->HasImplicitReturnType = true;
14987 // Enter a new evaluation context to insulate the block from any
14988 // cleanups from the enclosing full-expression.
14989 PushExpressionEvaluationContext(
14990 ExpressionEvaluationContext::PotentiallyEvaluated);
14993 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14995 assert(ParamInfo.getIdentifier() == nullptr &&
14996 "block-id should have no identifier!");
14997 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14998 BlockScopeInfo *CurBlock = getCurBlock();
15000 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15001 QualType T = Sig->getType();
15003 // FIXME: We should allow unexpanded parameter packs here, but that would,
15004 // in turn, make the block expression contain unexpanded parameter packs.
15005 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15006 // Drop the parameters.
15007 FunctionProtoType::ExtProtoInfo EPI;
15008 EPI.HasTrailingReturn = false;
15009 EPI.TypeQuals.addConst();
15010 T = Context.getFunctionType(Context.DependentTy, None, EPI);
15011 Sig = Context.getTrivialTypeSourceInfo(T);
15014 // GetTypeForDeclarator always produces a function type for a block
15015 // literal signature. Furthermore, it is always a FunctionProtoType
15016 // unless the function was written with a typedef.
15017 assert(T->isFunctionType() &&
15018 "GetTypeForDeclarator made a non-function block signature");
15020 // Look for an explicit signature in that function type.
15021 FunctionProtoTypeLoc ExplicitSignature;
15023 if ((ExplicitSignature = Sig->getTypeLoc()
15024 .getAsAdjusted<FunctionProtoTypeLoc>())) {
15026 // Check whether that explicit signature was synthesized by
15027 // GetTypeForDeclarator. If so, don't save that as part of the
15028 // written signature.
15029 if (ExplicitSignature.getLocalRangeBegin() ==
15030 ExplicitSignature.getLocalRangeEnd()) {
15031 // This would be much cheaper if we stored TypeLocs instead of
15032 // TypeSourceInfos.
15033 TypeLoc Result = ExplicitSignature.getReturnLoc();
15034 unsigned Size = Result.getFullDataSize();
15035 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15036 Sig->getTypeLoc().initializeFullCopy(Result, Size);
15038 ExplicitSignature = FunctionProtoTypeLoc();
15042 CurBlock->TheDecl->setSignatureAsWritten(Sig);
15043 CurBlock->FunctionType = T;
15045 const FunctionType *Fn = T->getAs<FunctionType>();
15046 QualType RetTy = Fn->getReturnType();
15048 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15050 CurBlock->TheDecl->setIsVariadic(isVariadic);
15052 // Context.DependentTy is used as a placeholder for a missing block
15053 // return type. TODO: what should we do with declarators like:
15055 // If the answer is "apply template argument deduction"....
15056 if (RetTy != Context.DependentTy) {
15057 CurBlock->ReturnType = RetTy;
15058 CurBlock->TheDecl->setBlockMissingReturnType(false);
15059 CurBlock->HasImplicitReturnType = false;
15062 // Push block parameters from the declarator if we had them.
15063 SmallVector<ParmVarDecl*, 8> Params;
15064 if (ExplicitSignature) {
15065 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15066 ParmVarDecl *Param = ExplicitSignature.getParam(I);
15067 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15068 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15069 // Diagnose this as an extension in C17 and earlier.
15070 if (!getLangOpts().C2x)
15071 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15073 Params.push_back(Param);
15076 // Fake up parameter variables if we have a typedef, like
15077 // ^ fntype { ... }
15078 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15079 for (const auto &I : Fn->param_types()) {
15080 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15081 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15082 Params.push_back(Param);
15086 // Set the parameters on the block decl.
15087 if (!Params.empty()) {
15088 CurBlock->TheDecl->setParams(Params);
15089 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15090 /*CheckParameterNames=*/false);
15093 // Finally we can process decl attributes.
15094 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15096 // Put the parameter variables in scope.
15097 for (auto AI : CurBlock->TheDecl->parameters()) {
15098 AI->setOwningFunction(CurBlock->TheDecl);
15100 // If this has an identifier, add it to the scope stack.
15101 if (AI->getIdentifier()) {
15102 CheckShadow(CurBlock->TheScope, AI);
15104 PushOnScopeChains(AI, CurBlock->TheScope);
15109 /// ActOnBlockError - If there is an error parsing a block, this callback
15110 /// is invoked to pop the information about the block from the action impl.
15111 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15112 // Leave the expression-evaluation context.
15113 DiscardCleanupsInEvaluationContext();
15114 PopExpressionEvaluationContext();
15116 // Pop off CurBlock, handle nested blocks.
15118 PopFunctionScopeInfo();
15121 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15122 /// literal was successfully completed. ^(int x){...}
15123 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15124 Stmt *Body, Scope *CurScope) {
15125 // If blocks are disabled, emit an error.
15126 if (!LangOpts.Blocks)
15127 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15129 // Leave the expression-evaluation context.
15130 if (hasAnyUnrecoverableErrorsInThisFunction())
15131 DiscardCleanupsInEvaluationContext();
15132 assert(!Cleanup.exprNeedsCleanups() &&
15133 "cleanups within block not correctly bound!");
15134 PopExpressionEvaluationContext();
15136 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15137 BlockDecl *BD = BSI->TheDecl;
15139 if (BSI->HasImplicitReturnType)
15140 deduceClosureReturnType(*BSI);
15142 QualType RetTy = Context.VoidTy;
15143 if (!BSI->ReturnType.isNull())
15144 RetTy = BSI->ReturnType;
15146 bool NoReturn = BD->hasAttr<NoReturnAttr>();
15149 // If the user wrote a function type in some form, try to use that.
15150 if (!BSI->FunctionType.isNull()) {
15151 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15153 FunctionType::ExtInfo Ext = FTy->getExtInfo();
15154 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15156 // Turn protoless block types into nullary block types.
15157 if (isa<FunctionNoProtoType>(FTy)) {
15158 FunctionProtoType::ExtProtoInfo EPI;
15160 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15162 // Otherwise, if we don't need to change anything about the function type,
15163 // preserve its sugar structure.
15164 } else if (FTy->getReturnType() == RetTy &&
15165 (!NoReturn || FTy->getNoReturnAttr())) {
15166 BlockTy = BSI->FunctionType;
15168 // Otherwise, make the minimal modifications to the function type.
15170 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15171 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15172 EPI.TypeQuals = Qualifiers();
15174 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15177 // If we don't have a function type, just build one from nothing.
15179 FunctionProtoType::ExtProtoInfo EPI;
15180 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15181 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15184 DiagnoseUnusedParameters(BD->parameters());
15185 BlockTy = Context.getBlockPointerType(BlockTy);
15187 // If needed, diagnose invalid gotos and switches in the block.
15188 if (getCurFunction()->NeedsScopeChecking() &&
15189 !PP.isCodeCompletionEnabled())
15190 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15192 BD->setBody(cast<CompoundStmt>(Body));
15194 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15195 DiagnoseUnguardedAvailabilityViolations(BD);
15197 // Try to apply the named return value optimization. We have to check again
15198 // if we can do this, though, because blocks keep return statements around
15199 // to deduce an implicit return type.
15200 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15201 !BD->isDependentContext())
15202 computeNRVO(Body, BSI);
15204 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15205 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15206 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15207 NTCUK_Destruct|NTCUK_Copy);
15211 // Pop the block scope now but keep it alive to the end of this function.
15212 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15213 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15215 // Set the captured variables on the block.
15216 SmallVector<BlockDecl::Capture, 4> Captures;
15217 for (Capture &Cap : BSI->Captures) {
15218 if (Cap.isInvalid() || Cap.isThisCapture())
15221 VarDecl *Var = Cap.getVariable();
15222 Expr *CopyExpr = nullptr;
15223 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15224 if (const RecordType *Record =
15225 Cap.getCaptureType()->getAs<RecordType>()) {
15226 // The capture logic needs the destructor, so make sure we mark it.
15227 // Usually this is unnecessary because most local variables have
15228 // their destructors marked at declaration time, but parameters are
15229 // an exception because it's technically only the call site that
15230 // actually requires the destructor.
15231 if (isa<ParmVarDecl>(Var))
15232 FinalizeVarWithDestructor(Var, Record);
15234 // Enter a separate potentially-evaluated context while building block
15235 // initializers to isolate their cleanups from those of the block
15237 // FIXME: Is this appropriate even when the block itself occurs in an
15238 // unevaluated operand?
15239 EnterExpressionEvaluationContext EvalContext(
15240 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15242 SourceLocation Loc = Cap.getLocation();
15244 ExprResult Result = BuildDeclarationNameExpr(
15245 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15247 // According to the blocks spec, the capture of a variable from
15248 // the stack requires a const copy constructor. This is not true
15249 // of the copy/move done to move a __block variable to the heap.
15250 if (!Result.isInvalid() &&
15251 !Result.get()->getType().isConstQualified()) {
15252 Result = ImpCastExprToType(Result.get(),
15253 Result.get()->getType().withConst(),
15254 CK_NoOp, VK_LValue);
15257 if (!Result.isInvalid()) {
15258 Result = PerformCopyInitialization(
15259 InitializedEntity::InitializeBlock(Var->getLocation(),
15260 Cap.getCaptureType(), false),
15261 Loc, Result.get());
15264 // Build a full-expression copy expression if initialization
15265 // succeeded and used a non-trivial constructor. Recover from
15266 // errors by pretending that the copy isn't necessary.
15267 if (!Result.isInvalid() &&
15268 !cast<CXXConstructExpr>(Result.get())->getConstructor()
15270 Result = MaybeCreateExprWithCleanups(Result);
15271 CopyExpr = Result.get();
15276 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15278 Captures.push_back(NewCap);
15280 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15282 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15284 // If the block isn't obviously global, i.e. it captures anything at
15285 // all, then we need to do a few things in the surrounding context:
15286 if (Result->getBlockDecl()->hasCaptures()) {
15287 // First, this expression has a new cleanup object.
15288 ExprCleanupObjects.push_back(Result->getBlockDecl());
15289 Cleanup.setExprNeedsCleanups(true);
15291 // It also gets a branch-protected scope if any of the captured
15292 // variables needs destruction.
15293 for (const auto &CI : Result->getBlockDecl()->captures()) {
15294 const VarDecl *var = CI.getVariable();
15295 if (var->getType().isDestructedType() != QualType::DK_none) {
15296 setFunctionHasBranchProtectedScope();
15302 if (getCurFunction())
15303 getCurFunction()->addBlock(BD);
15308 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15309 SourceLocation RPLoc) {
15310 TypeSourceInfo *TInfo;
15311 GetTypeFromParser(Ty, &TInfo);
15312 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15315 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15316 Expr *E, TypeSourceInfo *TInfo,
15317 SourceLocation RPLoc) {
15318 Expr *OrigExpr = E;
15321 // CUDA device code does not support varargs.
15322 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15323 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15324 CUDAFunctionTarget T = IdentifyCUDATarget(F);
15325 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15326 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15330 // NVPTX does not support va_arg expression.
15331 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15332 Context.getTargetInfo().getTriple().isNVPTX())
15333 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15335 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15336 // as Microsoft ABI on an actual Microsoft platform, where
15337 // __builtin_ms_va_list and __builtin_va_list are the same.)
15338 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15339 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15340 QualType MSVaListType = Context.getBuiltinMSVaListType();
15341 if (Context.hasSameType(MSVaListType, E->getType())) {
15342 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15343 return ExprError();
15348 // Get the va_list type
15349 QualType VaListType = Context.getBuiltinVaListType();
15351 if (VaListType->isArrayType()) {
15352 // Deal with implicit array decay; for example, on x86-64,
15353 // va_list is an array, but it's supposed to decay to
15354 // a pointer for va_arg.
15355 VaListType = Context.getArrayDecayedType(VaListType);
15356 // Make sure the input expression also decays appropriately.
15357 ExprResult Result = UsualUnaryConversions(E);
15358 if (Result.isInvalid())
15359 return ExprError();
15361 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15362 // If va_list is a record type and we are compiling in C++ mode,
15363 // check the argument using reference binding.
15364 InitializedEntity Entity = InitializedEntity::InitializeParameter(
15365 Context, Context.getLValueReferenceType(VaListType), false);
15366 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15367 if (Init.isInvalid())
15368 return ExprError();
15369 E = Init.getAs<Expr>();
15371 // Otherwise, the va_list argument must be an l-value because
15372 // it is modified by va_arg.
15373 if (!E->isTypeDependent() &&
15374 CheckForModifiableLvalue(E, BuiltinLoc, *this))
15375 return ExprError();
15379 if (!IsMS && !E->isTypeDependent() &&
15380 !Context.hasSameType(VaListType, E->getType()))
15382 Diag(E->getBeginLoc(),
15383 diag::err_first_argument_to_va_arg_not_of_type_va_list)
15384 << OrigExpr->getType() << E->getSourceRange());
15386 if (!TInfo->getType()->isDependentType()) {
15387 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15388 diag::err_second_parameter_to_va_arg_incomplete,
15389 TInfo->getTypeLoc()))
15390 return ExprError();
15392 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15394 diag::err_second_parameter_to_va_arg_abstract,
15395 TInfo->getTypeLoc()))
15396 return ExprError();
15398 if (!TInfo->getType().isPODType(Context)) {
15399 Diag(TInfo->getTypeLoc().getBeginLoc(),
15400 TInfo->getType()->isObjCLifetimeType()
15401 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15402 : diag::warn_second_parameter_to_va_arg_not_pod)
15403 << TInfo->getType()
15404 << TInfo->getTypeLoc().getSourceRange();
15407 // Check for va_arg where arguments of the given type will be promoted
15408 // (i.e. this va_arg is guaranteed to have undefined behavior).
15409 QualType PromoteType;
15410 if (TInfo->getType()->isPromotableIntegerType()) {
15411 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15412 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15413 PromoteType = QualType();
15415 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15416 PromoteType = Context.DoubleTy;
15417 if (!PromoteType.isNull())
15418 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15419 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15420 << TInfo->getType()
15422 << TInfo->getTypeLoc().getSourceRange());
15425 QualType T = TInfo->getType().getNonLValueExprType(Context);
15426 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15429 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15430 // The type of __null will be int or long, depending on the size of
15431 // pointers on the target.
15433 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15434 if (pw == Context.getTargetInfo().getIntWidth())
15435 Ty = Context.IntTy;
15436 else if (pw == Context.getTargetInfo().getLongWidth())
15437 Ty = Context.LongTy;
15438 else if (pw == Context.getTargetInfo().getLongLongWidth())
15439 Ty = Context.LongLongTy;
15441 llvm_unreachable("I don't know size of pointer!");
15444 return new (Context) GNUNullExpr(Ty, TokenLoc);
15447 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15448 SourceLocation BuiltinLoc,
15449 SourceLocation RPLoc) {
15450 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15453 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15454 SourceLocation BuiltinLoc,
15455 SourceLocation RPLoc,
15456 DeclContext *ParentContext) {
15457 return new (Context)
15458 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15461 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15463 if (!getLangOpts().ObjC)
15466 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15469 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15471 // Ignore any parens, implicit casts (should only be
15472 // array-to-pointer decays), and not-so-opaque values. The last is
15473 // important for making this trigger for property assignments.
15474 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15475 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15476 if (OV->getSourceExpr())
15477 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15479 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15480 if (!PT->isObjCIdType() &&
15481 !(ID && ID->getIdentifier()->isStr("NSString")))
15483 if (!SL->isAscii())
15487 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15488 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15489 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15494 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15495 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15496 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15497 !SrcExpr->isNullPointerConstant(
15498 getASTContext(), Expr::NPC_NeverValueDependent)) {
15499 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15502 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15504 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15506 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15516 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15517 const Expr *SrcExpr) {
15518 if (!DstType->isFunctionPointerType() ||
15519 !SrcExpr->getType()->isFunctionType())
15522 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15526 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15530 return !S.checkAddressOfFunctionIsAvailable(FD,
15532 SrcExpr->getBeginLoc());
15535 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15536 SourceLocation Loc,
15537 QualType DstType, QualType SrcType,
15538 Expr *SrcExpr, AssignmentAction Action,
15539 bool *Complained) {
15541 *Complained = false;
15543 // Decode the result (notice that AST's are still created for extensions).
15544 bool CheckInferredResultType = false;
15545 bool isInvalid = false;
15546 unsigned DiagKind = 0;
15548 ConversionFixItGenerator ConvHints;
15549 bool MayHaveConvFixit = false;
15550 bool MayHaveFunctionDiff = false;
15551 const ObjCInterfaceDecl *IFace = nullptr;
15552 const ObjCProtocolDecl *PDecl = nullptr;
15556 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15560 if (getLangOpts().CPlusPlus) {
15561 DiagKind = diag::err_typecheck_convert_pointer_int;
15564 DiagKind = diag::ext_typecheck_convert_pointer_int;
15566 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15567 MayHaveConvFixit = true;
15570 if (getLangOpts().CPlusPlus) {
15571 DiagKind = diag::err_typecheck_convert_int_pointer;
15574 DiagKind = diag::ext_typecheck_convert_int_pointer;
15576 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15577 MayHaveConvFixit = true;
15579 case IncompatibleFunctionPointer:
15580 if (getLangOpts().CPlusPlus) {
15581 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15584 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15586 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15587 MayHaveConvFixit = true;
15589 case IncompatiblePointer:
15590 if (Action == AA_Passing_CFAudited) {
15591 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15592 } else if (getLangOpts().CPlusPlus) {
15593 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15596 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15598 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15599 SrcType->isObjCObjectPointerType();
15600 if (Hint.isNull() && !CheckInferredResultType) {
15601 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15603 else if (CheckInferredResultType) {
15604 SrcType = SrcType.getUnqualifiedType();
15605 DstType = DstType.getUnqualifiedType();
15607 MayHaveConvFixit = true;
15609 case IncompatiblePointerSign:
15610 if (getLangOpts().CPlusPlus) {
15611 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15614 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15617 case FunctionVoidPointer:
15618 if (getLangOpts().CPlusPlus) {
15619 DiagKind = diag::err_typecheck_convert_pointer_void_func;
15622 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15625 case IncompatiblePointerDiscardsQualifiers: {
15626 // Perform array-to-pointer decay if necessary.
15627 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15631 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15632 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15633 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15634 DiagKind = diag::err_typecheck_incompatible_address_space;
15637 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15638 DiagKind = diag::err_typecheck_incompatible_ownership;
15642 llvm_unreachable("unknown error case for discarding qualifiers!");
15645 case CompatiblePointerDiscardsQualifiers:
15646 // If the qualifiers lost were because we were applying the
15647 // (deprecated) C++ conversion from a string literal to a char*
15648 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
15649 // Ideally, this check would be performed in
15650 // checkPointerTypesForAssignment. However, that would require a
15651 // bit of refactoring (so that the second argument is an
15652 // expression, rather than a type), which should be done as part
15653 // of a larger effort to fix checkPointerTypesForAssignment for
15655 if (getLangOpts().CPlusPlus &&
15656 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15658 if (getLangOpts().CPlusPlus) {
15659 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
15662 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
15666 case IncompatibleNestedPointerQualifiers:
15667 if (getLangOpts().CPlusPlus) {
15669 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15671 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15674 case IncompatibleNestedPointerAddressSpaceMismatch:
15675 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15678 case IntToBlockPointer:
15679 DiagKind = diag::err_int_to_block_pointer;
15682 case IncompatibleBlockPointer:
15683 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15686 case IncompatibleObjCQualifiedId: {
15687 if (SrcType->isObjCQualifiedIdType()) {
15688 const ObjCObjectPointerType *srcOPT =
15689 SrcType->castAs<ObjCObjectPointerType>();
15690 for (auto *srcProto : srcOPT->quals()) {
15694 if (const ObjCInterfaceType *IFaceT =
15695 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15696 IFace = IFaceT->getDecl();
15698 else if (DstType->isObjCQualifiedIdType()) {
15699 const ObjCObjectPointerType *dstOPT =
15700 DstType->castAs<ObjCObjectPointerType>();
15701 for (auto *dstProto : dstOPT->quals()) {
15705 if (const ObjCInterfaceType *IFaceT =
15706 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15707 IFace = IFaceT->getDecl();
15709 if (getLangOpts().CPlusPlus) {
15710 DiagKind = diag::err_incompatible_qualified_id;
15713 DiagKind = diag::warn_incompatible_qualified_id;
15717 case IncompatibleVectors:
15718 if (getLangOpts().CPlusPlus) {
15719 DiagKind = diag::err_incompatible_vectors;
15722 DiagKind = diag::warn_incompatible_vectors;
15725 case IncompatibleObjCWeakRef:
15726 DiagKind = diag::err_arc_weak_unavailable_assign;
15730 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15732 *Complained = true;
15736 DiagKind = diag::err_typecheck_convert_incompatible;
15737 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15738 MayHaveConvFixit = true;
15740 MayHaveFunctionDiff = true;
15744 QualType FirstType, SecondType;
15747 case AA_Initializing:
15748 // The destination type comes first.
15749 FirstType = DstType;
15750 SecondType = SrcType;
15755 case AA_Passing_CFAudited:
15756 case AA_Converting:
15759 // The source type comes first.
15760 FirstType = SrcType;
15761 SecondType = DstType;
15765 PartialDiagnostic FDiag = PDiag(DiagKind);
15766 if (Action == AA_Passing_CFAudited)
15767 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15769 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15771 // If we can fix the conversion, suggest the FixIts.
15772 assert(ConvHints.isNull() || Hint.isNull());
15773 if (!ConvHints.isNull()) {
15774 for (FixItHint &H : ConvHints.Hints)
15779 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15781 if (MayHaveFunctionDiff)
15782 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15785 if ((DiagKind == diag::warn_incompatible_qualified_id ||
15786 DiagKind == diag::err_incompatible_qualified_id) &&
15787 PDecl && IFace && !IFace->hasDefinition())
15788 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15791 if (SecondType == Context.OverloadTy)
15792 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15793 FirstType, /*TakingAddress=*/true);
15795 if (CheckInferredResultType)
15796 EmitRelatedResultTypeNote(SrcExpr);
15798 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15799 EmitRelatedResultTypeNoteForReturn(DstType);
15802 *Complained = true;
15806 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15807 llvm::APSInt *Result) {
15808 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15810 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15811 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15815 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15818 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15819 llvm::APSInt *Result,
15822 class IDDiagnoser : public VerifyICEDiagnoser {
15826 IDDiagnoser(unsigned DiagID)
15827 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15829 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15830 S.Diag(Loc, DiagID) << SR;
15832 } Diagnoser(DiagID);
15834 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15837 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15839 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15843 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15844 VerifyICEDiagnoser &Diagnoser,
15846 SourceLocation DiagLoc = E->getBeginLoc();
15848 if (getLangOpts().CPlusPlus11) {
15849 // C++11 [expr.const]p5:
15850 // If an expression of literal class type is used in a context where an
15851 // integral constant expression is required, then that class type shall
15852 // have a single non-explicit conversion function to an integral or
15853 // unscoped enumeration type
15854 ExprResult Converted;
15855 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15857 CXX11ConvertDiagnoser(bool Silent)
15858 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15861 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15862 QualType T) override {
15863 return S.Diag(Loc, diag::err_ice_not_integral) << T;
15866 SemaDiagnosticBuilder diagnoseIncomplete(
15867 Sema &S, SourceLocation Loc, QualType T) override {
15868 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15871 SemaDiagnosticBuilder diagnoseExplicitConv(
15872 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15873 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15876 SemaDiagnosticBuilder noteExplicitConv(
15877 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15878 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15879 << ConvTy->isEnumeralType() << ConvTy;
15882 SemaDiagnosticBuilder diagnoseAmbiguous(
15883 Sema &S, SourceLocation Loc, QualType T) override {
15884 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15887 SemaDiagnosticBuilder noteAmbiguous(
15888 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15889 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15890 << ConvTy->isEnumeralType() << ConvTy;
15893 SemaDiagnosticBuilder diagnoseConversion(
15894 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15895 llvm_unreachable("conversion functions are permitted");
15897 } ConvertDiagnoser(Diagnoser.Suppress);
15899 Converted = PerformContextualImplicitConversion(DiagLoc, E,
15901 if (Converted.isInvalid())
15903 E = Converted.get();
15904 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15905 return ExprError();
15906 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15907 // An ICE must be of integral or unscoped enumeration type.
15908 if (!Diagnoser.Suppress)
15909 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15910 return ExprError();
15913 ExprResult RValueExpr = DefaultLvalueConversion(E);
15914 if (RValueExpr.isInvalid())
15915 return ExprError();
15917 E = RValueExpr.get();
15919 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15920 // in the non-ICE case.
15921 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15923 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15924 if (!isa<ConstantExpr>(E))
15925 E = ConstantExpr::Create(Context, E);
15929 Expr::EvalResult EvalResult;
15930 SmallVector<PartialDiagnosticAt, 8> Notes;
15931 EvalResult.Diag = &Notes;
15933 // Try to evaluate the expression, and produce diagnostics explaining why it's
15934 // not a constant expression as a side-effect.
15936 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15937 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15939 if (!isa<ConstantExpr>(E))
15940 E = ConstantExpr::Create(Context, E, EvalResult.Val);
15942 // In C++11, we can rely on diagnostics being produced for any expression
15943 // which is not a constant expression. If no diagnostics were produced, then
15944 // this is a constant expression.
15945 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15947 *Result = EvalResult.Val.getInt();
15951 // If our only note is the usual "invalid subexpression" note, just point
15952 // the caret at its location rather than producing an essentially
15954 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15955 diag::note_invalid_subexpr_in_const_expr) {
15956 DiagLoc = Notes[0].first;
15960 if (!Folded || !AllowFold) {
15961 if (!Diagnoser.Suppress) {
15962 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15963 for (const PartialDiagnosticAt &Note : Notes)
15964 Diag(Note.first, Note.second);
15967 return ExprError();
15970 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15971 for (const PartialDiagnosticAt &Note : Notes)
15972 Diag(Note.first, Note.second);
15975 *Result = EvalResult.Val.getInt();
15980 // Handle the case where we conclude a expression which we speculatively
15981 // considered to be unevaluated is actually evaluated.
15982 class TransformToPE : public TreeTransform<TransformToPE> {
15983 typedef TreeTransform<TransformToPE> BaseTransform;
15986 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15988 // Make sure we redo semantic analysis
15989 bool AlwaysRebuild() { return true; }
15990 bool ReplacingOriginal() { return true; }
15992 // We need to special-case DeclRefExprs referring to FieldDecls which
15993 // are not part of a member pointer formation; normal TreeTransforming
15994 // doesn't catch this case because of the way we represent them in the AST.
15995 // FIXME: This is a bit ugly; is it really the best way to handle this
15998 // Error on DeclRefExprs referring to FieldDecls.
15999 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16000 if (isa<FieldDecl>(E->getDecl()) &&
16001 !SemaRef.isUnevaluatedContext())
16002 return SemaRef.Diag(E->getLocation(),
16003 diag::err_invalid_non_static_member_use)
16004 << E->getDecl() << E->getSourceRange();
16006 return BaseTransform::TransformDeclRefExpr(E);
16009 // Exception: filter out member pointer formation
16010 ExprResult TransformUnaryOperator(UnaryOperator *E) {
16011 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16014 return BaseTransform::TransformUnaryOperator(E);
16017 // The body of a lambda-expression is in a separate expression evaluation
16018 // context so never needs to be transformed.
16019 // FIXME: Ideally we wouldn't transform the closure type either, and would
16020 // just recreate the capture expressions and lambda expression.
16021 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16022 return SkipLambdaBody(E, Body);
16027 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16028 assert(isUnevaluatedContext() &&
16029 "Should only transform unevaluated expressions");
16030 ExprEvalContexts.back().Context =
16031 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16032 if (isUnevaluatedContext())
16034 return TransformToPE(*this).TransformExpr(E);
16038 Sema::PushExpressionEvaluationContext(
16039 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16040 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16041 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16042 LambdaContextDecl, ExprContext);
16044 if (!MaybeODRUseExprs.empty())
16045 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16049 Sema::PushExpressionEvaluationContext(
16050 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16051 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16052 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16053 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16058 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16059 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16060 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16061 if (E->getOpcode() == UO_Deref)
16062 return CheckPossibleDeref(S, E->getSubExpr());
16063 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16064 return CheckPossibleDeref(S, E->getBase());
16065 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16066 return CheckPossibleDeref(S, E->getBase());
16067 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16069 QualType Ty = E->getType();
16070 if (const auto *Ptr = Ty->getAs<PointerType>())
16071 Inner = Ptr->getPointeeType();
16072 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16073 Inner = Arr->getElementType();
16077 if (Inner->hasAttr(attr::NoDeref))
16085 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16086 for (const Expr *E : Rec.PossibleDerefs) {
16087 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16089 const ValueDecl *Decl = DeclRef->getDecl();
16090 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16091 << Decl->getName() << E->getSourceRange();
16092 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16094 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16095 << E->getSourceRange();
16098 Rec.PossibleDerefs.clear();
16101 /// Check whether E, which is either a discarded-value expression or an
16102 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16103 /// and if so, remove it from the list of volatile-qualified assignments that
16104 /// we are going to warn are deprecated.
16105 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16106 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16109 // Note: ignoring parens here is not justified by the standard rules, but
16110 // ignoring parentheses seems like a more reasonable approach, and this only
16111 // drives a deprecation warning so doesn't affect conformance.
16112 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16113 if (BO->getOpcode() == BO_Assign) {
16114 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16115 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16121 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16122 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16123 RebuildingImmediateInvocation)
16126 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16127 /// It's OK if this fails; we'll also remove this in
16128 /// HandleImmediateInvocations, but catching it here allows us to avoid
16129 /// walking the AST looking for it in simple cases.
16130 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16131 if (auto *DeclRef =
16132 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16133 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16135 E = MaybeCreateExprWithCleanups(E);
16137 ConstantExpr *Res = ConstantExpr::Create(
16138 getASTContext(), E.get(),
16139 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16141 /*IsImmediateInvocation*/ true);
16142 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16146 static void EvaluateAndDiagnoseImmediateInvocation(
16147 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16148 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16149 Expr::EvalResult Eval;
16150 Eval.Diag = &Notes;
16151 ConstantExpr *CE = Candidate.getPointer();
16152 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
16153 SemaRef.getASTContext(), true);
16154 if (!Result || !Notes.empty()) {
16155 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16156 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16157 InnerExpr = FunctionalCast->getSubExpr();
16158 FunctionDecl *FD = nullptr;
16159 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16160 FD = cast<FunctionDecl>(Call->getCalleeDecl());
16161 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16162 FD = Call->getConstructor();
16164 llvm_unreachable("unhandled decl kind");
16165 assert(FD->isConsteval());
16166 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16167 for (auto &Note : Notes)
16168 SemaRef.Diag(Note.first, Note.second);
16171 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16174 static void RemoveNestedImmediateInvocation(
16175 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16176 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16177 struct ComplexRemove : TreeTransform<ComplexRemove> {
16178 using Base = TreeTransform<ComplexRemove>;
16179 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16180 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16181 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16183 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16184 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16185 SmallVector<Sema::ImmediateInvocationCandidate,
16186 4>::reverse_iterator Current)
16187 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16188 void RemoveImmediateInvocation(ConstantExpr* E) {
16189 auto It = std::find_if(CurrentII, IISet.rend(),
16190 [E](Sema::ImmediateInvocationCandidate Elem) {
16191 return Elem.getPointer() == E;
16193 assert(It != IISet.rend() &&
16194 "ConstantExpr marked IsImmediateInvocation should "
16196 It->setInt(1); // Mark as deleted
16198 ExprResult TransformConstantExpr(ConstantExpr *E) {
16199 if (!E->isImmediateInvocation())
16200 return Base::TransformConstantExpr(E);
16201 RemoveImmediateInvocation(E);
16202 return Base::TransformExpr(E->getSubExpr());
16204 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16205 /// we need to remove its DeclRefExpr from the DRSet.
16206 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16207 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16208 return Base::TransformCXXOperatorCallExpr(E);
16210 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16212 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16215 /// ConstantExpr are the first layer of implicit node to be removed so if
16216 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16217 if (auto *CE = dyn_cast<ConstantExpr>(Init))
16218 if (CE->isImmediateInvocation())
16219 RemoveImmediateInvocation(CE);
16220 return Base::TransformInitializer(Init, NotCopyInit);
16222 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16226 bool AlwaysRebuild() { return false; }
16227 bool ReplacingOriginal() { return true; }
16228 bool AllowSkippingCXXConstructExpr() {
16229 bool Res = AllowSkippingFirstCXXConstructExpr;
16230 AllowSkippingFirstCXXConstructExpr = true;
16233 bool AllowSkippingFirstCXXConstructExpr = true;
16234 } Transformer(SemaRef, Rec.ReferenceToConsteval,
16235 Rec.ImmediateInvocationCandidates, It);
16237 /// CXXConstructExpr with a single argument are getting skipped by
16238 /// TreeTransform in some situtation because they could be implicit. This
16239 /// can only occur for the top-level CXXConstructExpr because it is used
16240 /// nowhere in the expression being transformed therefore will not be rebuilt.
16241 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16242 /// skipping the first CXXConstructExpr.
16243 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16244 Transformer.AllowSkippingFirstCXXConstructExpr = false;
16246 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16247 assert(Res.isUsable());
16248 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16249 It->getPointer()->setSubExpr(Res.get());
16253 HandleImmediateInvocations(Sema &SemaRef,
16254 Sema::ExpressionEvaluationContextRecord &Rec) {
16255 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16256 Rec.ReferenceToConsteval.size() == 0) ||
16257 SemaRef.RebuildingImmediateInvocation)
16260 /// When we have more then 1 ImmediateInvocationCandidates we need to check
16261 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16262 /// need to remove ReferenceToConsteval in the immediate invocation.
16263 if (Rec.ImmediateInvocationCandidates.size() > 1) {
16265 /// Prevent sema calls during the tree transform from adding pointers that
16266 /// are already in the sets.
16267 llvm::SaveAndRestore<bool> DisableIITracking(
16268 SemaRef.RebuildingImmediateInvocation, true);
16270 /// Prevent diagnostic during tree transfrom as they are duplicates
16271 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16273 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16274 It != Rec.ImmediateInvocationCandidates.rend(); It++)
16276 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16277 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16278 Rec.ReferenceToConsteval.size()) {
16279 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16280 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16281 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16282 bool VisitDeclRefExpr(DeclRefExpr *E) {
16284 return DRSet.size();
16286 } Visitor(Rec.ReferenceToConsteval);
16287 Visitor.TraverseStmt(
16288 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16290 for (auto CE : Rec.ImmediateInvocationCandidates)
16292 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16293 for (auto DR : Rec.ReferenceToConsteval) {
16294 auto *FD = cast<FunctionDecl>(DR->getDecl());
16295 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16297 SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16301 void Sema::PopExpressionEvaluationContext() {
16302 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16303 unsigned NumTypos = Rec.NumTypos;
16305 if (!Rec.Lambdas.empty()) {
16306 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16307 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16308 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16310 if (Rec.isUnevaluated()) {
16311 // C++11 [expr.prim.lambda]p2:
16312 // A lambda-expression shall not appear in an unevaluated operand
16314 D = diag::err_lambda_unevaluated_operand;
16315 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16316 // C++1y [expr.const]p2:
16317 // A conditional-expression e is a core constant expression unless the
16318 // evaluation of e, following the rules of the abstract machine, would
16319 // evaluate [...] a lambda-expression.
16320 D = diag::err_lambda_in_constant_expression;
16321 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16322 // C++17 [expr.prim.lamda]p2:
16323 // A lambda-expression shall not appear [...] in a template-argument.
16324 D = diag::err_lambda_in_invalid_context;
16326 llvm_unreachable("Couldn't infer lambda error message.");
16328 for (const auto *L : Rec.Lambdas)
16329 Diag(L->getBeginLoc(), D);
16333 WarnOnPendingNoDerefs(Rec);
16334 HandleImmediateInvocations(*this, Rec);
16336 // Warn on any volatile-qualified simple-assignments that are not discarded-
16337 // value expressions nor unevaluated operands (those cases get removed from
16338 // this list by CheckUnusedVolatileAssignment).
16339 for (auto *BO : Rec.VolatileAssignmentLHSs)
16340 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16343 // When are coming out of an unevaluated context, clear out any
16344 // temporaries that we may have created as part of the evaluation of
16345 // the expression in that context: they aren't relevant because they
16346 // will never be constructed.
16347 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16348 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16349 ExprCleanupObjects.end());
16350 Cleanup = Rec.ParentCleanup;
16351 CleanupVarDeclMarking();
16352 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16353 // Otherwise, merge the contexts together.
16355 Cleanup.mergeFrom(Rec.ParentCleanup);
16356 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16357 Rec.SavedMaybeODRUseExprs.end());
16360 // Pop the current expression evaluation context off the stack.
16361 ExprEvalContexts.pop_back();
16363 // The global expression evaluation context record is never popped.
16364 ExprEvalContexts.back().NumTypos += NumTypos;
16367 void Sema::DiscardCleanupsInEvaluationContext() {
16368 ExprCleanupObjects.erase(
16369 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16370 ExprCleanupObjects.end());
16372 MaybeODRUseExprs.clear();
16375 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16376 ExprResult Result = CheckPlaceholderExpr(E);
16377 if (Result.isInvalid())
16378 return ExprError();
16380 if (!E->getType()->isVariablyModifiedType())
16382 return TransformToPotentiallyEvaluated(E);
16385 /// Are we in a context that is potentially constant evaluated per C++20
16386 /// [expr.const]p12?
16387 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16388 /// C++2a [expr.const]p12:
16389 // An expression or conversion is potentially constant evaluated if it is
16390 switch (SemaRef.ExprEvalContexts.back().Context) {
16391 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16392 // -- a manifestly constant-evaluated expression,
16393 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16394 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16395 case Sema::ExpressionEvaluationContext::DiscardedStatement:
16396 // -- a potentially-evaluated expression,
16397 case Sema::ExpressionEvaluationContext::UnevaluatedList:
16398 // -- an immediate subexpression of a braced-init-list,
16400 // -- [FIXME] an expression of the form & cast-expression that occurs
16401 // within a templated entity
16402 // -- a subexpression of one of the above that is not a subexpression of
16403 // a nested unevaluated operand.
16406 case Sema::ExpressionEvaluationContext::Unevaluated:
16407 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16408 // Expressions in this context are never evaluated.
16411 llvm_unreachable("Invalid context");
16414 /// Return true if this function has a calling convention that requires mangling
16415 /// in the size of the parameter pack.
16416 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16417 // These manglings don't do anything on non-Windows or non-x86 platforms, so
16418 // we don't need parameter type sizes.
16419 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16420 if (!TT.isOSWindows() || !TT.isX86())
16423 // If this is C++ and this isn't an extern "C" function, parameters do not
16424 // need to be complete. In this case, C++ mangling will apply, which doesn't
16425 // use the size of the parameters.
16426 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16429 // Stdcall, fastcall, and vectorcall need this special treatment.
16430 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16432 case CC_X86StdCall:
16433 case CC_X86FastCall:
16434 case CC_X86VectorCall:
16442 /// Require that all of the parameter types of function be complete. Normally,
16443 /// parameter types are only required to be complete when a function is called
16444 /// or defined, but to mangle functions with certain calling conventions, the
16445 /// mangler needs to know the size of the parameter list. In this situation,
16446 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16447 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16448 /// result in a linker error. Clang doesn't implement this behavior, and instead
16449 /// attempts to error at compile time.
16450 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16451 SourceLocation Loc) {
16452 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16454 ParmVarDecl *Param;
16457 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16458 : FD(FD), Param(Param) {}
16460 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16461 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16464 case CC_X86StdCall:
16465 CCName = "stdcall";
16467 case CC_X86FastCall:
16468 CCName = "fastcall";
16470 case CC_X86VectorCall:
16471 CCName = "vectorcall";
16474 llvm_unreachable("CC does not need mangling");
16477 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16478 << Param->getDeclName() << FD->getDeclName() << CCName;
16482 for (ParmVarDecl *Param : FD->parameters()) {
16483 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16484 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16489 enum class OdrUseContext {
16490 /// Declarations in this context are not odr-used.
16492 /// Declarations in this context are formally odr-used, but this is a
16493 /// dependent context.
16495 /// Declarations in this context are odr-used but not actually used (yet).
16497 /// Declarations in this context are used.
16502 /// Are we within a context in which references to resolved functions or to
16503 /// variables result in odr-use?
16504 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16505 OdrUseContext Result;
16507 switch (SemaRef.ExprEvalContexts.back().Context) {
16508 case Sema::ExpressionEvaluationContext::Unevaluated:
16509 case Sema::ExpressionEvaluationContext::UnevaluatedList:
16510 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16511 return OdrUseContext::None;
16513 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16514 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16515 Result = OdrUseContext::Used;
16518 case Sema::ExpressionEvaluationContext::DiscardedStatement:
16519 Result = OdrUseContext::FormallyOdrUsed;
16522 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16523 // A default argument formally results in odr-use, but doesn't actually
16524 // result in a use in any real sense until it itself is used.
16525 Result = OdrUseContext::FormallyOdrUsed;
16529 if (SemaRef.CurContext->isDependentContext())
16530 return OdrUseContext::Dependent;
16535 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16536 return Func->isConstexpr() &&
16537 (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
16540 /// Mark a function referenced, and check whether it is odr-used
16541 /// (C++ [basic.def.odr]p2, C99 6.9p3)
16542 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16543 bool MightBeOdrUse) {
16544 assert(Func && "No function?");
16546 Func->setReferenced();
16548 // Recursive functions aren't really used until they're used from some other
16550 bool IsRecursiveCall = CurContext == Func;
16552 // C++11 [basic.def.odr]p3:
16553 // A function whose name appears as a potentially-evaluated expression is
16554 // odr-used if it is the unique lookup result or the selected member of a
16555 // set of overloaded functions [...].
16557 // We (incorrectly) mark overload resolution as an unevaluated context, so we
16558 // can just check that here.
16559 OdrUseContext OdrUse =
16560 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16561 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16562 OdrUse = OdrUseContext::FormallyOdrUsed;
16564 // Trivial default constructors and destructors are never actually used.
16565 // FIXME: What about other special members?
16566 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16567 OdrUse == OdrUseContext::Used) {
16568 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16569 if (Constructor->isDefaultConstructor())
16570 OdrUse = OdrUseContext::FormallyOdrUsed;
16571 if (isa<CXXDestructorDecl>(Func))
16572 OdrUse = OdrUseContext::FormallyOdrUsed;
16575 // C++20 [expr.const]p12:
16576 // A function [...] is needed for constant evaluation if it is [...] a
16577 // constexpr function that is named by an expression that is potentially
16578 // constant evaluated
16579 bool NeededForConstantEvaluation =
16580 isPotentiallyConstantEvaluatedContext(*this) &&
16581 isImplicitlyDefinableConstexprFunction(Func);
16583 // Determine whether we require a function definition to exist, per
16584 // C++11 [temp.inst]p3:
16585 // Unless a function template specialization has been explicitly
16586 // instantiated or explicitly specialized, the function template
16587 // specialization is implicitly instantiated when the specialization is
16588 // referenced in a context that requires a function definition to exist.
16589 // C++20 [temp.inst]p7:
16590 // The existence of a definition of a [...] function is considered to
16591 // affect the semantics of the program if the [...] function is needed for
16592 // constant evaluation by an expression
16593 // C++20 [basic.def.odr]p10:
16594 // Every program shall contain exactly one definition of every non-inline
16595 // function or variable that is odr-used in that program outside of a
16596 // discarded statement
16597 // C++20 [special]p1:
16598 // The implementation will implicitly define [defaulted special members]
16599 // if they are odr-used or needed for constant evaluation.
16601 // Note that we skip the implicit instantiation of templates that are only
16602 // used in unused default arguments or by recursive calls to themselves.
16603 // This is formally non-conforming, but seems reasonable in practice.
16604 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16605 NeededForConstantEvaluation);
16607 // C++14 [temp.expl.spec]p6:
16608 // If a template [...] is explicitly specialized then that specialization
16609 // shall be declared before the first use of that specialization that would
16610 // cause an implicit instantiation to take place, in every translation unit
16611 // in which such a use occurs
16612 if (NeedDefinition &&
16613 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16614 Func->getMemberSpecializationInfo()))
16615 checkSpecializationVisibility(Loc, Func);
16617 if (getLangOpts().CUDA)
16618 CheckCUDACall(Loc, Func);
16620 if (getLangOpts().SYCLIsDevice)
16621 checkSYCLDeviceFunction(Loc, Func);
16623 // If we need a definition, try to create one.
16624 if (NeedDefinition && !Func->getBody()) {
16625 runWithSufficientStackSpace(Loc, [&] {
16626 if (CXXConstructorDecl *Constructor =
16627 dyn_cast<CXXConstructorDecl>(Func)) {
16628 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16629 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16630 if (Constructor->isDefaultConstructor()) {
16631 if (Constructor->isTrivial() &&
16632 !Constructor->hasAttr<DLLExportAttr>())
16634 DefineImplicitDefaultConstructor(Loc, Constructor);
16635 } else if (Constructor->isCopyConstructor()) {
16636 DefineImplicitCopyConstructor(Loc, Constructor);
16637 } else if (Constructor->isMoveConstructor()) {
16638 DefineImplicitMoveConstructor(Loc, Constructor);
16640 } else if (Constructor->getInheritedConstructor()) {
16641 DefineInheritingConstructor(Loc, Constructor);
16643 } else if (CXXDestructorDecl *Destructor =
16644 dyn_cast<CXXDestructorDecl>(Func)) {
16645 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16646 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16647 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16649 DefineImplicitDestructor(Loc, Destructor);
16651 if (Destructor->isVirtual() && getLangOpts().AppleKext)
16652 MarkVTableUsed(Loc, Destructor->getParent());
16653 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16654 if (MethodDecl->isOverloadedOperator() &&
16655 MethodDecl->getOverloadedOperator() == OO_Equal) {
16656 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16657 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16658 if (MethodDecl->isCopyAssignmentOperator())
16659 DefineImplicitCopyAssignment(Loc, MethodDecl);
16660 else if (MethodDecl->isMoveAssignmentOperator())
16661 DefineImplicitMoveAssignment(Loc, MethodDecl);
16663 } else if (isa<CXXConversionDecl>(MethodDecl) &&
16664 MethodDecl->getParent()->isLambda()) {
16665 CXXConversionDecl *Conversion =
16666 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16667 if (Conversion->isLambdaToBlockPointerConversion())
16668 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16670 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16671 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16672 MarkVTableUsed(Loc, MethodDecl->getParent());
16675 if (Func->isDefaulted() && !Func->isDeleted()) {
16676 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16677 if (DCK != DefaultedComparisonKind::None)
16678 DefineDefaultedComparison(Loc, Func, DCK);
16681 // Implicit instantiation of function templates and member functions of
16682 // class templates.
16683 if (Func->isImplicitlyInstantiable()) {
16684 TemplateSpecializationKind TSK =
16685 Func->getTemplateSpecializationKindForInstantiation();
16686 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16687 bool FirstInstantiation = PointOfInstantiation.isInvalid();
16688 if (FirstInstantiation) {
16689 PointOfInstantiation = Loc;
16690 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16691 } else if (TSK != TSK_ImplicitInstantiation) {
16692 // Use the point of use as the point of instantiation, instead of the
16693 // point of explicit instantiation (which we track as the actual point
16694 // of instantiation). This gives better backtraces in diagnostics.
16695 PointOfInstantiation = Loc;
16698 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16699 Func->isConstexpr()) {
16700 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16701 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16702 CodeSynthesisContexts.size())
16703 PendingLocalImplicitInstantiations.push_back(
16704 std::make_pair(Func, PointOfInstantiation));
16705 else if (Func->isConstexpr())
16706 // Do not defer instantiations of constexpr functions, to avoid the
16707 // expression evaluator needing to call back into Sema if it sees a
16708 // call to such a function.
16709 InstantiateFunctionDefinition(PointOfInstantiation, Func);
16711 Func->setInstantiationIsPending(true);
16712 PendingInstantiations.push_back(
16713 std::make_pair(Func, PointOfInstantiation));
16714 // Notify the consumer that a function was implicitly instantiated.
16715 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16719 // Walk redefinitions, as some of them may be instantiable.
16720 for (auto i : Func->redecls()) {
16721 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16722 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16728 // C++14 [except.spec]p17:
16729 // An exception-specification is considered to be needed when:
16730 // - the function is odr-used or, if it appears in an unevaluated operand,
16731 // would be odr-used if the expression were potentially-evaluated;
16733 // Note, we do this even if MightBeOdrUse is false. That indicates that the
16734 // function is a pure virtual function we're calling, and in that case the
16735 // function was selected by overload resolution and we need to resolve its
16736 // exception specification for a different reason.
16737 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16738 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16739 ResolveExceptionSpec(Loc, FPT);
16741 // If this is the first "real" use, act on that.
16742 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16743 // Keep track of used but undefined functions.
16744 if (!Func->isDefined()) {
16745 if (mightHaveNonExternalLinkage(Func))
16746 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16747 else if (Func->getMostRecentDecl()->isInlined() &&
16748 !LangOpts.GNUInline &&
16749 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16750 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16751 else if (isExternalWithNoLinkageType(Func))
16752 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16755 // Some x86 Windows calling conventions mangle the size of the parameter
16756 // pack into the name. Computing the size of the parameters requires the
16757 // parameter types to be complete. Check that now.
16758 if (funcHasParameterSizeMangling(*this, Func))
16759 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16761 // In the MS C++ ABI, the compiler emits destructor variants where they are
16762 // used. If the destructor is used here but defined elsewhere, mark the
16763 // virtual base destructors referenced. If those virtual base destructors
16764 // are inline, this will ensure they are defined when emitting the complete
16765 // destructor variant. This checking may be redundant if the destructor is
16766 // provided later in this TU.
16767 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16768 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16769 CXXRecordDecl *Parent = Dtor->getParent();
16770 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16771 CheckCompleteDestructorVariant(Loc, Dtor);
16775 Func->markUsed(Context);
16779 /// Directly mark a variable odr-used. Given a choice, prefer to use
16780 /// MarkVariableReferenced since it does additional checks and then
16781 /// calls MarkVarDeclODRUsed.
16782 /// If the variable must be captured:
16783 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16784 /// - else capture it in the DeclContext that maps to the
16785 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16787 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16788 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16789 // Keep track of used but undefined variables.
16790 // FIXME: We shouldn't suppress this warning for static data members.
16791 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
16792 (!Var->isExternallyVisible() || Var->isInline() ||
16793 SemaRef.isExternalWithNoLinkageType(Var)) &&
16794 !(Var->isStaticDataMember() && Var->hasInit())) {
16795 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
16796 if (old.isInvalid())
16799 QualType CaptureType, DeclRefType;
16800 if (SemaRef.LangOpts.OpenMP)
16801 SemaRef.tryCaptureOpenMPLambdas(Var);
16802 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
16803 /*EllipsisLoc*/ SourceLocation(),
16804 /*BuildAndDiagnose*/ true,
16805 CaptureType, DeclRefType,
16806 FunctionScopeIndexToStopAt);
16808 Var->markUsed(SemaRef.Context);
16811 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16812 SourceLocation Loc,
16813 unsigned CapturingScopeIndex) {
16814 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16818 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16819 ValueDecl *var, DeclContext *DC) {
16820 DeclContext *VarDC = var->getDeclContext();
16822 // If the parameter still belongs to the translation unit, then
16823 // we're actually just using one parameter in the declaration of
16825 if (isa<ParmVarDecl>(var) &&
16826 isa<TranslationUnitDecl>(VarDC))
16829 // For C code, don't diagnose about capture if we're not actually in code
16830 // right now; it's impossible to write a non-constant expression outside of
16831 // function context, so we'll get other (more useful) diagnostics later.
16833 // For C++, things get a bit more nasty... it would be nice to suppress this
16834 // diagnostic for certain cases like using a local variable in an array bound
16835 // for a member of a local class, but the correct predicate is not obvious.
16836 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16839 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16840 unsigned ContextKind = 3; // unknown
16841 if (isa<CXXMethodDecl>(VarDC) &&
16842 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16844 } else if (isa<FunctionDecl>(VarDC)) {
16846 } else if (isa<BlockDecl>(VarDC)) {
16850 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16851 << var << ValueKind << ContextKind << VarDC;
16852 S.Diag(var->getLocation(), diag::note_entity_declared_at)
16855 // FIXME: Add additional diagnostic info about class etc. which prevents
16860 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16861 bool &SubCapturesAreNested,
16862 QualType &CaptureType,
16863 QualType &DeclRefType) {
16864 // Check whether we've already captured it.
16865 if (CSI->CaptureMap.count(Var)) {
16866 // If we found a capture, any subcaptures are nested.
16867 SubCapturesAreNested = true;
16869 // Retrieve the capture type for this variable.
16870 CaptureType = CSI->getCapture(Var).getCaptureType();
16872 // Compute the type of an expression that refers to this variable.
16873 DeclRefType = CaptureType.getNonReferenceType();
16875 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16876 // are mutable in the sense that user can change their value - they are
16877 // private instances of the captured declarations.
16878 const Capture &Cap = CSI->getCapture(Var);
16879 if (Cap.isCopyCapture() &&
16880 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16881 !(isa<CapturedRegionScopeInfo>(CSI) &&
16882 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16883 DeclRefType.addConst();
16889 // Only block literals, captured statements, and lambda expressions can
16890 // capture; other scopes don't work.
16891 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16892 SourceLocation Loc,
16893 const bool Diagnose, Sema &S) {
16894 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16895 return getLambdaAwareParentOfDeclContext(DC);
16896 else if (Var->hasLocalStorage()) {
16898 diagnoseUncapturableValueReference(S, Loc, Var, DC);
16903 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16904 // certain types of variables (unnamed, variably modified types etc.)
16905 // so check for eligibility.
16906 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16907 SourceLocation Loc,
16908 const bool Diagnose, Sema &S) {
16910 bool IsBlock = isa<BlockScopeInfo>(CSI);
16911 bool IsLambda = isa<LambdaScopeInfo>(CSI);
16913 // Lambdas are not allowed to capture unnamed variables
16914 // (e.g. anonymous unions).
16915 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16916 // assuming that's the intent.
16917 if (IsLambda && !Var->getDeclName()) {
16919 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16920 S.Diag(Var->getLocation(), diag::note_declared_at);
16925 // Prohibit variably-modified types in blocks; they're difficult to deal with.
16926 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16928 S.Diag(Loc, diag::err_ref_vm_type);
16929 S.Diag(Var->getLocation(), diag::note_previous_decl)
16930 << Var->getDeclName();
16934 // Prohibit structs with flexible array members too.
16935 // We cannot capture what is in the tail end of the struct.
16936 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16937 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16940 S.Diag(Loc, diag::err_ref_flexarray_type);
16942 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
16943 << Var->getDeclName();
16944 S.Diag(Var->getLocation(), diag::note_previous_decl)
16945 << Var->getDeclName();
16950 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16951 // Lambdas and captured statements are not allowed to capture __block
16952 // variables; they don't support the expected semantics.
16953 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16955 S.Diag(Loc, diag::err_capture_block_variable)
16956 << Var->getDeclName() << !IsLambda;
16957 S.Diag(Var->getLocation(), diag::note_previous_decl)
16958 << Var->getDeclName();
16962 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16963 if (S.getLangOpts().OpenCL && IsBlock &&
16964 Var->getType()->isBlockPointerType()) {
16966 S.Diag(Loc, diag::err_opencl_block_ref_block);
16973 // Returns true if the capture by block was successful.
16974 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16975 SourceLocation Loc,
16976 const bool BuildAndDiagnose,
16977 QualType &CaptureType,
16978 QualType &DeclRefType,
16980 Sema &S, bool Invalid) {
16981 bool ByRef = false;
16983 // Blocks are not allowed to capture arrays, excepting OpenCL.
16984 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
16985 // (decayed to pointers).
16986 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
16987 if (BuildAndDiagnose) {
16988 S.Diag(Loc, diag::err_ref_array_type);
16989 S.Diag(Var->getLocation(), diag::note_previous_decl)
16990 << Var->getDeclName();
16997 // Forbid the block-capture of autoreleasing variables.
16999 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17000 if (BuildAndDiagnose) {
17001 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17003 S.Diag(Var->getLocation(), diag::note_previous_decl)
17004 << Var->getDeclName();
17011 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17012 if (const auto *PT = CaptureType->getAs<PointerType>()) {
17013 QualType PointeeTy = PT->getPointeeType();
17015 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17016 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17017 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17018 if (BuildAndDiagnose) {
17019 SourceLocation VarLoc = Var->getLocation();
17020 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17021 S.Diag(VarLoc, diag::note_declare_parameter_strong);
17026 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17027 if (HasBlocksAttr || CaptureType->isReferenceType() ||
17028 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17029 // Block capture by reference does not change the capture or
17030 // declaration reference types.
17033 // Block capture by copy introduces 'const'.
17034 CaptureType = CaptureType.getNonReferenceType().withConst();
17035 DeclRefType = CaptureType;
17038 // Actually capture the variable.
17039 if (BuildAndDiagnose)
17040 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17041 CaptureType, Invalid);
17047 /// Capture the given variable in the captured region.
17048 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17050 SourceLocation Loc,
17051 const bool BuildAndDiagnose,
17052 QualType &CaptureType,
17053 QualType &DeclRefType,
17054 const bool RefersToCapturedVariable,
17055 Sema &S, bool Invalid) {
17056 // By default, capture variables by reference.
17058 // Using an LValue reference type is consistent with Lambdas (see below).
17059 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17060 if (S.isOpenMPCapturedDecl(Var)) {
17061 bool HasConst = DeclRefType.isConstQualified();
17062 DeclRefType = DeclRefType.getUnqualifiedType();
17063 // Don't lose diagnostics about assignments to const.
17065 DeclRefType.addConst();
17067 // Do not capture firstprivates in tasks.
17068 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17071 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17072 RSI->OpenMPCaptureLevel);
17076 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17078 CaptureType = DeclRefType;
17080 // Actually capture the variable.
17081 if (BuildAndDiagnose)
17082 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17083 Loc, SourceLocation(), CaptureType, Invalid);
17088 /// Capture the given variable in the lambda.
17089 static bool captureInLambda(LambdaScopeInfo *LSI,
17091 SourceLocation Loc,
17092 const bool BuildAndDiagnose,
17093 QualType &CaptureType,
17094 QualType &DeclRefType,
17095 const bool RefersToCapturedVariable,
17096 const Sema::TryCaptureKind Kind,
17097 SourceLocation EllipsisLoc,
17098 const bool IsTopScope,
17099 Sema &S, bool Invalid) {
17100 // Determine whether we are capturing by reference or by value.
17101 bool ByRef = false;
17102 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17103 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17105 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17108 // Compute the type of the field that will capture this variable.
17110 // C++11 [expr.prim.lambda]p15:
17111 // An entity is captured by reference if it is implicitly or
17112 // explicitly captured but not captured by copy. It is
17113 // unspecified whether additional unnamed non-static data
17114 // members are declared in the closure type for entities
17115 // captured by reference.
17117 // FIXME: It is not clear whether we want to build an lvalue reference
17118 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17119 // to do the former, while EDG does the latter. Core issue 1249 will
17120 // clarify, but for now we follow GCC because it's a more permissive and
17121 // easily defensible position.
17122 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17124 // C++11 [expr.prim.lambda]p14:
17125 // For each entity captured by copy, an unnamed non-static
17126 // data member is declared in the closure type. The
17127 // declaration order of these members is unspecified. The type
17128 // of such a data member is the type of the corresponding
17129 // captured entity if the entity is not a reference to an
17130 // object, or the referenced type otherwise. [Note: If the
17131 // captured entity is a reference to a function, the
17132 // corresponding data member is also a reference to a
17133 // function. - end note ]
17134 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17135 if (!RefType->getPointeeType()->isFunctionType())
17136 CaptureType = RefType->getPointeeType();
17139 // Forbid the lambda copy-capture of autoreleasing variables.
17141 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17142 if (BuildAndDiagnose) {
17143 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17144 S.Diag(Var->getLocation(), diag::note_previous_decl)
17145 << Var->getDeclName();
17152 // Make sure that by-copy captures are of a complete and non-abstract type.
17153 if (!Invalid && BuildAndDiagnose) {
17154 if (!CaptureType->isDependentType() &&
17155 S.RequireCompleteSizedType(
17157 diag::err_capture_of_incomplete_or_sizeless_type,
17158 Var->getDeclName()))
17160 else if (S.RequireNonAbstractType(Loc, CaptureType,
17161 diag::err_capture_of_abstract_type))
17166 // Compute the type of a reference to this captured variable.
17168 DeclRefType = CaptureType.getNonReferenceType();
17170 // C++ [expr.prim.lambda]p5:
17171 // The closure type for a lambda-expression has a public inline
17172 // function call operator [...]. This function call operator is
17173 // declared const (9.3.1) if and only if the lambda-expression's
17174 // parameter-declaration-clause is not followed by mutable.
17175 DeclRefType = CaptureType.getNonReferenceType();
17176 if (!LSI->Mutable && !CaptureType->isReferenceType())
17177 DeclRefType.addConst();
17180 // Add the capture.
17181 if (BuildAndDiagnose)
17182 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17183 Loc, EllipsisLoc, CaptureType, Invalid);
17188 bool Sema::tryCaptureVariable(
17189 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17190 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17191 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17192 // An init-capture is notionally from the context surrounding its
17193 // declaration, but its parent DC is the lambda class.
17194 DeclContext *VarDC = Var->getDeclContext();
17195 if (Var->isInitCapture())
17196 VarDC = VarDC->getParent();
17198 DeclContext *DC = CurContext;
17199 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17200 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17201 // We need to sync up the Declaration Context with the
17202 // FunctionScopeIndexToStopAt
17203 if (FunctionScopeIndexToStopAt) {
17204 unsigned FSIndex = FunctionScopes.size() - 1;
17205 while (FSIndex != MaxFunctionScopesIndex) {
17206 DC = getLambdaAwareParentOfDeclContext(DC);
17212 // If the variable is declared in the current context, there is no need to
17214 if (VarDC == DC) return true;
17216 // Capture global variables if it is required to use private copy of this
17218 bool IsGlobal = !Var->hasLocalStorage();
17220 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17221 MaxFunctionScopesIndex)))
17223 Var = Var->getCanonicalDecl();
17225 // Walk up the stack to determine whether we can capture the variable,
17226 // performing the "simple" checks that don't depend on type. We stop when
17227 // we've either hit the declared scope of the variable or find an existing
17228 // capture of that variable. We start from the innermost capturing-entity
17229 // (the DC) and ensure that all intervening capturing-entities
17230 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17231 // declcontext can either capture the variable or have already captured
17233 CaptureType = Var->getType();
17234 DeclRefType = CaptureType.getNonReferenceType();
17235 bool Nested = false;
17236 bool Explicit = (Kind != TryCapture_Implicit);
17237 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17239 // Only block literals, captured statements, and lambda expressions can
17240 // capture; other scopes don't work.
17241 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17245 // We need to check for the parent *first* because, if we *have*
17246 // private-captured a global variable, we need to recursively capture it in
17247 // intermediate blocks, lambdas, etc.
17250 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17256 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
17257 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17260 // Check whether we've already captured it.
17261 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17263 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17266 // If we are instantiating a generic lambda call operator body,
17267 // we do not want to capture new variables. What was captured
17268 // during either a lambdas transformation or initial parsing
17270 if (isGenericLambdaCallOperatorSpecialization(DC)) {
17271 if (BuildAndDiagnose) {
17272 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17273 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17274 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17275 Diag(Var->getLocation(), diag::note_previous_decl)
17276 << Var->getDeclName();
17277 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17279 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17284 // Try to capture variable-length arrays types.
17285 if (Var->getType()->isVariablyModifiedType()) {
17286 // We're going to walk down into the type and look for VLA
17288 QualType QTy = Var->getType();
17289 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17290 QTy = PVD->getOriginalType();
17291 captureVariablyModifiedType(Context, QTy, CSI);
17294 if (getLangOpts().OpenMP) {
17295 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17296 // OpenMP private variables should not be captured in outer scope, so
17297 // just break here. Similarly, global variables that are captured in a
17298 // target region should not be captured outside the scope of the region.
17299 if (RSI->CapRegionKind == CR_OpenMP) {
17300 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17301 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17302 // If the variable is private (i.e. not captured) and has variably
17303 // modified type, we still need to capture the type for correct
17304 // codegen in all regions, associated with the construct. Currently,
17305 // it is captured in the innermost captured region only.
17306 if (IsOpenMPPrivateDecl != OMPC_unknown &&
17307 Var->getType()->isVariablyModifiedType()) {
17308 QualType QTy = Var->getType();
17309 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17310 QTy = PVD->getOriginalType();
17311 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17313 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17314 FunctionScopes[FunctionScopesIndex - I]);
17315 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17316 "Wrong number of captured regions associated with the "
17317 "OpenMP construct.");
17318 captureVariablyModifiedType(Context, QTy, OuterRSI);
17322 IsOpenMPPrivateDecl != OMPC_private &&
17323 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17324 RSI->OpenMPCaptureLevel);
17325 // Do not capture global if it is not privatized in outer regions.
17327 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17328 RSI->OpenMPCaptureLevel);
17330 // When we detect target captures we are looking from inside the
17331 // target region, therefore we need to propagate the capture from the
17332 // enclosing region. Therefore, the capture is not initially nested.
17334 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17336 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17337 (IsGlobal && !IsGlobalCap)) {
17338 Nested = !IsTargetCap;
17339 DeclRefType = DeclRefType.getUnqualifiedType();
17340 CaptureType = Context.getLValueReferenceType(DeclRefType);
17346 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17347 // No capture-default, and this is not an explicit capture
17348 // so cannot capture this variable.
17349 if (BuildAndDiagnose) {
17350 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
17351 Diag(Var->getLocation(), diag::note_previous_decl)
17352 << Var->getDeclName();
17353 if (cast<LambdaScopeInfo>(CSI)->Lambda)
17354 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17355 diag::note_lambda_decl);
17356 // FIXME: If we error out because an outer lambda can not implicitly
17357 // capture a variable that an inner lambda explicitly captures, we
17358 // should have the inner lambda do the explicit capture - because
17359 // it makes for cleaner diagnostics later. This would purely be done
17360 // so that the diagnostic does not misleadingly claim that a variable
17361 // can not be captured by a lambda implicitly even though it is captured
17362 // explicitly. Suggestion:
17363 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17364 // at the function head
17365 // - cache the StartingDeclContext - this must be a lambda
17366 // - captureInLambda in the innermost lambda the variable.
17371 FunctionScopesIndex--;
17374 } while (!VarDC->Equals(DC));
17376 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17377 // computing the type of the capture at each step, checking type-specific
17378 // requirements, and adding captures if requested.
17379 // If the variable had already been captured previously, we start capturing
17380 // at the lambda nested within that one.
17381 bool Invalid = false;
17382 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17384 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17386 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17387 // certain types of variables (unnamed, variably modified types etc.)
17388 // so check for eligibility.
17391 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17393 // After encountering an error, if we're actually supposed to capture, keep
17394 // capturing in nested contexts to suppress any follow-on diagnostics.
17395 if (Invalid && !BuildAndDiagnose)
17398 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17399 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17400 DeclRefType, Nested, *this, Invalid);
17402 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17403 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17404 CaptureType, DeclRefType, Nested,
17408 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17410 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17411 DeclRefType, Nested, Kind, EllipsisLoc,
17412 /*IsTopScope*/ I == N - 1, *this, Invalid);
17416 if (Invalid && !BuildAndDiagnose)
17422 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17423 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17424 QualType CaptureType;
17425 QualType DeclRefType;
17426 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17427 /*BuildAndDiagnose=*/true, CaptureType,
17428 DeclRefType, nullptr);
17431 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17432 QualType CaptureType;
17433 QualType DeclRefType;
17434 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17435 /*BuildAndDiagnose=*/false, CaptureType,
17436 DeclRefType, nullptr);
17439 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17440 QualType CaptureType;
17441 QualType DeclRefType;
17443 // Determine whether we can capture this variable.
17444 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17445 /*BuildAndDiagnose=*/false, CaptureType,
17446 DeclRefType, nullptr))
17449 return DeclRefType;
17453 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17454 // The produced TemplateArgumentListInfo* points to data stored within this
17455 // object, so should only be used in contexts where the pointer will not be
17456 // used after the CopiedTemplateArgs object is destroyed.
17457 class CopiedTemplateArgs {
17459 TemplateArgumentListInfo TemplateArgStorage;
17461 template<typename RefExpr>
17462 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17464 E->copyTemplateArgumentsInto(TemplateArgStorage);
17466 operator TemplateArgumentListInfo*()
17467 #ifdef __has_cpp_attribute
17468 #if __has_cpp_attribute(clang::lifetimebound)
17469 [[clang::lifetimebound]]
17473 return HasArgs ? &TemplateArgStorage : nullptr;
17478 /// Walk the set of potential results of an expression and mark them all as
17479 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17481 /// \return A new expression if we found any potential results, ExprEmpty() if
17482 /// not, and ExprError() if we diagnosed an error.
17483 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17484 NonOdrUseReason NOUR) {
17485 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17486 // an object that satisfies the requirements for appearing in a
17487 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17488 // is immediately applied." This function handles the lvalue-to-rvalue
17489 // conversion part.
17491 // If we encounter a node that claims to be an odr-use but shouldn't be, we
17492 // transform it into the relevant kind of non-odr-use node and rebuild the
17493 // tree of nodes leading to it.
17495 // This is a mini-TreeTransform that only transforms a restricted subset of
17496 // nodes (and only certain operands of them).
17498 // Rebuild a subexpression.
17499 auto Rebuild = [&](Expr *Sub) {
17500 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17503 // Check whether a potential result satisfies the requirements of NOUR.
17504 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17505 // Any entity other than a VarDecl is always odr-used whenever it's named
17506 // in a potentially-evaluated expression.
17507 auto *VD = dyn_cast<VarDecl>(D);
17511 // C++2a [basic.def.odr]p4:
17512 // A variable x whose name appears as a potentially-evalauted expression
17513 // e is odr-used by e unless
17514 // -- x is a reference that is usable in constant expressions, or
17515 // -- x is a variable of non-reference type that is usable in constant
17516 // expressions and has no mutable subobjects, and e is an element of
17517 // the set of potential results of an expression of
17518 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
17519 // conversion is applied, or
17520 // -- x is a variable of non-reference type, and e is an element of the
17521 // set of potential results of a discarded-value expression to which
17522 // the lvalue-to-rvalue conversion is not applied
17524 // We check the first bullet and the "potentially-evaluated" condition in
17525 // BuildDeclRefExpr. We check the type requirements in the second bullet
17526 // in CheckLValueToRValueConversionOperand below.
17529 case NOUR_Unevaluated:
17530 llvm_unreachable("unexpected non-odr-use-reason");
17532 case NOUR_Constant:
17533 // Constant references were handled when they were built.
17534 if (VD->getType()->isReferenceType())
17536 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17537 if (RD->hasMutableFields())
17539 if (!VD->isUsableInConstantExpressions(S.Context))
17543 case NOUR_Discarded:
17544 if (VD->getType()->isReferenceType())
17551 // Mark that this expression does not constitute an odr-use.
17552 auto MarkNotOdrUsed = [&] {
17553 S.MaybeODRUseExprs.remove(E);
17554 if (LambdaScopeInfo *LSI = S.getCurLambda())
17555 LSI->markVariableExprAsNonODRUsed(E);
17558 // C++2a [basic.def.odr]p2:
17559 // The set of potential results of an expression e is defined as follows:
17560 switch (E->getStmtClass()) {
17561 // -- If e is an id-expression, ...
17562 case Expr::DeclRefExprClass: {
17563 auto *DRE = cast<DeclRefExpr>(E);
17564 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17567 // Rebuild as a non-odr-use DeclRefExpr.
17569 return DeclRefExpr::Create(
17570 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17571 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17572 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17573 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17576 case Expr::FunctionParmPackExprClass: {
17577 auto *FPPE = cast<FunctionParmPackExpr>(E);
17578 // If any of the declarations in the pack is odr-used, then the expression
17579 // as a whole constitutes an odr-use.
17580 for (VarDecl *D : *FPPE)
17581 if (IsPotentialResultOdrUsed(D))
17582 return ExprEmpty();
17584 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17585 // nothing cares about whether we marked this as an odr-use, but it might
17586 // be useful for non-compiler tools.
17591 // -- If e is a subscripting operation with an array operand...
17592 case Expr::ArraySubscriptExprClass: {
17593 auto *ASE = cast<ArraySubscriptExpr>(E);
17594 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17595 if (!OldBase->getType()->isArrayType())
17597 ExprResult Base = Rebuild(OldBase);
17598 if (!Base.isUsable())
17600 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17601 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17602 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17603 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17604 ASE->getRBracketLoc());
17607 case Expr::MemberExprClass: {
17608 auto *ME = cast<MemberExpr>(E);
17609 // -- If e is a class member access expression [...] naming a non-static
17611 if (isa<FieldDecl>(ME->getMemberDecl())) {
17612 ExprResult Base = Rebuild(ME->getBase());
17613 if (!Base.isUsable())
17615 return MemberExpr::Create(
17616 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17617 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17618 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17619 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17620 ME->getObjectKind(), ME->isNonOdrUse());
17623 if (ME->getMemberDecl()->isCXXInstanceMember())
17626 // -- If e is a class member access expression naming a static data member,
17628 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17631 // Rebuild as a non-odr-use MemberExpr.
17633 return MemberExpr::Create(
17634 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17635 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17636 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17637 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17638 return ExprEmpty();
17641 case Expr::BinaryOperatorClass: {
17642 auto *BO = cast<BinaryOperator>(E);
17643 Expr *LHS = BO->getLHS();
17644 Expr *RHS = BO->getRHS();
17645 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17646 if (BO->getOpcode() == BO_PtrMemD) {
17647 ExprResult Sub = Rebuild(LHS);
17648 if (!Sub.isUsable())
17651 // -- If e is a comma expression, ...
17652 } else if (BO->getOpcode() == BO_Comma) {
17653 ExprResult Sub = Rebuild(RHS);
17654 if (!Sub.isUsable())
17660 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17664 // -- If e has the form (e1)...
17665 case Expr::ParenExprClass: {
17666 auto *PE = cast<ParenExpr>(E);
17667 ExprResult Sub = Rebuild(PE->getSubExpr());
17668 if (!Sub.isUsable())
17670 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17673 // -- If e is a glvalue conditional expression, ...
17674 // We don't apply this to a binary conditional operator. FIXME: Should we?
17675 case Expr::ConditionalOperatorClass: {
17676 auto *CO = cast<ConditionalOperator>(E);
17677 ExprResult LHS = Rebuild(CO->getLHS());
17678 if (LHS.isInvalid())
17679 return ExprError();
17680 ExprResult RHS = Rebuild(CO->getRHS());
17681 if (RHS.isInvalid())
17682 return ExprError();
17683 if (!LHS.isUsable() && !RHS.isUsable())
17684 return ExprEmpty();
17685 if (!LHS.isUsable())
17686 LHS = CO->getLHS();
17687 if (!RHS.isUsable())
17688 RHS = CO->getRHS();
17689 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17690 CO->getCond(), LHS.get(), RHS.get());
17693 // [Clang extension]
17694 // -- If e has the form __extension__ e1...
17695 case Expr::UnaryOperatorClass: {
17696 auto *UO = cast<UnaryOperator>(E);
17697 if (UO->getOpcode() != UO_Extension)
17699 ExprResult Sub = Rebuild(UO->getSubExpr());
17700 if (!Sub.isUsable())
17702 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17706 // [Clang extension]
17707 // -- If e has the form _Generic(...), the set of potential results is the
17708 // union of the sets of potential results of the associated expressions.
17709 case Expr::GenericSelectionExprClass: {
17710 auto *GSE = cast<GenericSelectionExpr>(E);
17712 SmallVector<Expr *, 4> AssocExprs;
17713 bool AnyChanged = false;
17714 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17715 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17716 if (AssocExpr.isInvalid())
17717 return ExprError();
17718 if (AssocExpr.isUsable()) {
17719 AssocExprs.push_back(AssocExpr.get());
17722 AssocExprs.push_back(OrigAssocExpr);
17726 return AnyChanged ? S.CreateGenericSelectionExpr(
17727 GSE->getGenericLoc(), GSE->getDefaultLoc(),
17728 GSE->getRParenLoc(), GSE->getControllingExpr(),
17729 GSE->getAssocTypeSourceInfos(), AssocExprs)
17733 // [Clang extension]
17734 // -- If e has the form __builtin_choose_expr(...), the set of potential
17735 // results is the union of the sets of potential results of the
17736 // second and third subexpressions.
17737 case Expr::ChooseExprClass: {
17738 auto *CE = cast<ChooseExpr>(E);
17740 ExprResult LHS = Rebuild(CE->getLHS());
17741 if (LHS.isInvalid())
17742 return ExprError();
17744 ExprResult RHS = Rebuild(CE->getLHS());
17745 if (RHS.isInvalid())
17746 return ExprError();
17748 if (!LHS.get() && !RHS.get())
17749 return ExprEmpty();
17750 if (!LHS.isUsable())
17751 LHS = CE->getLHS();
17752 if (!RHS.isUsable())
17753 RHS = CE->getRHS();
17755 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17756 RHS.get(), CE->getRParenLoc());
17759 // Step through non-syntactic nodes.
17760 case Expr::ConstantExprClass: {
17761 auto *CE = cast<ConstantExpr>(E);
17762 ExprResult Sub = Rebuild(CE->getSubExpr());
17763 if (!Sub.isUsable())
17765 return ConstantExpr::Create(S.Context, Sub.get());
17768 // We could mostly rely on the recursive rebuilding to rebuild implicit
17769 // casts, but not at the top level, so rebuild them here.
17770 case Expr::ImplicitCastExprClass: {
17771 auto *ICE = cast<ImplicitCastExpr>(E);
17772 // Only step through the narrow set of cast kinds we expect to encounter.
17773 // Anything else suggests we've left the region in which potential results
17775 switch (ICE->getCastKind()) {
17777 case CK_DerivedToBase:
17778 case CK_UncheckedDerivedToBase: {
17779 ExprResult Sub = Rebuild(ICE->getSubExpr());
17780 if (!Sub.isUsable())
17782 CXXCastPath Path(ICE->path());
17783 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17784 ICE->getValueKind(), &Path);
17797 // Can't traverse through this node. Nothing to do.
17798 return ExprEmpty();
17801 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
17802 // Check whether the operand is or contains an object of non-trivial C union
17804 if (E->getType().isVolatileQualified() &&
17805 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
17806 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
17807 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
17808 Sema::NTCUC_LValueToRValueVolatile,
17809 NTCUK_Destruct|NTCUK_Copy);
17811 // C++2a [basic.def.odr]p4:
17812 // [...] an expression of non-volatile-qualified non-class type to which
17813 // the lvalue-to-rvalue conversion is applied [...]
17814 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
17817 ExprResult Result =
17818 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
17819 if (Result.isInvalid())
17820 return ExprError();
17821 return Result.get() ? Result : E;
17824 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17825 Res = CorrectDelayedTyposInExpr(Res);
17827 if (!Res.isUsable())
17830 // If a constant-expression is a reference to a variable where we delay
17831 // deciding whether it is an odr-use, just assume we will apply the
17832 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
17833 // (a non-type template argument), we have special handling anyway.
17834 return CheckLValueToRValueConversionOperand(Res.get());
17837 void Sema::CleanupVarDeclMarking() {
17838 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17840 MaybeODRUseExprSet LocalMaybeODRUseExprs;
17841 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17843 for (Expr *E : LocalMaybeODRUseExprs) {
17844 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17845 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17846 DRE->getLocation(), *this);
17847 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17848 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17850 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17851 for (VarDecl *VD : *FP)
17852 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17854 llvm_unreachable("Unexpected expression");
17858 assert(MaybeODRUseExprs.empty() &&
17859 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
17862 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17863 VarDecl *Var, Expr *E) {
17864 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
17865 isa<FunctionParmPackExpr>(E)) &&
17866 "Invalid Expr argument to DoMarkVarDeclReferenced");
17867 Var->setReferenced();
17869 if (Var->isInvalidDecl())
17872 auto *MSI = Var->getMemberSpecializationInfo();
17873 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17874 : Var->getTemplateSpecializationKind();
17876 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17877 bool UsableInConstantExpr =
17878 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17880 // C++20 [expr.const]p12:
17881 // A variable [...] is needed for constant evaluation if it is [...] a
17882 // variable whose name appears as a potentially constant evaluated
17883 // expression that is either a contexpr variable or is of non-volatile
17884 // const-qualified integral type or of reference type
17885 bool NeededForConstantEvaluation =
17886 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17888 bool NeedDefinition =
17889 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17891 VarTemplateSpecializationDecl *VarSpec =
17892 dyn_cast<VarTemplateSpecializationDecl>(Var);
17893 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
17894 "Can't instantiate a partial template specialization.");
17896 // If this might be a member specialization of a static data member, check
17897 // the specialization is visible. We already did the checks for variable
17898 // template specializations when we created them.
17899 if (NeedDefinition && TSK != TSK_Undeclared &&
17900 !isa<VarTemplateSpecializationDecl>(Var))
17901 SemaRef.checkSpecializationVisibility(Loc, Var);
17903 // Perform implicit instantiation of static data members, static data member
17904 // templates of class templates, and variable template specializations. Delay
17905 // instantiations of variable templates, except for those that could be used
17906 // in a constant expression.
17907 if (NeedDefinition && isTemplateInstantiation(TSK)) {
17908 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17909 // instantiation declaration if a variable is usable in a constant
17910 // expression (among other cases).
17911 bool TryInstantiating =
17912 TSK == TSK_ImplicitInstantiation ||
17913 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17915 if (TryInstantiating) {
17916 SourceLocation PointOfInstantiation =
17917 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17918 bool FirstInstantiation = PointOfInstantiation.isInvalid();
17919 if (FirstInstantiation) {
17920 PointOfInstantiation = Loc;
17922 MSI->setPointOfInstantiation(PointOfInstantiation);
17924 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17927 bool InstantiationDependent = false;
17928 bool IsNonDependent =
17929 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17930 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17933 // Do not instantiate specializations that are still type-dependent.
17934 if (IsNonDependent) {
17935 if (UsableInConstantExpr) {
17936 // Do not defer instantiations of variables that could be used in a
17937 // constant expression.
17938 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17939 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17941 } else if (FirstInstantiation ||
17942 isa<VarTemplateSpecializationDecl>(Var)) {
17943 // FIXME: For a specialization of a variable template, we don't
17944 // distinguish between "declaration and type implicitly instantiated"
17945 // and "implicit instantiation of definition requested", so we have
17946 // no direct way to avoid enqueueing the pending instantiation
17948 SemaRef.PendingInstantiations
17949 .push_back(std::make_pair(Var, PointOfInstantiation));
17955 // C++2a [basic.def.odr]p4:
17956 // A variable x whose name appears as a potentially-evaluated expression e
17957 // is odr-used by e unless
17958 // -- x is a reference that is usable in constant expressions
17959 // -- x is a variable of non-reference type that is usable in constant
17960 // expressions and has no mutable subobjects [FIXME], and e is an
17961 // element of the set of potential results of an expression of
17962 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
17963 // conversion is applied
17964 // -- x is a variable of non-reference type, and e is an element of the set
17965 // of potential results of a discarded-value expression to which the
17966 // lvalue-to-rvalue conversion is not applied [FIXME]
17968 // We check the first part of the second bullet here, and
17969 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17970 // FIXME: To get the third bullet right, we need to delay this even for
17971 // variables that are not usable in constant expressions.
17973 // If we already know this isn't an odr-use, there's nothing more to do.
17974 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17975 if (DRE->isNonOdrUse())
17977 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17978 if (ME->isNonOdrUse())
17982 case OdrUseContext::None:
17983 assert((!E || isa<FunctionParmPackExpr>(E)) &&
17984 "missing non-odr-use marking for unevaluated decl ref");
17987 case OdrUseContext::FormallyOdrUsed:
17988 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
17992 case OdrUseContext::Used:
17993 // If we might later find that this expression isn't actually an odr-use,
17994 // delay the marking.
17995 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
17996 SemaRef.MaybeODRUseExprs.insert(E);
17998 MarkVarDeclODRUsed(Var, Loc, SemaRef);
18001 case OdrUseContext::Dependent:
18002 // If this is a dependent context, we don't need to mark variables as
18003 // odr-used, but we may still need to track them for lambda capture.
18004 // FIXME: Do we also need to do this inside dependent typeid expressions
18005 // (which are modeled as unevaluated at this point)?
18006 const bool RefersToEnclosingScope =
18007 (SemaRef.CurContext != Var->getDeclContext() &&
18008 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18009 if (RefersToEnclosingScope) {
18010 LambdaScopeInfo *const LSI =
18011 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18012 if (LSI && (!LSI->CallOperator ||
18013 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18014 // If a variable could potentially be odr-used, defer marking it so
18015 // until we finish analyzing the full expression for any
18016 // lvalue-to-rvalue
18017 // or discarded value conversions that would obviate odr-use.
18018 // Add it to the list of potential captures that will be analyzed
18019 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18020 // unless the variable is a reference that was initialized by a constant
18021 // expression (this will never need to be captured or odr-used).
18023 // FIXME: We can simplify this a lot after implementing P0588R1.
18024 assert(E && "Capture variable should be used in an expression.");
18025 if (!Var->getType()->isReferenceType() ||
18026 !Var->isUsableInConstantExpressions(SemaRef.Context))
18027 LSI->addPotentialCapture(E->IgnoreParens());
18034 /// Mark a variable referenced, and check whether it is odr-used
18035 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
18036 /// used directly for normal expressions referring to VarDecl.
18037 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18038 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18041 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18042 Decl *D, Expr *E, bool MightBeOdrUse) {
18043 if (SemaRef.isInOpenMPDeclareTargetContext())
18044 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18046 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18047 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18051 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18053 // If this is a call to a method via a cast, also mark the method in the
18054 // derived class used in case codegen can devirtualize the call.
18055 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18058 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18061 // Only attempt to devirtualize if this is truly a virtual call.
18062 bool IsVirtualCall = MD->isVirtual() &&
18063 ME->performsVirtualDispatch(SemaRef.getLangOpts());
18064 if (!IsVirtualCall)
18067 // If it's possible to devirtualize the call, mark the called function
18069 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18070 ME->getBase(), SemaRef.getLangOpts().AppleKext);
18072 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18075 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18076 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18077 // TODO: update this with DR# once a defect report is filed.
18078 // C++11 defect. The address of a pure member should not be an ODR use, even
18079 // if it's a qualified reference.
18080 bool OdrUse = true;
18081 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18082 if (Method->isVirtual() &&
18083 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18086 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18087 if (!isConstantEvaluated() && FD->isConsteval() &&
18088 !RebuildingImmediateInvocation)
18089 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18090 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18093 /// Perform reference-marking and odr-use handling for a MemberExpr.
18094 void Sema::MarkMemberReferenced(MemberExpr *E) {
18095 // C++11 [basic.def.odr]p2:
18096 // A non-overloaded function whose name appears as a potentially-evaluated
18097 // expression or a member of a set of candidate functions, if selected by
18098 // overload resolution when referred to from a potentially-evaluated
18099 // expression, is odr-used, unless it is a pure virtual function and its
18100 // name is not explicitly qualified.
18101 bool MightBeOdrUse = true;
18102 if (E->performsVirtualDispatch(getLangOpts())) {
18103 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18104 if (Method->isPure())
18105 MightBeOdrUse = false;
18107 SourceLocation Loc =
18108 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18109 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18112 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
18113 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18114 for (VarDecl *VD : *E)
18115 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18118 /// Perform marking for a reference to an arbitrary declaration. It
18119 /// marks the declaration referenced, and performs odr-use checking for
18120 /// functions and variables. This method should not be used when building a
18121 /// normal expression which refers to a variable.
18122 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18123 bool MightBeOdrUse) {
18124 if (MightBeOdrUse) {
18125 if (auto *VD = dyn_cast<VarDecl>(D)) {
18126 MarkVariableReferenced(Loc, VD);
18130 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18131 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18134 D->setReferenced();
18138 // Mark all of the declarations used by a type as referenced.
18139 // FIXME: Not fully implemented yet! We need to have a better understanding
18140 // of when we're entering a context we should not recurse into.
18141 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18142 // TreeTransforms rebuilding the type in a new context. Rather than
18143 // duplicating the TreeTransform logic, we should consider reusing it here.
18144 // Currently that causes problems when rebuilding LambdaExprs.
18145 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18147 SourceLocation Loc;
18150 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18152 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18154 bool TraverseTemplateArgument(const TemplateArgument &Arg);
18158 bool MarkReferencedDecls::TraverseTemplateArgument(
18159 const TemplateArgument &Arg) {
18161 // A non-type template argument is a constant-evaluated context.
18162 EnterExpressionEvaluationContext Evaluated(
18163 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18164 if (Arg.getKind() == TemplateArgument::Declaration) {
18165 if (Decl *D = Arg.getAsDecl())
18166 S.MarkAnyDeclReferenced(Loc, D, true);
18167 } else if (Arg.getKind() == TemplateArgument::Expression) {
18168 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18172 return Inherited::TraverseTemplateArgument(Arg);
18175 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18176 MarkReferencedDecls Marker(*this, Loc);
18177 Marker.TraverseType(T);
18181 /// Helper class that marks all of the declarations referenced by
18182 /// potentially-evaluated subexpressions as "referenced".
18183 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18185 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18186 bool SkipLocalVariables;
18188 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18189 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18191 void visitUsedDecl(SourceLocation Loc, Decl *D) {
18192 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18195 void VisitDeclRefExpr(DeclRefExpr *E) {
18196 // If we were asked not to visit local variables, don't.
18197 if (SkipLocalVariables) {
18198 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18199 if (VD->hasLocalStorage())
18202 S.MarkDeclRefReferenced(E);
18205 void VisitMemberExpr(MemberExpr *E) {
18206 S.MarkMemberReferenced(E);
18207 Visit(E->getBase());
18212 /// Mark any declarations that appear within this expression or any
18213 /// potentially-evaluated subexpressions as "referenced".
18215 /// \param SkipLocalVariables If true, don't mark local variables as
18217 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18218 bool SkipLocalVariables) {
18219 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18222 /// Emit a diagnostic that describes an effect on the run-time behavior
18223 /// of the program being compiled.
18225 /// This routine emits the given diagnostic when the code currently being
18226 /// type-checked is "potentially evaluated", meaning that there is a
18227 /// possibility that the code will actually be executable. Code in sizeof()
18228 /// expressions, code used only during overload resolution, etc., are not
18229 /// potentially evaluated. This routine will suppress such diagnostics or,
18230 /// in the absolutely nutty case of potentially potentially evaluated
18231 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18234 /// This routine should be used for all diagnostics that describe the run-time
18235 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18236 /// Failure to do so will likely result in spurious diagnostics or failures
18237 /// during overload resolution or within sizeof/alignof/typeof/typeid.
18238 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18239 const PartialDiagnostic &PD) {
18240 switch (ExprEvalContexts.back().Context) {
18241 case ExpressionEvaluationContext::Unevaluated:
18242 case ExpressionEvaluationContext::UnevaluatedList:
18243 case ExpressionEvaluationContext::UnevaluatedAbstract:
18244 case ExpressionEvaluationContext::DiscardedStatement:
18245 // The argument will never be evaluated, so don't complain.
18248 case ExpressionEvaluationContext::ConstantEvaluated:
18249 // Relevant diagnostics should be produced by constant evaluation.
18252 case ExpressionEvaluationContext::PotentiallyEvaluated:
18253 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18254 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18255 FunctionScopes.back()->PossiblyUnreachableDiags.
18256 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18260 // The initializer of a constexpr variable or of the first declaration of a
18261 // static data member is not syntactically a constant evaluated constant,
18262 // but nonetheless is always required to be a constant expression, so we
18263 // can skip diagnosing.
18264 // FIXME: Using the mangling context here is a hack.
18265 if (auto *VD = dyn_cast_or_null<VarDecl>(
18266 ExprEvalContexts.back().ManglingContextDecl)) {
18267 if (VD->isConstexpr() ||
18268 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18270 // FIXME: For any other kind of variable, we should build a CFG for its
18271 // initializer and check whether the context in question is reachable.
18281 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18282 const PartialDiagnostic &PD) {
18283 return DiagRuntimeBehavior(
18284 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18287 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18288 CallExpr *CE, FunctionDecl *FD) {
18289 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18292 // If we're inside a decltype's expression, don't check for a valid return
18293 // type or construct temporaries until we know whether this is the last call.
18294 if (ExprEvalContexts.back().ExprContext ==
18295 ExpressionEvaluationContextRecord::EK_Decltype) {
18296 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18300 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18305 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18306 : FD(FD), CE(CE) { }
18308 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18310 S.Diag(Loc, diag::err_call_incomplete_return)
18311 << T << CE->getSourceRange();
18315 S.Diag(Loc, diag::err_call_function_incomplete_return)
18316 << CE->getSourceRange() << FD->getDeclName() << T;
18317 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18318 << FD->getDeclName();
18320 } Diagnoser(FD, CE);
18322 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18328 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18329 // will prevent this condition from triggering, which is what we want.
18330 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18331 SourceLocation Loc;
18333 unsigned diagnostic = diag::warn_condition_is_assignment;
18334 bool IsOrAssign = false;
18336 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18337 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18340 IsOrAssign = Op->getOpcode() == BO_OrAssign;
18342 // Greylist some idioms by putting them into a warning subcategory.
18343 if (ObjCMessageExpr *ME
18344 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18345 Selector Sel = ME->getSelector();
18347 // self = [<foo> init...]
18348 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18349 diagnostic = diag::warn_condition_is_idiomatic_assignment;
18351 // <foo> = [<bar> nextObject]
18352 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18353 diagnostic = diag::warn_condition_is_idiomatic_assignment;
18356 Loc = Op->getOperatorLoc();
18357 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18358 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18361 IsOrAssign = Op->getOperator() == OO_PipeEqual;
18362 Loc = Op->getOperatorLoc();
18363 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18364 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18366 // Not an assignment.
18370 Diag(Loc, diagnostic) << E->getSourceRange();
18372 SourceLocation Open = E->getBeginLoc();
18373 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18374 Diag(Loc, diag::note_condition_assign_silence)
18375 << FixItHint::CreateInsertion(Open, "(")
18376 << FixItHint::CreateInsertion(Close, ")");
18379 Diag(Loc, diag::note_condition_or_assign_to_comparison)
18380 << FixItHint::CreateReplacement(Loc, "!=");
18382 Diag(Loc, diag::note_condition_assign_to_comparison)
18383 << FixItHint::CreateReplacement(Loc, "==");
18386 /// Redundant parentheses over an equality comparison can indicate
18387 /// that the user intended an assignment used as condition.
18388 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18389 // Don't warn if the parens came from a macro.
18390 SourceLocation parenLoc = ParenE->getBeginLoc();
18391 if (parenLoc.isInvalid() || parenLoc.isMacroID())
18393 // Don't warn for dependent expressions.
18394 if (ParenE->isTypeDependent())
18397 Expr *E = ParenE->IgnoreParens();
18399 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18400 if (opE->getOpcode() == BO_EQ &&
18401 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18402 == Expr::MLV_Valid) {
18403 SourceLocation Loc = opE->getOperatorLoc();
18405 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18406 SourceRange ParenERange = ParenE->getSourceRange();
18407 Diag(Loc, diag::note_equality_comparison_silence)
18408 << FixItHint::CreateRemoval(ParenERange.getBegin())
18409 << FixItHint::CreateRemoval(ParenERange.getEnd());
18410 Diag(Loc, diag::note_equality_comparison_to_assign)
18411 << FixItHint::CreateReplacement(Loc, "=");
18415 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18416 bool IsConstexpr) {
18417 DiagnoseAssignmentAsCondition(E);
18418 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18419 DiagnoseEqualityWithExtraParens(parenE);
18421 ExprResult result = CheckPlaceholderExpr(E);
18422 if (result.isInvalid()) return ExprError();
18425 if (!E->isTypeDependent()) {
18426 if (getLangOpts().CPlusPlus)
18427 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18429 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18430 if (ERes.isInvalid())
18431 return ExprError();
18434 QualType T = E->getType();
18435 if (!T->isScalarType()) { // C99 6.8.4.1p1
18436 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18437 << T << E->getSourceRange();
18438 return ExprError();
18440 CheckBoolLikeConversion(E, Loc);
18446 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18447 Expr *SubExpr, ConditionKind CK) {
18448 // Empty conditions are valid in for-statements.
18450 return ConditionResult();
18454 case ConditionKind::Boolean:
18455 Cond = CheckBooleanCondition(Loc, SubExpr);
18458 case ConditionKind::ConstexprIf:
18459 Cond = CheckBooleanCondition(Loc, SubExpr, true);
18462 case ConditionKind::Switch:
18463 Cond = CheckSwitchCondition(Loc, SubExpr);
18466 if (Cond.isInvalid())
18467 return ConditionError();
18469 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18470 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18471 if (!FullExpr.get())
18472 return ConditionError();
18474 return ConditionResult(*this, nullptr, FullExpr,
18475 CK == ConditionKind::ConstexprIf);
18479 /// A visitor for rebuilding a call to an __unknown_any expression
18480 /// to have an appropriate type.
18481 struct RebuildUnknownAnyFunction
18482 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18486 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18488 ExprResult VisitStmt(Stmt *S) {
18489 llvm_unreachable("unexpected statement!");
18492 ExprResult VisitExpr(Expr *E) {
18493 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18494 << E->getSourceRange();
18495 return ExprError();
18498 /// Rebuild an expression which simply semantically wraps another
18499 /// expression which it shares the type and value kind of.
18500 template <class T> ExprResult rebuildSugarExpr(T *E) {
18501 ExprResult SubResult = Visit(E->getSubExpr());
18502 if (SubResult.isInvalid()) return ExprError();
18504 Expr *SubExpr = SubResult.get();
18505 E->setSubExpr(SubExpr);
18506 E->setType(SubExpr->getType());
18507 E->setValueKind(SubExpr->getValueKind());
18508 assert(E->getObjectKind() == OK_Ordinary);
18512 ExprResult VisitParenExpr(ParenExpr *E) {
18513 return rebuildSugarExpr(E);
18516 ExprResult VisitUnaryExtension(UnaryOperator *E) {
18517 return rebuildSugarExpr(E);
18520 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18521 ExprResult SubResult = Visit(E->getSubExpr());
18522 if (SubResult.isInvalid()) return ExprError();
18524 Expr *SubExpr = SubResult.get();
18525 E->setSubExpr(SubExpr);
18526 E->setType(S.Context.getPointerType(SubExpr->getType()));
18527 assert(E->getValueKind() == VK_RValue);
18528 assert(E->getObjectKind() == OK_Ordinary);
18532 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18533 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18535 E->setType(VD->getType());
18537 assert(E->getValueKind() == VK_RValue);
18538 if (S.getLangOpts().CPlusPlus &&
18539 !(isa<CXXMethodDecl>(VD) &&
18540 cast<CXXMethodDecl>(VD)->isInstance()))
18541 E->setValueKind(VK_LValue);
18546 ExprResult VisitMemberExpr(MemberExpr *E) {
18547 return resolveDecl(E, E->getMemberDecl());
18550 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18551 return resolveDecl(E, E->getDecl());
18556 /// Given a function expression of unknown-any type, try to rebuild it
18557 /// to have a function type.
18558 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18559 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18560 if (Result.isInvalid()) return ExprError();
18561 return S.DefaultFunctionArrayConversion(Result.get());
18565 /// A visitor for rebuilding an expression of type __unknown_anytype
18566 /// into one which resolves the type directly on the referring
18567 /// expression. Strict preservation of the original source
18568 /// structure is not a goal.
18569 struct RebuildUnknownAnyExpr
18570 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18574 /// The current destination type.
18577 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18578 : S(S), DestType(CastType) {}
18580 ExprResult VisitStmt(Stmt *S) {
18581 llvm_unreachable("unexpected statement!");
18584 ExprResult VisitExpr(Expr *E) {
18585 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18586 << E->getSourceRange();
18587 return ExprError();
18590 ExprResult VisitCallExpr(CallExpr *E);
18591 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18593 /// Rebuild an expression which simply semantically wraps another
18594 /// expression which it shares the type and value kind of.
18595 template <class T> ExprResult rebuildSugarExpr(T *E) {
18596 ExprResult SubResult = Visit(E->getSubExpr());
18597 if (SubResult.isInvalid()) return ExprError();
18598 Expr *SubExpr = SubResult.get();
18599 E->setSubExpr(SubExpr);
18600 E->setType(SubExpr->getType());
18601 E->setValueKind(SubExpr->getValueKind());
18602 assert(E->getObjectKind() == OK_Ordinary);
18606 ExprResult VisitParenExpr(ParenExpr *E) {
18607 return rebuildSugarExpr(E);
18610 ExprResult VisitUnaryExtension(UnaryOperator *E) {
18611 return rebuildSugarExpr(E);
18614 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18615 const PointerType *Ptr = DestType->getAs<PointerType>();
18617 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18618 << E->getSourceRange();
18619 return ExprError();
18622 if (isa<CallExpr>(E->getSubExpr())) {
18623 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18624 << E->getSourceRange();
18625 return ExprError();
18628 assert(E->getValueKind() == VK_RValue);
18629 assert(E->getObjectKind() == OK_Ordinary);
18630 E->setType(DestType);
18632 // Build the sub-expression as if it were an object of the pointee type.
18633 DestType = Ptr->getPointeeType();
18634 ExprResult SubResult = Visit(E->getSubExpr());
18635 if (SubResult.isInvalid()) return ExprError();
18636 E->setSubExpr(SubResult.get());
18640 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18642 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18644 ExprResult VisitMemberExpr(MemberExpr *E) {
18645 return resolveDecl(E, E->getMemberDecl());
18648 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18649 return resolveDecl(E, E->getDecl());
18654 /// Rebuilds a call expression which yielded __unknown_anytype.
18655 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18656 Expr *CalleeExpr = E->getCallee();
18660 FK_FunctionPointer,
18665 QualType CalleeType = CalleeExpr->getType();
18666 if (CalleeType == S.Context.BoundMemberTy) {
18667 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18668 Kind = FK_MemberFunction;
18669 CalleeType = Expr::findBoundMemberType(CalleeExpr);
18670 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18671 CalleeType = Ptr->getPointeeType();
18672 Kind = FK_FunctionPointer;
18674 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18675 Kind = FK_BlockPointer;
18677 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18679 // Verify that this is a legal result type of a function.
18680 if (DestType->isArrayType() || DestType->isFunctionType()) {
18681 unsigned diagID = diag::err_func_returning_array_function;
18682 if (Kind == FK_BlockPointer)
18683 diagID = diag::err_block_returning_array_function;
18685 S.Diag(E->getExprLoc(), diagID)
18686 << DestType->isFunctionType() << DestType;
18687 return ExprError();
18690 // Otherwise, go ahead and set DestType as the call's result.
18691 E->setType(DestType.getNonLValueExprType(S.Context));
18692 E->setValueKind(Expr::getValueKindForType(DestType));
18693 assert(E->getObjectKind() == OK_Ordinary);
18695 // Rebuild the function type, replacing the result type with DestType.
18696 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18698 // __unknown_anytype(...) is a special case used by the debugger when
18699 // it has no idea what a function's signature is.
18701 // We want to build this call essentially under the K&R
18702 // unprototyped rules, but making a FunctionNoProtoType in C++
18703 // would foul up all sorts of assumptions. However, we cannot
18704 // simply pass all arguments as variadic arguments, nor can we
18705 // portably just call the function under a non-variadic type; see
18706 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18707 // However, it turns out that in practice it is generally safe to
18708 // call a function declared as "A foo(B,C,D);" under the prototype
18709 // "A foo(B,C,D,...);". The only known exception is with the
18710 // Windows ABI, where any variadic function is implicitly cdecl
18711 // regardless of its normal CC. Therefore we change the parameter
18712 // types to match the types of the arguments.
18714 // This is a hack, but it is far superior to moving the
18715 // corresponding target-specific code from IR-gen to Sema/AST.
18717 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18718 SmallVector<QualType, 8> ArgTypes;
18719 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18720 ArgTypes.reserve(E->getNumArgs());
18721 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18722 Expr *Arg = E->getArg(i);
18723 QualType ArgType = Arg->getType();
18724 if (E->isLValue()) {
18725 ArgType = S.Context.getLValueReferenceType(ArgType);
18726 } else if (E->isXValue()) {
18727 ArgType = S.Context.getRValueReferenceType(ArgType);
18729 ArgTypes.push_back(ArgType);
18731 ParamTypes = ArgTypes;
18733 DestType = S.Context.getFunctionType(DestType, ParamTypes,
18734 Proto->getExtProtoInfo());
18736 DestType = S.Context.getFunctionNoProtoType(DestType,
18737 FnType->getExtInfo());
18740 // Rebuild the appropriate pointer-to-function type.
18742 case FK_MemberFunction:
18746 case FK_FunctionPointer:
18747 DestType = S.Context.getPointerType(DestType);
18750 case FK_BlockPointer:
18751 DestType = S.Context.getBlockPointerType(DestType);
18755 // Finally, we can recurse.
18756 ExprResult CalleeResult = Visit(CalleeExpr);
18757 if (!CalleeResult.isUsable()) return ExprError();
18758 E->setCallee(CalleeResult.get());
18760 // Bind a temporary if necessary.
18761 return S.MaybeBindToTemporary(E);
18764 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18765 // Verify that this is a legal result type of a call.
18766 if (DestType->isArrayType() || DestType->isFunctionType()) {
18767 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18768 << DestType->isFunctionType() << DestType;
18769 return ExprError();
18772 // Rewrite the method result type if available.
18773 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
18774 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
18775 Method->setReturnType(DestType);
18778 // Change the type of the message.
18779 E->setType(DestType.getNonReferenceType());
18780 E->setValueKind(Expr::getValueKindForType(DestType));
18782 return S.MaybeBindToTemporary(E);
18785 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18786 // The only case we should ever see here is a function-to-pointer decay.
18787 if (E->getCastKind() == CK_FunctionToPointerDecay) {
18788 assert(E->getValueKind() == VK_RValue);
18789 assert(E->getObjectKind() == OK_Ordinary);
18791 E->setType(DestType);
18793 // Rebuild the sub-expression as the pointee (function) type.
18794 DestType = DestType->castAs<PointerType>()->getPointeeType();
18796 ExprResult Result = Visit(E->getSubExpr());
18797 if (!Result.isUsable()) return ExprError();
18799 E->setSubExpr(Result.get());
18801 } else if (E->getCastKind() == CK_LValueToRValue) {
18802 assert(E->getValueKind() == VK_RValue);
18803 assert(E->getObjectKind() == OK_Ordinary);
18805 assert(isa<BlockPointerType>(E->getType()));
18807 E->setType(DestType);
18809 // The sub-expression has to be a lvalue reference, so rebuild it as such.
18810 DestType = S.Context.getLValueReferenceType(DestType);
18812 ExprResult Result = Visit(E->getSubExpr());
18813 if (!Result.isUsable()) return ExprError();
18815 E->setSubExpr(Result.get());
18818 llvm_unreachable("Unhandled cast type!");
18822 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18823 ExprValueKind ValueKind = VK_LValue;
18824 QualType Type = DestType;
18826 // We know how to make this work for certain kinds of decls:
18829 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18830 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18831 DestType = Ptr->getPointeeType();
18832 ExprResult Result = resolveDecl(E, VD);
18833 if (Result.isInvalid()) return ExprError();
18834 return S.ImpCastExprToType(Result.get(), Type,
18835 CK_FunctionToPointerDecay, VK_RValue);
18838 if (!Type->isFunctionType()) {
18839 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18840 << VD << E->getSourceRange();
18841 return ExprError();
18843 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18844 // We must match the FunctionDecl's type to the hack introduced in
18845 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18846 // type. See the lengthy commentary in that routine.
18847 QualType FDT = FD->getType();
18848 const FunctionType *FnType = FDT->castAs<FunctionType>();
18849 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18850 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18851 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18852 SourceLocation Loc = FD->getLocation();
18853 FunctionDecl *NewFD = FunctionDecl::Create(
18854 S.Context, FD->getDeclContext(), Loc, Loc,
18855 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18856 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18857 /*ConstexprKind*/ CSK_unspecified);
18859 if (FD->getQualifier())
18860 NewFD->setQualifierInfo(FD->getQualifierLoc());
18862 SmallVector<ParmVarDecl*, 16> Params;
18863 for (const auto &AI : FT->param_types()) {
18864 ParmVarDecl *Param =
18865 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18866 Param->setScopeInfo(0, Params.size());
18867 Params.push_back(Param);
18869 NewFD->setParams(Params);
18870 DRE->setDecl(NewFD);
18871 VD = DRE->getDecl();
18875 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18876 if (MD->isInstance()) {
18877 ValueKind = VK_RValue;
18878 Type = S.Context.BoundMemberTy;
18881 // Function references aren't l-values in C.
18882 if (!S.getLangOpts().CPlusPlus)
18883 ValueKind = VK_RValue;
18886 } else if (isa<VarDecl>(VD)) {
18887 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18888 Type = RefTy->getPointeeType();
18889 } else if (Type->isFunctionType()) {
18890 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18891 << VD << E->getSourceRange();
18892 return ExprError();
18897 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18898 << VD << E->getSourceRange();
18899 return ExprError();
18902 // Modifying the declaration like this is friendly to IR-gen but
18903 // also really dangerous.
18904 VD->setType(DestType);
18906 E->setValueKind(ValueKind);
18910 /// Check a cast of an unknown-any type. We intentionally only
18911 /// trigger this for C-style casts.
18912 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18913 Expr *CastExpr, CastKind &CastKind,
18914 ExprValueKind &VK, CXXCastPath &Path) {
18915 // The type we're casting to must be either void or complete.
18916 if (!CastType->isVoidType() &&
18917 RequireCompleteType(TypeRange.getBegin(), CastType,
18918 diag::err_typecheck_cast_to_incomplete))
18919 return ExprError();
18921 // Rewrite the casted expression from scratch.
18922 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18923 if (!result.isUsable()) return ExprError();
18925 CastExpr = result.get();
18926 VK = CastExpr->getValueKind();
18927 CastKind = CK_NoOp;
18932 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18933 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18936 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18937 Expr *arg, QualType ¶mType) {
18938 // If the syntactic form of the argument is not an explicit cast of
18939 // any sort, just do default argument promotion.
18940 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18942 ExprResult result = DefaultArgumentPromotion(arg);
18943 if (result.isInvalid()) return ExprError();
18944 paramType = result.get()->getType();
18948 // Otherwise, use the type that was written in the explicit cast.
18949 assert(!arg->hasPlaceholderType());
18950 paramType = castArg->getTypeAsWritten();
18952 // Copy-initialize a parameter of that type.
18953 InitializedEntity entity =
18954 InitializedEntity::InitializeParameter(Context, paramType,
18955 /*consumed*/ false);
18956 return PerformCopyInitialization(entity, callLoc, arg);
18959 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18961 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18963 E = E->IgnoreParenImpCasts();
18964 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18965 E = call->getCallee();
18966 diagID = diag::err_uncasted_call_of_unknown_any;
18972 SourceLocation loc;
18974 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18975 loc = ref->getLocation();
18976 d = ref->getDecl();
18977 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18978 loc = mem->getMemberLoc();
18979 d = mem->getMemberDecl();
18980 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18981 diagID = diag::err_uncasted_call_of_unknown_any;
18982 loc = msg->getSelectorStartLoc();
18983 d = msg->getMethodDecl();
18985 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
18986 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
18987 << orig->getSourceRange();
18988 return ExprError();
18991 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18992 << E->getSourceRange();
18993 return ExprError();
18996 S.Diag(loc, diagID) << d << orig->getSourceRange();
18998 // Never recoverable.
18999 return ExprError();
19002 /// Check for operands with placeholder types and complain if found.
19003 /// Returns ExprError() if there was an error and no recovery was possible.
19004 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19005 if (!getLangOpts().CPlusPlus) {
19006 // C cannot handle TypoExpr nodes on either side of a binop because it
19007 // doesn't handle dependent types properly, so make sure any TypoExprs have
19008 // been dealt with before checking the operands.
19009 ExprResult Result = CorrectDelayedTyposInExpr(E);
19010 if (!Result.isUsable()) return ExprError();
19014 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19015 if (!placeholderType) return E;
19017 switch (placeholderType->getKind()) {
19019 // Overloaded expressions.
19020 case BuiltinType::Overload: {
19021 // Try to resolve a single function template specialization.
19022 // This is obligatory.
19023 ExprResult Result = E;
19024 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19027 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19028 // leaves Result unchanged on failure.
19030 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19033 // If that failed, try to recover with a call.
19034 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19035 /*complain*/ true);
19039 // Bound member functions.
19040 case BuiltinType::BoundMember: {
19041 ExprResult result = E;
19042 const Expr *BME = E->IgnoreParens();
19043 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19044 // Try to give a nicer diagnostic if it is a bound member that we recognize.
19045 if (isa<CXXPseudoDestructorExpr>(BME)) {
19046 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19047 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19048 if (ME->getMemberNameInfo().getName().getNameKind() ==
19049 DeclarationName::CXXDestructorName)
19050 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19052 tryToRecoverWithCall(result, PD,
19053 /*complain*/ true);
19057 // ARC unbridged casts.
19058 case BuiltinType::ARCUnbridgedCast: {
19059 Expr *realCast = stripARCUnbridgedCast(E);
19060 diagnoseARCUnbridgedCast(realCast);
19064 // Expressions of unknown type.
19065 case BuiltinType::UnknownAny:
19066 return diagnoseUnknownAnyExpr(*this, E);
19069 case BuiltinType::PseudoObject:
19070 return checkPseudoObjectRValue(E);
19072 case BuiltinType::BuiltinFn: {
19073 // Accept __noop without parens by implicitly converting it to a call expr.
19074 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19076 auto *FD = cast<FunctionDecl>(DRE->getDecl());
19077 if (FD->getBuiltinID() == Builtin::BI__noop) {
19078 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19079 CK_BuiltinFnToFnPtr)
19081 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19082 VK_RValue, SourceLocation());
19086 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19087 return ExprError();
19090 case BuiltinType::IncompleteMatrixIdx:
19091 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19094 diag::err_matrix_incomplete_index);
19095 return ExprError();
19097 // Expressions of unknown type.
19098 case BuiltinType::OMPArraySection:
19099 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19100 return ExprError();
19102 // Expressions of unknown type.
19103 case BuiltinType::OMPArrayShaping:
19104 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19106 case BuiltinType::OMPIterator:
19107 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19109 // Everything else should be impossible.
19110 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19111 case BuiltinType::Id:
19112 #include "clang/Basic/OpenCLImageTypes.def"
19113 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19114 case BuiltinType::Id:
19115 #include "clang/Basic/OpenCLExtensionTypes.def"
19116 #define SVE_TYPE(Name, Id, SingletonId) \
19117 case BuiltinType::Id:
19118 #include "clang/Basic/AArch64SVEACLETypes.def"
19119 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19120 #define PLACEHOLDER_TYPE(Id, SingletonId)
19121 #include "clang/AST/BuiltinTypes.def"
19125 llvm_unreachable("invalid placeholder type!");
19128 bool Sema::CheckCaseExpression(Expr *E) {
19129 if (E->isTypeDependent())
19131 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19132 return E->getType()->isIntegralOrEnumerationType();
19136 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19138 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19139 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19140 "Unknown Objective-C Boolean value!");
19141 QualType BoolT = Context.ObjCBuiltinBoolTy;
19142 if (!Context.getBOOLDecl()) {
19143 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19144 Sema::LookupOrdinaryName);
19145 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19146 NamedDecl *ND = Result.getFoundDecl();
19147 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19148 Context.setBOOLDecl(TD);
19151 if (Context.getBOOLDecl())
19152 BoolT = Context.getBOOLType();
19153 return new (Context)
19154 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19157 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19158 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19159 SourceLocation RParen) {
19161 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19163 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19164 return Spec.getPlatform() == Platform;
19167 VersionTuple Version;
19168 if (Spec != AvailSpecs.end())
19169 Version = Spec->getVersion();
19171 // The use of `@available` in the enclosing function should be analyzed to
19172 // warn when it's used inappropriately (i.e. not if(@available)).
19173 if (getCurFunctionOrMethodDecl())
19174 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19175 else if (getCurBlock() || getCurLambda())
19176 getCurFunction()->HasPotentialAvailabilityViolations = true;
19178 return new (Context)
19179 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19182 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19183 ArrayRef<Expr *> SubExprs, QualType T) {
19184 if (!Context.getLangOpts().RecoveryAST)
19185 return ExprError();
19187 if (isSFINAEContext())
19188 return ExprError();
19190 if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19191 // We don't know the concrete type, fallback to dependent type.
19192 T = Context.DependentTy;
19193 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);