clang 24.0.0git
SemaExpr.cpp
Go to the documentation of this file.
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
19#include "clang/AST/ASTLambda.h"
21#include "clang/AST/Attr.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ExprObjC.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
46#include "clang/Sema/DeclSpec.h"
51#include "clang/Sema/Lookup.h"
52#include "clang/Sema/Overload.h"
54#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaARM.h"
58#include "clang/Sema/SemaCUDA.h"
60#include "clang/Sema/SemaHLSL.h"
62#include "clang/Sema/SemaObjC.h"
67#include "clang/Sema/Template.h"
68#include "llvm/ADT/STLExtras.h"
69#include "llvm/ADT/StringExtras.h"
70#include "llvm/IR/DerivedTypes.h"
71#include "llvm/Support/ConvertUTF.h"
72#include "llvm/Support/SaveAndRestore.h"
73#include "llvm/Support/TimeProfiler.h"
74#include "llvm/Support/TypeSize.h"
75#include <limits>
76#include <optional>
77
78using namespace clang;
79using namespace sema;
80
81bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
82 // See if this is an auto-typed variable whose initializer we are parsing.
83 if (ParsingInitForAutoVars.count(D))
84 return false;
85
86 // See if this is a deleted function.
87 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
88 if (FD->isDeleted())
89 return false;
90
91 // If the function has a deduced return type, and we can't deduce it,
92 // then we can't use it either.
93 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
94 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
95 return false;
96
97 // See if this is an aligned allocation/deallocation function that is
98 // unavailable.
99 if (TreatUnavailableAsInvalid &&
101 return false;
102 }
103
104 // See if this function is unavailable.
105 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
106 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
107 return false;
108
110 return false;
111
112 return true;
113}
114
116 // Warn if this is used but marked unused.
117 if (const auto *A = D->getAttr<UnusedAttr>()) {
118 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
119 // should diagnose them.
120 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
121 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
122 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
123 if (DC && !DC->hasAttr<UnusedAttr>())
124 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
125 }
126 }
127}
128
130 assert(Decl && Decl->isDeleted());
131
132 if (Decl->isDefaulted()) {
133 // If the method was explicitly defaulted, point at that declaration.
134 if (!Decl->isImplicit())
135 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
136
137 // Try to diagnose why this special member function was implicitly
138 // deleted. This might fail, if that reason no longer applies.
140 return;
141 }
142
143 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
144 if (Ctor && Ctor->isInheritingConstructor())
146
147 Diag(Decl->getLocation(), diag::note_availability_specified_here)
148 << Decl << 1;
149}
150
151/// Determine whether a FunctionDecl was ever declared with an
152/// explicit storage class.
154 for (auto *I : D->redecls()) {
155 if (I->getStorageClass() != SC_None)
156 return true;
157 }
158 return false;
159}
160
161/// Check whether we're in an extern inline function and referring to a
162/// variable or function with internal linkage (C11 6.7.4p3).
163///
164/// This is only a warning because we used to silently accept this code, but
165/// in many cases it will not behave correctly. This is not enabled in C++ mode
166/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
167/// and so while there may still be user mistakes, most of the time we can't
168/// prove that there are errors.
170 const NamedDecl *D,
171 SourceLocation Loc) {
172 // This is disabled under C++; there are too many ways for this to fire in
173 // contexts where the warning is a false positive, or where it is technically
174 // correct but benign.
175 //
176 // WG14 N3622 which removed the constraint entirely in C2y. It is left
177 // enabled in earlier language modes because this is a constraint in those
178 // language modes. But in C2y mode, we still want to issue the "incompatible
179 // with previous standards" diagnostic, too.
180 if (S.getLangOpts().CPlusPlus)
181 return;
182
183 // Check if this is an inlined function or method.
184 FunctionDecl *Current = S.getCurFunctionDecl();
185 if (!Current)
186 return;
187 if (!Current->isInlined())
188 return;
189 if (!Current->isExternallyVisible())
190 return;
191
192 // Check if the decl has internal linkage.
194 return;
195
196 // Downgrade from ExtWarn to Extension if
197 // (1) the supposedly external inline function is in the main file,
198 // and probably won't be included anywhere else.
199 // (2) the thing we're referencing is a pure function.
200 // (3) the thing we're referencing is another inline function.
201 // This last can give us false negatives, but it's better than warning on
202 // wrappers for simple C library functions.
203 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
204 unsigned DiagID;
205 if (S.getLangOpts().C2y)
206 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
207 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
209 DiagID = diag::ext_internal_in_extern_inline_quiet;
210 else
211 DiagID = diag::ext_internal_in_extern_inline;
212
213 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
215 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
216 << D;
217}
218
220 const FunctionDecl *First = Cur->getFirstDecl();
221
222 // Suggest "static" on the function, if possible.
224 SourceLocation DeclBegin = First->getSourceRange().getBegin();
225 Diag(DeclBegin, diag::note_convert_inline_to_static)
226 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
227 }
228}
229
231 const ObjCInterfaceDecl *UnknownObjCClass,
232 bool ObjCPropertyAccess,
233 bool AvoidPartialAvailabilityChecks,
234 ObjCInterfaceDecl *ClassReceiver,
235 bool SkipTrailingRequiresClause) {
236 SourceLocation Loc = Locs.front();
238 // If there were any diagnostics suppressed by template argument deduction,
239 // emit them now.
240 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
241 if (Pos != SuppressedDiagnostics.end()) {
242 for (const auto &[DiagLoc, PD] : Pos->second) {
243 DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID()));
244 PD.Emit(Builder);
245 }
246 // Clear out the list of suppressed diagnostics, so that we don't emit
247 // them again for this specialization. However, we don't obsolete this
248 // entry from the table, because we want to avoid ever emitting these
249 // diagnostics again.
250 Pos->second.clear();
251 }
252
253 // C++ [basic.start.main]p3:
254 // The function 'main' shall not be used within a program.
255 if (cast<FunctionDecl>(D)->isMain())
256 Diag(Loc, diag::ext_main_used);
257
259 }
260
261 // See if this is an auto-typed variable whose initializer we are parsing.
262 if (ParsingInitForAutoVars.count(D)) {
263 if (isa<BindingDecl>(D)) {
264 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
265 << D->getDeclName();
266 } else {
267 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
268 << diag::ParsingInitFor::Var << D->getDeclName()
269 << cast<VarDecl>(D)->getType();
270 }
271 return true;
272 }
273
274 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
275 // See if this is a deleted function.
276 if (FD->isDeleted()) {
277 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
278 if (Ctor && Ctor->isInheritingConstructor())
279 Diag(Loc, diag::err_deleted_inherited_ctor_use)
280 << Ctor->getParent()
281 << Ctor->getInheritedConstructor().getConstructor()->getParent();
282 else {
283 StringLiteral *Msg = FD->getDeletedMessage();
284 Diag(Loc, diag::err_deleted_function_use)
285 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
286 }
288 return true;
289 }
290
291 // [expr.prim.id]p4
292 // A program that refers explicitly or implicitly to a function with a
293 // trailing requires-clause whose constraint-expression is not satisfied,
294 // other than to declare it, is ill-formed. [...]
295 //
296 // See if this is a function with constraints that need to be satisfied.
297 // Check this before deducing the return type, as it might instantiate the
298 // definition.
299 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
300 ConstraintSatisfaction Satisfaction;
301 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
302 /*ForOverloadResolution*/ true))
303 // A diagnostic will have already been generated (non-constant
304 // constraint expression, for example)
305 return true;
306 if (!Satisfaction.IsSatisfied) {
307 Diag(Loc,
308 diag::err_reference_to_function_with_unsatisfied_constraints)
309 << D;
310 DiagnoseUnsatisfiedConstraint(Satisfaction);
311 return true;
312 }
313 }
314
315 // If the function has a deduced return type, and we can't deduce it,
316 // then we can't use it either.
317 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
318 DeduceReturnType(FD, Loc))
319 return true;
320
321 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
322 return true;
323
324 }
325
326 if (auto *Concept = dyn_cast<ConceptDecl>(D);
328 return true;
329
330 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
331 // Lambdas are only default-constructible or assignable in C++2a onwards.
332 if (MD->getParent()->isLambda() &&
334 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
335 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
336 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
338 }
339 }
340
341 auto getReferencedObjCProp = [](const NamedDecl *D) ->
342 const ObjCPropertyDecl * {
343 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
344 return MD->findPropertyDecl();
345 return nullptr;
346 };
347 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
348 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
349 return true;
350 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
351 return true;
352 }
353
354 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
355 // Only the variables omp_in and omp_out are allowed in the combiner.
356 // Only the variables omp_priv and omp_orig are allowed in the
357 // initializer-clause.
358 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
359 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
360 isa<VarDecl>(D)) {
361 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
363 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
364 return true;
365 }
366
367 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
368 // List-items in map clauses on this construct may only refer to the declared
369 // variable var and entities that could be referenced by a procedure defined
370 // at the same location.
371 // [OpenMP 5.2] Also allow iterator declared variables.
372 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
373 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
374 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
376 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
377 return true;
378 }
379
380 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
381 Diag(Loc, diag::err_use_of_empty_using_if_exists);
382 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
383 return true;
384 }
385
386 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
387 AvoidPartialAvailabilityChecks, ClassReceiver);
388
389 DiagnoseUnusedOfDecl(*this, D, Loc);
390
392
393 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
394 if (getLangOpts().getFPEvalMethod() !=
396 PP.getLastFPEvalPragmaLocation().isValid() &&
397 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
398 Diag(D->getLocation(),
399 diag::err_type_available_only_in_default_eval_method)
400 << D->getName();
401 }
402
403 if (auto *VD = dyn_cast<ValueDecl>(D))
404 checkTypeSupport(VD->getType(), Loc, VD);
405
406 if (LangOpts.SYCLIsDevice ||
407 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
408 if (!Context.getTargetInfo().isTLSSupported())
409 if (const auto *VD = dyn_cast<VarDecl>(D))
410 if (VD->getTLSKind() != VarDecl::TLS_None)
411 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
412 }
413
414 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(D))
415 SYCL().CheckDeviceUseOfDecl(D, Loc);
416
417 return false;
418}
419
421 ArrayRef<Expr *> Args) {
422 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
423 if (!Attr)
424 return;
425
426 // The number of formal parameters of the declaration.
427 unsigned NumFormalParams;
428
429 // The kind of declaration. This is also an index into a %select in
430 // the diagnostic.
431 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
432
433 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
434 NumFormalParams = MD->param_size();
435 CalleeKind = CK_Method;
436 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
437 NumFormalParams = FD->param_size();
438 CalleeKind = CK_Function;
439 if (FD->hasCXXExplicitFunctionObjectParameter())
440 NumFormalParams++;
441 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
442 QualType Ty = VD->getType();
443 const FunctionType *Fn = nullptr;
444 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
445 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
446 if (!Fn)
447 return;
448 CalleeKind = CK_Function;
449 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
450 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
451 CalleeKind = CK_Block;
452 } else {
453 return;
454 }
455
456 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
457 NumFormalParams = proto->getNumParams();
458 else
459 NumFormalParams = 0;
460 } else {
461 return;
462 }
463
464 // "NullPos" is the number of formal parameters at the end which
465 // effectively count as part of the variadic arguments. This is
466 // useful if you would prefer to not have *any* formal parameters,
467 // but the language forces you to have at least one.
468 unsigned NullPos = Attr->getNullPos();
469 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
470 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
471
472 // The number of arguments which should follow the sentinel.
473 unsigned NumArgsAfterSentinel = Attr->getSentinel();
474
475 // If there aren't enough arguments for all the formal parameters,
476 // the sentinel, and the args after the sentinel, complain.
477 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
478 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
479 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
480 return;
481 }
482
483 // Otherwise, find the sentinel expression.
484 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
485 if (!SentinelExpr)
486 return;
487 if (SentinelExpr->isValueDependent())
488 return;
489 if (Context.isSentinelNullExpr(SentinelExpr))
490 return;
491
492 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
493 // or 'NULL' if those are actually defined in the context. Only use
494 // 'nil' for ObjC methods, where it's much more likely that the
495 // variadic arguments form a list of object pointers.
496 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
497 std::string NullValue;
498 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
499 NullValue = "nil";
500 else if (getLangOpts().CPlusPlus11)
501 NullValue = "nullptr";
502 else if (PP.isMacroDefined("NULL"))
503 NullValue = "NULL";
504 else
505 NullValue = "(void*) 0";
506
507 if (MissingNilLoc.isInvalid())
508 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
509 else
510 Diag(MissingNilLoc, diag::warn_missing_sentinel)
511 << int(CalleeKind)
512 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
513 Diag(D->getLocation(), diag::note_sentinel_here)
514 << int(CalleeKind) << Attr->getRange();
515}
516
518 return E ? E->getSourceRange() : SourceRange();
519}
520
521//===----------------------------------------------------------------------===//
522// Standard Promotions and Conversions
523//===----------------------------------------------------------------------===//
524
525/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
527 // Handle any placeholder expressions which made it here.
528 if (E->hasPlaceholderType()) {
530 if (result.isInvalid()) return ExprError();
531 E = result.get();
532 }
533
534 QualType Ty = E->getType();
535 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
536
537 if (Ty->isFunctionType()) {
538 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
539 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
541 return ExprError();
542
543 E = ImpCastExprToType(E, Context.getPointerType(Ty),
544 CK_FunctionToPointerDecay).get();
545 } else if (Ty->isArrayType()) {
546 // In C90 mode, arrays only promote to pointers if the array expression is
547 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
548 // type 'array of type' is converted to an expression that has type 'pointer
549 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
550 // that has type 'array of type' ...". The relevant change is "an lvalue"
551 // (C90) to "an expression" (C99).
552 //
553 // C++ 4.2p1:
554 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
555 // T" can be converted to an rvalue of type "pointer to T".
556 //
557 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
558 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
559 CK_ArrayToPointerDecay);
560 if (Res.isInvalid())
561 return ExprError();
562 E = Res.get();
563 }
564 }
565 return E;
566}
567
569 // Check to see if we are dereferencing a null pointer. If so,
570 // and if not volatile-qualified, this is undefined behavior that the
571 // optimizer will delete, so warn about it. People sometimes try to use this
572 // to get a deterministic trap and are surprised by clang's behavior. This
573 // only handles the pattern "*null", which is a very syntactic check.
574 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
575 if (UO && UO->getOpcode() == UO_Deref &&
576 UO->getSubExpr()->getType()->isPointerType()) {
577 const LangAS AS =
578 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
579 if ((!isTargetAddressSpace(AS) ||
580 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
581 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
583 !UO->getType().isVolatileQualified()) {
584 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
585 S.PDiag(diag::warn_indirection_through_null)
586 << UO->getSubExpr()->getSourceRange());
587 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
588 S.PDiag(diag::note_indirection_through_null));
589 }
590 }
591}
592
593static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
594 SourceLocation AssignLoc,
595 const Expr* RHS) {
596 const ObjCIvarDecl *IV = OIRE->getDecl();
597 if (!IV)
598 return;
599
600 DeclarationName MemberName = IV->getDeclName();
602 if (!Member || !Member->isStr("isa"))
603 return;
604
605 const Expr *Base = OIRE->getBase();
606 QualType BaseType = Base->getType();
607 if (OIRE->isArrow())
608 BaseType = BaseType->getPointeeType();
609 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
610 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
611 ObjCInterfaceDecl *ClassDeclared = nullptr;
612 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
613 if (!ClassDeclared->getSuperClass()
614 && (*ClassDeclared->ivar_begin()) == IV) {
615 if (RHS) {
616 NamedDecl *ObjectSetClass =
618 &S.Context.Idents.get("object_setClass"),
620 if (ObjectSetClass) {
621 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
622 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
624 "object_setClass(")
626 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
627 << FixItHint::CreateInsertion(RHSLocEnd, ")");
628 }
629 else
630 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
631 } else {
632 NamedDecl *ObjectGetClass =
634 &S.Context.Idents.get("object_getClass"),
636 if (ObjectGetClass)
637 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
639 "object_getClass(")
641 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
642 else
643 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
644 }
645 S.Diag(IV->getLocation(), diag::note_ivar_decl);
646 }
647 }
648}
649
651 // Handle any placeholder expressions which made it here.
652 if (E->hasPlaceholderType()) {
654 if (result.isInvalid()) return ExprError();
655 E = result.get();
656 }
657
658 // C++ [conv.lval]p1:
659 // A glvalue of a non-function, non-array type T can be
660 // converted to a prvalue.
661 if (!E->isGLValue()) return E;
662
663 QualType T = E->getType();
664 assert(!T.isNull() && "r-value conversion on typeless expression?");
665
666 // lvalue-to-rvalue conversion cannot be applied to types that decay to
667 // pointers (i.e. function or array types).
668 if (T->canDecayToPointerType())
669 return E;
670
671 // We don't want to throw lvalue-to-rvalue casts on top of
672 // expressions of certain types in C++.
673 // In HLSL LvaluetoRvalue conversion is allowed on records.
674 if (getLangOpts().CPlusPlus) {
675 if (T == Context.OverloadTy || (T->isRecordType() && !getLangOpts().HLSL) ||
676 (T->isDependentType() && !T->isAnyPointerType() &&
677 !T->isMemberPointerType()))
678 return E;
679 }
680
681 // The C standard is actually really unclear on this point, and
682 // DR106 tells us what the result should be but not why. It's
683 // generally best to say that void types just doesn't undergo
684 // lvalue-to-rvalue at all. Note that expressions of unqualified
685 // 'void' type are never l-values, but qualified void can be.
686 if (T->isVoidType())
687 return E;
688
689 // OpenCL usually rejects direct accesses to values of 'half' type.
690 if (getLangOpts().OpenCL &&
691 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
692 T->isHalfType()) {
693 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
694 << 0 << T;
695 return ExprError();
696 }
697
699 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
700 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
701 &Context.Idents.get("object_getClass"),
703 if (ObjectGetClass)
704 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
705 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
707 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
708 else
709 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
710 }
711 else if (const ObjCIvarRefExpr *OIRE =
712 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
713 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
714
715 // C++ [conv.lval]p1:
716 // [...] If T is a non-class type, the type of the prvalue is the
717 // cv-unqualified version of T. Otherwise, the type of the
718 // rvalue is T.
719 //
720 // C99 6.3.2.1p2:
721 // If the lvalue has qualified type, the value has the unqualified
722 // version of the type of the lvalue; otherwise, the value has the
723 // type of the lvalue.
724 if (T.hasQualifiers())
725 T = T.getUnqualifiedType();
726
727 if (getLangOpts().HLSL)
728 if (const auto *MT = T->getAs<ConstantMatrixType>(); MT && MT->getLayout())
729 T = Context.getCanonicalType(T);
730
731 // Under the MS ABI, lock down the inheritance model now.
732 if (T->isMemberPointerType() &&
733 Context.getTargetInfo().getCXXABI().isMicrosoft())
734 (void)isCompleteType(E->getExprLoc(), T);
735
737 if (Res.isInvalid())
738 return Res;
739 E = Res.get();
740
741 // Loading a __weak object implicitly retains the value, so we need a cleanup to
742 // balance that.
744 Cleanup.setExprNeedsCleanups(true);
745
747 Cleanup.setExprNeedsCleanups(true);
748
750 return ExprError();
751
752 // C++ [conv.lval]p3:
753 // If T is cv std::nullptr_t, the result is a null pointer constant.
754 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
755 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
757
758 // C11 6.3.2.1p2:
759 // ... if the lvalue has atomic type, the value has the non-atomic version
760 // of the type of the lvalue ...
761 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
762 T = Atomic->getValueType().getUnqualifiedType();
763 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
764 nullptr, VK_PRValue, FPOptionsOverride());
765 }
766
767 return Res;
768}
769
772 if (Res.isInvalid())
773 return ExprError();
774 Res = DefaultLvalueConversion(Res.get());
775 if (Res.isInvalid())
776 return ExprError();
777 return Res;
778}
779
781 QualType Ty = E->getType();
782 ExprResult Res = E;
783 // Only do implicit cast for a function type, but not for a pointer
784 // to function type.
785 if (Ty->isFunctionType()) {
786 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
787 CK_FunctionToPointerDecay);
788 if (Res.isInvalid())
789 return ExprError();
790 }
791 Res = DefaultLvalueConversion(Res.get());
792 if (Res.isInvalid())
793 return ExprError();
794 return Res.get();
795}
796
797/// UsualUnaryFPConversions - Promotes floating-point types according to the
798/// current language semantics.
800 QualType Ty = E->getType();
801 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
802
803 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
804 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
805 (getLangOpts().getFPEvalMethod() !=
807 PP.getLastFPEvalPragmaLocation().isValid())) {
808 switch (EvalMethod) {
809 default:
810 llvm_unreachable("Unrecognized float evaluation method");
811 break;
813 llvm_unreachable("Float evaluation method should be set by now");
814 break;
816 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
817 // Widen the expression to double.
818 return Ty->isComplexType()
820 Context.getComplexType(Context.DoubleTy),
821 CK_FloatingComplexCast)
822 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
823 break;
825 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
826 // Widen the expression to long double.
827 return Ty->isComplexType()
829 E, Context.getComplexType(Context.LongDoubleTy),
830 CK_FloatingComplexCast)
831 : ImpCastExprToType(E, Context.LongDoubleTy,
832 CK_FloatingCast);
833 break;
834 }
835 }
836
837 // Half FP have to be promoted to float unless it is natively supported
838 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
839 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
840
841 return E;
842}
843
844/// UsualUnaryConversions - Performs various conversions that are common to most
845/// operators (C99 6.3). The conversions of array and function types are
846/// sometimes suppressed. For example, the array->pointer conversion doesn't
847/// apply if the array is an argument to the sizeof or address (&) operators.
848/// In these instances, this routine should *not* be called.
850 // First, convert to an r-value.
852 if (Res.isInvalid())
853 return ExprError();
854
855 // Promote floating-point types.
856 Res = UsualUnaryFPConversions(Res.get());
857 if (Res.isInvalid())
858 return ExprError();
859 E = Res.get();
860
861 QualType Ty = E->getType();
862 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
863
864 // Try to perform integral promotions if the object has a theoretically
865 // promotable type.
867 // C99 6.3.1.1p2:
868 //
869 // The following may be used in an expression wherever an int or
870 // unsigned int may be used:
871 // - an object or expression with an integer type whose integer
872 // conversion rank is less than or equal to the rank of int
873 // and unsigned int.
874 // - A bit-field of type _Bool, int, signed int, or unsigned int.
875 //
876 // If an int can represent all values of the original type, the
877 // value is converted to an int; otherwise, it is converted to an
878 // unsigned int. These are called the integer promotions. All
879 // other types are unchanged by the integer promotions.
880
881 QualType PTy = Context.isPromotableBitField(E);
882 if (!PTy.isNull()) {
883 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
884 return E;
885 }
886 if (Context.isPromotableIntegerType(Ty)) {
887 QualType PT = Context.getPromotedIntegerType(Ty);
888 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
889 return E;
890 }
891 }
892 return E;
893}
894
895/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
896/// do not have a prototype. Arguments that have type float or __fp16
897/// are promoted to double. All other argument types are converted by
898/// UsualUnaryConversions().
900 QualType Ty = E->getType();
901 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
902
904 if (Res.isInvalid())
905 return ExprError();
906 E = Res.get();
907
908 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
909 // promote to double.
910 // Note that default argument promotion applies only to float (and
911 // half/fp16); it does not apply to _Float16.
912 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
913 if (BTy && (BTy->getKind() == BuiltinType::Half ||
914 BTy->getKind() == BuiltinType::Float)) {
915 if (getLangOpts().OpenCL &&
916 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
917 if (BTy->getKind() == BuiltinType::Half) {
918 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
919 }
920 } else {
921 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
922 }
923 }
924 if (BTy &&
925 getLangOpts().getExtendIntArgs() ==
927 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
928 Context.getTypeSizeInChars(BTy) <
929 Context.getTypeSizeInChars(Context.LongLongTy)) {
930 E = (Ty->isUnsignedIntegerType())
931 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
932 .get()
933 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
934 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
935 "Unexpected typesize for LongLongTy");
936 }
937
938 // C++ performs lvalue-to-rvalue conversion as a default argument
939 // promotion, even on class types, but note:
940 // C++11 [conv.lval]p2:
941 // When an lvalue-to-rvalue conversion occurs in an unevaluated
942 // operand or a subexpression thereof the value contained in the
943 // referenced object is not accessed. Otherwise, if the glvalue
944 // has a class type, the conversion copy-initializes a temporary
945 // of type T from the glvalue and the result of the conversion
946 // is a prvalue for the temporary.
947 // FIXME: add some way to gate this entire thing for correctness in
948 // potentially potentially evaluated contexts.
952 E->getExprLoc(), E);
953 if (Temp.isInvalid())
954 return ExprError();
955 E = Temp.get();
956 }
957
958 // C++ [expr.call]p7, per CWG722:
959 // An argument that has (possibly cv-qualified) type std::nullptr_t is
960 // converted to void* ([conv.ptr]).
961 // (This does not apply to C23 nullptr)
963 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
964
965 return E;
966}
967
969 if (Ty->isIncompleteType()) {
970 // C++11 [expr.call]p7:
971 // After these conversions, if the argument does not have arithmetic,
972 // enumeration, pointer, pointer to member, or class type, the program
973 // is ill-formed.
974 //
975 // Since we've already performed null pointer conversion, array-to-pointer
976 // decay and function-to-pointer decay, the only such type in C++ is cv
977 // void. This also handles initializer lists as variadic arguments.
978 if (Ty->isVoidType())
979 return VarArgKind::Invalid;
980
981 if (Ty->isObjCObjectType())
982 return VarArgKind::Invalid;
983 return VarArgKind::Valid;
984 }
985
987 return VarArgKind::Invalid;
988
989 if (Context.getTargetInfo().getTriple().isWasm() &&
991 return VarArgKind::Invalid;
992 }
993
994 if (Ty.isCXX98PODType(Context))
995 return VarArgKind::Valid;
996
997 // C++11 [expr.call]p7:
998 // Passing a potentially-evaluated argument of class type (Clause 9)
999 // having a non-trivial copy constructor, a non-trivial move constructor,
1000 // or a non-trivial destructor, with no corresponding parameter,
1001 // is conditionally-supported with implementation-defined semantics.
1002 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
1004 if (!Record->hasNonTrivialCopyConstructor() &&
1005 !Record->hasNonTrivialMoveConstructor() &&
1006 !Record->hasNonTrivialDestructor())
1008
1009 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1010 return VarArgKind::Valid;
1011
1012 if (Ty->isObjCObjectType())
1013 return VarArgKind::Invalid;
1014
1015 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1016 return VarArgKind::Valid;
1017
1018 if (getLangOpts().MSVCCompat)
1020
1021 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1022 return VarArgKind::Valid;
1023
1024 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1025 // permitted to reject them. We should consider doing so.
1026 return VarArgKind::Undefined;
1027}
1028
1030 // Don't allow one to pass an Objective-C interface to a vararg.
1031 const QualType &Ty = E->getType();
1032 VarArgKind VAK = isValidVarArgType(Ty);
1033
1034 // Complain about passing non-POD types through varargs.
1035 switch (VAK) {
1038 E->getBeginLoc(), nullptr,
1039 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1040 [[fallthrough]];
1041 case VarArgKind::Valid:
1042 if (Ty->isRecordType()) {
1043 // This is unlikely to be what the user intended. If the class has a
1044 // 'c_str' member function, the user probably meant to call that.
1045 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1046 PDiag(diag::warn_pass_class_arg_to_vararg)
1047 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1048 }
1049 break;
1050
1053 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1054 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1055 << getLangOpts().CPlusPlus11 << Ty << CT);
1056 break;
1057
1060 Diag(E->getBeginLoc(),
1061 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1062 << Ty << CT;
1063 else if (Ty->isObjCObjectType())
1064 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1065 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1066 << Ty << CT);
1067 else
1068 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1069 << isa<InitListExpr>(E) << Ty << CT;
1070 break;
1071 }
1072}
1073
1075 FunctionDecl *FDecl) {
1076 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1077 // Strip the unbridged-cast placeholder expression off, if applicable.
1078 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1079 (CT == VariadicCallType::Method ||
1080 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1081 E = ObjC().stripARCUnbridgedCast(E);
1082
1083 // Otherwise, do normal placeholder checking.
1084 } else {
1085 ExprResult ExprRes = CheckPlaceholderExpr(E);
1086 if (ExprRes.isInvalid())
1087 return ExprError();
1088 E = ExprRes.get();
1089 }
1090 }
1091
1093 if (ExprRes.isInvalid())
1094 return ExprError();
1095
1096 // Copy blocks to the heap.
1097 if (ExprRes.get()->getType()->isBlockPointerType())
1098 maybeExtendBlockObject(ExprRes);
1099
1100 E = ExprRes.get();
1101
1102 // Diagnostics regarding non-POD argument types are
1103 // emitted along with format string checking in Sema::CheckFunctionCall().
1105 // Turn this into a trap.
1106 CXXScopeSpec SS;
1107 SourceLocation TemplateKWLoc;
1108 UnqualifiedId Name;
1109 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1110 E->getBeginLoc());
1111 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1112 /*HasTrailingLParen=*/true,
1113 /*IsAddressOfOperand=*/false);
1114 if (TrapFn.isInvalid())
1115 return ExprError();
1116
1117 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1118 E->getEndLoc());
1119 if (Call.isInvalid())
1120 return ExprError();
1121
1122 ExprResult Comma =
1123 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1124 if (Comma.isInvalid())
1125 return ExprError();
1126 return Comma.get();
1127 }
1128
1129 if (!getLangOpts().CPlusPlus &&
1131 diag::err_call_incomplete_argument))
1132 return ExprError();
1133
1134 return E;
1135}
1136
1137/// Convert complex integers to complex floats and real integers to
1138/// real floats as required for complex arithmetic. Helper function of
1139/// UsualArithmeticConversions()
1140///
1141/// \return false if the integer expression is an integer type and is
1142/// successfully converted to the (complex) float type.
1144 ExprResult &ComplexExpr,
1145 QualType IntTy,
1146 QualType ComplexTy,
1147 bool SkipCast) {
1148 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1149 if (SkipCast) return false;
1150 if (IntTy->isIntegerType()) {
1151 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1152 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1153 } else {
1154 assert(IntTy->isComplexIntegerType());
1155 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1156 CK_IntegralComplexToFloatingComplex);
1157 }
1158 return false;
1159}
1160
1161// This handles complex/complex, complex/float, or float/complex.
1162// When both operands are complex, the shorter operand is converted to the
1163// type of the longer, and that is the type of the result. This corresponds
1164// to what is done when combining two real floating-point operands.
1165// The fun begins when size promotion occur across type domains.
1166// From H&S 6.3.4: When one operand is complex and the other is a real
1167// floating-point type, the less precise type is converted, within it's
1168// real or complex domain, to the precision of the other type. For example,
1169// when combining a "long double" with a "double _Complex", the
1170// "double _Complex" is promoted to "long double _Complex".
1172 QualType ShorterType,
1173 QualType LongerType,
1174 bool PromotePrecision) {
1175 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1177 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1178
1179 if (PromotePrecision) {
1180 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1181 Shorter =
1182 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1183 } else {
1184 if (LongerIsComplex)
1185 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1186 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1187 }
1188 }
1189 return Result;
1190}
1191
1192/// Handle arithmetic conversion with complex types. Helper function of
1193/// UsualArithmeticConversions()
1195 ExprResult &RHS, QualType LHSType,
1196 QualType RHSType, bool IsCompAssign) {
1197 // Handle (complex) integer types.
1198 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1199 /*SkipCast=*/false))
1200 return LHSType;
1201 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1202 /*SkipCast=*/IsCompAssign))
1203 return RHSType;
1204
1205 // Compute the rank of the two types, regardless of whether they are complex.
1206 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1207 if (Order < 0)
1208 // Promote the precision of the LHS if not an assignment.
1209 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1210 /*PromotePrecision=*/!IsCompAssign);
1211 // Promote the precision of the RHS unless it is already the same as the LHS.
1212 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1213 /*PromotePrecision=*/Order > 0);
1214}
1215
1216/// Handle arithmetic conversion from integer to float. Helper function
1217/// of UsualArithmeticConversions()
1219 ExprResult &IntExpr,
1220 QualType FloatTy, QualType IntTy,
1221 bool ConvertFloat, bool ConvertInt) {
1222 if (IntTy->isIntegerType()) {
1223 if (ConvertInt)
1224 // Convert intExpr to the lhs floating point type.
1225 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1226 CK_IntegralToFloating);
1227 return FloatTy;
1228 }
1229
1230 // Convert both sides to the appropriate complex float.
1231 assert(IntTy->isComplexIntegerType());
1232 QualType result = S.Context.getComplexType(FloatTy);
1233
1234 // _Complex int -> _Complex float
1235 if (ConvertInt)
1236 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1237 CK_IntegralComplexToFloatingComplex);
1238
1239 // float -> _Complex float
1240 if (ConvertFloat)
1241 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1242 CK_FloatingRealToComplex);
1243
1244 return result;
1245}
1246
1247/// Handle arithmethic conversion with floating point types. Helper
1248/// function of UsualArithmeticConversions()
1250 ExprResult &RHS, QualType LHSType,
1251 QualType RHSType, bool IsCompAssign) {
1252 bool LHSFloat = LHSType->isRealFloatingType();
1253 bool RHSFloat = RHSType->isRealFloatingType();
1254
1255 // N1169 4.1.4: If one of the operands has a floating type and the other
1256 // operand has a fixed-point type, the fixed-point operand
1257 // is converted to the floating type [...]
1258 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1259 if (LHSFloat)
1260 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1261 else if (!IsCompAssign)
1262 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1263 return LHSFloat ? LHSType : RHSType;
1264 }
1265
1266 // If we have two real floating types, convert the smaller operand
1267 // to the bigger result.
1268 if (LHSFloat && RHSFloat) {
1269 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1270 if (order > 0) {
1271 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1272 return LHSType;
1273 }
1274
1275 assert(order < 0 && "illegal float comparison");
1276 if (!IsCompAssign)
1277 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1278 return RHSType;
1279 }
1280
1281 if (LHSFloat) {
1282 // Half FP has to be promoted to float unless it is natively supported
1283 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1284 LHSType = S.Context.FloatTy;
1285
1286 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1287 /*ConvertFloat=*/!IsCompAssign,
1288 /*ConvertInt=*/ true);
1289 }
1290 assert(RHSFloat);
1291 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1292 /*ConvertFloat=*/ true,
1293 /*ConvertInt=*/!IsCompAssign);
1294}
1295
1296/// Diagnose attempts to convert between __float128, __ibm128 and
1297/// long double if there is no support for such conversion.
1298/// Helper function of UsualArithmeticConversions().
1299static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1300 QualType RHSType) {
1301 // No issue if either is not a floating point type.
1302 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1303 return false;
1304
1305 // No issue if both have the same 128-bit float semantics.
1306 auto *LHSComplex = LHSType->getAs<ComplexType>();
1307 auto *RHSComplex = RHSType->getAs<ComplexType>();
1308
1309 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1310 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1311
1312 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1313 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1314
1315 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1316 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1317 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1318 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1319 return false;
1320
1321 return true;
1322}
1323
1324typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1325
1326namespace {
1327/// These helper callbacks are placed in an anonymous namespace to
1328/// permit their use as function template parameters.
1329ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1330 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1331}
1332
1333ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1334 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1335 CK_IntegralComplexCast);
1336}
1337}
1338
1339/// Handle integer arithmetic conversions. Helper function of
1340/// UsualArithmeticConversions()
1341template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1343 ExprResult &RHS, QualType LHSType,
1344 QualType RHSType, bool IsCompAssign) {
1345 // The rules for this case are in C99 6.3.1.8
1346 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1347 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1348 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1349 if (LHSSigned == RHSSigned) {
1350 // Same signedness; use the higher-ranked type
1351 if (order >= 0) {
1352 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1353 return LHSType;
1354 } else if (!IsCompAssign)
1355 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1356 return RHSType;
1357 } else if (order != (LHSSigned ? 1 : -1)) {
1358 // The unsigned type has greater than or equal rank to the
1359 // signed type, so use the unsigned type
1360 if (RHSSigned) {
1361 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1362 return LHSType;
1363 } else if (!IsCompAssign)
1364 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1365 return RHSType;
1366 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1367 // The two types are different widths; if we are here, that
1368 // means the signed type is larger than the unsigned type, so
1369 // use the signed type.
1370 if (LHSSigned) {
1371 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1372 return LHSType;
1373 } else if (!IsCompAssign)
1374 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1375 return RHSType;
1376 } else {
1377 // The signed type is higher-ranked than the unsigned type,
1378 // but isn't actually any bigger (like unsigned int and long
1379 // on most 32-bit systems). Use the unsigned type corresponding
1380 // to the signed type.
1381 QualType result =
1382 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1383 RHS = (*doRHSCast)(S, RHS.get(), result);
1384 if (!IsCompAssign)
1385 LHS = (*doLHSCast)(S, LHS.get(), result);
1386 return result;
1387 }
1388}
1389
1390/// Handle conversions with GCC complex int extension. Helper function
1391/// of UsualArithmeticConversions()
1393 ExprResult &RHS, QualType LHSType,
1394 QualType RHSType,
1395 bool IsCompAssign) {
1396 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1397 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1398
1399 if (LHSComplexInt && RHSComplexInt) {
1400 QualType LHSEltType = LHSComplexInt->getElementType();
1401 QualType RHSEltType = RHSComplexInt->getElementType();
1402 QualType ScalarType =
1404 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1405
1406 return S.Context.getComplexType(ScalarType);
1407 }
1408
1409 if (LHSComplexInt) {
1410 QualType LHSEltType = LHSComplexInt->getElementType();
1411 QualType ScalarType =
1413 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1415 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1416 CK_IntegralRealToComplex);
1417
1418 return ComplexType;
1419 }
1420
1421 assert(RHSComplexInt);
1422
1423 QualType RHSEltType = RHSComplexInt->getElementType();
1424 QualType ScalarType =
1426 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1428
1429 if (!IsCompAssign)
1430 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1431 CK_IntegralRealToComplex);
1432 return ComplexType;
1433}
1434
1436 ExprResult &RHS,
1437 QualType LHSType,
1438 QualType RHSType,
1439 bool IsCompAssign) {
1440
1441 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1442 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1443
1444 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1445 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1446
1447 bool LHSHasTrap =
1448 LhsOBT && LhsOBT->getBehaviorKind() ==
1449 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1450 bool RHSHasTrap =
1451 RhsOBT && RhsOBT->getBehaviorKind() ==
1452 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1453 bool LHSHasWrap =
1454 LhsOBT && LhsOBT->getBehaviorKind() ==
1455 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1456 bool RHSHasWrap =
1457 RhsOBT && RhsOBT->getBehaviorKind() ==
1458 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1459
1460 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1461 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1462
1463 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1464 if (LHSHasTrap || RHSHasTrap)
1465 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1466 else if (LHSHasWrap || RHSHasWrap)
1467 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1468
1469 QualType LHSConvType = LHSUnderlyingType;
1470 QualType RHSConvType = RHSUnderlyingType;
1471 if (DominantBehavior) {
1472 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1473 LHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1474 LHSUnderlyingType);
1475 else
1476 LHSConvType = LHSType;
1477
1478 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1479 RHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1480 RHSUnderlyingType);
1481 else
1482 RHSConvType = RHSType;
1483 }
1484
1486 S, LHS, RHS, LHSConvType, RHSConvType, IsCompAssign);
1487}
1488
1489/// Return the rank of a given fixed point or integer type. The value itself
1490/// doesn't matter, but the values must be increasing with proper increasing
1491/// rank as described in N1169 4.1.1.
1492static unsigned GetFixedPointRank(QualType Ty) {
1493 const auto *BTy = Ty->getAs<BuiltinType>();
1494 assert(BTy && "Expected a builtin type.");
1495
1496 switch (BTy->getKind()) {
1497 case BuiltinType::ShortFract:
1498 case BuiltinType::UShortFract:
1499 case BuiltinType::SatShortFract:
1500 case BuiltinType::SatUShortFract:
1501 return 1;
1502 case BuiltinType::Fract:
1503 case BuiltinType::UFract:
1504 case BuiltinType::SatFract:
1505 case BuiltinType::SatUFract:
1506 return 2;
1507 case BuiltinType::LongFract:
1508 case BuiltinType::ULongFract:
1509 case BuiltinType::SatLongFract:
1510 case BuiltinType::SatULongFract:
1511 return 3;
1512 case BuiltinType::ShortAccum:
1513 case BuiltinType::UShortAccum:
1514 case BuiltinType::SatShortAccum:
1515 case BuiltinType::SatUShortAccum:
1516 return 4;
1517 case BuiltinType::Accum:
1518 case BuiltinType::UAccum:
1519 case BuiltinType::SatAccum:
1520 case BuiltinType::SatUAccum:
1521 return 5;
1522 case BuiltinType::LongAccum:
1523 case BuiltinType::ULongAccum:
1524 case BuiltinType::SatLongAccum:
1525 case BuiltinType::SatULongAccum:
1526 return 6;
1527 default:
1528 if (BTy->isInteger())
1529 return 0;
1530 llvm_unreachable("Unexpected fixed point or integer type");
1531 }
1532}
1533
1534/// handleFixedPointConversion - Fixed point operations between fixed
1535/// point types and integers or other fixed point types do not fall under
1536/// usual arithmetic conversion since these conversions could result in loss
1537/// of precsision (N1169 4.1.4). These operations should be calculated with
1538/// the full precision of their result type (N1169 4.1.6.2.1).
1540 QualType RHSTy) {
1541 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1542 "Expected at least one of the operands to be a fixed point type");
1543 assert((LHSTy->isFixedPointOrIntegerType() ||
1544 RHSTy->isFixedPointOrIntegerType()) &&
1545 "Special fixed point arithmetic operation conversions are only "
1546 "applied to ints or other fixed point types");
1547
1548 // If one operand has signed fixed-point type and the other operand has
1549 // unsigned fixed-point type, then the unsigned fixed-point operand is
1550 // converted to its corresponding signed fixed-point type and the resulting
1551 // type is the type of the converted operand.
1552 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1554 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1556
1557 // The result type is the type with the highest rank, whereby a fixed-point
1558 // conversion rank is always greater than an integer conversion rank; if the
1559 // type of either of the operands is a saturating fixedpoint type, the result
1560 // type shall be the saturating fixed-point type corresponding to the type
1561 // with the highest rank; the resulting value is converted (taking into
1562 // account rounding and overflow) to the precision of the resulting type.
1563 // Same ranks between signed and unsigned types are resolved earlier, so both
1564 // types are either signed or both unsigned at this point.
1565 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1566 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1567
1568 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1569
1571 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1572
1573 return ResultTy;
1574}
1575
1576/// Check that the usual arithmetic conversions can be performed on this pair of
1577/// expressions that might be of enumeration type.
1579 SourceLocation Loc,
1580 ArithConvKind ACK) {
1581 // C++2a [expr.arith.conv]p1:
1582 // If one operand is of enumeration type and the other operand is of a
1583 // different enumeration type or a floating-point type, this behavior is
1584 // deprecated ([depr.arith.conv.enum]).
1585 //
1586 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1587 // Eventually we will presumably reject these cases (in C++23 onwards?).
1589 R = RHS->getEnumCoercedType(Context);
1590 bool LEnum = L->isUnscopedEnumerationType(),
1591 REnum = R->isUnscopedEnumerationType();
1592 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1593 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1594 (REnum && L->isFloatingType())) {
1595 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1597 ? diag::warn_arith_conv_enum_float_cxx20
1598 : diag::warn_arith_conv_enum_float)
1599 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1600 << L << R;
1601 } else if (!IsCompAssign && LEnum && REnum &&
1602 !Context.hasSameUnqualifiedType(L, R)) {
1603 unsigned DiagID;
1604 // In C++ 26, usual arithmetic conversions between 2 different enum types
1605 // are ill-formed.
1607 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1608 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1609 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1610 // If either enumeration type is unnamed, it's less likely that the
1611 // user cares about this, but this situation is still deprecated in
1612 // C++2a. Use a different warning group.
1613 DiagID = getLangOpts().CPlusPlus20
1614 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1615 : diag::warn_arith_conv_mixed_anon_enum_types;
1616 } else if (ACK == ArithConvKind::Conditional) {
1617 // Conditional expressions are separated out because they have
1618 // historically had a different warning flag.
1619 DiagID = getLangOpts().CPlusPlus20
1620 ? diag::warn_conditional_mixed_enum_types_cxx20
1621 : diag::warn_conditional_mixed_enum_types;
1622 } else if (ACK == ArithConvKind::Comparison) {
1623 // Comparison expressions are separated out because they have
1624 // historically had a different warning flag.
1625 DiagID = getLangOpts().CPlusPlus20
1626 ? diag::warn_comparison_mixed_enum_types_cxx20
1627 : diag::warn_comparison_mixed_enum_types;
1628 } else {
1629 DiagID = getLangOpts().CPlusPlus20
1630 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1631 : diag::warn_arith_conv_mixed_enum_types;
1632 }
1633 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1634 << (int)ACK << L << R;
1635 }
1636}
1637
1639 Expr *RHS, SourceLocation Loc,
1640 ArithConvKind ACK) {
1641 QualType LHSType = LHS->getType().getUnqualifiedType();
1642 QualType RHSType = RHS->getType().getUnqualifiedType();
1643
1644 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1645 !RHSType->isUnicodeCharacterType())
1646 return;
1647
1648 if (ACK == ArithConvKind::Comparison) {
1649 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1650 return;
1651
1652 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1653 if (T->isChar8Type())
1654 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1655 if (T->isChar16Type())
1656 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1657 assert(T->isChar32Type());
1658 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1659 };
1660
1661 Expr::EvalResult LHSRes, RHSRes;
1662 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1664 SemaRef.isConstantEvaluatedContext());
1665 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1667 SemaRef.isConstantEvaluatedContext());
1668
1669 // Don't warn if the one known value is a representable
1670 // in the type of both expressions.
1671 if (LHSSuccess != RHSuccess) {
1672 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1673 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1674 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1675 return;
1676 }
1677
1678 if (!LHSSuccess || !RHSuccess) {
1679 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1680 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1681 << RHSType;
1682 return;
1683 }
1684
1685 llvm::APSInt LHSValue(32);
1686 LHSValue = LHSRes.Val.getInt();
1687 llvm::APSInt RHSValue(32);
1688 RHSValue = RHSRes.Val.getInt();
1689
1690 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1691 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1692 if (LHSSafe && RHSSafe)
1693 return;
1694
1695 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1696 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1697 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1698 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1699 return;
1700 }
1701
1702 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1703 return;
1704
1705 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1706 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1707 << RHSType;
1708}
1709
1710/// UsualArithmeticConversions - Performs various conversions that are common to
1711/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1712/// routine returns the first non-arithmetic type found. The client is
1713/// responsible for emitting appropriate error diagnostics.
1715 SourceLocation Loc,
1716 ArithConvKind ACK) {
1717
1718 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1719
1720 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1721
1722 if (ACK != ArithConvKind::CompAssign) {
1723 LHS = UsualUnaryConversions(LHS.get());
1724 if (LHS.isInvalid())
1725 return QualType();
1726 }
1727
1728 RHS = UsualUnaryConversions(RHS.get());
1729 if (RHS.isInvalid())
1730 return QualType();
1731
1732 // For conversion purposes, we ignore any qualifiers.
1733 // For example, "const float" and "float" are equivalent.
1734 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1735 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1736
1737 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1738 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1739 LHSType = AtomicLHS->getValueType();
1740
1741 // If both types are identical, no conversion is needed.
1742 if (Context.hasSameType(LHSType, RHSType))
1743 return Context.getCommonSugaredType(LHSType, RHSType);
1744
1745 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1746 // The caller can deal with this (e.g. pointer + int).
1747 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1748 return QualType();
1749
1750 // Apply unary and bitfield promotions to the LHS's type.
1751 QualType LHSUnpromotedType = LHSType;
1752 if (Context.isPromotableIntegerType(LHSType))
1753 LHSType = Context.getPromotedIntegerType(LHSType);
1754 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1755 if (!LHSBitfieldPromoteTy.isNull())
1756 LHSType = LHSBitfieldPromoteTy;
1757 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1758 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1759
1760 // If both types are identical, no conversion is needed.
1761 if (Context.hasSameType(LHSType, RHSType))
1762 return Context.getCommonSugaredType(LHSType, RHSType);
1763
1764 // At this point, we have two different arithmetic types.
1765
1766 if ((LHSType->isFixedPointType() && RHSType->isBitIntType()) ||
1767 (LHSType->isBitIntType() && RHSType->isFixedPointType()))
1768 return QualType();
1769
1770 // Diagnose attempts to convert between __ibm128, __float128 and long double
1771 // where such conversions currently can't be handled.
1772 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1773 return QualType();
1774
1775 // Handle complex types first (C99 6.3.1.8p1).
1776 if (LHSType->isComplexType() || RHSType->isComplexType())
1777 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1779
1780 // Now handle "real" floating types (i.e. float, double, long double).
1781 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1782 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1784
1785 // Handle GCC complex int extension.
1786 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1787 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1789
1790 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1791 return handleFixedPointConversion(*this, LHSType, RHSType);
1792
1793 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1795 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1796
1797 // Finally, we have two differing integer types.
1799 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1800}
1801
1802//===----------------------------------------------------------------------===//
1803// Semantic Analysis for various Expression Types
1804//===----------------------------------------------------------------------===//
1805
1806
1808 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1809 bool PredicateIsExpr, void *ControllingExprOrType,
1810 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1811 unsigned NumAssocs = ArgTypes.size();
1812 assert(NumAssocs == ArgExprs.size());
1813
1814 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1815 for (unsigned i = 0; i < NumAssocs; ++i) {
1816 if (ArgTypes[i])
1817 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1818 else
1819 Types[i] = nullptr;
1820 }
1821
1822 // If we have a controlling type, we need to convert it from a parsed type
1823 // into a semantic type and then pass that along.
1824 if (!PredicateIsExpr) {
1825 TypeSourceInfo *ControllingType;
1826 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1827 &ControllingType);
1828 assert(ControllingType && "couldn't get the type out of the parser");
1829 ControllingExprOrType = ControllingType;
1830 }
1831
1833 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1834 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1835 delete [] Types;
1836 return ER;
1837}
1838
1839// Helper function to determine type compatibility for C _Generic expressions.
1840// Multiple compatible types within the same _Generic expression is ambiguous
1841// and not valid.
1843 QualType U) {
1844 // Try to handle special types like OverflowBehaviorTypes
1845 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1846 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1847
1848 if (TOBT || UOBT) {
1849 if (TOBT && UOBT) {
1850 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1851 return Ctx.typesAreCompatible(TOBT->getUnderlyingType(),
1852 UOBT->getUnderlyingType());
1853 return false;
1854 }
1855 return false;
1856 }
1857
1858 // We're dealing with types that don't require special handling.
1859 return Ctx.typesAreCompatible(T, U);
1860}
1861
1863 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1864 bool PredicateIsExpr, void *ControllingExprOrType,
1866 unsigned NumAssocs = Types.size();
1867 assert(NumAssocs == Exprs.size());
1868 assert(ControllingExprOrType &&
1869 "Must have either a controlling expression or a controlling type");
1870
1871 Expr *ControllingExpr = nullptr;
1872 TypeSourceInfo *ControllingType = nullptr;
1873 if (PredicateIsExpr) {
1874 // Decay and strip qualifiers for the controlling expression type, and
1875 // handle placeholder type replacement. See committee discussion from WG14
1876 // DR423.
1880 reinterpret_cast<Expr *>(ControllingExprOrType));
1881 if (R.isInvalid())
1882 return ExprError();
1883 ControllingExpr = R.get();
1884 } else {
1885 // The extension form uses the type directly rather than converting it.
1886 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1887 if (!ControllingType)
1888 return ExprError();
1889 }
1890
1891 bool TypeErrorFound = false,
1892 IsResultDependent = ControllingExpr
1893 ? ControllingExpr->isTypeDependent()
1894 : ControllingType->getType()->isDependentType(),
1895 ContainsUnexpandedParameterPack =
1896 ControllingExpr
1897 ? ControllingExpr->containsUnexpandedParameterPack()
1898 : ControllingType->getType()->containsUnexpandedParameterPack();
1899
1900 // The controlling expression is an unevaluated operand, so side effects are
1901 // likely unintended.
1902 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1903 ControllingExpr->HasSideEffects(Context, false))
1904 Diag(ControllingExpr->getExprLoc(),
1905 diag::warn_side_effects_unevaluated_context);
1906
1907 for (unsigned i = 0; i < NumAssocs; ++i) {
1908 if (Exprs[i]->containsUnexpandedParameterPack())
1909 ContainsUnexpandedParameterPack = true;
1910
1911 if (Types[i]) {
1912 if (Types[i]->getType()->containsUnexpandedParameterPack())
1913 ContainsUnexpandedParameterPack = true;
1914
1915 if (Types[i]->getType()->isDependentType()) {
1916 IsResultDependent = true;
1917 } else {
1918 // We relax the restriction on use of incomplete types and non-object
1919 // types with the type-based extension of _Generic. Allowing incomplete
1920 // objects means those can be used as "tags" for a type-safe way to map
1921 // to a value. Similarly, matching on function types rather than
1922 // function pointer types can be useful. However, the restriction on VM
1923 // types makes sense to retain as there are open questions about how
1924 // the selection can be made at compile time.
1925 //
1926 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1927 // complete object type other than a variably modified type."
1928 // C2y removed the requirement that an expression form must
1929 // use a complete type, though it's still as-if the type has undergone
1930 // lvalue conversion. We support this as an extension in C23 and
1931 // earlier because GCC does so.
1932 unsigned D = 0;
1933 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1934 D = LangOpts.C2y ? diag::compat_c2y_assoc_type_incomplete
1935 : diag::compat_pre_c2y_assoc_type_incomplete;
1936 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1937 D = diag::err_assoc_type_nonobject;
1938 else if (Types[i]->getType()->isVariablyModifiedType())
1939 D = diag::err_assoc_type_variably_modified;
1940 else if (ControllingExpr) {
1941 // Because the controlling expression undergoes lvalue conversion,
1942 // array conversion, and function conversion, an association which is
1943 // of array type, function type, or is qualified can never be
1944 // reached. We will warn about this so users are less surprised by
1945 // the unreachable association. However, we don't have to handle
1946 // function types; that's not an object type, so it's handled above.
1947 //
1948 // The logic is somewhat different for C++ because C++ has different
1949 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1950 // If T is a non-class type, the type of the prvalue is the cv-
1951 // unqualified version of T. Otherwise, the type of the prvalue is T.
1952 // The result of these rules is that all qualified types in an
1953 // association in C are unreachable, and in C++, only qualified non-
1954 // class types are unreachable.
1955 //
1956 // NB: this does not apply when the first operand is a type rather
1957 // than an expression, because the type form does not undergo
1958 // conversion.
1959 unsigned Reason = 0;
1960 QualType QT = Types[i]->getType();
1961 if (QT->isArrayType())
1962 Reason = 1;
1963 else if (QT.hasQualifiers() &&
1964 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1965 Reason = 2;
1966
1967 if (Reason)
1968 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1969 diag::warn_unreachable_association)
1970 << QT << (Reason - 1);
1971 }
1972
1973 if (D != 0) {
1974 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1975 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1976 if (getDiagnostics().getDiagnosticLevel(
1977 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1979 TypeErrorFound = true;
1980 }
1981
1982 // C11 6.5.1.1p2 "No two generic associations in the same generic
1983 // selection shall specify compatible types."
1984 for (unsigned j = i+1; j < NumAssocs; ++j)
1985 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1987 Types[j]->getType())) {
1988 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1989 diag::err_assoc_compatible_types)
1990 << Types[j]->getTypeLoc().getSourceRange()
1991 << Types[j]->getType()
1992 << Types[i]->getType();
1993 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1994 diag::note_compat_assoc)
1995 << Types[i]->getTypeLoc().getSourceRange()
1996 << Types[i]->getType();
1997 TypeErrorFound = true;
1998 }
1999 }
2000 }
2001 }
2002 if (TypeErrorFound)
2003 return ExprError();
2004
2005 // If we determined that the generic selection is result-dependent, don't
2006 // try to compute the result expression.
2007 if (IsResultDependent) {
2008 if (ControllingExpr)
2009 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
2010 Types, Exprs, DefaultLoc, RParenLoc,
2011 ContainsUnexpandedParameterPack);
2012 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
2013 Exprs, DefaultLoc, RParenLoc,
2014 ContainsUnexpandedParameterPack);
2015 }
2016
2017 SmallVector<unsigned, 1> CompatIndices;
2018 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2019 // Look at the canonical type of the controlling expression in case it was a
2020 // deduced type like __auto_type. However, when issuing diagnostics, use the
2021 // type the user wrote in source rather than the canonical one.
2022 for (unsigned i = 0; i < NumAssocs; ++i) {
2023 if (!Types[i])
2024 DefaultIndex = i;
2025 else {
2026 bool Compatible;
2027 QualType ControllingQT =
2028 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2029 : ControllingType->getType().getCanonicalType();
2030 QualType AssocQT = Types[i]->getType();
2031
2032 Compatible =
2033 areTypesCompatibleForGeneric(Context, ControllingQT, AssocQT);
2034
2035 if (Compatible)
2036 CompatIndices.push_back(i);
2037 }
2038 }
2039
2040 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2041 TypeSourceInfo *ControllingType) {
2042 // We strip parens here because the controlling expression is typically
2043 // parenthesized in macro definitions.
2044 if (ControllingExpr)
2045 ControllingExpr = ControllingExpr->IgnoreParens();
2046
2047 SourceRange SR = ControllingExpr
2048 ? ControllingExpr->getSourceRange()
2049 : ControllingType->getTypeLoc().getSourceRange();
2050 QualType QT = ControllingExpr ? ControllingExpr->getType()
2051 : ControllingType->getType();
2052
2053 return std::make_pair(SR, QT);
2054 };
2055
2056 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2057 // type compatible with at most one of the types named in its generic
2058 // association list."
2059 if (CompatIndices.size() > 1) {
2060 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2061 SourceRange SR = P.first;
2062 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
2063 << SR << P.second << (unsigned)CompatIndices.size();
2064 for (unsigned I : CompatIndices) {
2065 Diag(Types[I]->getTypeLoc().getBeginLoc(),
2066 diag::note_compat_assoc)
2067 << Types[I]->getTypeLoc().getSourceRange()
2068 << Types[I]->getType();
2069 }
2070 return ExprError();
2071 }
2072
2073 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2074 // its controlling expression shall have type compatible with exactly one of
2075 // the types named in its generic association list."
2076 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2077 CompatIndices.size() == 0) {
2078 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2079 SourceRange SR = P.first;
2080 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
2081 return ExprError();
2082 }
2083
2084 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2085 // type name that is compatible with the type of the controlling expression,
2086 // then the result expression of the generic selection is the expression
2087 // in that generic association. Otherwise, the result expression of the
2088 // generic selection is the expression in the default generic association."
2089 unsigned ResultIndex =
2090 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2091
2092 if (ControllingExpr) {
2094 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
2095 ContainsUnexpandedParameterPack, ResultIndex);
2096 }
2098 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
2099 ContainsUnexpandedParameterPack, ResultIndex);
2100}
2101
2103 switch (Kind) {
2104 default:
2105 llvm_unreachable("unexpected TokenKind");
2106 case tok::kw___func__:
2107 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2108 case tok::kw___FUNCTION__:
2110 case tok::kw___FUNCDNAME__:
2111 return PredefinedIdentKind::FuncDName; // [MS]
2112 case tok::kw___FUNCSIG__:
2113 return PredefinedIdentKind::FuncSig; // [MS]
2114 case tok::kw_L__FUNCTION__:
2115 return PredefinedIdentKind::LFunction; // [MS]
2116 case tok::kw_L__FUNCSIG__:
2117 return PredefinedIdentKind::LFuncSig; // [MS]
2118 case tok::kw___PRETTY_FUNCTION__:
2120 }
2121}
2122
2123/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2124/// to determine the value of a PredefinedExpr. This can be either a
2125/// block, lambda, captured statement, function, otherwise a nullptr.
2127 auto LSI = S.FunctionScopes.rbegin();
2128
2129 auto tryAdjustLambdaContext = [&S, &LSI](DeclContext *&DC) {
2130 if (isLambdaCallOperator(DC)) {
2131 auto E = S.FunctionScopes.rend();
2132 while (LSI != E && !isa<LambdaScopeInfo>(*LSI))
2133 ++LSI;
2134 assert(LSI != E && "Should be in a lambda scope info");
2135 if (dyn_cast<LambdaScopeInfo>(*LSI)->BeforeCompoundStatement)
2136 DC = DC->getParent();
2137 ++LSI;
2138 }
2139 };
2140
2141 tryAdjustLambdaContext(DC);
2142 while (DC &&
2144 DC = DC->getParent();
2145 tryAdjustLambdaContext(DC);
2146 }
2147
2148 return cast_or_null<Decl>(DC);
2149}
2150
2151/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2152/// location of the token and the offset of the ud-suffix within it.
2154 unsigned Offset) {
2155 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2156 S.getLangOpts());
2157}
2158
2159/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2160/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2162 IdentifierInfo *UDSuffix,
2163 SourceLocation UDSuffixLoc,
2164 ArrayRef<Expr*> Args,
2165 SourceLocation LitEndLoc) {
2166 assert(Args.size() <= 2 && "too many arguments for literal operator");
2167
2168 QualType ArgTy[2];
2169 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2170 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2171 if (ArgTy[ArgIdx]->isArrayType())
2172 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2173 }
2174
2175 DeclarationName OpName =
2177 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2178 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2179
2180 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2181 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2182 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2183 /*AllowStringTemplatePack*/ false,
2184 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2185 return ExprError();
2186
2187 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2188}
2189
2191 // StringToks needs backing storage as it doesn't hold array elements itself
2192 std::vector<Token> ExpandedToks;
2193 if (getLangOpts().MicrosoftExt)
2194 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2195
2196 StringLiteralParser Literal(StringToks, PP,
2198 if (Literal.hadError)
2199 return ExprError();
2200
2201 SmallVector<SourceLocation, 4> StringTokLocs;
2202 for (const Token &Tok : StringToks)
2203 StringTokLocs.push_back(Tok.getLocation());
2204
2205 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2207 false, {}, StringTokLocs);
2208
2209 if (!Literal.getUDSuffix().empty()) {
2210 SourceLocation UDSuffixLoc =
2211 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2212 Literal.getUDSuffixOffset());
2213 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2214 }
2215
2216 return Lit;
2217}
2218
2219std::vector<Token>
2221 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2222 // local macros that expand to string literals that may be concatenated.
2223 // These macros are expanded here (in Sema), because StringLiteralParser
2224 // (in Lex) doesn't know the enclosing function (because it hasn't been
2225 // parsed yet).
2226 assert(getLangOpts().MicrosoftExt);
2227
2228 // Note: Although function local macros are defined only inside functions,
2229 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2230 // expansion of macros into empty string literals without additional checks.
2231 Decl *CurrentDecl = getPredefinedExprDecl(*this, CurContext);
2232 if (!CurrentDecl)
2233 CurrentDecl = Context.getTranslationUnitDecl();
2234
2235 std::vector<Token> ExpandedToks;
2236 ExpandedToks.reserve(Toks.size());
2237 for (const Token &Tok : Toks) {
2239 assert(tok::isStringLiteral(Tok.getKind()));
2240 ExpandedToks.emplace_back(Tok);
2241 continue;
2242 }
2243 if (isa<TranslationUnitDecl>(CurrentDecl))
2244 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2245 // Stringify predefined expression
2246 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2247 << Tok.getKind();
2248 SmallString<64> Str;
2249 llvm::raw_svector_ostream OS(Str);
2250 Token &Exp = ExpandedToks.emplace_back();
2251 Exp.startToken();
2252 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2253 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2254 OS << 'L';
2255 Exp.setKind(tok::wide_string_literal);
2256 } else {
2257 Exp.setKind(tok::string_literal);
2258 }
2259 OS << '"'
2261 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2262 << '"';
2263 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2264 }
2265 return ExpandedToks;
2266}
2267
2270 assert(!StringToks.empty() && "Must have at least one string!");
2271
2272 // StringToks needs backing storage as it doesn't hold array elements itself
2273 std::vector<Token> ExpandedToks;
2274 if (getLangOpts().MicrosoftExt)
2275 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2276
2277 StringLiteralParser Literal(
2279 if (Literal.hadError)
2280 return ExprError();
2281
2282 SmallVector<SourceLocation, 4> StringTokLocs;
2283 for (const Token &Tok : StringToks)
2284 StringTokLocs.push_back(Tok.getLocation());
2285
2286 QualType CharTy = Context.CharTy;
2288 if (Literal.isWide()) {
2289 CharTy = Context.getWideCharType();
2291 } else if (Literal.isUTF8()) {
2292 if (getLangOpts().Char8)
2293 CharTy = Context.Char8Ty;
2294 else if (getLangOpts().C23)
2295 CharTy = Context.UnsignedCharTy;
2297 } else if (Literal.isUTF16()) {
2298 CharTy = Context.Char16Ty;
2300 } else if (Literal.isUTF32()) {
2301 CharTy = Context.Char32Ty;
2303 } else if (Literal.isPascal()) {
2304 CharTy = Context.UnsignedCharTy;
2305 }
2306
2307 // Warn on u8 string literals before C++20 and C23, whose type
2308 // was an array of char before but becomes an array of char8_t.
2309 // In C++20, it cannot be used where a pointer to char is expected.
2310 // In C23, it might have an unexpected value if char was signed.
2311 if (Kind == StringLiteralKind::UTF8 &&
2313 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2314 : !getLangOpts().C23)) {
2315 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2316 ? diag::warn_cxx20_compat_utf8_string
2317 : diag::warn_c23_compat_utf8_string);
2318
2319 // Create removals for all 'u8' prefixes in the string literal(s). This
2320 // ensures C++20/C23 compatibility (but may change the program behavior when
2321 // built by non-Clang compilers for which the execution character set is
2322 // not always UTF-8).
2323 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2324 SourceLocation RemovalDiagLoc;
2325 for (const Token &Tok : StringToks) {
2326 if (Tok.getKind() == tok::utf8_string_literal) {
2327 if (RemovalDiagLoc.isInvalid())
2328 RemovalDiagLoc = Tok.getLocation();
2330 Tok.getLocation(),
2331 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2333 }
2334 }
2335 Diag(RemovalDiagLoc, RemovalDiag);
2336 }
2337
2338 QualType StrTy =
2339 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2340
2341 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2343 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2344 if (Literal.getUDSuffix().empty())
2345 return Lit;
2346
2347 // We're building a user-defined literal.
2348 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2349 SourceLocation UDSuffixLoc =
2350 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2351 Literal.getUDSuffixOffset());
2352
2353 // Make sure we're allowed user-defined literals here.
2354 if (!UDLScope)
2355 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2356
2357 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2358 // operator "" X (str, len)
2359 QualType SizeType = Context.getSizeType();
2360
2361 DeclarationName OpName =
2362 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2363 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2364 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2365
2366 QualType ArgTy[] = {
2367 Context.getArrayDecayedType(StrTy), SizeType
2368 };
2369
2370 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2371 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2372 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2373 /*AllowStringTemplatePack*/ true,
2374 /*DiagnoseMissing*/ true, Lit)) {
2375
2376 case LOLR_Cooked: {
2377 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2378 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2379 StringTokLocs[0]);
2380 Expr *Args[] = { Lit, LenArg };
2381
2382 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2383 }
2384
2385 case LOLR_Template: {
2386 TemplateArgumentListInfo ExplicitArgs;
2387 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2388 TemplateArgumentLocInfo ArgInfo(Lit);
2389 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2390 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2391 &ExplicitArgs);
2392 }
2393
2395 TemplateArgumentListInfo ExplicitArgs;
2396
2397 unsigned CharBits = Context.getIntWidth(CharTy);
2398 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2399 llvm::APSInt Value(CharBits, CharIsUnsigned);
2400
2401 TemplateArgument TypeArg(CharTy);
2402 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2403 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2404
2405 SourceLocation Loc = StringTokLocs.back();
2406 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2407 Value = Lit->getCodeUnit(I);
2408 TemplateArgument Arg(Context, Value, CharTy);
2410 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2411 }
2412 return BuildLiteralOperatorCall(R, OpNameInfo, {}, Loc, &ExplicitArgs);
2413 }
2414 case LOLR_Raw:
2416 llvm_unreachable("unexpected literal operator lookup result");
2417 case LOLR_Error:
2418 return ExprError();
2419 }
2420 llvm_unreachable("unexpected literal operator lookup result");
2421}
2422
2425 SourceLocation Loc,
2426 const CXXScopeSpec *SS) {
2427 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2428 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2429}
2430
2433 const DeclarationNameInfo &NameInfo,
2434 const CXXScopeSpec *SS, NamedDecl *FoundD,
2435 SourceLocation TemplateKWLoc,
2436 const TemplateArgumentListInfo *TemplateArgs) {
2439 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2440 TemplateArgs);
2441}
2442
2443// CUDA/HIP: Check whether a captured reference variable is referencing a
2444// host variable in a device or host device lambda.
2446 VarDecl *VD) {
2447 if (!S.getLangOpts().CUDA || !VD->hasInit())
2448 return false;
2449 assert(VD->getType()->isReferenceType());
2450
2451 // Check whether the reference variable is referencing a host variable.
2452 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2453 if (!DRE)
2454 return false;
2455 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2456 if (!Referee || !Referee->hasGlobalStorage() ||
2457 Referee->hasAttr<CUDADeviceAttr>())
2458 return false;
2459
2460 // Check whether the current function is a device or host device lambda.
2461 // Check whether the reference variable is a capture by getDeclContext()
2462 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2463 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2464 if (MD && MD->getParent()->isLambda() &&
2465 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2466 VD->getDeclContext() != MD)
2467 return true;
2468
2469 return false;
2470}
2471
2473 // A declaration named in an unevaluated operand never constitutes an odr-use.
2475 return NOUR_Unevaluated;
2476
2477 // C++2a [basic.def.odr]p4:
2478 // A variable x whose name appears as a potentially-evaluated expression e
2479 // is odr-used by e unless [...] x is a reference that is usable in
2480 // constant expressions.
2481 // CUDA/HIP:
2482 // If a reference variable referencing a host variable is captured in a
2483 // device or host device lambda, the value of the referee must be copied
2484 // to the capture and the reference variable must be treated as odr-use
2485 // since the value of the referee is not known at compile time and must
2486 // be loaded from the captured.
2487 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2488 if (VD->getType()->isReferenceType() &&
2489 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2491 VD->isUsableInConstantExpressions(Context))
2492 return NOUR_Constant;
2493 }
2494
2495 // All remaining non-variable cases constitute an odr-use. For variables, we
2496 // need to wait and see how the expression is used.
2497 return NOUR_None;
2498}
2499
2502 const DeclarationNameInfo &NameInfo,
2503 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2504 SourceLocation TemplateKWLoc,
2505 const TemplateArgumentListInfo *TemplateArgs) {
2506 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2507 NeedToCaptureVariable(D, NameInfo.getLoc());
2508
2510 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2511 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2513
2514 // C++ [except.spec]p17:
2515 // An exception-specification is considered to be needed when:
2516 // - in an expression, the function is the unique lookup result or
2517 // the selected member of a set of overloaded functions.
2518 //
2519 // We delay doing this until after we've built the function reference and
2520 // marked it as used so that:
2521 // a) if the function is defaulted, we get errors from defining it before /
2522 // instead of errors from computing its exception specification, and
2523 // b) if the function is a defaulted comparison, we can use the body we
2524 // build when defining it as input to the exception specification
2525 // computation rather than computing a new body.
2526 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2527 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2528 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2529 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2530 }
2531 }
2532
2533 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2535 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2537
2538 const auto *FD = dyn_cast<FieldDecl>(D);
2539 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2540 FD = IFD->getAnonField();
2541 if (FD) {
2542 UnusedPrivateFields.remove(FD);
2543 // Just in case we're building an illegal pointer-to-member.
2544 if (FD->isBitField())
2546 }
2547
2548 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2549 // designates a bit-field.
2550 if (const auto *BD = dyn_cast<BindingDecl>(D))
2551 if (const auto *BE = BD->getBinding())
2552 E->setObjectKind(BE->getObjectKind());
2553
2554 return E;
2555}
2556
2557// Diagnose when a macro cannot be expanded because it's a function-like macro
2558// being used as a function-like macro. Returns true if a diagnostic is emitted.
2560 SourceLocation TypoLoc) {
2561
2562 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
2563 if (II->hasMacroDefinition()) {
2564 MacroInfo *MI = SemaRef.PP.getMacroInfo(II);
2565 if (MI && MI->isFunctionLike()) {
2566 // If the identifier is immediately followed by '(', the user did
2567 // attempt to invoke it as a function-like macro; the failure is
2568 // for some other reason (e.g. wrong argument count), which the
2569 // preprocessor already diagnosed separately. Don't suggest adding
2570 // parens in that case, since they're already there.
2571 SourceManager &SM = SemaRef.getSourceManager();
2572 const LangOptions &LangOpts = SemaRef.getLangOpts();
2573 std::optional<Token> NextTok =
2574 Lexer::findNextToken(TypoLoc, SM, LangOpts);
2575 if (NextTok && NextTok->is(tok::l_paren))
2576 return false;
2577 SemaRef.Diag(TypoLoc,
2578 diag::err_undeclared_var_use_suggest_func_like_macro)
2579 << II->getName();
2580 SemaRef.Diag(MI->getDefinitionLoc(),
2581 diag::note_function_like_macro_requires_parens)
2582 << II->getName();
2583 return true;
2584 }
2585 }
2586 }
2587 return false;
2588}
2589
2590void
2593 DeclarationNameInfo &NameInfo,
2594 const TemplateArgumentListInfo *&TemplateArgs) {
2596 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2597 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2598
2599 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2600 Id.TemplateId->NumArgs);
2601 translateTemplateArguments(TemplateArgsPtr, Buffer);
2602
2603 TemplateName TName = Id.TemplateId->Template.get();
2605 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2606 TemplateArgs = &Buffer;
2607 } else {
2608 NameInfo = GetNameFromUnqualifiedId(Id);
2609 TemplateArgs = nullptr;
2610 }
2611}
2612
2614 // During a default argument instantiation the CurContext points
2615 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2616 // function parameter list, hence add an explicit check.
2617 bool isDefaultArgument =
2618 !CodeSynthesisContexts.empty() &&
2619 CodeSynthesisContexts.back().Kind ==
2621 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2622 bool isInstance = CurMethod && CurMethod->isInstance() &&
2623 R.getNamingClass() == CurMethod->getParent() &&
2624 !isDefaultArgument;
2625
2626 // There are two ways we can find a class-scope declaration during template
2627 // instantiation that we did not find in the template definition: if it is a
2628 // member of a dependent base class, or if it is declared after the point of
2629 // use in the same class. Distinguish these by comparing the class in which
2630 // the member was found to the naming class of the lookup.
2631 unsigned DiagID = diag::err_found_in_dependent_base;
2632 unsigned NoteID = diag::note_member_declared_at;
2633 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2634 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2635 : diag::err_found_later_in_class;
2636 } else if (getLangOpts().MSVCCompat) {
2637 DiagID = diag::ext_found_in_dependent_base;
2638 NoteID = diag::note_dependent_member_use;
2639 }
2640
2641 if (isInstance) {
2642 // Give a code modification hint to insert 'this->'.
2643 Diag(R.getNameLoc(), DiagID)
2644 << R.getLookupName()
2645 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2646 CheckCXXThisCapture(R.getNameLoc());
2647 } else {
2648 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2649 // they're not shadowed).
2650 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2651 }
2652
2653 for (const NamedDecl *D : R)
2654 Diag(D->getLocation(), NoteID);
2655
2656 // Return true if we are inside a default argument instantiation
2657 // and the found name refers to an instance member function, otherwise
2658 // the caller will try to create an implicit member call and this is wrong
2659 // for default arguments.
2660 //
2661 // FIXME: Is this special case necessary? We could allow the caller to
2662 // diagnose this.
2663 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2664 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2665 return true;
2666 }
2667
2668 // Tell the callee to try to recover.
2669 return false;
2670}
2671
2674 TemplateArgumentListInfo *ExplicitTemplateArgs,
2675 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2676 DeclarationName Name = R.getLookupName();
2677 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2678
2679 unsigned diagnostic = diag::err_undeclared_var_use;
2680 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2684 diagnostic = diag::err_undeclared_use;
2685 diagnostic_suggest = diag::err_undeclared_use_suggest;
2686 }
2687
2688 // If the original lookup was an unqualified lookup, fake an
2689 // unqualified lookup. This is useful when (for example) the
2690 // original lookup would not have found something because it was a
2691 // dependent name.
2692 DeclContext *DC =
2693 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2694 while (DC) {
2695 if (isa<CXXRecordDecl>(DC)) {
2696 if (ExplicitTemplateArgs) {
2698 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2699 /*EnteringContext*/ false, TemplateNameIsRequired,
2700 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2701 return true;
2702 } else {
2703 LookupQualifiedName(R, DC);
2704 }
2705
2706 if (!R.empty()) {
2707 // Don't give errors about ambiguities in this lookup.
2708 R.suppressDiagnostics();
2709
2710 // If there's a best viable function among the results, only mention
2711 // that one in the notes.
2712 OverloadCandidateSet Candidates(R.getNameLoc(),
2714 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2716 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2717 OR_Success) {
2718 R.clear();
2719 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2720 R.resolveKind();
2721 }
2722
2724 }
2725
2726 R.clear();
2727 }
2728
2729 DC = DC->getLookupParent();
2730 }
2731
2732 // We didn't find anything, so try to correct for a typo.
2733 TypoCorrection Corrected;
2734 if (S && (Corrected =
2735 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2736 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2737 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2738 bool DroppedSpecifier =
2739 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2740 R.setLookupName(Corrected.getCorrection());
2741
2742 bool AcceptableWithRecovery = false;
2743 bool AcceptableWithoutRecovery = false;
2744 NamedDecl *ND = Corrected.getFoundDecl();
2745 if (ND) {
2746 if (Corrected.isOverloaded()) {
2747 OverloadCandidateSet OCS(R.getNameLoc(),
2750 for (NamedDecl *CD : Corrected) {
2751 if (FunctionTemplateDecl *FTD =
2752 dyn_cast<FunctionTemplateDecl>(CD))
2754 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2755 Args, OCS);
2756 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2757 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2759 Args, OCS);
2760 }
2761 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2762 case OR_Success:
2763 ND = Best->FoundDecl;
2764 Corrected.setCorrectionDecl(ND);
2765 break;
2766 default:
2767 // FIXME: Arbitrarily pick the first declaration for the note.
2768 Corrected.setCorrectionDecl(ND);
2769 break;
2770 }
2771 }
2772 R.addDecl(ND);
2773 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2776 if (!Record)
2779 R.setNamingClass(Record);
2780 }
2781
2782 auto *UnderlyingND = ND->getUnderlyingDecl();
2783 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2784 isa<FunctionTemplateDecl>(UnderlyingND);
2785 // FIXME: If we ended up with a typo for a type name or
2786 // Objective-C class name, we're in trouble because the parser
2787 // is in the wrong place to recover. Suggest the typo
2788 // correction, but don't make it a fix-it since we're not going
2789 // to recover well anyway.
2790 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2791 getAsTypeTemplateDecl(UnderlyingND) ||
2792 isa<ObjCInterfaceDecl>(UnderlyingND);
2793 } else {
2794 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2795 // because we aren't able to recover.
2796 AcceptableWithoutRecovery = true;
2797 }
2798
2799 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2800 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2801 ? diag::note_implicit_param_decl
2802 : diag::note_previous_decl;
2803 if (SS.isEmpty())
2804 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2805 PDiag(NoteID), AcceptableWithRecovery);
2806 else
2807 diagnoseTypo(Corrected,
2808 PDiag(diag::err_no_member_suggest)
2809 << Name << computeDeclContext(SS, false)
2810 << DroppedSpecifier << NameRange,
2811 PDiag(NoteID), AcceptableWithRecovery);
2812
2813 if (Corrected.WillReplaceSpecifier()) {
2815 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2816 SS.MakeTrivial(Context, NNS,
2817 NNS ? NameRange.getBegin() : SourceRange());
2818 }
2819
2820 // Tell the callee whether to try to recover.
2821 return !AcceptableWithRecovery;
2822 }
2823 }
2824 R.clear();
2825
2826 if (diagnoseFunctionLikeMacro(SemaRef, Name, R.getNameLoc()))
2827 return true;
2828
2829 // Emit a special diagnostic for failed member lookups.
2830 // FIXME: computing the declaration context might fail here (?)
2831 if (!SS.isEmpty()) {
2832 Diag(R.getNameLoc(), diag::err_no_member)
2833 << Name << computeDeclContext(SS, false) << NameRange;
2834 return true;
2835 }
2836
2837 // Give up, we can't recover.
2838 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2839 return true;
2840}
2841
2842/// In Microsoft mode, if we are inside a template class whose parent class has
2843/// dependent base classes, and we can't resolve an unqualified identifier, then
2844/// assume the identifier is a member of a dependent base class. We can only
2845/// recover successfully in static methods, instance methods, and other contexts
2846/// where 'this' is available. This doesn't precisely match MSVC's
2847/// instantiation model, but it's close enough.
2848static Expr *
2850 DeclarationNameInfo &NameInfo,
2851 SourceLocation TemplateKWLoc,
2852 const TemplateArgumentListInfo *TemplateArgs) {
2853 // Only try to recover from lookup into dependent bases in static methods or
2854 // contexts where 'this' is available.
2855 QualType ThisType = S.getCurrentThisType();
2856 const CXXRecordDecl *RD = nullptr;
2857 if (!ThisType.isNull())
2858 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2859 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2860 RD = MD->getParent();
2861 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2862 return nullptr;
2863
2864 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2865 // is available, suggest inserting 'this->' as a fixit.
2866 SourceLocation Loc = NameInfo.getLoc();
2867 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2868 DB << NameInfo.getName() << RD;
2869
2870 if (!ThisType.isNull()) {
2871 DB << FixItHint::CreateInsertion(Loc, "this->");
2873 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2874 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2875 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2876 }
2877
2878 // Synthesize a fake NNS that points to the derived class. This will
2879 // perform name lookup during template instantiation.
2880 CXXScopeSpec SS;
2881 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2882 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2884 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2885 TemplateArgs);
2886}
2887
2889 SourceLocation TemplateKWLoc,
2890 UnqualifiedId &Id, bool HasTrailingLParen,
2891 bool IsAddressOfOperand,
2893 bool IsInlineAsmIdentifier) {
2894 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2895 "cannot be direct & operand and have a trailing lparen");
2896 if (SS.isInvalid())
2897 return ExprError();
2898
2899 TemplateArgumentListInfo TemplateArgsBuffer;
2900
2901 // Decompose the UnqualifiedId into the following data.
2902 DeclarationNameInfo NameInfo;
2903 const TemplateArgumentListInfo *TemplateArgs;
2904 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2905
2906 DeclarationName Name = NameInfo.getName();
2908 SourceLocation NameLoc = NameInfo.getLoc();
2909
2911 Id.TemplateId->Template)
2912 if (TemplateName TN = Id.TemplateId->Template.get();
2914 return CheckVarOrConceptTemplateTemplateId(NameInfo, TN, TemplateArgs);
2915
2916 if (II && II->isEditorPlaceholder()) {
2917 // FIXME: When typed placeholders are supported we can create a typed
2918 // placeholder expression node.
2919 return ExprError();
2920 }
2921
2922 // This specially handles arguments of attributes appertains to a type of C
2923 // struct field such that the name lookup within a struct finds the member
2924 // name, which is not the case for other contexts in C.
2925 // A late-parsed attribute on a function pointer field has the pointee's
2926 // parameters in the struct's scope too; as when the attribute was written, a
2927 // parameter shadows a field of the same name.
2928 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope() &&
2929 llvm::none_of(S->decls(), [&](Decl *D) {
2930 return isa<ParmVarDecl>(D) &&
2931 cast<ParmVarDecl>(D)->getDeclName() == NameInfo.getName();
2932 })) {
2933 // See if this is reference to a field of struct.
2934 LookupResult R(*this, NameInfo, LookupMemberName);
2935 // LookupName handles a name lookup from within anonymous struct.
2936 if (LookupName(R, S)) {
2937 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2938 QualType type = VD->getType().getNonReferenceType();
2939 // This will eventually be translated into MemberExpr upon
2940 // the use of instantiated struct fields.
2941 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2942 }
2943 }
2944 }
2945
2946 // Perform the required lookup.
2947 LookupResult R(*this, NameInfo,
2951 if (TemplateKWLoc.isValid() || TemplateArgs) {
2952 // Lookup the template name again to correctly establish the context in
2953 // which it was found. This is really unfortunate as we already did the
2954 // lookup to determine that it was a template name in the first place. If
2955 // this becomes a performance hit, we can work harder to preserve those
2956 // results until we get here but it's likely not worth it.
2957 AssumedTemplateKind AssumedTemplate;
2958 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2959 /*EnteringContext=*/false, TemplateKWLoc,
2960 &AssumedTemplate))
2961 return ExprError();
2962
2963 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2964 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2965 IsAddressOfOperand, TemplateArgs);
2966 } else {
2967 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2968 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2969 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2970
2971 // If the result might be in a dependent base class, this is a dependent
2972 // id-expression.
2973 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2974 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2975 IsAddressOfOperand, TemplateArgs);
2976
2977 // If this reference is in an Objective-C method, then we need to do
2978 // some special Objective-C lookup, too.
2979 if (IvarLookupFollowUp) {
2980 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2981 if (E.isInvalid())
2982 return ExprError();
2983
2984 if (Expr *Ex = E.getAs<Expr>())
2985 return Ex;
2986 }
2987 }
2988
2989 if (R.isAmbiguous())
2990 return ExprError();
2991
2992 // This could be an implicitly declared function reference if the language
2993 // mode allows it as a feature.
2994 if (R.empty() && HasTrailingLParen && II &&
2995 getLangOpts().implicitFunctionsAllowed()) {
2996 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2997 if (D) R.addDecl(D);
2998 }
2999
3000 // Determine whether this name might be a candidate for
3001 // argument-dependent lookup.
3002 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
3003
3004 if (R.empty() && !ADL) {
3005 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
3006 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
3007 TemplateKWLoc, TemplateArgs))
3008 return E;
3009 }
3010
3011 // Don't diagnose an empty lookup for inline assembly.
3012 if (IsInlineAsmIdentifier)
3013 return ExprError();
3014
3015 // If this name wasn't predeclared and if this is not a function
3016 // call, diagnose the problem.
3017 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
3018 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
3019 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
3020 "Typo correction callback misconfigured");
3021 if (CCC) {
3022 // Make sure the callback knows what the typo being diagnosed is.
3023 CCC->setTypoName(II);
3024 if (SS.isValid())
3025 CCC->setTypoNNS(SS.getScopeRep());
3026 }
3027 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
3028 // a template name, but we happen to have always already looked up the name
3029 // before we get here if it must be a template name.
3030 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
3031 {}, nullptr))
3032 return ExprError();
3033
3034 assert(!R.empty() &&
3035 "DiagnoseEmptyLookup returned false but added no results");
3036
3037 // If we found an Objective-C instance variable, let
3038 // LookupInObjCMethod build the appropriate expression to
3039 // reference the ivar.
3040 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
3041 R.clear();
3042 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
3043 // In a hopelessly buggy code, Objective-C instance variable
3044 // lookup fails and no expression will be built to reference it.
3045 if (!E.isInvalid() && !E.get())
3046 return ExprError();
3047 return E;
3048 }
3049 }
3050
3051 // This is guaranteed from this point on.
3052 assert(!R.empty() || ADL);
3053
3054 // Check whether this might be a C++ implicit instance member access.
3055 // C++ [class.mfct.non-static]p3:
3056 // When an id-expression that is not part of a class member access
3057 // syntax and not used to form a pointer to member is used in the
3058 // body of a non-static member function of class X, if name lookup
3059 // resolves the name in the id-expression to a non-static non-type
3060 // member of some class C, the id-expression is transformed into a
3061 // class member access expression using (*this) as the
3062 // postfix-expression to the left of the . operator.
3063 //
3064 // But we don't actually need to do this for '&' operands if R
3065 // resolved to a function or overloaded function set, because the
3066 // expression is ill-formed if it actually works out to be a
3067 // non-static member function:
3068 //
3069 // C++ [expr.ref]p4:
3070 // Otherwise, if E1.E2 refers to a non-static member function. . .
3071 // [t]he expression can be used only as the left-hand operand of a
3072 // member function call.
3073 //
3074 // There are other safeguards against such uses, but it's important
3075 // to get this right here so that we don't end up making a
3076 // spuriously dependent expression if we're inside a dependent
3077 // instance method.
3078 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3079 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
3080 S);
3081
3082 if (TemplateArgs || TemplateKWLoc.isValid()) {
3083
3084 // In C++1y, if this is a variable template id, then check it
3085 // in BuildTemplateIdExpr().
3086 // The single lookup result must be a variable template declaration.
3090 assert(R.getAsSingle<TemplateDecl>() &&
3091 "There should only be one declaration found.");
3092 }
3093
3094 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
3095 }
3096
3097 return BuildDeclarationNameExpr(SS, R, ADL);
3098}
3099
3101 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3102 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3103 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3104 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
3105
3106 if (R.isAmbiguous())
3107 return ExprError();
3108
3109 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3110 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3111 NameInfo, /*TemplateArgs=*/nullptr);
3112
3113 if (R.empty()) {
3114 // Don't diagnose problems with invalid record decl, the secondary no_member
3115 // diagnostic during template instantiation is likely bogus, e.g. if a class
3116 // is invalid because it's derived from an invalid base class, then missing
3117 // members were likely supposed to be inherited.
3119 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
3120 if (CD->isInvalidDecl() || CD->isBeingDefined())
3121 return ExprError();
3122 Diag(NameInfo.getLoc(), diag::err_no_member)
3123 << NameInfo.getName() << DC << SS.getRange();
3124 return ExprError();
3125 }
3126
3127 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3128 QualType ET;
3129 TypeLocBuilder TLB;
3130 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
3131 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
3132 SS.getScopeRep(), TagD,
3133 /*OwnsTag=*/false);
3134 auto TL = TLB.push<TagTypeLoc>(ET);
3136 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3137 TL.setNameLoc(NameInfo.getLoc());
3138 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
3139 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
3140 SS.getScopeRep(), TypedefD);
3141 TLB.push<TypedefTypeLoc>(ET).set(
3142 /*ElaboratedKeywordLoc=*/SourceLocation(),
3143 SS.getWithLocInContext(Context), NameInfo.getLoc());
3144 } else {
3145 // FIXME: What else can appear here?
3146 ET = SemaRef.Context.getTypeDeclType(TD);
3147 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
3148 assert(SS.isEmpty());
3149 }
3150
3151 // Diagnose a missing typename if this resolved unambiguously to a type in
3152 // a dependent context. If we can recover with a type, downgrade this to
3153 // a warning in Microsoft compatibility mode.
3154 unsigned DiagID = diag::err_typename_missing;
3155 if (RecoveryTSI && getLangOpts().MSVCCompat)
3156 DiagID = diag::ext_typename_missing;
3157 SourceLocation Loc = SS.getBeginLoc();
3158 auto D = Diag(Loc, DiagID);
3159 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3160
3161 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3162 // context.
3163 if (!RecoveryTSI)
3164 return ExprError();
3165
3166 // Only issue the fixit if we're prepared to recover.
3167 D << FixItHint::CreateInsertion(Loc, "typename ");
3168
3169 // Recover by pretending this was an elaborated type.
3170 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3171
3172 return ExprEmpty();
3173 }
3174
3175 // If necessary, build an implicit class member access.
3176 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3178 /*TemplateKWLoc=*/SourceLocation(),
3179 R, /*TemplateArgs=*/nullptr,
3180 /*S=*/nullptr);
3181
3182 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3183}
3184
3186 NestedNameSpecifier Qualifier,
3187 NamedDecl *FoundDecl,
3188 NamedDecl *Member) {
3189 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3190 if (!RD)
3191 return From;
3192
3193 QualType DestRecordType;
3194 QualType DestType;
3195 QualType FromRecordType;
3196 QualType FromType = From->getType();
3197 bool PointerConversions = false;
3198 if (isa<FieldDecl>(Member)) {
3199 DestRecordType = Context.getCanonicalTagType(RD);
3200 auto FromPtrType = FromType->getAs<PointerType>();
3201 DestRecordType = Context.getAddrSpaceQualType(
3202 DestRecordType, FromPtrType
3203 ? FromType->getPointeeType().getAddressSpace()
3204 : FromType.getAddressSpace());
3205
3206 if (FromPtrType) {
3207 DestType = Context.getPointerType(DestRecordType);
3208 FromRecordType = FromPtrType->getPointeeType();
3209 PointerConversions = true;
3210 } else {
3211 DestType = DestRecordType;
3212 FromRecordType = FromType;
3213 }
3214 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3215 if (!Method->isImplicitObjectMemberFunction())
3216 return From;
3217
3218 DestType = Method->getThisType().getNonReferenceType();
3219 DestRecordType = Method->getFunctionObjectParameterType();
3220
3221 if (FromType->getAs<PointerType>()) {
3222 FromRecordType = FromType->getPointeeType();
3223 PointerConversions = true;
3224 } else {
3225 FromRecordType = FromType;
3226 DestType = DestRecordType;
3227 }
3228
3229 LangAS FromAS = FromRecordType.getAddressSpace();
3230 LangAS DestAS = DestRecordType.getAddressSpace();
3231 if (FromAS != DestAS) {
3232 QualType FromRecordTypeWithoutAS =
3233 Context.removeAddrSpaceQualType(FromRecordType);
3234 QualType FromTypeWithDestAS =
3235 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3236 if (PointerConversions)
3237 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3238 From = ImpCastExprToType(From, FromTypeWithDestAS,
3239 CK_AddressSpaceConversion, From->getValueKind())
3240 .get();
3241 }
3242 } else {
3243 // No conversion necessary.
3244 return From;
3245 }
3246
3247 if (DestType->isDependentType() || FromType->isDependentType())
3248 return From;
3249
3250 // If the unqualified types are the same, no conversion is necessary.
3251 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3252 return From;
3253
3254 SourceRange FromRange = From->getSourceRange();
3255 SourceLocation FromLoc = FromRange.getBegin();
3256
3257 ExprValueKind VK = From->getValueKind();
3258
3259 // C++ [class.member.lookup]p8:
3260 // [...] Ambiguities can often be resolved by qualifying a name with its
3261 // class name.
3262 //
3263 // If the member was a qualified name and the qualified referred to a
3264 // specific base subobject type, we'll cast to that intermediate type
3265 // first and then to the object in which the member is declared. That allows
3266 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3267 //
3268 // class Base { public: int x; };
3269 // class Derived1 : public Base { };
3270 // class Derived2 : public Base { };
3271 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3272 //
3273 // void VeryDerived::f() {
3274 // x = 17; // error: ambiguous base subobjects
3275 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3276 // }
3277 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3278 QualType QType = QualType(Qualifier.getAsType(), 0);
3279 assert(QType->isRecordType() && "lookup done with non-record type");
3280
3281 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3282
3283 // In C++98, the qualifier type doesn't actually have to be a base
3284 // type of the object type, in which case we just ignore it.
3285 // Otherwise build the appropriate casts.
3286 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3287 CXXCastPath BasePath;
3288 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3289 FromLoc, FromRange, &BasePath))
3290 return ExprError();
3291
3292 if (PointerConversions)
3293 QType = Context.getPointerType(QType);
3294 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3295 VK, &BasePath).get();
3296
3297 FromType = QType;
3298 FromRecordType = QRecordType;
3299
3300 // If the qualifier type was the same as the destination type,
3301 // we're done.
3302 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3303 return From;
3304 }
3305 }
3306
3307 CXXCastPath BasePath;
3308 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3309 FromLoc, FromRange, &BasePath,
3310 /*IgnoreAccess=*/true))
3311 return ExprError();
3312
3313 // Propagate qualifiers to base subobjects as per:
3314 // C++ [basic.type.qualifier]p1.2:
3315 // A volatile object is [...] a subobject of a volatile object.
3316 Qualifiers FromTypeQuals = FromType.getQualifiers();
3317 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3318 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3319
3320 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3321 &BasePath);
3322}
3323
3325 const LookupResult &R,
3326 bool HasTrailingLParen) {
3327 // Only when used directly as the postfix-expression of a call.
3328 if (!HasTrailingLParen)
3329 return false;
3330
3331 // Never if a scope specifier was provided.
3332 if (SS.isNotEmpty())
3333 return false;
3334
3335 // Only in C++ or ObjC++.
3336 if (!getLangOpts().CPlusPlus)
3337 return false;
3338
3339 // Turn off ADL when we find certain kinds of declarations during
3340 // normal lookup:
3341 for (const NamedDecl *D : R) {
3342 // C++0x [basic.lookup.argdep]p3:
3343 // -- a declaration of a class member
3344 // Since using decls preserve this property, we check this on the
3345 // original decl.
3346 if (D->isCXXClassMember())
3347 return false;
3348
3349 // C++0x [basic.lookup.argdep]p3:
3350 // -- a block-scope function declaration that is not a
3351 // using-declaration
3352 // NOTE: we also trigger this for function templates (in fact, we
3353 // don't check the decl type at all, since all other decl types
3354 // turn off ADL anyway).
3355 if (isa<UsingShadowDecl>(D))
3356 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3357 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3358 return false;
3359
3360 // C++0x [basic.lookup.argdep]p3:
3361 // -- a declaration that is neither a function or a function
3362 // template
3363 // And also for builtin functions.
3364 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3365 // But also builtin functions.
3366 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3367 return false;
3368 } else if (!isa<FunctionTemplateDecl>(D))
3369 return false;
3370 }
3371
3372 return true;
3373}
3374
3375
3376/// Diagnoses obvious problems with the use of the given declaration
3377/// as an expression. This is only actually called for lookups that
3378/// were not overloaded, and it doesn't promise that the declaration
3379/// will in fact be used.
3381 bool AcceptInvalid) {
3382 if (D->isInvalidDecl() && !AcceptInvalid)
3383 return true;
3384
3385 if (isa<TypedefNameDecl>(D)) {
3386 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3387 return true;
3388 }
3389
3390 if (isa<ObjCInterfaceDecl>(D)) {
3391 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3392 return true;
3393 }
3394
3395 if (isa<NamespaceDecl>(D)) {
3396 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3397 return true;
3398 }
3399
3400 return false;
3401}
3402
3403// Certain multiversion types should be treated as overloaded even when there is
3404// only one result.
3406 assert(R.isSingleResult() && "Expected only a single result");
3407 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3408 return FD &&
3409 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3410}
3411
3413 LookupResult &R, bool NeedsADL,
3414 bool AcceptInvalidDecl) {
3415 // If this is a single, fully-resolved result and we don't need ADL,
3416 // just build an ordinary singleton decl ref.
3417 if (!NeedsADL && R.isSingleResult() &&
3418 !R.getAsSingle<FunctionTemplateDecl>() &&
3420 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3421 R.getRepresentativeDecl(), nullptr,
3422 AcceptInvalidDecl);
3423
3424 // We only need to check the declaration if there's exactly one
3425 // result, because in the overloaded case the results can only be
3426 // functions and function templates.
3427 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3428 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3429 AcceptInvalidDecl))
3430 return ExprError();
3431
3432 // Otherwise, just build an unresolved lookup expression. Suppress
3433 // any lookup-related diagnostics; we'll hash these out later, when
3434 // we've picked a target.
3435 R.suppressDiagnostics();
3436
3438 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3439 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3440 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3441
3442 return ULE;
3443}
3444
3446 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3447 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3448 bool AcceptInvalidDecl) {
3449 assert(D && "Cannot refer to a NULL declaration");
3450 assert(!isa<FunctionTemplateDecl>(D) &&
3451 "Cannot refer unambiguously to a function template");
3452
3453 SourceLocation Loc = NameInfo.getLoc();
3454 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3455 // Recovery from invalid cases (e.g. D is an invalid Decl).
3456 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3457 // diagnostics, as invalid decls use int as a fallback type.
3458 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3459 }
3460
3461 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3462 // Specifically diagnose references to class templates that are missing
3463 // a template argument list.
3464 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3465 return ExprError();
3466 }
3467
3468 // Make sure that we're referring to a value.
3470 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3471 Diag(D->getLocation(), diag::note_declared_at);
3472 return ExprError();
3473 }
3474
3475 // Check whether this declaration can be used. Note that we suppress
3476 // this check when we're going to perform argument-dependent lookup
3477 // on this function name, because this might not be the function
3478 // that overload resolution actually selects.
3479 if (DiagnoseUseOfDecl(D, Loc))
3480 return ExprError();
3481
3482 auto *VD = cast<ValueDecl>(D);
3483
3484 // Only create DeclRefExpr's for valid Decl's.
3485 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3486 return ExprError();
3487
3488 // Handle members of anonymous structs and unions. If we got here,
3489 // and the reference is to a class member indirect field, then this
3490 // must be the subject of a pointer-to-member expression.
3491 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3492 IndirectField && !IndirectField->isCXXClassMember())
3494 IndirectField);
3495
3496 QualType type = VD->getType();
3497 if (type.isNull())
3498 return ExprError();
3499 ExprValueKind valueKind = VK_PRValue;
3500
3501 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3502 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3503 // is expanded by some outer '...' in the context of the use.
3504 type = type.getNonPackExpansionType();
3505
3506 switch (D->getKind()) {
3507 // Ignore all the non-ValueDecl kinds.
3508#define ABSTRACT_DECL(kind)
3509#define VALUE(type, base)
3510#define DECL(type, base) case Decl::type:
3511#include "clang/AST/DeclNodes.inc"
3512 llvm_unreachable("invalid value decl kind");
3513
3514 // These shouldn't make it here.
3515 case Decl::ObjCAtDefsField:
3516 llvm_unreachable("forming non-member reference to ivar?");
3517
3518 // Enum constants are always r-values and never references.
3519 // Unresolved using declarations are dependent.
3520 case Decl::EnumConstant:
3521 case Decl::UnresolvedUsingValue:
3522 case Decl::OMPDeclareReduction:
3523 case Decl::OMPDeclareMapper:
3524 valueKind = VK_PRValue;
3525 break;
3526
3527 // Fields and indirect fields that got here must be for
3528 // pointer-to-member expressions; we just call them l-values for
3529 // internal consistency, because this subexpression doesn't really
3530 // exist in the high-level semantics.
3531 case Decl::Field:
3532 case Decl::IndirectField:
3533 case Decl::ObjCIvar:
3534 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3535 "building reference to field in C?");
3536
3537 // These can't have reference type in well-formed programs, but
3538 // for internal consistency we do this anyway.
3539 type = type.getNonReferenceType();
3540 valueKind = VK_LValue;
3541 break;
3542
3543 // Non-type template parameters are either l-values or r-values
3544 // depending on the type.
3545 case Decl::NonTypeTemplateParm: {
3546 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3547 type = reftype->getPointeeType();
3548 valueKind = VK_LValue; // even if the parameter is an r-value reference
3549 break;
3550 }
3551
3552 // [expr.prim.id.unqual]p2:
3553 // If the entity is a template parameter object for a template
3554 // parameter of type T, the type of the expression is const T.
3555 // [...] The expression is an lvalue if the entity is a [...] template
3556 // parameter object.
3557 if (type->isRecordType()) {
3558 type = type.getUnqualifiedType().withConst();
3559 valueKind = VK_LValue;
3560 break;
3561 }
3562
3563 // For non-references, we need to strip qualifiers just in case
3564 // the template parameter was declared as 'const int' or whatever.
3565 valueKind = VK_PRValue;
3566 type = type.getUnqualifiedType();
3567 break;
3568 }
3569
3570 case Decl::Var:
3571 case Decl::VarTemplateSpecialization:
3572 case Decl::VarTemplatePartialSpecialization:
3573 case Decl::Decomposition:
3574 case Decl::Binding:
3575 case Decl::OMPCapturedExpr:
3576 // In C, "extern void blah;" is valid and is an r-value.
3577 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3578 type->isVoidType()) {
3579 valueKind = VK_PRValue;
3580 break;
3581 }
3582 [[fallthrough]];
3583
3584 case Decl::ImplicitParam:
3585 case Decl::ParmVar: {
3586 // These are always l-values.
3587 valueKind = VK_LValue;
3588 type = type.getNonReferenceType();
3589
3590 // FIXME: Does the addition of const really only apply in
3591 // potentially-evaluated contexts? Since the variable isn't actually
3592 // captured in an unevaluated context, it seems that the answer is no.
3593 if (!isUnevaluatedContext()) {
3594 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3595 if (!CapturedType.isNull())
3596 type = CapturedType;
3597 }
3598 break;
3599 }
3600
3601 case Decl::Function: {
3602 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3603 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3604 type = Context.BuiltinFnTy;
3605 valueKind = VK_PRValue;
3606 break;
3607 }
3608 }
3609
3610 const FunctionType *fty = type->castAs<FunctionType>();
3611
3612 // If we're referring to a function with an __unknown_anytype
3613 // result type, make the entire expression __unknown_anytype.
3614 if (fty->getReturnType() == Context.UnknownAnyTy) {
3615 type = Context.UnknownAnyTy;
3616 valueKind = VK_PRValue;
3617 break;
3618 }
3619
3620 // Functions are l-values in C++.
3621 if (getLangOpts().CPlusPlus) {
3622 valueKind = VK_LValue;
3623 break;
3624 }
3625
3626 // C99 DR 316 says that, if a function type comes from a
3627 // function definition (without a prototype), that type is only
3628 // used for checking compatibility. Therefore, when referencing
3629 // the function, we pretend that we don't have the full function
3630 // type.
3631 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3632 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3633 fty->getExtInfo());
3634
3635 // Functions are r-values in C.
3636 valueKind = VK_PRValue;
3637 break;
3638 }
3639
3640 case Decl::CXXDeductionGuide:
3641 llvm_unreachable("building reference to deduction guide");
3642
3643 case Decl::MSProperty:
3644 case Decl::MSGuid:
3645 case Decl::TemplateParamObject:
3646 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3647 // capture in OpenMP, or duplicated between host and device?
3648 valueKind = VK_LValue;
3649 break;
3650
3651 case Decl::UnnamedGlobalConstant:
3652 valueKind = VK_LValue;
3653 break;
3654
3655 case Decl::CXXMethod:
3656 // If we're referring to a method with an __unknown_anytype
3657 // result type, make the entire expression __unknown_anytype.
3658 // This should only be possible with a type written directly.
3659 if (const FunctionProtoType *proto =
3660 dyn_cast<FunctionProtoType>(VD->getType()))
3661 if (proto->getReturnType() == Context.UnknownAnyTy) {
3662 type = Context.UnknownAnyTy;
3663 valueKind = VK_PRValue;
3664 break;
3665 }
3666
3667 // C++ methods are l-values if static, r-values if non-static.
3668 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3669 valueKind = VK_LValue;
3670 break;
3671 }
3672 [[fallthrough]];
3673
3674 case Decl::CXXConversion:
3675 case Decl::CXXDestructor:
3676 case Decl::CXXConstructor:
3677 valueKind = VK_PRValue;
3678 break;
3679 }
3680
3681 auto *E =
3682 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3683 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3684 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3685 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3686 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3687 // diagnostics).
3688 if (VD->isInvalidDecl() && E)
3689 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3690 return E;
3691}
3692
3693static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3695 Target.resize(CharByteWidth * (Source.size() + 1));
3696 char *ResultPtr = &Target[0];
3697 const llvm::UTF8 *ErrorPtr;
3698 bool success =
3699 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3700 (void)success;
3701 assert(success);
3702 Target.resize(ResultPtr - &Target[0]);
3703}
3704
3707 Decl *currentDecl = getPredefinedExprDecl(*this, CurContext);
3708 if (!currentDecl) {
3709 Diag(Loc, diag::ext_predef_outside_function);
3710 currentDecl = Context.getTranslationUnitDecl();
3711 }
3712
3713 QualType ResTy;
3714 StringLiteral *SL = nullptr;
3715 if (cast<DeclContext>(currentDecl)->isDependentContext())
3716 ResTy = Context.DependentTy;
3717 else {
3718 // Pre-defined identifiers are of type char[x], where x is the length of
3719 // the string.
3720 bool ForceElaboratedPrinting =
3721 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3722 auto Str =
3723 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3724 unsigned Length = Str.length();
3725
3726 llvm::APInt LengthI(32, Length + 1);
3729 ResTy =
3730 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3731 SmallString<32> RawChars;
3732 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3733 Str, RawChars);
3734 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3736 /*IndexTypeQuals*/ 0);
3738 /*Pascal*/ false, ResTy, Loc);
3739 } else {
3740 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3741 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3743 /*IndexTypeQuals*/ 0);
3745 /*Pascal*/ false, ResTy, Loc);
3746 }
3747 }
3748
3749 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3750 SL);
3751}
3752
3756
3758 SmallString<16> CharBuffer;
3759 bool Invalid = false;
3760 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3761 if (Invalid)
3762 return ExprError();
3763
3764 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3765 PP, Tok.getKind());
3766 if (Literal.hadError())
3767 return ExprError();
3768
3769 QualType Ty;
3770 if (Literal.isWide())
3771 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3772 else if (Literal.isUTF8() && getLangOpts().C23)
3773 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3774 else if (Literal.isUTF8() && getLangOpts().Char8)
3775 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3776 else if (Literal.isUTF16())
3777 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3778 else if (Literal.isUTF32())
3779 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3780 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3781 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3782 else
3783 Ty = Context.CharTy; // 'x' -> char in C++;
3784 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3785
3787 if (Literal.isWide())
3789 else if (Literal.isUTF16())
3791 else if (Literal.isUTF32())
3793 else if (Literal.isUTF8())
3795
3796 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3797 Tok.getLocation());
3798
3799 if (Literal.getUDSuffix().empty())
3800 return Lit;
3801
3802 // We're building a user-defined literal.
3803 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3804 SourceLocation UDSuffixLoc =
3805 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3806
3807 // Make sure we're allowed user-defined literals here.
3808 if (!UDLScope)
3809 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3810
3811 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3812 // operator "" X (ch)
3813 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3814 Lit, Tok.getLocation());
3815}
3816
3818 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3820 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3821 Context.IntTy, Loc);
3822}
3823
3825 ExprResult Inner;
3826 if (getLangOpts().CPlusPlus) {
3827 Inner = ActOnCXXBoolLiteral(Loc, Value ? tok::kw_true : tok::kw_false);
3828 } else {
3829 // C doesn't actually have a way to represent literal values of type
3830 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3831 Inner = ActOnIntegerConstant(Loc, Value ? 1 : 0);
3832 Inner =
3833 ImpCastExprToType(Inner.get(), Context.BoolTy, CK_IntegralToBoolean);
3834 }
3835 return Inner;
3836}
3837
3839 QualType Ty, SourceLocation Loc) {
3840 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3841
3842 using llvm::APFloat;
3843 APFloat Val(Format);
3844
3845 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3846 if (RM == llvm::RoundingMode::Dynamic)
3847 RM = llvm::RoundingMode::NearestTiesToEven;
3848 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3849
3850 // Overflow is always an error, but underflow is only an error if
3851 // we underflowed to zero (APFloat reports denormals as underflow).
3852 if ((result & APFloat::opOverflow) ||
3853 ((result & APFloat::opUnderflow) && Val.isZero())) {
3854 unsigned diagnostic;
3855 SmallString<20> buffer;
3856 if (result & APFloat::opOverflow) {
3857 diagnostic = diag::warn_float_overflow;
3858 APFloat::getLargest(Format).toString(buffer);
3859 } else {
3860 diagnostic = diag::warn_float_underflow;
3861 APFloat::getSmallest(Format).toString(buffer);
3862 }
3863
3864 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3865 }
3866
3867 bool isExact = (result == APFloat::opOK);
3868 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3869}
3870
3871bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3872 assert(E && "Invalid expression");
3873
3874 if (E->isValueDependent())
3875 return false;
3876
3877 QualType QT = E->getType();
3878 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3879 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3880 return true;
3881 }
3882
3883 llvm::APSInt ValueAPS;
3885
3886 if (R.isInvalid())
3887 return true;
3888
3889 // GCC allows the value of unroll count to be 0.
3890 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3891 // "The values of 0 and 1 block any unrolling of the loop."
3892 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3893 // '#pragma unroll' cases.
3894 bool ValueIsPositive =
3895 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3896 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3897 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3898 << toString(ValueAPS, 10) << ValueIsPositive;
3899 return true;
3900 }
3901
3902 return false;
3903}
3904
3906 // Fast path for a single digit (which is quite common). A single digit
3907 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3908 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3909 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3910 return ActOnIntegerConstant(Tok.getLocation(), Val);
3911 }
3912
3913 SmallString<128> SpellingBuffer;
3914 // NumericLiteralParser wants to overread by one character. Add padding to
3915 // the buffer in case the token is copied to the buffer. If getSpelling()
3916 // returns a StringRef to the memory buffer, it should have a null char at
3917 // the EOF, so it is also safe.
3918 SpellingBuffer.resize(Tok.getLength() + 1);
3919
3920 // Get the spelling of the token, which eliminates trigraphs, etc.
3921 bool Invalid = false;
3922 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3923 if (Invalid)
3924 return ExprError();
3925
3926 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3927 PP.getSourceManager(), PP.getLangOpts(),
3928 PP.getTargetInfo(), PP.getDiagnostics());
3929 if (Literal.hadError)
3930 return ExprError();
3931
3932 if (Literal.hasUDSuffix()) {
3933 // We're building a user-defined literal.
3934 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3935 SourceLocation UDSuffixLoc =
3936 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3937
3938 // Make sure we're allowed user-defined literals here.
3939 if (!UDLScope)
3940 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3941
3942 QualType CookedTy;
3943 if (Literal.isFloatingLiteral()) {
3944 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3945 // long double, the literal is treated as a call of the form
3946 // operator "" X (f L)
3947 CookedTy = Context.LongDoubleTy;
3948 } else {
3949 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3950 // unsigned long long, the literal is treated as a call of the form
3951 // operator "" X (n ULL)
3952 CookedTy = Context.UnsignedLongLongTy;
3953 }
3954
3955 DeclarationName OpName =
3956 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3957 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3958 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3959
3960 SourceLocation TokLoc = Tok.getLocation();
3961
3962 // Perform literal operator lookup to determine if we're building a raw
3963 // literal or a cooked one.
3964 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3965 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3966 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3967 /*AllowStringTemplatePack*/ false,
3968 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3970 // Lookup failure for imaginary constants isn't fatal, there's still the
3971 // GNU extension producing _Complex types.
3972 break;
3973 case LOLR_Error:
3974 return ExprError();
3975 case LOLR_Cooked: {
3976 Expr *Lit;
3977 if (Literal.isFloatingLiteral()) {
3978 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3979 } else {
3980 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3981 if (Literal.GetIntegerValue(ResultVal))
3982 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3983 << /* Unsigned */ 1;
3984 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3985 Tok.getLocation());
3986 }
3987 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3988 }
3989
3990 case LOLR_Raw: {
3991 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3992 // literal is treated as a call of the form
3993 // operator "" X ("n")
3994 unsigned Length = Literal.getUDSuffixOffset();
3995 QualType StrTy = Context.getConstantArrayType(
3996 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3997 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3998 Expr *Lit =
3999 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
4001 /*Pascal*/ false, StrTy, TokLoc);
4002 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4003 }
4004
4005 case LOLR_Template: {
4006 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
4007 // template), L is treated as a call fo the form
4008 // operator "" X <'c1', 'c2', ... 'ck'>()
4009 // where n is the source character sequence c1 c2 ... ck.
4010 TemplateArgumentListInfo ExplicitArgs;
4011 unsigned CharBits = Context.getIntWidth(Context.CharTy);
4012 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4013 llvm::APSInt Value(CharBits, CharIsUnsigned);
4014 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4015 Value = TokSpelling[I];
4016 TemplateArgument Arg(Context, Value, Context.CharTy);
4018 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
4019 }
4020 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
4021 }
4023 llvm_unreachable("unexpected literal operator lookup result");
4024 }
4025 }
4026
4027 Expr *Res;
4028
4029 if (Literal.isFixedPointLiteral()) {
4030 QualType Ty;
4031
4032 if (Literal.isAccum) {
4033 if (Literal.isHalf) {
4034 Ty = Context.ShortAccumTy;
4035 } else if (Literal.isLong) {
4036 Ty = Context.LongAccumTy;
4037 } else {
4038 Ty = Context.AccumTy;
4039 }
4040 } else if (Literal.isFract) {
4041 if (Literal.isHalf) {
4042 Ty = Context.ShortFractTy;
4043 } else if (Literal.isLong) {
4044 Ty = Context.LongFractTy;
4045 } else {
4046 Ty = Context.FractTy;
4047 }
4048 }
4049
4050 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
4051
4052 bool isSigned = !Literal.isUnsigned;
4053 unsigned scale = Context.getFixedPointScale(Ty);
4054 unsigned bit_width = Context.getTypeInfo(Ty).Width;
4055
4056 llvm::APInt Val(bit_width, 0, isSigned);
4057 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
4058 bool ValIsZero = Val.isZero() && !Overflowed;
4059
4060 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4061 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4062 // Clause 6.4.4 - The value of a constant shall be in the range of
4063 // representable values for its type, with exception for constants of a
4064 // fract type with a value of exactly 1; such a constant shall denote
4065 // the maximal value for the type.
4066 --Val;
4067 else if (Val.ugt(MaxVal) || Overflowed)
4068 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4069
4071 Tok.getLocation(), scale);
4072 } else if (Literal.isFloatingLiteral()) {
4073 QualType Ty;
4074 if (Literal.isHalf){
4075 if (getLangOpts().HLSL ||
4076 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4077 Ty = Context.HalfTy;
4078 else {
4079 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4080 return ExprError();
4081 }
4082 } else if (Literal.isFloat)
4083 Ty = Context.FloatTy;
4084 else if (Literal.isLong)
4085 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4086 else if (Literal.isFloat16)
4087 Ty = Context.Float16Ty;
4088 else if (Literal.isFloat128)
4089 Ty = Context.Float128Ty;
4090 else if (getLangOpts().HLSL)
4091 Ty = Context.FloatTy;
4092 else
4093 Ty = Context.DoubleTy;
4094
4095 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4096
4097 if (Ty == Context.DoubleTy) {
4098 if (getLangOpts().SinglePrecisionConstants) {
4099 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4100 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4101 }
4102 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4103 "cl_khr_fp64", getLangOpts())) {
4104 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4105 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4107 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4108 }
4109 }
4110 } else if (!Literal.isIntegerLiteral()) {
4111 return ExprError();
4112 } else {
4113 QualType Ty;
4114
4115 // 'z/uz' literals are a C++23 feature.
4116 if (Literal.isSizeT) {
4117 if (getLangOpts().CPlusPlus)
4118 DiagCompat(Tok.getLocation(), diag_compat::size_t_suffix);
4119 else
4120 Diag(Tok.getLocation(), diag::err_cxx23_size_t_suffix);
4121 }
4122
4123 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4124 // but we do not currently support the suffix in C++ mode because it's not
4125 // entirely clear whether WG21 will prefer this suffix to return a library
4126 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4127 // literals are a C++ extension.
4128 if (Literal.isBitInt)
4129 PP.Diag(Tok.getLocation(),
4130 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4131 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4132 : diag::ext_c23_bitint_suffix);
4133
4134 // Get the value in the widest-possible width. What is "widest" depends on
4135 // whether the literal is a bit-precise integer or not. For a bit-precise
4136 // integer type, try to scan the source to determine how many bits are
4137 // needed to represent the value. This may seem a bit expensive, but trying
4138 // to get the integer value from an overly-wide APInt is *extremely*
4139 // expensive, so the naive approach of assuming
4140 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4141 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4142 if (Literal.isBitInt)
4143 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4144 Literal.getLiteralDigits(), Literal.getRadix());
4145 if (Literal.MicrosoftInteger) {
4146 if (Literal.MicrosoftInteger == 128 &&
4147 !Context.getTargetInfo().hasInt128Type())
4148 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4149 << Literal.isUnsigned;
4150 BitsNeeded = std::max<unsigned>(BitsNeeded, Literal.MicrosoftInteger);
4151 }
4152
4153 llvm::APInt ResultVal(BitsNeeded, 0);
4154
4155 if (Literal.GetIntegerValue(ResultVal)) {
4156 // If this value didn't fit into uintmax_t, error and force to ull.
4157 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4158 << /* Unsigned */ 1;
4159 Ty = Context.UnsignedLongLongTy;
4160 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4161 "long long is not intmax_t?");
4162 } else {
4163 // If this value fits into a ULL, try to figure out what else it fits into
4164 // according to the rules of C99 6.4.4.1p5.
4165
4166 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4167 // be an unsigned int.
4168 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4169
4170 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4171 // suffix for portability of code with C++, but both `l` and `ll` are
4172 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4173 // same.
4174 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4175 Literal.isLong = true;
4176 Literal.isLongLong = false;
4177 }
4178
4179 // Check from smallest to largest, picking the smallest type we can.
4180 unsigned Width = 0;
4181
4182 // Microsoft specific integer suffixes are explicitly sized.
4183 if (Literal.MicrosoftInteger) {
4184 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4185 Width = 8;
4186 Ty = Context.CharTy;
4187 } else {
4188 Width = Literal.MicrosoftInteger;
4189 Ty = Context.getIntTypeForBitwidth(Width,
4190 /*Signed=*/!Literal.isUnsigned);
4191 }
4192 // To maintain consistency with MSVC, we chose to truncate directly
4193 // without issuing any warnings.
4194 ResultVal = ResultVal.zextOrTrunc(Width);
4195 }
4196
4197 // Bit-precise integer literals are automagically-sized based on the
4198 // width required by the literal.
4199 if (Literal.isBitInt) {
4200 // The signed version has one more bit for the sign value. There are no
4201 // zero-width bit-precise integers, even if the literal value is 0.
4202 Width = std::max(ResultVal.getActiveBits(), 1u) +
4203 (Literal.isUnsigned ? 0u : 1u);
4204
4205 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4206 // and reset the type to the largest supported width.
4207 unsigned int MaxBitIntWidth =
4208 Context.getTargetInfo().getMaxBitIntWidth();
4209 if (Width > MaxBitIntWidth) {
4210 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4211 << Literal.isUnsigned;
4212 Width = MaxBitIntWidth;
4213 }
4214
4215 // Reset the result value to the smaller APInt and select the correct
4216 // type to be used. Note, we zext even for signed values because the
4217 // literal itself is always an unsigned value (a preceeding - is a
4218 // unary operator, not part of the literal).
4219 ResultVal = ResultVal.zextOrTrunc(Width);
4220 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4221 }
4222
4223 // Check C++23 size_t literals.
4224 if (Literal.isSizeT) {
4225 assert(!Literal.MicrosoftInteger &&
4226 "size_t literals can't be Microsoft literals");
4227 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4228 Context.getTargetInfo().getSizeType());
4229
4230 // Does it fit in size_t?
4231 if (ResultVal.isIntN(SizeTSize)) {
4232 // Does it fit in ssize_t?
4233 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4234 Ty = Context.getSignedSizeType();
4235 else if (AllowUnsigned)
4236 Ty = Context.getSizeType();
4237 Width = SizeTSize;
4238 }
4239 }
4240
4241 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4242 !Literal.isSizeT) {
4243 // Are int/unsigned possibilities?
4244 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4245
4246 // Does it fit in a unsigned int?
4247 if (ResultVal.isIntN(IntSize)) {
4248 // Does it fit in a signed int?
4249 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4250 Ty = Context.IntTy;
4251 else if (AllowUnsigned)
4252 Ty = Context.UnsignedIntTy;
4253 Width = IntSize;
4254 }
4255 }
4256
4257 // Are long/unsigned long possibilities?
4258 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4259 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4260
4261 // Does it fit in a unsigned long?
4262 if (ResultVal.isIntN(LongSize)) {
4263 // Does it fit in a signed long?
4264 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4265 Ty = Context.LongTy;
4266 else if (AllowUnsigned)
4267 Ty = Context.UnsignedLongTy;
4268 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4269 // is compatible.
4270 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4271 const unsigned LongLongSize =
4272 Context.getTargetInfo().getLongLongWidth();
4273 Diag(Tok.getLocation(),
4275 ? Literal.isLong
4276 ? diag::warn_old_implicitly_unsigned_long_cxx
4277 : /*C++98 UB*/ diag::
4278 ext_old_implicitly_unsigned_long_cxx
4279 : diag::warn_old_implicitly_unsigned_long)
4280 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4281 : /*will be ill-formed*/ 1);
4282 Ty = Context.UnsignedLongTy;
4283 }
4284 Width = LongSize;
4285 }
4286 }
4287
4288 // Check long long if needed.
4289 if (Ty.isNull() && !Literal.isSizeT) {
4290 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4291
4292 // Does it fit in a unsigned long long?
4293 if (ResultVal.isIntN(LongLongSize)) {
4294 // Does it fit in a signed long long?
4295 // To be compatible with MSVC, hex integer literals ending with the
4296 // LL or i64 suffix are always signed in Microsoft mode.
4297 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4298 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4299 Ty = Context.LongLongTy;
4300 else if (AllowUnsigned)
4301 Ty = Context.UnsignedLongLongTy;
4302 Width = LongLongSize;
4303
4304 // 'long long' is a C99 or C++11 feature, whether the literal
4305 // explicitly specified 'long long' or we needed the extra width.
4306 if (getLangOpts().CPlusPlus)
4307 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4308 ? diag::warn_cxx98_compat_longlong
4309 : diag::ext_cxx11_longlong);
4310 else if (!getLangOpts().C99)
4311 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4312 }
4313 }
4314
4315 // If we still couldn't decide a type, we either have 'size_t' literal
4316 // that is out of range, or a decimal literal that does not fit in a
4317 // signed long long and has no U suffix.
4318 if (Ty.isNull()) {
4319 if (Literal.isSizeT)
4320 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4321 << Literal.isUnsigned;
4322 else
4323 Diag(Tok.getLocation(),
4324 diag::ext_integer_literal_too_large_for_signed);
4325 Ty = Context.UnsignedLongLongTy;
4326 Width = Context.getTargetInfo().getLongLongWidth();
4327 }
4328
4329 if (ResultVal.getBitWidth() != Width)
4330 ResultVal = ResultVal.trunc(Width);
4331 }
4332 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4333 }
4334
4335 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4336 if (Literal.isImaginary) {
4337 Res = new (Context) ImaginaryLiteral(Res,
4338 Context.getComplexType(Res->getType()));
4339
4340 // In C++, this is a GNU extension. In C, it's a C2y extension.
4341 if (getLangOpts().CPlusPlus)
4342 Diag(Tok.getLocation(), diag::ext_gnu_imaginary_constant);
4343 else
4344 DiagCompat(Tok.getLocation(), diag_compat::imaginary_constant);
4345 }
4346 return Res;
4347}
4348
4350 assert(E && "ActOnParenExpr() missing expr");
4351 QualType ExprTy = E->getType();
4352 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4353 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4354 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4355 return new (Context) ParenExpr(L, R, E);
4356}
4357
4359 SourceLocation Loc,
4360 SourceRange ArgRange) {
4361 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4362 // scalar or vector data type argument..."
4363 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4364 // type (C99 6.2.5p18) or void.
4365 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4366 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4367 << T << ArgRange;
4368 return true;
4369 }
4370
4371 assert((T->isVoidType() || !T->isIncompleteType()) &&
4372 "Scalar types should always be complete");
4373 return false;
4374}
4375
4377 SourceLocation Loc,
4378 SourceRange ArgRange) {
4379 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4380 if (!T->isVectorType() && !T->isSizelessVectorType())
4381 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4382 << ""
4383 << "__builtin_vectorelements" << T << ArgRange;
4384
4385 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
4386 if (T->isSVESizelessBuiltinType()) {
4387 llvm::StringMap<bool> CallerFeatureMap;
4388 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
4389 return S.ARM().checkSVETypeSupport(T, Loc, FD, CallerFeatureMap);
4390 }
4391 }
4392
4393 return false;
4394}
4395
4397 SourceLocation Loc,
4398 SourceRange ArgRange) {
4399 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4400 return true;
4401
4402 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4403 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4404 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4405 return true;
4406 }
4407
4408 return false;
4409}
4410
4412 SourceLocation Loc,
4413 SourceRange ArgRange,
4414 UnaryExprOrTypeTrait TraitKind) {
4415 // Invalid types must be hard errors for SFINAE in C++.
4416 if (S.LangOpts.CPlusPlus)
4417 return true;
4418
4419 // C99 6.5.3.4p1:
4420 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4421 TraitKind == UETT_PreferredAlignOf) {
4422
4423 // sizeof(function)/alignof(function) is allowed as an extension.
4424 if (T->isFunctionType()) {
4425 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4426 << getTraitSpelling(TraitKind) << ArgRange;
4427 return false;
4428 }
4429
4430 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4431 // this is an error (OpenCL v1.1 s6.3.k)
4432 if (T->isVoidType()) {
4433 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4434 : diag::ext_sizeof_alignof_void_type;
4435 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4436 return false;
4437 }
4438 }
4439 return true;
4440}
4441
4443 SourceLocation Loc,
4444 SourceRange ArgRange,
4445 UnaryExprOrTypeTrait TraitKind) {
4446 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4447 // runtime doesn't allow it.
4448 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4449 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4450 << T << (TraitKind == UETT_SizeOf)
4451 << ArgRange;
4452 return true;
4453 }
4454
4455 return false;
4456}
4457
4458/// Check whether E is a pointer from a decayed array type (the decayed
4459/// pointer type is equal to T) and emit a warning if it is.
4461 const Expr *E) {
4462 // Don't warn if the operation changed the type.
4463 if (T != E->getType())
4464 return;
4465
4466 // Now look for array decays.
4467 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4468 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4469 return;
4470
4471 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4472 << ICE->getType()
4473 << ICE->getSubExpr()->getType();
4474}
4475
4477 UnaryExprOrTypeTrait ExprKind) {
4478 QualType ExprTy = E->getType();
4479 assert(!ExprTy->isReferenceType());
4480
4481 bool IsUnevaluatedOperand =
4482 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4483 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4484 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4485 if (IsUnevaluatedOperand) {
4487 if (Result.isInvalid())
4488 return true;
4489 E = Result.get();
4490 }
4491
4492 // The operand for sizeof and alignof is in an unevaluated expression context,
4493 // so side effects could result in unintended consequences.
4494 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4495 // used to build SFINAE gadgets.
4496 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4497 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4499 !E->getType()->isVariableArrayType() &&
4500 E->HasSideEffects(Context, false))
4501 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4502
4503 if (ExprKind == UETT_VecStep)
4504 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4505 E->getSourceRange());
4506
4507 if (ExprKind == UETT_VectorElements)
4508 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4509 E->getSourceRange());
4510
4511 // Explicitly list some types as extensions.
4512 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4513 E->getSourceRange(), ExprKind))
4514 return false;
4515
4516 // WebAssembly tables are always illegal operands to unary expressions and
4517 // type traits.
4518 if (Context.getTargetInfo().getTriple().isWasm() &&
4520 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4521 << getTraitSpelling(ExprKind);
4522 return true;
4523 }
4524
4525 // 'alignof' applied to an expression only requires the base element type of
4526 // the expression to be complete. 'sizeof' requires the expression's type to
4527 // be complete (and will attempt to complete it if it's an array of unknown
4528 // bound).
4529 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4531 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4532 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4533 getTraitSpelling(ExprKind), E->getSourceRange()))
4534 return true;
4535 } else {
4537 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4538 getTraitSpelling(ExprKind), E->getSourceRange()))
4539 return true;
4540 }
4541
4542 // Completing the expression's type may have changed it.
4543 ExprTy = E->getType();
4544 assert(!ExprTy->isReferenceType());
4545
4546 if (ExprTy->isFunctionType()) {
4547 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4548 << getTraitSpelling(ExprKind) << E->getSourceRange();
4549 return true;
4550 }
4551
4552 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4553 E->getSourceRange(), ExprKind))
4554 return true;
4555
4556 if (ExprKind == UETT_CountOf) {
4557 // The type has to be an array type. We already checked for incomplete
4558 // types above.
4559 QualType ExprType = E->IgnoreParens()->getType();
4560 if (!ExprType->isArrayType()) {
4561 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4562 return true;
4563 }
4564 // FIXME: warn on _Countof on an array parameter. Not warning on it
4565 // currently because there are papers in WG14 about array types which do
4566 // not decay that could impact this behavior, so we want to see if anything
4567 // changes here before coming up with a warning group for _Countof-related
4568 // diagnostics.
4569 }
4570
4571 if (ExprKind == UETT_SizeOf) {
4572 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4573 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4574 QualType OType = PVD->getOriginalType();
4575 QualType Type = PVD->getType();
4576 if (Type->isPointerType() && OType->isArrayType()) {
4577 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4578 << Type << OType;
4579 Diag(PVD->getLocation(), diag::note_declared_at);
4580 }
4581 }
4582 }
4583
4584 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4585 // decays into a pointer and returns an unintended result. This is most
4586 // likely a typo for "sizeof(array) op x".
4587 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4588 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4589 BO->getLHS());
4590 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4591 BO->getRHS());
4592 }
4593 }
4594
4595 return false;
4596}
4597
4598static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4599 // Cannot know anything else if the expression is dependent.
4600 if (E->isTypeDependent())
4601 return false;
4602
4603 if (E->getObjectKind() == OK_BitField) {
4604 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4605 << 1 << E->getSourceRange();
4606 return true;
4607 }
4608
4609 ValueDecl *D = nullptr;
4610 Expr *Inner = E->IgnoreParens();
4611 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4612 D = DRE->getDecl();
4613 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4614 D = ME->getMemberDecl();
4615 }
4616
4617 // If it's a field, require the containing struct to have a
4618 // complete definition so that we can compute the layout.
4619 //
4620 // This can happen in C++11 onwards, either by naming the member
4621 // in a way that is not transformed into a member access expression
4622 // (in an unevaluated operand, for instance), or by naming the member
4623 // in a trailing-return-type.
4624 //
4625 // For the record, since __alignof__ on expressions is a GCC
4626 // extension, GCC seems to permit this but always gives the
4627 // nonsensical answer 0.
4628 //
4629 // We don't really need the layout here --- we could instead just
4630 // directly check for all the appropriate alignment-lowing
4631 // attributes --- but that would require duplicating a lot of
4632 // logic that just isn't worth duplicating for such a marginal
4633 // use-case.
4634 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4635 // Fast path this check, since we at least know the record has a
4636 // definition if we can find a member of it.
4637 if (!FD->getParent()->isCompleteDefinition()) {
4638 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4639 << E->getSourceRange();
4640 return true;
4641 }
4642
4643 // Otherwise, if it's a field, and the field doesn't have
4644 // reference type, then it must have a complete type (or be a
4645 // flexible array member, which we explicitly want to
4646 // white-list anyway), which makes the following checks trivial.
4647 if (!FD->getType()->isReferenceType())
4648 return false;
4649 }
4650
4651 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4652}
4653
4655 E = E->IgnoreParens();
4656
4657 // Cannot know anything else if the expression is dependent.
4658 if (E->isTypeDependent())
4659 return false;
4660
4661 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4662}
4663
4665 CapturingScopeInfo *CSI) {
4666 assert(T->isVariablyModifiedType());
4667 assert(CSI != nullptr);
4668
4669 // We're going to walk down into the type and look for VLA expressions.
4670 do {
4671 const Type *Ty = T.getTypePtr();
4672 switch (Ty->getTypeClass()) {
4673#define TYPE(Class, Base)
4674#define ABSTRACT_TYPE(Class, Base)
4675#define NON_CANONICAL_TYPE(Class, Base)
4676#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4677#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4678#include "clang/AST/TypeNodes.inc"
4679 T = QualType();
4680 break;
4681 // These types are never variably-modified.
4682 case Type::Builtin:
4683 case Type::Complex:
4684 case Type::Vector:
4685 case Type::ExtVector:
4686 case Type::ConstantMatrix:
4687 case Type::Record:
4688 case Type::Enum:
4689 case Type::TemplateSpecialization:
4690 case Type::ObjCObject:
4691 case Type::ObjCInterface:
4692 case Type::ObjCObjectPointer:
4693 case Type::ObjCTypeParam:
4694 case Type::Pipe:
4695 case Type::BitInt:
4696 case Type::HLSLInlineSpirv:
4697 llvm_unreachable("type class is never variably-modified!");
4698 case Type::Adjusted:
4699 T = cast<AdjustedType>(Ty)->getOriginalType();
4700 break;
4701 case Type::Decayed:
4702 T = cast<DecayedType>(Ty)->getPointeeType();
4703 break;
4704 case Type::ArrayParameter:
4705 T = cast<ArrayParameterType>(Ty)->getElementType();
4706 break;
4707 case Type::Pointer:
4708 T = cast<PointerType>(Ty)->getPointeeType();
4709 break;
4710 case Type::BlockPointer:
4711 T = cast<BlockPointerType>(Ty)->getPointeeType();
4712 break;
4713 case Type::LValueReference:
4714 case Type::RValueReference:
4715 T = cast<ReferenceType>(Ty)->getPointeeType();
4716 break;
4717 case Type::MemberPointer:
4718 T = cast<MemberPointerType>(Ty)->getPointeeType();
4719 break;
4720 case Type::ConstantArray:
4721 case Type::IncompleteArray:
4722 // Losing element qualification here is fine.
4723 T = cast<ArrayType>(Ty)->getElementType();
4724 break;
4725 case Type::VariableArray: {
4726 // Losing element qualification here is fine.
4728
4729 // Unknown size indication requires no size computation.
4730 // Otherwise, evaluate and record it.
4731 auto Size = VAT->getSizeExpr();
4732 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4734 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4735
4736 T = VAT->getElementType();
4737 break;
4738 }
4739 case Type::FunctionProto:
4740 case Type::FunctionNoProto:
4741 T = cast<FunctionType>(Ty)->getReturnType();
4742 break;
4743 case Type::Paren:
4744 case Type::TypeOf:
4745 case Type::UnaryTransform:
4746 case Type::Attributed:
4747 case Type::BTFTagAttributed:
4748 case Type::OverflowBehavior:
4749 case Type::HLSLAttributedResource:
4750 case Type::SubstTemplateTypeParm:
4751 case Type::MacroQualified:
4752 case Type::CountAttributed:
4753 case Type::LateParsedAttr:
4754 // Keep walking after single level desugaring.
4755 T = T.getSingleStepDesugaredType(Context);
4756 break;
4757 case Type::Typedef:
4758 T = cast<TypedefType>(Ty)->desugar();
4759 break;
4760 case Type::Decltype:
4761 T = cast<DecltypeType>(Ty)->desugar();
4762 break;
4763 case Type::PackIndexing:
4764 T = cast<PackIndexingType>(Ty)->desugar();
4765 break;
4766 case Type::Using:
4767 T = cast<UsingType>(Ty)->desugar();
4768 break;
4769 case Type::Auto:
4770 case Type::DeducedTemplateSpecialization:
4771 T = cast<DeducedType>(Ty)->getDeducedType();
4772 break;
4773 case Type::TypeOfExpr:
4774 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4775 break;
4776 case Type::Atomic:
4777 T = cast<AtomicType>(Ty)->getValueType();
4778 break;
4779 case Type::PredefinedSugar:
4780 T = cast<PredefinedSugarType>(Ty)->desugar();
4781 break;
4782 }
4783 } while (!T.isNull() && T->isVariablyModifiedType());
4784}
4785
4787 SourceLocation OpLoc,
4788 SourceRange ExprRange,
4789 UnaryExprOrTypeTrait ExprKind,
4790 StringRef KWName) {
4791 if (ExprType->isDependentType())
4792 return false;
4793
4794 // These builtins evaluate with the operand type as written; a reference is
4795 // not looked through.
4796 if (ExprKind == UETT_VectorElements)
4797 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4798 ExprRange);
4799 if (ExprKind == UETT_VecStep)
4800 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4801 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4802 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4803 ExprRange);
4804
4805 // C++ [expr.sizeof]p2:
4806 // When applied to a reference or a reference type, the result
4807 // is the size of the referenced type.
4808 // C++11 [expr.alignof]p3:
4809 // When alignof is applied to a reference type, the result
4810 // shall be the alignment of the referenced type.
4811 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4812 ExprType = Ref->getPointeeType();
4813
4814 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4815 // When alignof or _Alignof is applied to an array type, the result
4816 // is the alignment of the element type.
4817 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4818 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4819 // If the trait is 'alignof' in C before C2y, the ability to apply the
4820 // trait to an incomplete array is an extension.
4821 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4822 ExprType->isIncompleteArrayType())
4823 DiagCompat(OpLoc, diag_compat::alignof_incomplete_array);
4824 ExprType = Context.getBaseElementType(ExprType);
4825 }
4826
4827 // Explicitly list some types as extensions.
4828 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4829 ExprKind))
4830 return false;
4831
4833 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4834 KWName, ExprRange))
4835 return true;
4836
4837 if (ExprType->isFunctionType()) {
4838 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4839 return true;
4840 }
4841
4842 if (ExprKind == UETT_CountOf) {
4843 // The type has to be an array type. We already checked for incomplete
4844 // types above.
4845 if (!ExprType->isArrayType()) {
4846 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4847 return true;
4848 }
4849 }
4850
4851 // WebAssembly tables are always illegal operands to unary expressions and
4852 // type traits.
4853 if (Context.getTargetInfo().getTriple().isWasm() &&
4854 ExprType->isWebAssemblyTableType()) {
4855 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4856 << getTraitSpelling(ExprKind);
4857 return true;
4858 }
4859
4860 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4861 ExprKind))
4862 return true;
4863
4864 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4865 if (auto *TT = ExprType->getAs<TypedefType>()) {
4866 for (auto I = FunctionScopes.rbegin(),
4867 E = std::prev(FunctionScopes.rend());
4868 I != E; ++I) {
4869 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4870 if (CSI == nullptr)
4871 break;
4872 DeclContext *DC = nullptr;
4873 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4874 DC = LSI->CallOperator;
4875 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4876 DC = CRSI->TheCapturedDecl;
4877 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4878 DC = BSI->TheDecl;
4879 if (DC) {
4880 if (DC->containsDecl(TT->getDecl()))
4881 break;
4882 captureVariablyModifiedType(Context, ExprType, CSI);
4883 }
4884 }
4885 }
4886 }
4887
4888 return false;
4889}
4890
4892 SourceLocation OpLoc,
4893 UnaryExprOrTypeTrait ExprKind,
4894 SourceRange R) {
4895 if (!TInfo)
4896 return ExprError();
4897
4898 QualType T = TInfo->getType();
4899
4900 if (!T->isDependentType() &&
4901 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4902 getTraitSpelling(ExprKind)))
4903 return ExprError();
4904
4905 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4906 // properly deal with VLAs in nested calls of sizeof and typeof.
4907 if (currentEvaluationContext().isUnevaluated() &&
4908 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4909 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4910 TInfo->getType()->isVariablyModifiedType())
4911 TInfo = TransformToPotentiallyEvaluated(TInfo);
4912
4913 // It's possible that the transformation above failed.
4914 if (!TInfo)
4915 return ExprError();
4916
4917 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4918 return new (Context) UnaryExprOrTypeTraitExpr(
4919 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4920}
4921
4924 UnaryExprOrTypeTrait ExprKind) {
4926 if (PE.isInvalid())
4927 return ExprError();
4928
4929 E = PE.get();
4930
4931 // Verify that the operand is valid.
4932 bool isInvalid = false;
4933 if (E->isTypeDependent()) {
4934 // Delay type-checking for type-dependent expressions.
4935 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4936 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4937 } else if (ExprKind == UETT_VecStep) {
4939 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4940 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4941 isInvalid = true;
4942 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4943 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4944 isInvalid = true;
4945 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4946 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4948 }
4949
4950 if (isInvalid)
4951 return ExprError();
4952
4953 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4954 E->getType()->isVariableArrayType()) {
4956 if (PE.isInvalid()) return ExprError();
4957 E = PE.get();
4958 }
4959
4960 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4961 return new (Context) UnaryExprOrTypeTraitExpr(
4962 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4963}
4964
4967 UnaryExprOrTypeTrait ExprKind, bool IsType,
4968 void *TyOrEx, SourceRange ArgRange) {
4969 // If error parsing type, ignore.
4970 if (!TyOrEx) return ExprError();
4971
4972 if (IsType) {
4973 TypeSourceInfo *TInfo;
4974 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4975 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4976 }
4977
4978 Expr *ArgEx = (Expr *)TyOrEx;
4979 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4980 return Result;
4981}
4982
4984 SourceLocation OpLoc, SourceRange R) {
4985 if (!TInfo)
4986 return true;
4987 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4988 UETT_AlignOf, KWName);
4989}
4990
4992 SourceLocation OpLoc, SourceRange R) {
4993 TypeSourceInfo *TInfo;
4995 &TInfo);
4996 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4997}
4998
5000 bool IsReal) {
5001 if (V.get()->isTypeDependent())
5002 return S.Context.DependentTy;
5003
5004 // _Real and _Imag are only l-values for normal l-values.
5005 if (V.get()->getObjectKind() != OK_Ordinary) {
5006 V = S.DefaultLvalueConversion(V.get());
5007 if (V.isInvalid())
5008 return QualType();
5009 }
5010
5011 // These operators return the element type of a complex type.
5012 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
5013 return CT->getElementType();
5014
5015 // Otherwise they pass through real integer and floating point types here.
5016 if (V.get()->getType()->isArithmeticType())
5017 return V.get()->getType();
5018
5019 // Test for placeholders.
5020 ExprResult PR = S.CheckPlaceholderExpr(V.get());
5021 if (PR.isInvalid()) return QualType();
5022 if (PR.get() != V.get()) {
5023 V = PR;
5024 return CheckRealImagOperand(S, V, Loc, IsReal);
5025 }
5026
5027 // Reject anything else.
5028 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
5029 << (IsReal ? "__real" : "__imag");
5030 return QualType();
5031}
5032
5033
5034
5037 tok::TokenKind Kind, Expr *Input) {
5039 switch (Kind) {
5040 default: llvm_unreachable("Unknown unary op!");
5041 case tok::plusplus: Opc = UO_PostInc; break;
5042 case tok::minusminus: Opc = UO_PostDec; break;
5043 }
5044
5045 // Since this might is a postfix expression, get rid of ParenListExprs.
5047 if (Result.isInvalid()) return ExprError();
5048 Input = Result.get();
5049
5050 return BuildUnaryOp(S, OpLoc, Opc, Input);
5051}
5052
5053/// Diagnose if arithmetic on the given ObjC pointer is illegal.
5054///
5055/// \return true on error
5057 SourceLocation opLoc,
5058 Expr *op) {
5059 assert(op->getType()->isObjCObjectPointerType());
5061 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5062 return false;
5063
5064 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
5066 << op->getSourceRange();
5067 return true;
5068}
5069
5071 auto *BaseNoParens = Base->IgnoreParens();
5072 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
5073 return MSProp->getPropertyDecl()->getType()->isArrayType();
5074 return isa<MSPropertySubscriptExpr>(BaseNoParens);
5075}
5076
5077// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5078// Typically this is DependentTy, but can sometimes be more precise.
5079//
5080// There are cases when we could determine a non-dependent type:
5081// - LHS and RHS may have non-dependent types despite being type-dependent
5082// (e.g. unbounded array static members of the current instantiation)
5083// - one may be a dependent-sized array with known element type
5084// - one may be a dependent-typed valid index (enum in current instantiation)
5085//
5086// We *always* return a dependent type, in such cases it is DependentTy.
5087// This avoids creating type-dependent expressions with non-dependent types.
5088// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5090 const ASTContext &Ctx) {
5091 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5092 QualType LTy = LHS->getType(), RTy = RHS->getType();
5094 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5095 if (const PointerType *PT = LTy->getAs<PointerType>())
5096 Result = PT->getPointeeType();
5097 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5098 Result = AT->getElementType();
5099 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5100 if (const PointerType *PT = RTy->getAs<PointerType>())
5101 Result = PT->getPointeeType();
5102 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5103 Result = AT->getElementType();
5104 }
5105 // Ensure we return a dependent type.
5106 return Result->isDependentType() ? Result : Ctx.DependentTy;
5107}
5108
5110 SourceLocation lbLoc,
5111 MultiExprArg ArgExprs,
5112 SourceLocation rbLoc) {
5113
5114 if (base && !base->getType().isNull() &&
5115 base->hasPlaceholderType(BuiltinType::ArraySection)) {
5116 auto *AS = cast<ArraySectionExpr>(base);
5117 if (AS->isOMPArraySection())
5119 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
5120 /*Length*/ nullptr,
5121 /*Stride=*/nullptr, rbLoc);
5122
5123 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
5124 SourceLocation(), /*Length*/ nullptr,
5125 rbLoc);
5126 }
5127
5128 // Since this might be a postfix expression, get rid of ParenListExprs.
5129 if (isa<ParenListExpr>(base)) {
5131 if (result.isInvalid())
5132 return ExprError();
5133 base = result.get();
5134 }
5135
5136 // Check if base and idx form a MatrixSubscriptExpr.
5137 //
5138 // Helper to check for comma expressions, which are not allowed as indices for
5139 // matrix subscript expressions.
5140 //
5141 // In C++23, we get multiple arguments instead of a comma expression.
5142 auto CheckAndReportCommaError = [&](Expr *E) {
5143 if (ArgExprs.size() > 1 ||
5144 (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp())) {
5145 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5146 << SourceRange(base->getBeginLoc(), rbLoc);
5147 return true;
5148 }
5149 return false;
5150 };
5151 // The matrix subscript operator ([][])is considered a single operator.
5152 // Separating the index expressions by parenthesis is not allowed.
5153 if (base && !base->getType().isNull() &&
5154 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5155 !isa<MatrixSubscriptExpr>(base)) {
5156 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5157 << SourceRange(base->getBeginLoc(), rbLoc);
5158 return ExprError();
5159 }
5160 // If the base is a MatrixSubscriptExpr, try to create a new
5161 // MatrixSubscriptExpr.
5162 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5163 if (matSubscriptE && matSubscriptE->isIncomplete()) {
5164 if (CheckAndReportCommaError(ArgExprs.front()))
5165 return ExprError();
5166
5167 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5168 matSubscriptE->getRowIdx(),
5169 ArgExprs.front(), rbLoc);
5170 }
5171 if (base->getType()->isWebAssemblyTableType()) {
5172 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5173 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5174 return ExprError();
5175 }
5176
5177 CheckInvalidBuiltinCountedByRef(base,
5179
5180 // Handle any non-overload placeholder types in the base and index
5181 // expressions. We can't handle overloads here because the other
5182 // operand might be an overloadable type, in which case the overload
5183 // resolution for the operator overload should get the first crack
5184 // at the overload.
5185 bool IsMSPropertySubscript = false;
5186 if (base->getType()->isNonOverloadPlaceholderType()) {
5187 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5188 if (!IsMSPropertySubscript) {
5189 ExprResult result = CheckPlaceholderExpr(base);
5190 if (result.isInvalid())
5191 return ExprError();
5192 base = result.get();
5193 }
5194 }
5195
5196 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5197 if (base->getType()->isMatrixType()) {
5198 if (CheckAndReportCommaError(ArgExprs.front()))
5199 return ExprError();
5200
5201 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5202 rbLoc);
5203 }
5204
5205 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5206 Expr *idx = ArgExprs[0];
5207 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5209 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5210 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5211 << SourceRange(base->getBeginLoc(), rbLoc);
5212 }
5213 }
5214
5215 if (ArgExprs.size() == 1 &&
5216 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5217 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5218 if (result.isInvalid())
5219 return ExprError();
5220 ArgExprs[0] = result.get();
5221 } else {
5222 if (CheckArgsForPlaceholders(ArgExprs))
5223 return ExprError();
5224 }
5225
5226 // Build an unanalyzed expression if either operand is type-dependent.
5227 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5228 (base->isTypeDependent() ||
5230 !isa<PackExpansionExpr>(ArgExprs[0])) {
5231 return new (Context) ArraySubscriptExpr(
5232 base, ArgExprs.front(),
5233 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5234 VK_LValue, OK_Ordinary, rbLoc);
5235 }
5236
5237 // MSDN, property (C++)
5238 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5239 // This attribute can also be used in the declaration of an empty array in a
5240 // class or structure definition. For example:
5241 // __declspec(property(get=GetX, put=PutX)) int x[];
5242 // The above statement indicates that x[] can be used with one or more array
5243 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5244 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5245 if (IsMSPropertySubscript) {
5246 if (ArgExprs.size() > 1) {
5247 Diag(base->getExprLoc(),
5248 diag::err_ms_property_subscript_expects_single_arg);
5249 return ExprError();
5250 }
5251
5252 // Build MS property subscript expression if base is MS property reference
5253 // or MS property subscript.
5254 return new (Context)
5255 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5256 VK_LValue, OK_Ordinary, rbLoc);
5257 }
5258
5259 // Use C++ overloaded-operator rules if either operand has record
5260 // type. The spec says to do this if either type is *overloadable*,
5261 // but enum types can't declare subscript operators or conversion
5262 // operators, so there's nothing interesting for overload resolution
5263 // to do if there aren't any record types involved.
5264 //
5265 // ObjC pointers have their own subscripting logic that is not tied
5266 // to overload resolution and so should not take this path.
5267 //
5268 // Issue a better diagnostic if we tried to pass multiple arguments to
5269 // a builtin subscript operator rather than diagnosing this as a generic
5270 // overload resolution failure.
5271 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5272 !base->getType()->isRecordType() &&
5273 !base->getType()->isObjCObjectPointerType()) {
5274 Diag(base->getExprLoc(), diag::err_ovl_builtin_subscript_expects_single_arg)
5275 << base->getType() << base->getSourceRange();
5276 return ExprError();
5277 }
5278
5280 ((base->getType()->isRecordType() ||
5281 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5282 ArgExprs[0]->getType()->isRecordType())))) {
5283 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5284 }
5285
5286 ExprResult Res =
5287 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5288
5289 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5290 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5291
5292 return Res;
5293}
5294
5297 InitializationKind Kind =
5299 InitializationSequence InitSeq(*this, Entity, Kind, E);
5300 return InitSeq.Perform(*this, Entity, Kind, E);
5301}
5302
5304 Expr *RowIdx,
5305 SourceLocation RBLoc) {
5307 if (BaseR.isInvalid())
5308 return BaseR;
5309 Base = BaseR.get();
5310
5311 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5312 if (RowR.isInvalid())
5313 return RowR;
5314 RowIdx = RowR.get();
5315
5316 // Build an unanalyzed expression if any of the operands is type-dependent.
5317 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5318 return new (Context)
5319 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5320
5321 // Check that IndexExpr is an integer expression. If it is a constant
5322 // expression, check that it is less than Dim (= the number of elements in the
5323 // corresponding dimension).
5324 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5325 bool IsColumnIdx) -> Expr * {
5326 if (!IndexExpr->getType()->isIntegerType() &&
5327 !IndexExpr->isTypeDependent()) {
5328 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5329 << IsColumnIdx;
5330 return nullptr;
5331 }
5332
5333 if (std::optional<llvm::APSInt> Idx =
5334 IndexExpr->getIntegerConstantExpr(Context)) {
5335 if ((*Idx < 0 || *Idx >= Dim)) {
5336 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5337 << IsColumnIdx << Dim;
5338 return nullptr;
5339 }
5340 }
5341
5342 ExprResult ConvExpr = IndexExpr;
5343 assert(!ConvExpr.isInvalid() &&
5344 "should be able to convert any integer type to size type");
5345 return ConvExpr.get();
5346 };
5347
5348 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5349 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5350 if (!RowIdx)
5351 return ExprError();
5352
5353 QualType RowVecQT =
5354 Context.getExtVectorType(MTy->getElementType(), MTy->getNumColumns());
5355
5356 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5357}
5358
5360 Expr *ColumnIdx,
5361 SourceLocation RBLoc) {
5363 if (BaseR.isInvalid())
5364 return BaseR;
5365 Base = BaseR.get();
5366
5367 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5368 if (RowR.isInvalid())
5369 return RowR;
5370 RowIdx = RowR.get();
5371
5372 if (!ColumnIdx)
5373 return new (Context) MatrixSubscriptExpr(
5374 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5375
5376 // Build an unanalyzed expression if any of the operands is type-dependent.
5377 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5378 ColumnIdx->isTypeDependent())
5379 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5380 Context.DependentTy, RBLoc);
5381
5382 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5383 if (ColumnR.isInvalid())
5384 return ColumnR;
5385 ColumnIdx = ColumnR.get();
5386
5387 // Check that IndexExpr is an integer expression. If it is a constant
5388 // expression, check that it is less than Dim (= the number of elements in the
5389 // corresponding dimension).
5390 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5391 bool IsColumnIdx) -> Expr * {
5392 if (!IndexExpr->getType()->isIntegerType() &&
5393 !IndexExpr->isTypeDependent()) {
5394 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5395 << IsColumnIdx;
5396 return nullptr;
5397 }
5398
5399 if (std::optional<llvm::APSInt> Idx =
5400 IndexExpr->getIntegerConstantExpr(Context)) {
5401 if ((*Idx < 0 || *Idx >= Dim)) {
5402 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5403 << IsColumnIdx << Dim;
5404 return nullptr;
5405 }
5406 }
5407
5408 ExprResult ConvExpr = IndexExpr;
5409 assert(!ConvExpr.isInvalid() &&
5410 "should be able to convert any integer type to size type");
5411 return ConvExpr.get();
5412 };
5413
5414 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5415 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5416 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5417 if (!RowIdx || !ColumnIdx)
5418 return ExprError();
5419
5420 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5421 MTy->getElementType(), RBLoc);
5422}
5423
5424void Sema::CheckAddressOfNoDeref(const Expr *E) {
5425 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5426 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5427
5428 // For expressions like `&(*s).b`, the base is recorded and what should be
5429 // checked.
5430 const MemberExpr *Member = nullptr;
5431 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5432 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5433
5434 LastRecord.PossibleDerefs.erase(StrippedExpr);
5435}
5436
5437void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5439 return;
5440
5441 QualType ResultTy = E->getType();
5442 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5443
5444 // Bail if the element is an array since it is not memory access.
5445 if (isa<ArrayType>(ResultTy))
5446 return;
5447
5448 if (ResultTy->hasAttr(attr::NoDeref)) {
5449 LastRecord.PossibleDerefs.insert(E);
5450 return;
5451 }
5452
5453 // Check if the base type is a pointer to a member access of a struct
5454 // marked with noderef.
5455 const Expr *Base = E->getBase();
5456 QualType BaseTy = Base->getType();
5457 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5458 // Not a pointer access
5459 return;
5460
5461 const MemberExpr *Member = nullptr;
5462 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5463 Member->isArrow())
5464 Base = Member->getBase();
5465
5466 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5467 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5468 LastRecord.PossibleDerefs.insert(E);
5469 }
5470}
5471
5474 Expr *Idx, SourceLocation RLoc) {
5475 Expr *LHSExp = Base;
5476 Expr *RHSExp = Idx;
5477
5480
5481 // Per C++ core issue 1213, the result is an xvalue if either operand is
5482 // a non-lvalue array, and an lvalue otherwise.
5483 if (getLangOpts().CPlusPlus11) {
5484 for (auto *Op : {LHSExp, RHSExp}) {
5485 Op = Op->IgnoreImplicit();
5486 if (Op->getType()->isArrayType() && !Op->isLValue())
5487 VK = VK_XValue;
5488 }
5489 }
5490
5491 // Perform default conversions.
5492 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5494 if (Result.isInvalid())
5495 return ExprError();
5496 LHSExp = Result.get();
5497 }
5499 if (Result.isInvalid())
5500 return ExprError();
5501 RHSExp = Result.get();
5502
5503 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5504
5505 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5506 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5507 // in the subscript position. As a result, we need to derive the array base
5508 // and index from the expression types.
5509 Expr *BaseExpr, *IndexExpr;
5510 QualType ResultType;
5511 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5512 BaseExpr = LHSExp;
5513 IndexExpr = RHSExp;
5514 ResultType =
5516 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5517 BaseExpr = LHSExp;
5518 IndexExpr = RHSExp;
5519 ResultType = PTy->getPointeeType();
5520 } else if (const ObjCObjectPointerType *PTy =
5521 LHSTy->getAs<ObjCObjectPointerType>()) {
5522 BaseExpr = LHSExp;
5523 IndexExpr = RHSExp;
5524
5525 // Use custom logic if this should be the pseudo-object subscript
5526 // expression.
5527 if (!LangOpts.isSubscriptPointerArithmetic())
5528 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5529 nullptr, nullptr);
5530
5531 ResultType = PTy->getPointeeType();
5532 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5533 // Handle the uncommon case of "123[Ptr]".
5534 BaseExpr = RHSExp;
5535 IndexExpr = LHSExp;
5536 ResultType = PTy->getPointeeType();
5537 } else if (const ObjCObjectPointerType *PTy =
5538 RHSTy->getAs<ObjCObjectPointerType>()) {
5539 // Handle the uncommon case of "123[Ptr]".
5540 BaseExpr = RHSExp;
5541 IndexExpr = LHSExp;
5542 ResultType = PTy->getPointeeType();
5543 if (!LangOpts.isSubscriptPointerArithmetic()) {
5544 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5545 << ResultType << BaseExpr->getSourceRange();
5546 return ExprError();
5547 }
5548 } else if (LHSTy->isSubscriptableVectorType()) {
5549 if (LHSTy->isBuiltinType() &&
5550 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5551 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5552 if (BTy->isSVEBool())
5553 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5554 << LHSExp->getSourceRange()
5555 << RHSExp->getSourceRange());
5556 ResultType = BTy->getSveEltType(Context);
5557 } else if (Hexagon().isHLXVectorType(LHSTy)) {
5558 // There is no HLX vector element extract.
5559 return ExprError(Diag(LLoc, diag::err_subscript_hlx)
5560 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5561 } else {
5562 const VectorType *VTy = LHSTy->getAs<VectorType>();
5563 ResultType = VTy->getElementType();
5564 }
5565 BaseExpr = LHSExp; // vectors: V[123]
5566 IndexExpr = RHSExp;
5567 // We apply C++ DR1213 to vector subscripting too.
5568 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5569 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5570 if (Materialized.isInvalid())
5571 return ExprError();
5572 LHSExp = Materialized.get();
5573 }
5574 VK = LHSExp->getValueKind();
5575 if (VK != VK_PRValue)
5576 OK = OK_VectorComponent;
5577
5578 QualType BaseType = BaseExpr->getType();
5579 Qualifiers BaseQuals = BaseType.getQualifiers();
5580 Qualifiers MemberQuals = ResultType.getQualifiers();
5581 Qualifiers Combined = BaseQuals + MemberQuals;
5582 if (Combined != MemberQuals)
5583 ResultType = Context.getQualifiedType(ResultType, Combined);
5584 } else if (LHSTy->isArrayType()) {
5585 // If we see an array that wasn't promoted by
5586 // DefaultFunctionArrayLvalueConversion, it must be an array that
5587 // wasn't promoted because of the C90 rule that doesn't
5588 // allow promoting non-lvalue arrays. Warn, then
5589 // force the promotion here.
5590 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5591 << LHSExp->getSourceRange();
5592 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5593 CK_ArrayToPointerDecay).get();
5594 LHSTy = LHSExp->getType();
5595
5596 BaseExpr = LHSExp;
5597 IndexExpr = RHSExp;
5598 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5599 } else if (RHSTy->isArrayType()) {
5600 // Same as previous, except for 123[f().a] case
5601 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5602 << RHSExp->getSourceRange();
5603 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5604 CK_ArrayToPointerDecay).get();
5605 RHSTy = RHSExp->getType();
5606
5607 BaseExpr = RHSExp;
5608 IndexExpr = LHSExp;
5609 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5610 } else {
5611 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5612 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5613 }
5614 // C99 6.5.2.1p1
5615 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5616 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5617 << IndexExpr->getSourceRange());
5618
5619 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5620 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5621 !IndexExpr->isTypeDependent()) {
5622 std::optional<llvm::APSInt> IntegerContantExpr =
5624 if (!IntegerContantExpr.has_value() ||
5625 IntegerContantExpr.value().isNegative())
5626 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5627 }
5628
5629 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5630 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5631 // type. Note that Functions are not objects, and that (in C99 parlance)
5632 // incomplete types are not object types.
5633 if (ResultType->isFunctionType()) {
5634 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5635 << ResultType << BaseExpr->getSourceRange();
5636 return ExprError();
5637 }
5638
5639 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5640 // GNU extension: subscripting on pointer to void
5641 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5642 << BaseExpr->getSourceRange();
5643
5644 // C forbids expressions of unqualified void type from being l-values.
5645 // See IsCForbiddenLValueType.
5646 if (!ResultType.hasQualifiers())
5647 VK = VK_PRValue;
5648 } else if (!ResultType->isDependentType() &&
5649 !ResultType.isWebAssemblyReferenceType() &&
5651 LLoc, ResultType,
5652 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5653 return ExprError();
5654
5655 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5656 !ResultType.isCForbiddenLValueType());
5657
5659 FunctionScopes.size() > 1) {
5660 if (auto *TT =
5661 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5662 for (auto I = FunctionScopes.rbegin(),
5663 E = std::prev(FunctionScopes.rend());
5664 I != E; ++I) {
5665 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5666 if (CSI == nullptr)
5667 break;
5668 DeclContext *DC = nullptr;
5669 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5670 DC = LSI->CallOperator;
5671 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5672 DC = CRSI->TheCapturedDecl;
5673 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5674 DC = BSI->TheDecl;
5675 if (DC) {
5676 if (DC->containsDecl(TT->getDecl()))
5677 break;
5679 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5680 }
5681 }
5682 }
5683 }
5684
5685 return new (Context)
5686 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5687}
5688
5690 ParmVarDecl *Param, Expr *RewrittenInit,
5691 bool SkipImmediateInvocations) {
5692 if (Param->hasUnparsedDefaultArg()) {
5693 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5694 // If we've already cleared out the location for the default argument,
5695 // that means we're parsing it right now.
5696 if (!UnparsedDefaultArgLocs.count(Param)) {
5697 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5698 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5699 Param->setInvalidDecl();
5700 return true;
5701 }
5702
5703 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5704 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5706 diag::note_default_argument_declared_here);
5707 return true;
5708 }
5709
5710 if (Param->hasUninstantiatedDefaultArg()) {
5711 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5712 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5713 return true;
5714 }
5715
5716 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5717 assert(Init && "default argument but no initializer?");
5718
5719 // If the default expression creates temporaries, we need to
5720 // push them to the current stack of expression temporaries so they'll
5721 // be properly destroyed.
5722 // FIXME: We should really be rebuilding the default argument with new
5723 // bound temporaries; see the comment in PR5810.
5724 // We don't need to do that with block decls, though, because
5725 // blocks in default argument expression can never capture anything.
5726 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5727 // Set the "needs cleanups" bit regardless of whether there are
5728 // any explicit objects.
5729 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5730 // Append all the objects to the cleanup list. Right now, this
5731 // should always be a no-op, because blocks in default argument
5732 // expressions should never be able to capture anything.
5733 assert(!InitWithCleanup->getNumObjects() &&
5734 "default argument expression has capturing blocks?");
5735 }
5736 // C++ [expr.const]p15.1:
5737 // An expression or conversion is in an immediate function context if it is
5738 // potentially evaluated and [...] its innermost enclosing non-block scope
5739 // is a function parameter scope of an immediate function.
5741 *this,
5745 Param);
5746 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5747 SkipImmediateInvocations;
5748 runWithSufficientStackSpace(CallLoc, [&] {
5749 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5750 });
5751 return false;
5752}
5753
5758 }
5759
5760 bool HasImmediateCalls = false;
5761
5762 bool VisitCallExpr(CallExpr *E) override {
5763 if (const FunctionDecl *FD = E->getDirectCallee())
5764 HasImmediateCalls |= FD->isImmediateFunction();
5766 }
5767
5769 if (const FunctionDecl *FD = E->getConstructor())
5770 HasImmediateCalls |= FD->isImmediateFunction();
5772 }
5773
5774 // SourceLocExpr are not immediate invocations
5775 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5776 // need to be rebuilt so that they refer to the correct SourceLocation and
5777 // DeclContext.
5779 HasImmediateCalls = true;
5781 }
5782
5783 // A nested lambda might have parameters with immediate invocations
5784 // in their default arguments, or init-captures that are evaluated in the
5785 // enclosing context.
5786 // The compound statement is not visited (as it does not constitute a
5787 // subexpression).
5788 bool VisitLambdaExpr(LambdaExpr *E) override {
5789 auto Init = E->capture_init_begin();
5790 for (auto C = E->capture_begin(), CEnd = E->capture_end(); C != CEnd;
5791 ++C, ++Init) {
5792 if (E->isInitCapture(C) && !TraverseLambdaCapture(E, C, *Init))
5793 return false;
5794 }
5795 return VisitCXXMethodDecl(E->getCallOperator());
5796 }
5797
5799 return TraverseStmt(E->getExpr());
5800 }
5801
5803 return TraverseStmt(E->getExpr());
5804 }
5805};
5806
5808 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5811
5812 bool AlwaysRebuild() { return true; }
5813
5814 // Lambda bodies are not subexpressions of the enclosing default initializer,
5815 // but init-capture expressions are evaluated in the enclosing context. Keep
5816 // the existing closure type and capture declarations so the existing body
5817 // still refers to the right declarations.
5819 SmallVector<Expr *, 4> CaptureInits(E->capture_inits());
5820
5821 bool Changed = false;
5822 for (unsigned I = 0, N = E->capture_size(); I != N; ++I) {
5823 const LambdaCapture *C = E->capture_begin() + I;
5824 if (!E->isInitCapture(C))
5825 continue;
5826
5827 auto *VD = cast<VarDecl>(C->getCapturedVar());
5828 // Default initializers are rebuilt at their point of use, where the
5829 // lambda is no longer dependent, so init-capture packs have already been
5830 // expanded into separate captures.
5831 assert(!VD->isParameterPack() &&
5832 "unexpanded init-capture pack while rebuilding a default member "
5833 "initializer");
5834
5835 Expr *Init = CaptureInits[I];
5836 ExprResult NewInit =
5837 TransformInitializer(Init, VD->getInitStyle() == VarDecl::CallInit);
5838 if (NewInit.isInvalid())
5839 return ExprError();
5840
5841 // TransformInitializer strips the CXXConstructExpr that a copy or move
5842 // initialization produces, expecting the enclosing context to rebuild the
5843 // initialization. Rebuild the capture's initialization sequence here so
5844 // the closure still constructs its captured member; otherwise CodeGen is
5845 // left with a bare initializer for a non-trivially copyable capture and
5846 // crashes.
5847 Expr *NewInitE = NewInit.get();
5848 QualType CaptureType = SemaRef.buildLambdaInitCaptureInitialization(
5849 C->getLocation(), C->getCaptureKind() == LCK_ByRef,
5850 /*EllipsisLoc=*/SourceLocation(), /*NumExpansions=*/std::nullopt,
5851 VD->getIdentifier(), VD->getInitStyle() != VarDecl::CInit, NewInitE);
5852 if (CaptureType.isNull() || !NewInitE)
5853 return ExprError();
5854
5855 Changed |= NewInitE != Init;
5856 CaptureInits[I] = NewInitE;
5857 }
5858
5859 LambdaExpr *Lambda = E;
5860 if (Changed) {
5861 // Reuse the existing closure class: it owns the capture declarations,
5862 // fields, and call operator body. Only the LambdaExpr's capture
5863 // initializer list is replaced.
5864 Lambda = LambdaExpr::Create(
5865 SemaRef.Context, E->getLambdaClass(), E->getIntroducerRange(),
5867 E->hasExplicitParameters(), E->hasExplicitResultType(), CaptureInits,
5869 }
5870
5871 return SemaRef.MaybeBindToTemporary(Lambda);
5872 }
5874
5875 // Make sure we don't rebuild the this pointer as it would
5876 // cause it to incorrectly point it to the outermost class
5877 // in the case of nested struct initialization.
5879
5880 // Rewrite to source location to refer to the context in which they are used.
5882 DeclContext *DC = E->getParentContext();
5883 if (DC == SemaRef.CurContext)
5884 return E;
5885
5886 // FIXME: During instantiation, because the rebuild of defaults arguments
5887 // is not always done in the context of the template instantiator,
5888 // we run the risk of producing a dependent source location
5889 // that would never be rebuilt.
5890 // This usually happens during overload resolution, or in contexts
5891 // where the value of the source location does not matter.
5892 // However, we should find a better way to deal with source location
5893 // of function templates.
5894 if (!SemaRef.CurrentInstantiationScope ||
5895 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5896 DC = SemaRef.CurContext;
5897
5898 return getDerived().RebuildSourceLocExpr(
5899 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5900 }
5901};
5902
5904 FunctionDecl *FD, ParmVarDecl *Param,
5905 Expr *Init) {
5906 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5907
5908 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5909 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5910 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5911 InitializationContext =
5913 if (!InitializationContext.has_value())
5914 InitializationContext.emplace(CallLoc, Param, CurContext);
5915
5916 if (!Init && !Param->hasUnparsedDefaultArg()) {
5917 // Mark that we are replacing a default argument first.
5918 // If we are instantiating a template we won't have to
5919 // retransform immediate calls.
5920 // C++ [expr.const]p15.1:
5921 // An expression or conversion is in an immediate function context if it
5922 // is potentially evaluated and [...] its innermost enclosing non-block
5923 // scope is a function parameter scope of an immediate function.
5925 *this,
5929 Param);
5930
5931 if (Param->hasUninstantiatedDefaultArg()) {
5932 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5933 return ExprError();
5934 }
5935 // CWG2631
5936 // An immediate invocation that is not evaluated where it appears is
5937 // evaluated and checked for whether it is a constant expression at the
5938 // point where the enclosing initializer is used in a function call.
5940 if (!NestedDefaultChecking)
5941 V.TraverseDecl(Param);
5942
5943 // Rewrite the call argument that was created from the corresponding
5944 // parameter's default argument.
5945 if (V.HasImmediateCalls ||
5946 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5947 if (V.HasImmediateCalls)
5948 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5949 CallLoc, Param, CurContext};
5950 // Pass down lifetime extending flag, and collect temporaries in
5951 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5955 ExprResult Res;
5956 runWithSufficientStackSpace(CallLoc, [&] {
5957 Res = Immediate.TransformInitializer(Param->getInit(),
5958 /*NotCopy=*/false);
5959 });
5960 if (Res.isInvalid())
5961 return ExprError();
5962 Res = ConvertParamDefaultArgument(Param, Res.get(),
5963 Res.get()->getBeginLoc());
5964 if (Res.isInvalid())
5965 return ExprError();
5966 Init = Res.get();
5967 }
5968 }
5969
5971 CallLoc, FD, Param, Init,
5972 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5973 return ExprError();
5974
5975 if (getLangOpts().CUDA)
5976 CUDA().checkRTTIInDefaultInit(Param, Init ? Init : Param->getDefaultArg(),
5977 CallLoc);
5978
5979 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5980 Init, InitializationContext->Context);
5981}
5982
5984 FieldDecl *Field) {
5985 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5986 return Pattern;
5987 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5988 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5990 ClassPattern->lookup(Field->getDeclName());
5991 auto Rng = llvm::make_filter_range(
5992 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5993 if (Rng.empty())
5994 return nullptr;
5995 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5996 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5997 // && "Duplicated instantiation pattern for field decl");
5998 return cast<FieldDecl>(*Rng.begin());
5999}
6000
6001ExprResult Sema::BuildCXXDefaultInitInternal(SourceLocation Loc,
6002 FieldDecl *Field,
6003 const InitializedEntity &Entity,
6004 bool NestedDefaultChecking,
6005 bool NeedRebuild) {
6006 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
6007
6008 if (!Field->getInClassInitializer() &&
6009 isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
6010 // Maybe we haven't instantiated the in-class initializer. Go check the
6011 // pattern FieldDecl to see if it has one.
6012 FieldDecl *Pattern =
6014 assert(Pattern && "We must have set the Pattern!");
6015 if (!Pattern->hasInClassInitializer() ||
6016 InstantiateInClassInitializer(Loc, Field, Pattern,
6018 return ExprError();
6019 }
6020
6021 Expr *InClassInit = Field->getInClassInitializer();
6022 if (!InClassInit) {
6023 // DR1351:
6024 // If the brace-or-equal-initializer of a non-static data member
6025 // invokes a defaulted default constructor of its class or of an
6026 // enclosing class in a potentially evaluated subexpression, the
6027 // program is ill-formed.
6028 //
6029 // This resolution is unworkable: the exception specification of the
6030 // default constructor can be needed in an unevaluated context, in
6031 // particular, in the operand of a noexcept-expression, and we can be
6032 // unable to compute an exception specification for an enclosed class.
6033 //
6034 // Any attempt to resolve the exception specification of a defaulted default
6035 // constructor before the initializer is lexically complete will ultimately
6036 // come here at which point we can diagnose it.
6037 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6038 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
6039 << OutermostClass << Field;
6040 Diag(Field->getEndLoc(),
6041 diag::note_default_member_initializer_not_yet_parsed);
6042 // Recover by marking the field invalid, unless we're in a SFINAE context.
6043 if (!isSFINAEContext())
6044 Field->setInvalidDecl();
6045 return ExprError();
6046 }
6047
6048 if (getLangOpts().CUDA)
6049 CUDA().checkRTTIInDefaultInit(Field, InClassInit, Loc);
6050
6051 // CWG2631
6052 // An immediate invocation that is not evaluated where it appears is
6053 // evaluated and checked for whether it is a constant expression at the
6054 // point where the enclosing initializer is used in a [...] a constructor
6055 // definition, or an aggregate initialization.
6056 ImmediateCallVisitor V(getASTContext());
6057 if (!NestedDefaultChecking)
6058 V.TraverseDecl(Field);
6059
6060 // CWG1815
6061 // Support lifetime extension of temporary created by aggregate
6062 // initialization using a default member initializer. We should rebuild
6063 // the initializer in a lifetime extension context if the initializer
6064 // expression is an ExprWithCleanups. Then make sure the normal lifetime
6065 // extension code recurses into the default initializer and does lifetime
6066 // extension when warranted.
6067 bool ContainsAnyTemporaries = isa<ExprWithCleanups>(InClassInit);
6068 Expr *Init = InClassInit;
6069 if (!InClassInit->containsErrors() &&
6070 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
6071 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
6072 CurContext};
6073 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6074 NestedDefaultChecking;
6075 // Pass down lifetime extending flag, and collect temporaries in
6076 // CreateMaterializeTemporaryExpr when we rewrite the initializer.
6079
6080 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6081 ExprResult Res;
6083 Res = Immediate.TransformInitializer(InClassInit,
6084 /*CXXDirectInit=*/false);
6085 });
6086 if (!Res.isInvalid())
6087 Res = ConvertMemberDefaultInitExpression(Field, Entity, Res.get(), Loc);
6088 if (Res.isInvalid()) {
6089 Field->setInvalidDecl();
6090 return ExprError();
6091 }
6092 Init = Res.get();
6093 }
6094
6095 if (!NestedDefaultChecking)
6097 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/false);
6098 });
6099 return Init;
6100}
6101
6103 FieldDecl *Field) {
6104 assert(Field->hasInClassInitializer());
6105
6106 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6107
6108 // C++11 [class.base.init]p7:
6109 // The initialization of each base and member constitutes a
6110 // full-expression.
6111 // So this initializer gets an evaluation context of its own, and is finished
6112 // as a full-expression below.
6115 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6116
6118 if (!InitContext)
6119 InitContext.emplace(Loc, Field, CurContext);
6120
6121 // [class.temporary]/p7:
6122 // If such a temporary object would otherwise be destroyed at the end of the
6123 // for-range-initializer full-expression, the object persists for the lifetime
6124 // of the reference initialized by the for-range-initializer.
6125 //
6126 // A default member initializer used by a constructor is a separate
6127 // full-expression, we don't need extend temporaries lifetime in this
6128 // situation, the NeedRebuild will always false.
6129 ExprResult Init = BuildCXXDefaultInitInternal(
6130 Loc, Field,
6132 NestedDefaultChecking, /*NeedRebuild=*/false);
6133 if (Init.isInvalid())
6134 return ExprError();
6135
6136 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue=*/false);
6137 if (Init.isInvalid()) {
6138 Field->setInvalidDecl();
6139 return ExprError();
6140 }
6141
6143 Context, InitContext->Loc, Field, InitContext->Context,
6144 Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6145}
6146
6149 const InitializedEntity &MemberEntity) {
6150 assert(Field->hasInClassInitializer());
6151
6152 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6153
6154 // Unlike a mem-initializer, this initializer is a subexpression of the
6155 // full-expression containing the aggregate initialization. It is evaluated
6156 // exactly as that full-expression is, so inherit the enclosing context kind
6157 // rather than forcing a potentially evaluated one.
6159 *this, currentEvaluationContext().Context, Field);
6160 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6161
6163 if (!InitContext)
6164 InitContext.emplace(Loc, Field, CurContext);
6165
6166 // [class.temporary]/p7:
6167 // If such a temporary object would otherwise be destroyed at the end of the
6168 // for-range-initializer full-expression, the object persists for the lifetime
6169 // of the reference initialized by the for-range-initializer.
6170 //
6171 // A default member initializer used by an aggregate initialization belongs to
6172 // the full-expression containing the aggregate initialization. we need extend
6173 // temporaries lifetime in this situation, the NeedRebuild will always true.
6174
6175 // CWG1815: always rebuild, never share the AST built when the field was
6176 // declared. Only a copy rebuilt here has its MaterializeTemporaryExprs
6177 // collected in this context, which is what lets the aggregate initialization
6178 // lifetime-extend them; sharing one AST would also make several uses of the
6179 // same field fight over its extension. A mem-initializer has no such need,
6180 // as its temporaries die at the end of the initializer itself.
6181 ExprResult Init = BuildCXXDefaultInitInternal(
6182 Loc, Field, MemberEntity, NestedDefaultChecking, /*NeedRebuild=*/true);
6183 if (Init.isInvalid())
6184 return ExprError();
6185
6186 // Deliberately not finished as a full-expression: leaving the temporaries it
6187 // created on ExprCleanupObjects lets PopExpressionEvaluationContext merge
6188 // them into the enclosing context, which eventually wraps them all in a
6189 // single ExprWithCleanups. They are then destroyed at the end of the
6190 // containing full-expression, in reverse construction order.
6191
6193 Context, InitContext->Loc, Field, InitContext->Context,
6194 Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6195}
6196
6198 const FunctionProtoType *Proto,
6199 Expr *Fn) {
6200 if (Proto && Proto->isVariadic()) {
6201 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6203 else if (Fn && Fn->getType()->isBlockPointerType())
6205 else if (FDecl) {
6206 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6207 if (Method->isInstance())
6209 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6212 }
6214}
6215
6216namespace {
6217class FunctionCallCCC final : public FunctionCallFilterCCC {
6218public:
6219 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6220 unsigned NumArgs, MemberExpr *ME)
6221 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6222 FunctionName(FuncName) {}
6223
6224 bool ValidateCandidate(const TypoCorrection &candidate) override {
6225 if (!candidate.getCorrectionSpecifier() ||
6226 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6227 return false;
6228 }
6229
6231 }
6232
6233 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6234 return std::make_unique<FunctionCallCCC>(*this);
6235 }
6236
6237private:
6238 const IdentifierInfo *const FunctionName;
6239};
6240}
6241
6243 FunctionDecl *FDecl,
6244 ArrayRef<Expr *> Args) {
6245 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6246 DeclarationName FuncName = FDecl->getDeclName();
6247 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6248
6249 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6250 if (TypoCorrection Corrected = S.CorrectTypo(
6252 S.getScopeForContext(S.CurContext), nullptr, CCC,
6254 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6255 if (Corrected.isOverloaded()) {
6258 for (NamedDecl *CD : Corrected) {
6259 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6261 OCS);
6262 }
6263 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6264 case OR_Success:
6265 ND = Best->FoundDecl;
6266 Corrected.setCorrectionDecl(ND);
6267 break;
6268 default:
6269 break;
6270 }
6271 }
6272 ND = ND->getUnderlyingDecl();
6274 return Corrected;
6275 }
6276 }
6277 return TypoCorrection();
6278}
6279
6280// [C++26][[expr.unary.op]/p4
6281// A pointer to member is only formed when an explicit &
6282// is used and its operand is a qualified-id not enclosed in parentheses.
6284 if (!isa<ParenExpr>(Fn))
6285 return false;
6286
6287 Fn = Fn->IgnoreParens();
6288
6289 auto *UO = dyn_cast<UnaryOperator>(Fn);
6290 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6291 return false;
6292 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
6293 return DRE->hasQualifier();
6294 }
6295 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
6296 return bool(OVL->getQualifier());
6297 return false;
6298}
6299
6300bool
6302 FunctionDecl *FDecl,
6303 const FunctionProtoType *Proto,
6304 ArrayRef<Expr *> Args,
6305 SourceLocation RParenLoc,
6306 bool IsExecConfig) {
6307 // Bail out early if calling a builtin with custom typechecking.
6308 // For HLSL builtin aliases, argument conversion is still needed because
6309 // overload resolution may have selected a conversion sequence (e.g.,
6310 // vector-to-scalar truncation) that must be applied before the custom
6311 // type checker runs.
6312 if (FDecl)
6313 if (unsigned ID = FDecl->getBuiltinID())
6314 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6315 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6316 return false;
6317
6318 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6319 // assignment, to the types of the corresponding parameter, ...
6320
6321 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6322 bool HasExplicitObjectParameter =
6323 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6324 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6325 unsigned NumParams = Proto->getNumParams();
6326 bool Invalid = false;
6327 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6328 unsigned FnKind = Fn->getType()->isBlockPointerType()
6329 ? 1 /* block */
6330 : (IsExecConfig ? 3 /* kernel function (exec config) */
6331 : 0 /* function */);
6332
6333 // If too few arguments are available (and we don't have default
6334 // arguments for the remaining parameters), don't make the call.
6335 if (Args.size() < NumParams) {
6336 if (Args.size() < MinArgs) {
6337 TypoCorrection TC;
6338 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6339 unsigned diag_id =
6340 MinArgs == NumParams && !Proto->isVariadic()
6341 ? diag::err_typecheck_call_too_few_args_suggest
6342 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6344 TC, PDiag(diag_id)
6345 << FnKind << MinArgs - ExplicitObjectParameterOffset
6346 << static_cast<unsigned>(Args.size()) -
6347 ExplicitObjectParameterOffset
6348 << HasExplicitObjectParameter << TC.getCorrectionRange());
6349 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6350 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6351 ->getDeclName())
6352 Diag(RParenLoc,
6353 MinArgs == NumParams && !Proto->isVariadic()
6354 ? diag::err_typecheck_call_too_few_args_one
6355 : diag::err_typecheck_call_too_few_args_at_least_one)
6356 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6357 << HasExplicitObjectParameter << Fn->getSourceRange();
6358 else
6359 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6360 ? diag::err_typecheck_call_too_few_args
6361 : diag::err_typecheck_call_too_few_args_at_least)
6362 << FnKind << MinArgs - ExplicitObjectParameterOffset
6363 << static_cast<unsigned>(Args.size()) -
6364 ExplicitObjectParameterOffset
6365 << HasExplicitObjectParameter << Fn->getSourceRange();
6366
6367 // Emit the location of the prototype.
6368 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6369 Diag(FDecl->getLocation(), diag::note_callee_decl)
6370 << FDecl << FDecl->getParametersSourceRange();
6371
6372 return true;
6373 }
6374 // We reserve space for the default arguments when we create
6375 // the call expression, before calling ConvertArgumentsForCall.
6376 assert((Call->getNumArgs() == NumParams) &&
6377 "We should have reserved space for the default arguments before!");
6378 }
6379
6380 // If too many are passed and not variadic, error on the extras and drop
6381 // them.
6382 if (Args.size() > NumParams) {
6383 if (!Proto->isVariadic()) {
6384 TypoCorrection TC;
6385 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6386 unsigned diag_id =
6387 MinArgs == NumParams && !Proto->isVariadic()
6388 ? diag::err_typecheck_call_too_many_args_suggest
6389 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6391 TC, PDiag(diag_id)
6392 << FnKind << NumParams - ExplicitObjectParameterOffset
6393 << static_cast<unsigned>(Args.size()) -
6394 ExplicitObjectParameterOffset
6395 << HasExplicitObjectParameter << TC.getCorrectionRange());
6396 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6397 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6398 ->getDeclName())
6399 Diag(Args[NumParams]->getBeginLoc(),
6400 MinArgs == NumParams
6401 ? diag::err_typecheck_call_too_many_args_one
6402 : diag::err_typecheck_call_too_many_args_at_most_one)
6403 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6404 << static_cast<unsigned>(Args.size()) -
6405 ExplicitObjectParameterOffset
6406 << HasExplicitObjectParameter << Fn->getSourceRange()
6407 << SourceRange(Args[NumParams]->getBeginLoc(),
6408 Args.back()->getEndLoc());
6409 else
6410 Diag(Args[NumParams]->getBeginLoc(),
6411 MinArgs == NumParams
6412 ? diag::err_typecheck_call_too_many_args
6413 : diag::err_typecheck_call_too_many_args_at_most)
6414 << FnKind << NumParams - ExplicitObjectParameterOffset
6415 << static_cast<unsigned>(Args.size()) -
6416 ExplicitObjectParameterOffset
6417 << HasExplicitObjectParameter << Fn->getSourceRange()
6418 << SourceRange(Args[NumParams]->getBeginLoc(),
6419 Args.back()->getEndLoc());
6420
6421 // Emit the location of the prototype.
6422 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6423 Diag(FDecl->getLocation(), diag::note_callee_decl)
6424 << FDecl << FDecl->getParametersSourceRange();
6425
6426 // This deletes the extra arguments.
6427 Call->shrinkNumArgs(NumParams);
6428 return true;
6429 }
6430 }
6431 SmallVector<Expr *, 8> AllArgs;
6432 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6433
6434 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6435 AllArgs, CallType);
6436 if (Invalid)
6437 return true;
6438 unsigned TotalNumArgs = AllArgs.size();
6439 for (unsigned i = 0; i < TotalNumArgs; ++i)
6440 Call->setArg(i, AllArgs[i]);
6441
6442 Call->computeDependence();
6443 return false;
6444}
6445
6447 const FunctionProtoType *Proto,
6448 unsigned FirstParam, ArrayRef<Expr *> Args,
6449 SmallVectorImpl<Expr *> &AllArgs,
6450 VariadicCallType CallType, bool AllowExplicit,
6451 bool IsListInitialization) {
6452 unsigned NumParams = Proto->getNumParams();
6453 bool Invalid = false;
6454 size_t ArgIx = 0;
6455 // Continue to check argument types (even if we have too few/many args).
6456 for (unsigned i = FirstParam; i < NumParams; i++) {
6457 QualType ProtoArgType = Proto->getParamType(i);
6458
6459 Expr *Arg;
6460 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6461 if (ArgIx < Args.size()) {
6462 Arg = Args[ArgIx++];
6463
6464 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6465 diag::err_call_incomplete_argument, Arg))
6466 return true;
6467
6468 // Strip the unbridged-cast placeholder expression off, if applicable.
6469 bool CFAudited = false;
6470 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6471 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6472 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6473 Arg = ObjC().stripARCUnbridgedCast(Arg);
6474 else if (getLangOpts().ObjCAutoRefCount &&
6475 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6476 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6477 CFAudited = true;
6478
6479 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6480 ProtoArgType->isBlockPointerType())
6481 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6482 BE->getBlockDecl()->setDoesNotEscape();
6483 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6485 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6486 if (ArgExpr.isInvalid())
6487 return true;
6488 Arg = ArgExpr.getAs<Expr>();
6489 }
6490
6491 InitializedEntity Entity =
6493 ProtoArgType)
6495 Context, ProtoArgType, Proto->isParamConsumed(i));
6496
6497 // Remember that parameter belongs to a CF audited API.
6498 if (CFAudited)
6499 Entity.setParameterCFAudited();
6500
6501 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6502 // function boundaries is a common oversight.
6503 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6504 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6505 bool isPedantic =
6506 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6507 Diag(Arg->getExprLoc(),
6508 isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6509 : diag::warn_obt_discarded_at_function_boundary)
6510 << Arg->getType() << ProtoArgType;
6511 }
6512
6514 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6515 if (ArgE.isInvalid())
6516 return true;
6517
6518 Arg = ArgE.getAs<Expr>();
6519 } else {
6520 assert(Param && "can't use default arguments without a known callee");
6521
6522 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6523 if (ArgExpr.isInvalid())
6524 return true;
6525
6526 Arg = ArgExpr.getAs<Expr>();
6527 }
6528
6529 // Check for array bounds violations for each argument to the call. This
6530 // check only triggers warnings when the argument isn't a more complex Expr
6531 // with its own checking, such as a BinaryOperator.
6532 CheckArrayAccess(Arg);
6533
6534 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6535 CheckStaticArrayArgument(CallLoc, Param, Arg);
6536
6537 AllArgs.push_back(Arg);
6538 }
6539
6540 // If this is a variadic call, handle args passed through "...".
6541 if (CallType != VariadicCallType::DoesNotApply) {
6542 // Assume that extern "C" functions with variadic arguments that
6543 // return __unknown_anytype aren't *really* variadic.
6544 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6545 FDecl->isExternC()) {
6546 for (Expr *A : Args.slice(ArgIx)) {
6547 QualType paramType; // ignored
6548 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6549 Invalid |= arg.isInvalid();
6550 AllArgs.push_back(arg.get());
6551 }
6552
6553 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6554 } else {
6555 for (Expr *A : Args.slice(ArgIx)) {
6556 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6557 Invalid |= Arg.isInvalid();
6558 AllArgs.push_back(Arg.get());
6559 }
6560 }
6561
6562 // Check for array bounds violations.
6563 for (Expr *A : Args.slice(ArgIx))
6564 CheckArrayAccess(A);
6565 }
6566 return Invalid;
6567}
6568
6570 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6571 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6572 TL = DTL.getOriginalLoc();
6573 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6574 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6575 << ATL.getLocalSourceRange();
6576}
6577
6578void
6580 ParmVarDecl *Param,
6581 const Expr *ArgExpr) {
6582 // Static array parameters are not supported in C++.
6583 if (!Param || getLangOpts().CPlusPlus)
6584 return;
6585
6586 QualType OrigTy = Param->getOriginalType();
6587
6588 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6589 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6590 return;
6591
6592 if (ArgExpr->isNullPointerConstant(Context,
6594 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6595 DiagnoseCalleeStaticArrayParam(*this, Param);
6596 return;
6597 }
6598
6599 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6600 if (!CAT)
6601 return;
6602
6603 const ConstantArrayType *ArgCAT =
6604 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6605 if (!ArgCAT)
6606 return;
6607
6608 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6609 ArgCAT->getElementType())) {
6610 if (ArgCAT->getSize().ult(CAT->getSize())) {
6611 Diag(CallLoc, diag::warn_static_array_too_small)
6612 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6613 << (unsigned)CAT->getZExtSize() << 0;
6614 DiagnoseCalleeStaticArrayParam(*this, Param);
6615 }
6616 return;
6617 }
6618
6619 std::optional<CharUnits> ArgSize =
6621 std::optional<CharUnits> ParmSize =
6623 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6624 Diag(CallLoc, diag::warn_static_array_too_small)
6625 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6626 << (unsigned)ParmSize->getQuantity() << 1;
6627 DiagnoseCalleeStaticArrayParam(*this, Param);
6628 }
6629}
6630
6631/// Given a function expression of unknown-any type, try to rebuild it
6632/// to have a function type.
6634
6635/// Is the given type a placeholder that we need to lower out
6636/// immediately during argument processing?
6638 // Placeholders are never sugared.
6639 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6640 if (!placeholder) return false;
6641
6642 switch (placeholder->getKind()) {
6643 // Ignore all the non-placeholder types.
6644#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6645 case BuiltinType::Id:
6646#include "clang/Basic/OpenCLImageTypes.def"
6647#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6648 case BuiltinType::Id:
6649#include "clang/Basic/OpenCLExtensionTypes.def"
6650 // In practice we'll never use this, since all SVE types are sugared
6651 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6652#define SVE_TYPE(Name, Id, SingletonId) \
6653 case BuiltinType::Id:
6654#include "clang/Basic/AArch64ACLETypes.def"
6655#define PPC_VECTOR_TYPE(Name, Id, Size) \
6656 case BuiltinType::Id:
6657#include "clang/Basic/PPCTypes.def"
6658#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6659#include "clang/Basic/RISCVVTypes.def"
6660#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6661#include "clang/Basic/WebAssemblyReferenceTypes.def"
6662#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6663#include "clang/Basic/AMDGPUTypes.def"
6664#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6665#include "clang/Basic/HLSLIntangibleTypes.def"
6666#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6667#include "clang/Basic/HLSLPackedTypes.def"
6668#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6669#include "clang/Basic/SPIRVTypes.def"
6670#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6671#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6672#include "clang/AST/BuiltinTypes.def"
6673 return false;
6674
6675 case BuiltinType::UnresolvedTemplate:
6676 // We cannot lower out overload sets; they might validly be resolved
6677 // by the call machinery.
6678 case BuiltinType::Overload:
6679 return false;
6680
6681 // Unbridged casts in ARC can be handled in some call positions and
6682 // should be left in place.
6683 case BuiltinType::ARCUnbridgedCast:
6684 return false;
6685
6686 // Pseudo-objects should be converted as soon as possible.
6687 case BuiltinType::PseudoObject:
6688 return true;
6689
6690 // The debugger mode could theoretically but currently does not try
6691 // to resolve unknown-typed arguments based on known parameter types.
6692 case BuiltinType::UnknownAny:
6693 return true;
6694
6695 // These are always invalid as call arguments and should be reported.
6696 case BuiltinType::BoundMember:
6697 case BuiltinType::BuiltinFn:
6698 case BuiltinType::IncompleteMatrixIdx:
6699 case BuiltinType::ArraySection:
6700 case BuiltinType::OMPArrayShaping:
6701 case BuiltinType::OMPIterator:
6702 return true;
6703
6704 }
6705 llvm_unreachable("bad builtin type kind");
6706}
6707
6709 // Apply this processing to all the arguments at once instead of
6710 // dying at the first failure.
6711 bool hasInvalid = false;
6712 for (size_t i = 0, e = args.size(); i != e; i++) {
6713 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6714 ExprResult result = CheckPlaceholderExpr(args[i]);
6715 if (result.isInvalid()) hasInvalid = true;
6716 else args[i] = result.get();
6717 }
6718 }
6719 return hasInvalid;
6720}
6721
6722/// If a builtin function has a pointer argument with no explicit address
6723/// space, then it should be able to accept a pointer to any address
6724/// space as input. In order to do this, we need to replace the
6725/// standard builtin declaration with one that uses the same address space
6726/// as the call.
6727///
6728/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6729/// it does not contain any pointer arguments without
6730/// an address space qualifer. Otherwise the rewritten
6731/// FunctionDecl is returned.
6732/// TODO: Handle pointer return types.
6734 FunctionDecl *FDecl,
6735 MultiExprArg ArgExprs) {
6736
6737 QualType DeclType = FDecl->getType();
6738 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6739
6740 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6741 ArgExprs.size() < FT->getNumParams())
6742 return nullptr;
6743
6744 bool NeedsNewDecl = false;
6745 unsigned i = 0;
6746 SmallVector<QualType, 8> OverloadParams;
6747
6748 {
6749 // The lvalue conversions in this loop are only for type resolution and
6750 // don't actually occur.
6753 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6754
6755 for (QualType ParamType : FT->param_types()) {
6756
6757 // Convert array arguments to pointer to simplify type lookup.
6758 ExprResult ArgRes =
6760 if (ArgRes.isInvalid())
6761 return nullptr;
6762 Expr *Arg = ArgRes.get();
6763 QualType ArgType = Arg->getType();
6764 if (!ParamType->isPointerType() ||
6765 ParamType->getPointeeType().hasAddressSpace() ||
6766 !ArgType->isPointerType() ||
6767 !ArgType->getPointeeType().hasAddressSpace() ||
6768 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6769 OverloadParams.push_back(ParamType);
6770 continue;
6771 }
6772
6773 QualType PointeeType = ParamType->getPointeeType();
6774 NeedsNewDecl = true;
6775 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6776
6777 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6778 OverloadParams.push_back(Context.getPointerType(PointeeType));
6779 }
6780 }
6781
6782 if (!NeedsNewDecl)
6783 return nullptr;
6784
6786 EPI.Variadic = FT->isVariadic();
6787 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6788 OverloadParams, EPI);
6789 DeclContext *Parent = FDecl->getParent();
6790 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6791 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6792 FDecl->getIdentifier(), OverloadTy,
6793 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6794 false,
6795 /*hasPrototype=*/true);
6797 FT = cast<FunctionProtoType>(OverloadTy);
6798 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6799 QualType ParamType = FT->getParamType(i);
6800 ParmVarDecl *Parm =
6801 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6802 SourceLocation(), nullptr, ParamType,
6803 /*TInfo=*/nullptr, SC_None, nullptr);
6804 Parm->setScopeInfo(0, i);
6805 Params.push_back(Parm);
6806 }
6807 OverloadDecl->setParams(Params);
6808 // We cannot merge host/device attributes of redeclarations. They have to
6809 // be consistent when created.
6810 if (Sema->LangOpts.CUDA) {
6811 if (FDecl->hasAttr<CUDAHostAttr>())
6812 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6813 if (FDecl->hasAttr<CUDADeviceAttr>())
6814 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6815 }
6816 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6817 return OverloadDecl;
6818}
6819
6820static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6821 FunctionDecl *Callee,
6822 MultiExprArg ArgExprs) {
6823 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6824 // similar attributes) really don't like it when functions are called with an
6825 // invalid number of args.
6826 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6827 /*PartialOverloading=*/false) &&
6828 !Callee->isVariadic())
6829 return;
6830 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6831 return;
6832
6833 if (const EnableIfAttr *Attr =
6834 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6835 S.Diag(Fn->getBeginLoc(),
6836 isa<CXXMethodDecl>(Callee)
6837 ? diag::err_ovl_no_viable_member_function_in_call
6838 : diag::err_ovl_no_viable_function_in_call)
6839 << Callee << Callee->getSourceRange();
6840 S.Diag(Callee->getLocation(),
6841 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6842 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6843 return;
6844 }
6845}
6846
6848 const UnresolvedMemberExpr *const UME, Sema &S) {
6849
6850 const auto GetFunctionLevelDCIfCXXClass =
6851 [](Sema &S) -> const CXXRecordDecl * {
6852 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6853 if (!DC || !DC->getParent())
6854 return nullptr;
6855
6856 // If the call to some member function was made from within a member
6857 // function body 'M' return return 'M's parent.
6858 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6859 return MD->getParent()->getCanonicalDecl();
6860 // else the call was made from within a default member initializer of a
6861 // class, so return the class.
6862 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6863 return RD->getCanonicalDecl();
6864 return nullptr;
6865 };
6866 // If our DeclContext is neither a member function nor a class (in the
6867 // case of a lambda in a default member initializer), we can't have an
6868 // enclosing 'this'.
6869
6870 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6871 if (!CurParentClass)
6872 return false;
6873
6874 // The naming class for implicit member functions call is the class in which
6875 // name lookup starts.
6876 const CXXRecordDecl *const NamingClass =
6878 assert(NamingClass && "Must have naming class even for implicit access");
6879
6880 // If the unresolved member functions were found in a 'naming class' that is
6881 // related (either the same or derived from) to the class that contains the
6882 // member function that itself contained the implicit member access.
6883
6884 return CurParentClass == NamingClass ||
6885 CurParentClass->isDerivedFrom(NamingClass);
6886}
6887
6888static void
6890 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6891
6892 if (!UME)
6893 return;
6894
6895 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6896 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6897 // already been captured, or if this is an implicit member function call (if
6898 // it isn't, an attempt to capture 'this' should already have been made).
6899 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6900 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6901 return;
6902
6903 // Check if the naming class in which the unresolved members were found is
6904 // related (same as or is a base of) to the enclosing class.
6905
6907 return;
6908
6909
6910 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6911 // If the enclosing function is not dependent, then this lambda is
6912 // capture ready, so if we can capture this, do so.
6913 if (!EnclosingFunctionCtx->isDependentContext()) {
6914 // If the current lambda and all enclosing lambdas can capture 'this' -
6915 // then go ahead and capture 'this' (since our unresolved overload set
6916 // contains at least one non-static member function).
6917 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6918 S.CheckCXXThisCapture(CallLoc);
6919 } else if (S.CurContext->isDependentContext()) {
6920 // ... since this is an implicit member reference, that might potentially
6921 // involve a 'this' capture, mark 'this' for potential capture in
6922 // enclosing lambdas.
6923 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6924 CurLSI->addPotentialThisCapture(CallLoc);
6925 }
6926}
6927
6928// Once a call is fully resolved, warn for unqualified calls to specific
6929// C++ standard functions, like move and forward.
6931 const CallExpr *Call) {
6932 // We are only checking unary move and forward so exit early here.
6933 if (Call->getNumArgs() != 1)
6934 return;
6935
6936 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6937 if (!E || isa<UnresolvedLookupExpr>(E))
6938 return;
6939 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6940 if (!DRE || !DRE->getLocation().isValid())
6941 return;
6942
6943 if (DRE->getQualifier())
6944 return;
6945
6946 const FunctionDecl *FD = Call->getDirectCallee();
6947 if (!FD)
6948 return;
6949
6950 // Only warn for some functions deemed more frequent or problematic.
6951 unsigned BuiltinID = FD->getBuiltinID();
6952 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6953 return;
6954
6955 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6957 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6958}
6959
6961 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6962 Expr *ExecConfig) {
6964 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6965 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6966 if (Call.isInvalid())
6967 return Call;
6968
6969 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6970 // language modes.
6971 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6972 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6973 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6974 << ULE->getName();
6975 }
6976
6977 if (LangOpts.OpenMP)
6978 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6979 ExecConfig);
6980 if (LangOpts.CPlusPlus) {
6981 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6983
6984 // If we previously found that the id-expression of this call refers to a
6985 // consteval function but the call is dependent, we should not treat is an
6986 // an invalid immediate call.
6987 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6988 DRE && Call.get()->isValueDependent()) {
6990 }
6991 }
6992 return Call;
6993}
6994
6995// Any type that could be used to form a callable expression
6996static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6997 QualType T = E->getType();
6998 if (T->isDependentType())
6999 return true;
7000
7001 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
7002 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
7003 T->isFunctionType() || T->isFunctionReferenceType() ||
7004 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
7005 T->isBlockPointerType() || T->isRecordType() || T->isUndeducedType())
7006 return true;
7007
7010}
7011
7013 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7014 Expr *ExecConfig, bool IsExecConfig,
7015 bool AllowRecovery) {
7016 // Since this might be a postfix expression, get rid of ParenListExprs.
7018 if (Result.isInvalid()) return ExprError();
7019 Fn = Result.get();
7020
7021 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
7022 // later, when we check boolean conditions, for now we merely forward it
7023 // without any additional checking.
7024 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
7025 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
7026 const auto *FD = cast<FunctionDecl>(Fn->getReferencedDeclOfCallee());
7027
7028 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
7029 QualType FnPtrTy = Context.getPointerType(FD->getType());
7030 Expr *R = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7031 return CallExpr::Create(
7032 Context, R, ArgExprs, Context.AMDGPUFeaturePredicateTy,
7034 }
7035 }
7036
7037 if (CheckArgsForPlaceholders(ArgExprs))
7038 return ExprError();
7039
7040 // The result of __builtin_counted_by_ref cannot be used as a function
7041 // argument. It allows leaking and modification of bounds safety information.
7042 for (const Expr *Arg : ArgExprs)
7043 if (CheckInvalidBuiltinCountedByRef(Arg,
7045 return ExprError();
7046
7047 if (getLangOpts().CPlusPlus) {
7048 // If this is a pseudo-destructor expression, build the call immediately.
7050 if (!ArgExprs.empty()) {
7051 // Pseudo-destructor calls should not have any arguments.
7052 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
7054 SourceRange(ArgExprs.front()->getBeginLoc(),
7055 ArgExprs.back()->getEndLoc()));
7056 }
7057
7058 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
7059 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7060 }
7061 if (Fn->getType() == Context.PseudoObjectTy) {
7062 ExprResult result = CheckPlaceholderExpr(Fn);
7063 if (result.isInvalid()) return ExprError();
7064 Fn = result.get();
7065 }
7066
7067 // Determine whether this is a dependent call inside a C++ template,
7068 // in which case we won't do any semantic analysis now.
7069 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
7070 if (ExecConfig) {
7072 cast<CallExpr>(ExecConfig), ArgExprs,
7073 Context.DependentTy, VK_PRValue,
7074 RParenLoc, CurFPFeatureOverrides());
7075 } else {
7076
7078 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
7079 Fn->getBeginLoc());
7080
7081 // If the type of the function itself is not dependent
7082 // check that it is a reasonable as a function, as type deduction
7083 // later assume the CallExpr has a sensible TYPE.
7084 if (!MayBeFunctionType(Context, Fn))
7085 return ExprError(
7086 Diag(LParenLoc, diag::err_typecheck_call_not_function)
7087 << Fn->getType() << Fn->getSourceRange());
7088
7089 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7090 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7091 }
7092 }
7093
7094 // Determine whether this is a call to an object (C++ [over.call.object]).
7095 if (Fn->getType()->isRecordType())
7096 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
7097 RParenLoc);
7098
7099 if (Fn->getType() == Context.UnknownAnyTy) {
7100 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7101 if (result.isInvalid()) return ExprError();
7102 Fn = result.get();
7103 }
7104
7105 if (Fn->getType() == Context.BoundMemberTy) {
7106 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7107 RParenLoc, ExecConfig, IsExecConfig,
7108 AllowRecovery);
7109 }
7110 }
7111
7112 // Check for overloaded calls. This can happen even in C due to extensions.
7113 if (Fn->getType() == Context.OverloadTy) {
7115
7116 // We aren't supposed to apply this logic if there's an '&' involved.
7119 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7120 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7121 OverloadExpr *ovl = find.Expression;
7122 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
7124 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7125 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
7126 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7127 RParenLoc, ExecConfig, IsExecConfig,
7128 AllowRecovery);
7129 }
7130 }
7131
7132 // If we're directly calling a function, get the appropriate declaration.
7133 if (Fn->getType() == Context.UnknownAnyTy) {
7134 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7135 if (result.isInvalid()) return ExprError();
7136 Fn = result.get();
7137 }
7138
7139 Expr *NakedFn = Fn->IgnoreParens();
7140
7141 bool CallingNDeclIndirectly = false;
7142 NamedDecl *NDecl = nullptr;
7143 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
7144 if (UnOp->getOpcode() == UO_AddrOf) {
7145 CallingNDeclIndirectly = true;
7146 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7147 }
7148 }
7149
7150 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
7151 NDecl = DRE->getDecl();
7152
7153 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
7154 if (FDecl && FDecl->getBuiltinID()) {
7155 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
7156 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
7157 if (Context.BuiltinInfo.isTSBuiltin(FDecl->getBuiltinID()) &&
7158 !Context.BuiltinInfo.isAuxBuiltinID(FDecl->getBuiltinID())) {
7160 getFunctionLevelDeclContext(/*AllowLambda=*/true)));
7161 }
7162 }
7163
7164 // Rewrite the function decl for this builtin by replacing parameters
7165 // with no explicit address space with the address space of the arguments
7166 // in ArgExprs.
7167 if ((FDecl =
7168 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
7169 NDecl = FDecl;
7171 Context, DRE->getQualifierLoc(), SourceLocation(), FDecl, false,
7172 DRE->getLocation(), Fn->getType() /* BuiltinFnTy */,
7173 Fn->getValueKind(), FDecl, nullptr, DRE->isNonOdrUse());
7174 }
7175 }
7176 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
7177 NDecl = ME->getMemberDecl();
7178
7179 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
7180 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7181 FD, /*Complain=*/true, Fn->getBeginLoc()))
7182 return ExprError();
7183
7184 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
7185
7186 // If this expression is a call to a builtin function in HIP compilation,
7187 // allow a pointer-type argument to default address space to be passed as a
7188 // pointer-type parameter to a non-default address space. If Arg is declared
7189 // in the default address space and Param is declared in a non-default
7190 // address space, perform an implicit address space cast to the parameter
7191 // type.
7192 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
7193 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
7194 ++Idx) {
7195 ParmVarDecl *Param = FD->getParamDecl(Idx);
7196 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7197 !ArgExprs[Idx]->getType()->isPointerType())
7198 continue;
7199
7200 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7201 auto ArgTy = ArgExprs[Idx]->getType();
7202 auto ArgPtTy = ArgTy->getPointeeType();
7203 auto ArgAS = ArgPtTy.getAddressSpace();
7204
7205 // Add address space cast if target address spaces are different
7206 bool NeedImplicitASC =
7207 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7208 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7209 // or from specific AS which has target AS matching that of Param.
7211 if (!NeedImplicitASC)
7212 continue;
7213
7214 // First, ensure that the Arg is an RValue.
7215 if (ArgExprs[Idx]->isGLValue()) {
7216 ExprResult Res = DefaultLvalueConversion(ArgExprs[Idx]);
7217 if (Res.isInvalid())
7218 return ExprError();
7219 ArgExprs[Idx] = Res.get();
7220 }
7221
7222 // Construct a new arg type with address space of Param
7223 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7224 ArgPtQuals.setAddressSpace(ParamAS);
7225 auto NewArgPtTy =
7226 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7227 auto NewArgTy =
7228 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7229 ArgTy.getQualifiers());
7230
7231 // Finally perform an implicit address space cast
7232 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7233 CK_AddressSpaceConversion)
7234 .get();
7235 }
7236 }
7237 }
7238
7239 if (Context.isDependenceAllowed() &&
7240 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7241 assert(!getLangOpts().CPlusPlus);
7242 assert((Fn->containsErrors() ||
7243 llvm::any_of(ArgExprs,
7244 [](clang::Expr *E) { return E->containsErrors(); })) &&
7245 "should only occur in error-recovery path.");
7246 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7247 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7248 }
7249 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7250 ExecConfig, IsExecConfig);
7251}
7252
7254 MultiExprArg CallArgs) {
7255 std::string Name = Context.BuiltinInfo.getName(Id);
7256 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7258 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7259
7260 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7261 assert(BuiltInDecl && "failed to find builtin declaration");
7262
7263 ExprResult DeclRef =
7264 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7265 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7266
7268 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7269
7270 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7271 return Call.get();
7272}
7273
7275 SourceLocation BuiltinLoc,
7276 SourceLocation RParenLoc) {
7277 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7278 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7279}
7280
7282 SourceLocation BuiltinLoc,
7283 SourceLocation RParenLoc) {
7286 QualType SrcTy = E->getType();
7287 if (!SrcTy->isDependentType() &&
7288 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7289 return ExprError(
7290 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7291 << DestTy << SrcTy << E->getSourceRange());
7292 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7293}
7294
7296 SourceLocation BuiltinLoc,
7297 SourceLocation RParenLoc) {
7298 TypeSourceInfo *TInfo;
7299 GetTypeFromParser(ParsedDestTy, &TInfo);
7300 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7301}
7302
7304 SourceLocation LParenLoc,
7305 ArrayRef<Expr *> Args,
7306 SourceLocation RParenLoc, Expr *Config,
7307 bool IsExecConfig, ADLCallKind UsesADL) {
7308 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7309 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7310
7311 auto IsSJLJ = [&] {
7312 switch (BuiltinID) {
7313 case Builtin::BI__builtin_longjmp:
7314 case Builtin::BI__builtin_setjmp:
7315 case Builtin::BI__sigsetjmp:
7316 case Builtin::BI_longjmp:
7317 case Builtin::BI_setjmp:
7318 case Builtin::BIlongjmp:
7319 case Builtin::BIsetjmp:
7320 case Builtin::BIsiglongjmp:
7321 case Builtin::BIsigsetjmp:
7322 return true;
7323 default:
7324 return false;
7325 }
7326 };
7327
7328 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7329 if (!CurrentDefer.empty() && IsSJLJ()) {
7330 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7331 // for more than just blocks (e.g. lambdas, nested classes...).
7332 Scope *DeferParent = CurrentDefer.back().first;
7333 Scope *Block = CurScope->getBlockParent();
7334 if (DeferParent->Contains(*CurScope) &&
7335 (!Block || !DeferParent->Contains(*Block)))
7336 Diag(Fn->getExprLoc(), diag::err_defer_invalid_sjlj) << FDecl;
7337 }
7338
7339 // Functions with 'interrupt' attribute cannot be called directly.
7340 if (FDecl) {
7341 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7342 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7343 return ExprError();
7344 }
7345 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7346 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
7347 return ExprError();
7348 }
7349 }
7350
7351 // X86 interrupt handlers may only call routines with attribute
7352 // no_caller_saved_registers since there is no efficient way to
7353 // save and restore the non-GPR state.
7354 if (auto *Caller = getCurFunctionDecl()) {
7355 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7356 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7357 const TargetInfo &TI = Context.getTargetInfo();
7358 bool HasNonGPRRegisters =
7359 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
7360 if (HasNonGPRRegisters &&
7361 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7362 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
7363 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7364 if (FDecl)
7365 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7366 }
7367 }
7368 }
7369
7370 // Extract the return type from the builtin function pointer type.
7371 QualType ResultTy;
7372 if (BuiltinID)
7373 ResultTy = FDecl->getCallResultType();
7374 else
7375 ResultTy = Context.BoolTy;
7376
7377 // Promote the function operand.
7378 // We special-case function promotion here because we only allow promoting
7379 // builtin functions to function pointers in the callee of a call.
7381 if (BuiltinID &&
7382 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7383 // FIXME Several builtins still have setType in
7384 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7385 // Builtins.td to ensure they are correct before removing setType calls.
7386 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7387 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7388 } else
7390 if (Result.isInvalid())
7391 return ExprError();
7392 Fn = Result.get();
7393
7394 // Check for a valid function type, but only if it is not a builtin which
7395 // requires custom type checking. These will be handled by
7396 // CheckBuiltinFunctionCall below just after creation of the call expression.
7397 const FunctionType *FuncT = nullptr;
7398 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7399 retry:
7400 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7401 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7402 // have type pointer to function".
7403 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7404 if (!FuncT)
7405 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7406 << Fn->getType() << Fn->getSourceRange());
7407 } else if (const BlockPointerType *BPT =
7408 Fn->getType()->getAs<BlockPointerType>()) {
7409 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7410 } else {
7411 // Handle calls to expressions of unknown-any type.
7412 if (Fn->getType() == Context.UnknownAnyTy) {
7413 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7414 if (rewrite.isInvalid())
7415 return ExprError();
7416 Fn = rewrite.get();
7417 goto retry;
7418 }
7419
7420 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7421 << Fn->getType() << Fn->getSourceRange());
7422 }
7423 }
7424
7425 // Get the number of parameters in the function prototype, if any.
7426 // We will allocate space for max(Args.size(), NumParams) arguments
7427 // in the call expression.
7428 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7429 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7430
7431 CallExpr *TheCall;
7432 if (Config) {
7433 assert(UsesADL == ADLCallKind::NotADL &&
7434 "CUDAKernelCallExpr should not use ADL");
7435 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7436 Args, ResultTy, VK_PRValue, RParenLoc,
7437 CurFPFeatureOverrides(), NumParams);
7438 } else {
7439 TheCall =
7440 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7441 CurFPFeatureOverrides(), NumParams, UsesADL);
7442 }
7443
7444 // Bail out early if calling a builtin with custom type checking.
7445 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7446 // For HLSL builtin aliases, the call was resolved via overload resolution
7447 // which may have selected a conversion sequence (e.g., vector-to-scalar
7448 // truncation). Convert arguments to match the declared prototype before
7449 // the custom type checker runs, otherwise the builtin will operate on
7450 // the unconverted argument types.
7451 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7452 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7453 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, P, Args, RParenLoc,
7454 IsExecConfig))
7455 return ExprError();
7456 }
7457 }
7458 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7459 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
7460 E = CheckForImmediateInvocation(E, FDecl);
7461 return E;
7462 }
7463
7464 if (getLangOpts().CUDA) {
7465 if (Config) {
7466 // CUDA: Kernel calls must be to global functions
7467 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7468 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7469 << FDecl << Fn->getSourceRange());
7470
7471 // CUDA: Kernel function must have 'void' return type
7472 if (!FuncT->getReturnType()->isVoidType() &&
7473 !FuncT->getReturnType()->getAs<AutoType>() &&
7475 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7476 << Fn->getType() << Fn->getSourceRange());
7477 } else {
7478 // CUDA: Calls to global functions must be configured
7479 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7480 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7481 << FDecl << Fn->getSourceRange());
7482 }
7483 }
7484
7485 // Check for a valid return type
7486 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7487 FDecl))
7488 return ExprError();
7489
7490 // We know the result type of the call, set it.
7491 TheCall->setType(FuncT->getCallResultType(Context));
7493
7494 // WebAssembly tables can't be used as arguments.
7495 if (Context.getTargetInfo().getTriple().isWasm()) {
7496 for (const Expr *Arg : Args) {
7497 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7498 return ExprError(Diag(Arg->getExprLoc(),
7499 diag::err_wasm_table_as_function_parameter));
7500 }
7501 }
7502 }
7503
7504 // Check read_image{i|ui} sampler argument before ConvertArgumentsForCall
7505 // replaces sampler DeclRefExprs with their integer initializers.
7506 if (getLangOpts().OpenCL && FDecl) {
7507 OpenCL().checkBuiltinReadImage(FDecl, TheCall);
7508 }
7509
7510 if (Proto) {
7511 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7512 IsExecConfig))
7513 return ExprError();
7514 } else {
7515 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7516
7517 if (FDecl) {
7518 // Check if we have too few/too many template arguments, based
7519 // on our knowledge of the function definition.
7520 const FunctionDecl *Def = nullptr;
7521 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7522 Proto = Def->getType()->getAs<FunctionProtoType>();
7523 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7524 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7525 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7526 }
7527
7528 // If the function we're calling isn't a function prototype, but we have
7529 // a function prototype from a prior declaratiom, use that prototype.
7530 if (!FDecl->hasPrototype())
7531 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7532 }
7533
7534 // If we still haven't found a prototype to use but there are arguments to
7535 // the call, diagnose this as calling a function without a prototype.
7536 // However, if we found a function declaration, check to see if
7537 // -Wdeprecated-non-prototype was disabled where the function was declared.
7538 // If so, we will silence the diagnostic here on the assumption that this
7539 // interface is intentional and the user knows what they're doing. We will
7540 // also silence the diagnostic if there is a function declaration but it
7541 // was implicitly defined (the user already gets diagnostics about the
7542 // creation of the implicit function declaration, so the additional warning
7543 // is not helpful).
7544 if (!Proto && !Args.empty() &&
7545 (!FDecl || (!FDecl->isImplicit() &&
7546 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7547 FDecl->getLocation()))))
7548 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7549 << (FDecl != nullptr) << FDecl;
7550
7551 // Promote the arguments (C99 6.5.2.2p6).
7552 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7553 Expr *Arg = Args[i];
7554
7555 if (Proto && i < Proto->getNumParams()) {
7557 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7558 ExprResult ArgE =
7560 if (ArgE.isInvalid())
7561 return true;
7562
7563 Arg = ArgE.getAs<Expr>();
7564
7565 } else {
7567
7568 if (ArgE.isInvalid())
7569 return true;
7570
7571 Arg = ArgE.getAs<Expr>();
7572 }
7573
7574 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7575 diag::err_call_incomplete_argument, Arg))
7576 return ExprError();
7577
7578 TheCall->setArg(i, Arg);
7579 }
7580 TheCall->computeDependence();
7581 }
7582
7583 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7584 if (Method->isImplicitObjectMemberFunction())
7585 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7586 << Fn->getSourceRange() << 0);
7587
7588 // Check for sentinels
7589 if (NDecl)
7590 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7591
7592 // Warn for unions passing across security boundary (CMSE).
7593 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7594 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7595 if (const auto *RT =
7596 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7597 if (RT->getDecl()->isOrContainsUnion())
7598 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7599 << 0 << i;
7600 }
7601 }
7602 }
7603
7604 // Do special checking on direct calls to functions.
7605 if (FDecl) {
7606 if (CheckFunctionCall(FDecl, TheCall, Proto))
7607 return ExprError();
7608
7609 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7610 checkFortifiedLibcArgument(FDecl, TheCall);
7611
7612 if (BuiltinID)
7613 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7614 } else if (NDecl) {
7615 if (CheckPointerCall(NDecl, TheCall, Proto))
7616 return ExprError();
7617 } else {
7618 if (CheckOtherCall(TheCall, Proto))
7619 return ExprError();
7620 }
7621
7622 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7623}
7624
7627 SourceLocation RParenLoc, Expr *InitExpr) {
7628 assert(Ty && "ActOnCompoundLiteral(): missing type");
7629 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7630
7631 TypeSourceInfo *TInfo;
7632 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7633 if (!TInfo)
7634 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7635
7636 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7637}
7638
7641 SourceLocation RParenLoc, Expr *LiteralExpr) {
7642 QualType literalType = TInfo->getType();
7643
7644 if (literalType->isArrayType()) {
7646 LParenLoc, Context.getBaseElementType(literalType),
7647 diag::err_array_incomplete_or_sizeless_type,
7648 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7649 return ExprError();
7650 if (literalType->isVariableArrayType()) {
7651 // C23 6.7.10p4: An entity of variable length array type shall not be
7652 // initialized except by an empty initializer.
7653 //
7654 // The C extension warnings are issued from ParseBraceInitializer() and
7655 // do not need to be issued here. However, we continue to issue an error
7656 // in the case there are initializers or we are compiling C++. We allow
7657 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7658 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7659 // FIXME: should we allow this construct in C++ when it makes sense to do
7660 // so?
7661 //
7662 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7663 // shall specify an object type or an array of unknown size, but not a
7664 // variable length array type. This seems odd, as it allows 'int a[size] =
7665 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7666 // says, this is what's implemented here for C (except for the extension
7667 // that permits constant foldable size arrays)
7668
7669 auto diagID = LangOpts.CPlusPlus
7670 ? diag::err_variable_object_no_init
7671 : diag::err_compound_literal_with_vla_type;
7672 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7673 diagID))
7674 return ExprError();
7675 }
7676 } else if (!literalType->isDependentType() &&
7677 RequireCompleteType(LParenLoc, literalType,
7678 diag::err_typecheck_decl_incomplete_type,
7679 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7680 return ExprError();
7681
7682 InitializedEntity Entity
7686 SourceRange(LParenLoc, RParenLoc),
7687 /*InitList=*/true);
7688 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7689 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7690 &literalType);
7691 if (Result.isInvalid())
7692 return ExprError();
7693 LiteralExpr = Result.get();
7694
7695 // We treat the compound literal as being at file scope if it's not in a
7696 // function or method body, or within the function's prototype scope. This
7697 // means the following compound literal is not at file scope:
7698 // void func(char *para[(int [1]){ 0 }[0]);
7699 const Scope *S = getCurScope();
7700 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7701 !S->isInCFunctionScope() &&
7702 (!S || !S->isFunctionPrototypeScope());
7703
7704 // In C, compound literals are l-values for some reason.
7705 // For GCC compatibility, in C++, file-scope array compound literals with
7706 // constant initializers are also l-values, and compound literals are
7707 // otherwise prvalues.
7708 //
7709 // (GCC also treats C++ list-initialized file-scope array prvalues with
7710 // constant initializers as l-values, but that's non-conforming, so we don't
7711 // follow it there.)
7712 //
7713 // FIXME: It would be better to handle the lvalue cases as materializing and
7714 // lifetime-extending a temporary object, but our materialized temporaries
7715 // representation only supports lifetime extension from a variable, not "out
7716 // of thin air".
7717 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7718 // is bound to the result of applying array-to-pointer decay to the compound
7719 // literal.
7720 // FIXME: GCC supports compound literals of reference type, which should
7721 // obviously have a value kind derived from the kind of reference involved.
7723 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7724 ? VK_PRValue
7725 : VK_LValue;
7726
7727 // C99 6.5.2.5
7728 // "If the compound literal occurs outside the body of a function, the
7729 // initializer list shall consist of constant expressions."
7730 if (IsFileScope) {
7731 // An element with an immediate call or source_location is left for the
7732 // use site, and for its rebuild too when the rebuilt default arguments
7733 // could not be given the use-site location.
7734 bool DeferImmediate =
7738 // Store the element's value so CodeGen does not re-evaluate it outside a
7739 // constant context.
7740 auto CheckElement = [&](Expr *Init) -> Expr * {
7741 if (Init->isTypeDependent() || Init->isValueDependent())
7742 return Init;
7743 if (DeferImmediate) {
7745 V.TraverseStmt(Init);
7746 if (V.HasImmediateCalls)
7747 return Init;
7748 }
7749 Expr::EvalResult Eval;
7750 if (!Init->EvaluateAsConstantExpr(Eval, Context,
7751 ConstantExprKind::Initializer)) {
7752 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7753 << Init->getSourceBitField();
7754 return nullptr;
7755 }
7756 // An immediate invocation already is a ConstantExpr.
7758 return Init;
7759 return ConstantExpr::Create(Context, Init, Eval.Val);
7760 };
7761 if (auto *ILE = dyn_cast<InitListExpr>(LiteralExpr)) {
7762 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7763 Expr *Init = CheckElement(ILE->getInit(i));
7764 if (!Init)
7765 return ExprError();
7766 ILE->setInit(i, Init);
7767 }
7768 } else {
7769 LiteralExpr = CheckElement(LiteralExpr);
7770 if (!LiteralExpr)
7771 return ExprError();
7772 }
7773 }
7774
7775 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7776 LiteralExpr, IsFileScope);
7777 if (!IsFileScope && literalType.getAddressSpace() != LangAS::opencl_private &&
7778 literalType.getAddressSpace() != LangAS::Default) {
7779 // Embedded-C extensions to C99 6.5.2.5:
7780 // "If the compound literal occurs inside the body of a function, the
7781 // type name shall not be qualified by an address-space qualifier."
7782 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7783 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7784 return ExprError();
7785 }
7786
7787 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7788 // Compound literals that have automatic storage duration are destroyed at
7789 // the end of the scope in C; in C++, they're just temporaries.
7790
7791 // Emit diagnostics if it is or contains a C union type that is non-trivial
7792 // to destruct.
7797
7798 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7799 Cleanup.setExprNeedsCleanups(true);
7800 ExprCleanupObjects.push_back(E);
7801 if (literalType.isDestructedType()) {
7803 }
7804 }
7805
7808 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7809 E->getInitializer()->getExprLoc());
7810
7811 return MaybeBindToTemporary(E);
7812}
7813
7816 SourceLocation RBraceLoc) {
7817 // Only produce each kind of designated initialization diagnostic once.
7818 SourceLocation FirstDesignator;
7819 bool DiagnosedArrayDesignator = false;
7820 bool DiagnosedNestedDesignator = false;
7821 bool DiagnosedMixedDesignator = false;
7822
7823 // Check that any designated initializers are syntactically valid in the
7824 // current language mode.
7825 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7826 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7827 if (FirstDesignator.isInvalid())
7828 FirstDesignator = DIE->getBeginLoc();
7829
7830 if (!getLangOpts().CPlusPlus)
7831 break;
7832
7833 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7834 DiagnosedNestedDesignator = true;
7835 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7836 << DIE->getDesignatorsSourceRange();
7837 }
7838
7839 for (auto &Desig : DIE->designators()) {
7840 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7841 DiagnosedArrayDesignator = true;
7842 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7843 << Desig.getSourceRange();
7844 }
7845 }
7846
7847 if (!DiagnosedMixedDesignator &&
7848 !isa<DesignatedInitExpr>(InitArgList[0])) {
7849 DiagnosedMixedDesignator = true;
7850 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7851 << DIE->getSourceRange();
7852 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7853 << InitArgList[0]->getSourceRange();
7854 }
7855 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7856 isa<DesignatedInitExpr>(InitArgList[0])) {
7857 DiagnosedMixedDesignator = true;
7858 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7859 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7860 << DIE->getSourceRange();
7861 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7862 << InitArgList[I]->getSourceRange();
7863 }
7864 }
7865
7866 if (FirstDesignator.isValid()) {
7867 // Only diagnose designated initiaization as a C++20 extension if we didn't
7868 // already diagnose use of (non-C++20) C99 designator syntax.
7869 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7870 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7871 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7872 ? diag::warn_cxx17_compat_designated_init
7873 : diag::ext_cxx_designated_init);
7874 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7875 Diag(FirstDesignator, diag::ext_designated_init);
7876 }
7877 }
7878
7879 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7880}
7881
7883 MultiExprArg InitArgList,
7884 SourceLocation RBraceLoc, bool IsExplicit) {
7885 // Semantic analysis for initializers is done by ActOnDeclarator() and
7886 // CheckInitializer() - it requires knowledge of the object being initialized.
7887
7888 // Immediately handle non-overload placeholders. Overloads can be
7889 // resolved contextually, but everything else here can't.
7890 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7891 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7892 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7893
7894 // Ignore failures; dropping the entire initializer list because
7895 // of one failure would be terrible for indexing/etc.
7896 if (result.isInvalid()) continue;
7897
7898 InitArgList[I] = result.get();
7899 }
7900 }
7901
7902 InitListExpr *E = new (Context)
7903 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7904 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7905 return E;
7906}
7907
7909 assert(E.get()->getType()->isBlockPointerType());
7910 assert(E.get()->isPRValue());
7911
7912 // Only do this in an r-value context.
7913 if (!getLangOpts().ObjCAutoRefCount) return;
7914
7916 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7917 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7918 Cleanup.setExprNeedsCleanups(true);
7919}
7920
7922 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7923 // Also, callers should have filtered out the invalid cases with
7924 // pointers. Everything else should be possible.
7925
7926 QualType SrcTy = Src.get()->getType();
7927 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7928 return CK_NoOp;
7929
7930 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7932 llvm_unreachable("member pointer type in C");
7933
7934 case Type::STK_CPointer:
7937 switch (DestTy->getScalarTypeKind()) {
7938 case Type::STK_CPointer: {
7939 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7940 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7941 if (SrcAS != DestAS)
7942 return CK_AddressSpaceConversion;
7943 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7944 return CK_NoOp;
7945 return CK_BitCast;
7946 }
7948 return (SrcKind == Type::STK_BlockPointer
7949 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7951 if (SrcKind == Type::STK_ObjCObjectPointer)
7952 return CK_BitCast;
7953 if (SrcKind == Type::STK_CPointer)
7954 return CK_CPointerToObjCPointerCast;
7956 return CK_BlockPointerToObjCPointerCast;
7957 case Type::STK_Bool:
7958 return CK_PointerToBoolean;
7959 case Type::STK_Integral:
7960 return CK_PointerToIntegral;
7961 case Type::STK_Floating:
7966 llvm_unreachable("illegal cast from pointer");
7967 }
7968 llvm_unreachable("Should have returned before this");
7969
7971 switch (DestTy->getScalarTypeKind()) {
7973 return CK_FixedPointCast;
7974 case Type::STK_Bool:
7975 return CK_FixedPointToBoolean;
7976 case Type::STK_Integral:
7977 return CK_FixedPointToIntegral;
7978 case Type::STK_Floating:
7979 return CK_FixedPointToFloating;
7982 Diag(Src.get()->getExprLoc(),
7983 diag::err_unimplemented_conversion_with_fixed_point_type)
7984 << DestTy;
7985 return CK_IntegralCast;
7986 case Type::STK_CPointer:
7990 llvm_unreachable("illegal cast to pointer type");
7991 }
7992 llvm_unreachable("Should have returned before this");
7993
7994 case Type::STK_Bool: // casting from bool is like casting from an integer
7995 case Type::STK_Integral:
7996 switch (DestTy->getScalarTypeKind()) {
7997 case Type::STK_CPointer:
8002 return CK_NullToPointer;
8003 return CK_IntegralToPointer;
8004 case Type::STK_Bool:
8005 return CK_IntegralToBoolean;
8006 case Type::STK_Integral:
8007 return CK_IntegralCast;
8008 case Type::STK_Floating:
8009 return CK_IntegralToFloating;
8011 Src = ImpCastExprToType(Src.get(),
8012 DestTy->castAs<ComplexType>()->getElementType(),
8013 CK_IntegralCast);
8014 return CK_IntegralRealToComplex;
8016 Src = ImpCastExprToType(Src.get(),
8017 DestTy->castAs<ComplexType>()->getElementType(),
8018 CK_IntegralToFloating);
8019 return CK_FloatingRealToComplex;
8021 llvm_unreachable("member pointer type in C");
8023 return CK_IntegralToFixedPoint;
8024 }
8025 llvm_unreachable("Should have returned before this");
8026
8027 case Type::STK_Floating:
8028 switch (DestTy->getScalarTypeKind()) {
8029 case Type::STK_Floating:
8030 return CK_FloatingCast;
8031 case Type::STK_Bool:
8032 return CK_FloatingToBoolean;
8033 case Type::STK_Integral:
8034 return CK_FloatingToIntegral;
8036 Src = ImpCastExprToType(Src.get(),
8037 DestTy->castAs<ComplexType>()->getElementType(),
8038 CK_FloatingCast);
8039 return CK_FloatingRealToComplex;
8041 Src = ImpCastExprToType(Src.get(),
8042 DestTy->castAs<ComplexType>()->getElementType(),
8043 CK_FloatingToIntegral);
8044 return CK_IntegralRealToComplex;
8045 case Type::STK_CPointer:
8048 llvm_unreachable("valid float->pointer cast?");
8050 llvm_unreachable("member pointer type in C");
8052 return CK_FloatingToFixedPoint;
8053 }
8054 llvm_unreachable("Should have returned before this");
8055
8057 switch (DestTy->getScalarTypeKind()) {
8059 return CK_FloatingComplexCast;
8061 return CK_FloatingComplexToIntegralComplex;
8062 case Type::STK_Floating: {
8063 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8064 if (Context.hasSameType(ET, DestTy))
8065 return CK_FloatingComplexToReal;
8066 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
8067 return CK_FloatingCast;
8068 }
8069 case Type::STK_Bool:
8070 return CK_FloatingComplexToBoolean;
8071 case Type::STK_Integral:
8072 Src = ImpCastExprToType(Src.get(),
8073 SrcTy->castAs<ComplexType>()->getElementType(),
8074 CK_FloatingComplexToReal);
8075 return CK_FloatingToIntegral;
8076 case Type::STK_CPointer:
8079 llvm_unreachable("valid complex float->pointer cast?");
8081 llvm_unreachable("member pointer type in C");
8083 Diag(Src.get()->getExprLoc(),
8084 diag::err_unimplemented_conversion_with_fixed_point_type)
8085 << SrcTy;
8086 return CK_IntegralCast;
8087 }
8088 llvm_unreachable("Should have returned before this");
8089
8091 switch (DestTy->getScalarTypeKind()) {
8093 return CK_IntegralComplexToFloatingComplex;
8095 return CK_IntegralComplexCast;
8096 case Type::STK_Integral: {
8097 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8098 if (Context.hasSameType(ET, DestTy))
8099 return CK_IntegralComplexToReal;
8100 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
8101 return CK_IntegralCast;
8102 }
8103 case Type::STK_Bool:
8104 return CK_IntegralComplexToBoolean;
8105 case Type::STK_Floating:
8106 Src = ImpCastExprToType(Src.get(),
8107 SrcTy->castAs<ComplexType>()->getElementType(),
8108 CK_IntegralComplexToReal);
8109 return CK_IntegralToFloating;
8110 case Type::STK_CPointer:
8113 llvm_unreachable("valid complex int->pointer cast?");
8115 llvm_unreachable("member pointer type in C");
8117 Diag(Src.get()->getExprLoc(),
8118 diag::err_unimplemented_conversion_with_fixed_point_type)
8119 << SrcTy;
8120 return CK_IntegralCast;
8121 }
8122 llvm_unreachable("Should have returned before this");
8123 }
8124
8125 llvm_unreachable("Unhandled scalar cast");
8126}
8127
8129 QualType &eltType) {
8130 // Vectors are simple.
8131 if (const VectorType *vecType = type->getAs<VectorType>()) {
8132 len = vecType->getNumElements();
8133 eltType = vecType->getElementType();
8134 assert(eltType->isScalarType() || eltType->isMFloat8Type());
8135 return true;
8136 }
8137
8138 // We allow lax conversion to and from non-vector types, but only if
8139 // they're real types (i.e. non-complex, non-pointer scalar types).
8140 if (!type->isRealType()) return false;
8141
8142 len = 1;
8143 eltType = type;
8144 return true;
8145}
8146
8148 assert(srcTy->isVectorType() || destTy->isVectorType());
8149
8150 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8151 if (!FirstType->isSVESizelessBuiltinType())
8152 return false;
8153
8154 const auto *VecTy = SecondType->getAs<VectorType>();
8155 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
8156 };
8157
8158 return ValidScalableConversion(srcTy, destTy) ||
8159 ValidScalableConversion(destTy, srcTy);
8160}
8161
8163 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8164 return false;
8165
8166 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8167 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8168
8169 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8170 matSrcType->getNumColumns() == matDestType->getNumColumns();
8171}
8172
8174 assert(DestTy->isVectorType() || SrcTy->isVectorType());
8175
8176 uint64_t SrcLen, DestLen;
8177 QualType SrcEltTy, DestEltTy;
8178 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
8179 return false;
8180 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
8181 return false;
8182
8183 // x87 long double has padding bits, so it cannot be bitcast to another type.
8184 auto IsX87LongDouble = [&](QualType T) {
8185 return T->isRealFloatingType() && &Context.getFloatTypeSemantics(T) ==
8186 &llvm::APFloat::x87DoubleExtended();
8187 };
8188 if (IsX87LongDouble(SrcEltTy) != IsX87LongDouble(DestEltTy))
8189 return false;
8190
8191 // ASTContext::getTypeSize will return the size rounded up to a
8192 // power of 2, so instead of using that, we need to use the raw
8193 // element size multiplied by the element count.
8194 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
8195 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
8196
8197 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8198}
8199
8201 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
8202 "expected at least one type to be a vector here");
8203
8204 bool IsSrcTyAltivec =
8205 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8207 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8209 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8211
8212 bool IsDestTyAltivec = DestTy->isVectorType() &&
8213 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8215 (DestTy->castAs<VectorType>()->getVectorKind() ==
8217 (DestTy->castAs<VectorType>()->getVectorKind() ==
8219
8220 return (IsSrcTyAltivec || IsDestTyAltivec);
8221}
8222
8224 assert(destTy->isVectorType() || srcTy->isVectorType());
8225
8226 // Disallow lax conversions between scalars and ExtVectors (these
8227 // conversions are allowed for other vector types because common headers
8228 // depend on them). Most scalar OP ExtVector cases are handled by the
8229 // splat path anyway, which does what we want (convert, not bitcast).
8230 // What this rules out for ExtVectors is crazy things like char4*float.
8231 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8232 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8233
8234 return areVectorTypesSameSize(srcTy, destTy);
8235}
8236
8238 assert(destTy->isVectorType() || srcTy->isVectorType());
8239
8240 switch (Context.getLangOpts().getLaxVectorConversions()) {
8242 return false;
8243
8245 if (!srcTy->isIntegralOrEnumerationType()) {
8246 auto *Vec = srcTy->getAs<VectorType>();
8247 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8248 return false;
8249 }
8250 if (!destTy->isIntegralOrEnumerationType()) {
8251 auto *Vec = destTy->getAs<VectorType>();
8252 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8253 return false;
8254 }
8255 // OK, integer (vector) -> integer (vector) bitcast.
8256 break;
8257
8259 break;
8260 }
8261
8262 return areLaxCompatibleVectorTypes(srcTy, destTy);
8263}
8264
8266 CastKind &Kind) {
8267 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8268 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8269 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8270 << DestTy << SrcTy << R;
8271 }
8272 } else if (SrcTy->isMatrixType()) {
8273 return Diag(R.getBegin(),
8274 diag::err_invalid_conversion_between_matrix_and_type)
8275 << SrcTy << DestTy << R;
8276 } else if (DestTy->isMatrixType()) {
8277 return Diag(R.getBegin(),
8278 diag::err_invalid_conversion_between_matrix_and_type)
8279 << DestTy << SrcTy << R;
8280 }
8281
8282 Kind = CK_MatrixCast;
8283 return false;
8284}
8285
8287 CastKind &Kind) {
8288 assert(VectorTy->isVectorType() && "Not a vector type!");
8289
8290 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8291 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8292 return Diag(R.getBegin(),
8293 Ty->isVectorType() ?
8294 diag::err_invalid_conversion_between_vectors :
8295 diag::err_invalid_conversion_between_vector_and_integer)
8296 << VectorTy << Ty << R;
8297 } else
8298 return Diag(R.getBegin(),
8299 diag::err_invalid_conversion_between_vector_and_scalar)
8300 << VectorTy << Ty << R;
8301
8302 Kind = CK_BitCast;
8303 return false;
8304}
8305
8307 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8308
8309 if (DestElemTy == SplattedExpr->getType())
8310 return SplattedExpr;
8311
8312 assert(DestElemTy->isFloatingType() ||
8313 DestElemTy->isIntegralOrEnumerationType());
8314
8315 CastKind CK;
8316 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8317 // OpenCL requires that we convert `true` boolean expressions to -1, but
8318 // only when splatting vectors.
8319 if (DestElemTy->isFloatingType()) {
8320 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8321 // in two steps: boolean to signed integral, then to floating.
8322 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8323 CK_BooleanToSignedIntegral);
8324 SplattedExpr = CastExprRes.get();
8325 CK = CK_IntegralToFloating;
8326 } else {
8327 CK = CK_BooleanToSignedIntegral;
8328 }
8329 } else {
8330 ExprResult CastExprRes = SplattedExpr;
8331 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8332 if (CastExprRes.isInvalid())
8333 return ExprError();
8334 SplattedExpr = CastExprRes.get();
8335 }
8336 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8337}
8338
8340 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8341
8342 if (DestElemTy == SplattedExpr->getType())
8343 return SplattedExpr;
8344
8345 assert(DestElemTy->isFloatingType() ||
8346 DestElemTy->isIntegralOrEnumerationType());
8347
8348 ExprResult CastExprRes = SplattedExpr;
8349 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
8350 if (CastExprRes.isInvalid())
8351 return ExprError();
8352 SplattedExpr = CastExprRes.get();
8353
8354 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8355}
8356
8358 Expr *CastExpr, CastKind &Kind) {
8359 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8360
8361 QualType SrcTy = CastExpr->getType();
8362
8363 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8364 // an ExtVectorType.
8365 // In OpenCL, casts between vectors of different types are not allowed.
8366 // (See OpenCL 6.2).
8367 if (SrcTy->isVectorType()) {
8368 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8369 (getLangOpts().OpenCL &&
8370 !Context.hasSameUnqualifiedType(DestTy, SrcTy) &&
8371 !Context.areCompatibleVectorTypes(DestTy, SrcTy))) {
8372 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8373 << DestTy << SrcTy << R;
8374 return ExprError();
8375 }
8376 Kind = CK_BitCast;
8377 return CastExpr;
8378 }
8379
8380 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8381 // conversion will take place first from scalar to elt type, and then
8382 // splat from elt type to vector.
8383 if (SrcTy->isPointerType())
8384 return Diag(R.getBegin(),
8385 diag::err_invalid_conversion_between_vector_and_scalar)
8386 << DestTy << SrcTy << R;
8387
8388 Kind = CK_VectorSplat;
8389 return prepareVectorSplat(DestTy, CastExpr);
8390}
8391
8392/// Check that a call to alloc_size function specifies sufficient space for the
8393/// destination type.
8394static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8395 const Expr *E) {
8396 QualType SourceType = E->getType();
8397 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8398 DestType == SourceType)
8399 return;
8400
8401 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
8402 if (!CE)
8403 return;
8404
8405 // Find the total size allocated by the function call.
8406 if (!CE->getCalleeAllocSizeAttr())
8407 return;
8408 std::optional<llvm::APInt> AllocSize =
8409 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
8410 // Allocations of size zero are permitted as a special case. They are usually
8411 // done intentionally.
8412 if (!AllocSize || AllocSize->isZero())
8413 return;
8414 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
8415
8416 QualType TargetType = DestType->getPointeeType();
8417 // Find the destination size. As a special case function types have size of
8418 // one byte to match the sizeof operator behavior.
8419 auto LhsSize = TargetType->isFunctionType()
8420 ? CharUnits::One()
8421 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
8422 if (LhsSize && Size < LhsSize)
8423 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
8424 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8425}
8426
8429 Declarator &D, ParsedType &Ty,
8430 SourceLocation RParenLoc, Expr *CastExpr) {
8431 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8432 "ActOnCastExpr(): missing type or expr");
8433
8435 if (D.isInvalidType())
8436 return ExprError();
8437
8438 if (getLangOpts().CPlusPlus) {
8439 // Check that there are no default arguments (C++ only).
8441 }
8442
8444
8445 QualType castType = castTInfo->getType();
8446 Ty = CreateParsedType(castType, castTInfo);
8447
8448 bool isVectorLiteral = false;
8449
8450 // Check for an altivec or OpenCL literal,
8451 // i.e. all the elements are integer constants.
8452 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8453 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8454 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8455 && castType->isVectorType() && (PE || PLE)) {
8456 if (PLE && PLE->getNumExprs() == 0) {
8457 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8458 return ExprError();
8459 }
8460 if (PE || PLE->getNumExprs() == 1) {
8461 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8462 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8463 isVectorLiteral = true;
8464 }
8465 else
8466 isVectorLiteral = true;
8467 }
8468
8469 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8470 // then handle it as such.
8471 if (isVectorLiteral)
8472 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8473
8474 // If the Expr being casted is a ParenListExpr, handle it specially.
8475 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8476 // sequence of BinOp comma operators.
8479 if (Result.isInvalid()) return ExprError();
8480 CastExpr = Result.get();
8481 }
8482
8483 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8484 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8485
8487
8489
8491
8492 CheckSufficientAllocSize(*this, castType, CastExpr);
8493
8494 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8495}
8496
8498 SourceLocation RParenLoc, Expr *E,
8499 TypeSourceInfo *TInfo) {
8500 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8501 "Expected paren or paren list expression");
8502
8503 Expr **exprs;
8504 unsigned numExprs;
8505 Expr *subExpr;
8506 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8507 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8508 LiteralLParenLoc = PE->getLParenLoc();
8509 LiteralRParenLoc = PE->getRParenLoc();
8510 exprs = PE->getExprs();
8511 numExprs = PE->getNumExprs();
8512 } else { // isa<ParenExpr> by assertion at function entrance
8513 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8514 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8515 subExpr = cast<ParenExpr>(E)->getSubExpr();
8516 exprs = &subExpr;
8517 numExprs = 1;
8518 }
8519
8520 QualType Ty = TInfo->getType();
8521 assert(Ty->isVectorType() && "Expected vector type");
8522
8523 SmallVector<Expr *, 8> initExprs;
8524 const VectorType *VTy = Ty->castAs<VectorType>();
8525 unsigned numElems = VTy->getNumElements();
8526
8527 // '(...)' form of vector initialization in AltiVec: the number of
8528 // initializers must be one or must match the size of the vector.
8529 // If a single value is specified in the initializer then it will be
8530 // replicated to all the components of the vector
8532 VTy->getElementType()))
8533 return ExprError();
8535 // The number of initializers must be one or must match the size of the
8536 // vector. If a single value is specified in the initializer then it will
8537 // be replicated to all the components of the vector
8538 if (numExprs == 1) {
8539 QualType ElemTy = VTy->getElementType();
8540 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8541 if (Literal.isInvalid())
8542 return ExprError();
8543 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8544 PrepareScalarCast(Literal, ElemTy));
8545 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8546 }
8547 else if (numExprs < numElems) {
8548 Diag(E->getExprLoc(),
8549 diag::err_incorrect_number_of_vector_initializers);
8550 return ExprError();
8551 }
8552 else
8553 initExprs.append(exprs, exprs + numExprs);
8554 }
8555 else {
8556 // For OpenCL, when the number of initializers is a single value,
8557 // it will be replicated to all components of the vector.
8559 numExprs == 1) {
8560 QualType SrcTy = exprs[0]->getType();
8561 if (!SrcTy->isArithmeticType()) {
8562 Diag(exprs[0]->getBeginLoc(), diag::err_typecheck_convert_incompatible)
8563 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8564 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8565 return ExprError();
8566 }
8567 QualType ElemTy = VTy->getElementType();
8568 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8569 if (Literal.isInvalid())
8570 return ExprError();
8571 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8572 PrepareScalarCast(Literal, ElemTy));
8573 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8574 }
8575
8576 initExprs.append(exprs, exprs + numExprs);
8577 }
8578 // FIXME: This means that pretty-printing the final AST will produce curly
8579 // braces instead of the original commas.
8580 InitListExpr *initE =
8581 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8582 LiteralRParenLoc, /*isExplicit=*/false);
8583 initE->setType(Ty);
8584 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8585}
8586
8589 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8590 if (!E)
8591 return OrigExpr;
8592
8593 ExprResult Result(E->getExpr(0));
8594
8595 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8596 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8597 E->getExpr(i));
8598
8599 if (Result.isInvalid()) return ExprError();
8600
8601 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8602}
8603
8609
8611 unsigned NumUserSpecifiedExprs,
8612 SourceLocation InitLoc,
8613 SourceLocation LParenLoc,
8614 SourceLocation RParenLoc) {
8615 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8616 InitLoc, LParenLoc, RParenLoc);
8617}
8618
8619bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8620 SourceLocation QuestionLoc) {
8621 const Expr *NullExpr = LHSExpr;
8622 const Expr *NonPointerExpr = RHSExpr;
8626
8627 if (NullKind == Expr::NPCK_NotNull) {
8628 NullExpr = RHSExpr;
8629 NonPointerExpr = LHSExpr;
8630 NullKind =
8633 }
8634
8635 if (NullKind == Expr::NPCK_NotNull)
8636 return false;
8637
8638 if (NullKind == Expr::NPCK_ZeroExpression)
8639 return false;
8640
8641 if (NullKind == Expr::NPCK_ZeroLiteral) {
8642 // In this case, check to make sure that we got here from a "NULL"
8643 // string in the source code.
8644 NullExpr = NullExpr->IgnoreParenImpCasts();
8645 SourceLocation loc = NullExpr->getExprLoc();
8646 if (!findMacroSpelling(loc, "NULL"))
8647 return false;
8648 }
8649
8650 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8651 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8652 << NonPointerExpr->getType() << DiagType
8653 << NonPointerExpr->getSourceRange();
8654 return true;
8655}
8656
8657/// Return false if the condition expression is valid, true otherwise.
8658static bool checkCondition(Sema &S, const Expr *Cond,
8659 SourceLocation QuestionLoc) {
8660 QualType CondTy = Cond->getType();
8661
8662 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8663 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8664 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8665 << CondTy << Cond->getSourceRange();
8666 return true;
8667 }
8668
8669 // C99 6.5.15p2
8670 if (CondTy->isScalarType()) return false;
8671
8672 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8673 << CondTy << Cond->getSourceRange();
8674 return true;
8675}
8676
8677/// Return false if the NullExpr can be promoted to PointerTy,
8678/// true otherwise.
8680 QualType PointerTy) {
8681 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8682 !NullExpr.get()->isNullPointerConstant(S.Context,
8684 return true;
8685
8686 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8687 return false;
8688}
8689
8690/// Checks compatibility between two pointers and return the resulting
8691/// type.
8693 ExprResult &RHS,
8694 SourceLocation Loc) {
8695 QualType LHSTy = LHS.get()->getType();
8696 QualType RHSTy = RHS.get()->getType();
8697
8698 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8699 // Two identical pointers types are always compatible.
8700 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8701 }
8702
8703 QualType lhptee, rhptee;
8704
8705 // Get the pointee types.
8706 bool IsBlockPointer = false;
8707 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8708 lhptee = LHSBTy->getPointeeType();
8709 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8710 IsBlockPointer = true;
8711 } else {
8712 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8713 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8714 }
8715
8716 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8717 // differently qualified versions of compatible types, the result type is
8718 // a pointer to an appropriately qualified version of the composite
8719 // type.
8720
8721 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8722 // clause doesn't make sense for our extensions. E.g. address space 2 should
8723 // be incompatible with address space 3: they may live on different devices or
8724 // anything.
8725 Qualifiers lhQual = lhptee.getQualifiers();
8726 Qualifiers rhQual = rhptee.getQualifiers();
8727
8728 LangAS ResultAddrSpace = LangAS::Default;
8729 LangAS LAddrSpace = lhQual.getAddressSpace();
8730 LangAS RAddrSpace = rhQual.getAddressSpace();
8731
8732 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8733 // spaces is disallowed.
8734 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8735 ResultAddrSpace = LAddrSpace;
8736 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8737 ResultAddrSpace = RAddrSpace;
8738 else {
8739 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8740 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8741 << RHS.get()->getSourceRange();
8742 return QualType();
8743 }
8744
8745 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8746 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8747 lhQual.removeCVRQualifiers();
8748 rhQual.removeCVRQualifiers();
8749
8750 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8751 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8752 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8753 << RHS.get()->getSourceRange();
8754 return QualType();
8755 }
8756
8757 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8758 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8759 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8760 // qual types are compatible iff
8761 // * corresponded types are compatible
8762 // * CVR qualifiers are equal
8763 // * address spaces are equal
8764 // Thus for conditional operator we merge CVR and address space unqualified
8765 // pointees and if there is a composite type we return a pointer to it with
8766 // merged qualifiers.
8767 LHSCastKind =
8768 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8769 RHSCastKind =
8770 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8771 lhQual.removeAddressSpace();
8772 rhQual.removeAddressSpace();
8773
8774 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8775 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8776
8777 QualType CompositeTy = S.Context.mergeTypes(
8778 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8779 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8780
8781 if (CompositeTy.isNull()) {
8782 // In this situation, we assume void* type. No especially good
8783 // reason, but this is what gcc does, and we do have to pick
8784 // to get a consistent AST.
8785 QualType incompatTy;
8786 incompatTy = S.Context.getPointerType(
8787 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8788 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8789 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8790
8791 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8792 // for casts between types with incompatible address space qualifiers.
8793 // For the following code the compiler produces casts between global and
8794 // local address spaces of the corresponded innermost pointees:
8795 // local int *global *a;
8796 // global int *global *b;
8797 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8798 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8799 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8800 << RHS.get()->getSourceRange();
8801
8802 return incompatTy;
8803 }
8804
8805 // The pointer types are compatible.
8806 // In case of OpenCL ResultTy should have the address space qualifier
8807 // which is a superset of address spaces of both the 2nd and the 3rd
8808 // operands of the conditional operator.
8809 QualType ResultTy = [&, ResultAddrSpace]() {
8810 if (S.getLangOpts().OpenCL) {
8811 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8812 CompositeQuals.setAddressSpace(ResultAddrSpace);
8813 return S.Context
8814 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8815 .withCVRQualifiers(MergedCVRQual);
8816 }
8817 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8818 }();
8819 if (IsBlockPointer)
8820 ResultTy = S.Context.getBlockPointerType(ResultTy);
8821 else
8822 ResultTy = S.Context.getPointerType(ResultTy);
8823
8824 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8825 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8826 return ResultTy;
8827}
8828
8829/// Return the resulting type when the operands are both block pointers.
8831 ExprResult &LHS,
8832 ExprResult &RHS,
8833 SourceLocation Loc) {
8834 QualType LHSTy = LHS.get()->getType();
8835 QualType RHSTy = RHS.get()->getType();
8836
8837 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8838 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8840 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8841 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8842 return destType;
8843 }
8844 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8845 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8846 << RHS.get()->getSourceRange();
8847 return QualType();
8848 }
8849
8850 // We have 2 block pointer types.
8851 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8852}
8853
8854/// Return the resulting type when the operands are both pointers.
8855static QualType
8857 ExprResult &RHS,
8858 SourceLocation Loc) {
8859 // get the pointer types
8860 QualType LHSTy = LHS.get()->getType();
8861 QualType RHSTy = RHS.get()->getType();
8862
8863 // get the "pointed to" types
8864 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8865 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8866
8867 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8868 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8869 // Figure out necessary qualifiers (C99 6.5.15p6)
8870 QualType destPointee
8871 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8872 QualType destType = S.Context.getPointerType(destPointee);
8873 // Add qualifiers if necessary.
8874 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8875 // Promote to void*.
8876 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8877 return destType;
8878 }
8879 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8880 QualType destPointee
8881 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8882 QualType destType = S.Context.getPointerType(destPointee);
8883 // Add qualifiers if necessary.
8884 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8885 // Promote to void*.
8886 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8887 return destType;
8888 }
8889
8890 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8891}
8892
8893/// Return false if the first expression is not an integer and the second
8894/// expression is not a pointer, true otherwise.
8896 Expr* PointerExpr, SourceLocation Loc,
8897 bool IsIntFirstExpr) {
8898 if (!PointerExpr->getType()->isPointerType() ||
8899 !Int.get()->getType()->isIntegerType())
8900 return false;
8901
8902 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8903 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8904
8905 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8906 << Expr1->getType() << Expr2->getType()
8907 << Expr1->getSourceRange() << Expr2->getSourceRange();
8908 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8909 CK_IntegralToPointer);
8910 return true;
8911}
8912
8913/// Simple conversion between integer and floating point types.
8914///
8915/// Used when handling the OpenCL conditional operator where the
8916/// condition is a vector while the other operands are scalar.
8917///
8918/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8919/// types are either integer or floating type. Between the two
8920/// operands, the type with the higher rank is defined as the "result
8921/// type". The other operand needs to be promoted to the same type. No
8922/// other type promotion is allowed. We cannot use
8923/// UsualArithmeticConversions() for this purpose, since it always
8924/// promotes promotable types.
8926 ExprResult &RHS,
8927 SourceLocation QuestionLoc) {
8929 if (LHS.isInvalid())
8930 return QualType();
8932 if (RHS.isInvalid())
8933 return QualType();
8934
8935 // For conversion purposes, we ignore any qualifiers.
8936 // For example, "const float" and "float" are equivalent.
8937 QualType LHSType =
8939 QualType RHSType =
8941
8942 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8943 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8944 << LHSType << LHS.get()->getSourceRange();
8945 return QualType();
8946 }
8947
8948 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8949 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8950 << RHSType << RHS.get()->getSourceRange();
8951 return QualType();
8952 }
8953
8954 // If both types are identical, no conversion is needed.
8955 if (LHSType == RHSType)
8956 return LHSType;
8957
8958 // Now handle "real" floating types (i.e. float, double, long double).
8959 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8960 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8961 /*IsCompAssign = */ false);
8962
8963 // Finally, we have two differing integer types.
8965 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8966}
8967
8968/// Convert scalar operands to a vector that matches the
8969/// condition in length.
8970///
8971/// Used when handling the OpenCL conditional operator where the
8972/// condition is a vector while the other operands are scalar.
8973///
8974/// We first compute the "result type" for the scalar operands
8975/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8976/// into a vector of that type where the length matches the condition
8977/// vector type. s6.11.6 requires that the element types of the result
8978/// and the condition must have the same number of bits.
8979static QualType
8981 QualType CondTy, SourceLocation QuestionLoc) {
8982 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8983 if (ResTy.isNull()) return QualType();
8984
8985 const VectorType *CV = CondTy->getAs<VectorType>();
8986 assert(CV);
8987
8988 // Determine the vector result type
8989 unsigned NumElements = CV->getNumElements();
8990 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8991
8992 // Ensure that all types have the same number of bits
8994 != S.Context.getTypeSize(ResTy)) {
8995 // Since VectorTy is created internally, it does not pretty print
8996 // with an OpenCL name. Instead, we just print a description.
8997 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8998 SmallString<64> Str;
8999 llvm::raw_svector_ostream OS(Str);
9000 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
9001 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
9002 << CondTy << OS.str();
9003 return QualType();
9004 }
9005
9006 // Convert operands to the vector result type
9007 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
9008 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
9009
9010 return VectorTy;
9011}
9012
9013/// Return false if this is a valid OpenCL condition vector
9015 SourceLocation QuestionLoc) {
9016 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
9017 // integral type.
9018 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
9019 assert(CondTy);
9020 QualType EleTy = CondTy->getElementType();
9021 if (EleTy->isIntegerType()) return false;
9022
9023 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
9024 << Cond->getType() << Cond->getSourceRange();
9025 return true;
9026}
9027
9028/// Return false if the vector condition type and the vector
9029/// result type are compatible.
9030///
9031/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
9032/// number of elements, and their element types have the same number
9033/// of bits.
9034static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
9035 SourceLocation QuestionLoc) {
9036 const VectorType *CV = CondTy->getAs<VectorType>();
9037 const VectorType *RV = VecResTy->getAs<VectorType>();
9038 assert(CV && RV);
9039
9040 if (CV->getNumElements() != RV->getNumElements()) {
9041 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
9042 << CondTy << VecResTy;
9043 return true;
9044 }
9045
9046 QualType CVE = CV->getElementType();
9047 QualType RVE = RV->getElementType();
9048
9049 // Boolean vectors are permitted outside of OpenCL mode.
9050 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
9051 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
9052 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
9053 << CondTy << VecResTy;
9054 return true;
9055 }
9056
9057 return false;
9058}
9059
9060/// Return the resulting type for the conditional operator in
9061/// OpenCL (aka "ternary selection operator", OpenCL v1.1
9062/// s6.3.i) when the condition is a vector type.
9063static QualType
9065 ExprResult &LHS, ExprResult &RHS,
9066 SourceLocation QuestionLoc) {
9068 if (Cond.isInvalid())
9069 return QualType();
9070 QualType CondTy = Cond.get()->getType();
9071
9072 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
9073 return QualType();
9074
9075 // If either operand is a vector then find the vector type of the
9076 // result as specified in OpenCL v1.1 s6.3.i.
9077 if (LHS.get()->getType()->isVectorType() ||
9078 RHS.get()->getType()->isVectorType()) {
9079 bool IsBoolVecLang =
9080 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
9081 QualType VecResTy =
9082 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
9083 /*isCompAssign*/ false,
9084 /*AllowBothBool*/ true,
9085 /*AllowBoolConversions*/ false,
9086 /*AllowBooleanOperation*/ IsBoolVecLang);
9087 if (VecResTy.isNull())
9088 return QualType();
9089 // The result type must match the condition type as specified in
9090 // OpenCL v1.1 s6.11.6.
9091 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
9092 return QualType();
9093 return VecResTy;
9094 }
9095
9096 // Both operands are scalar.
9097 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
9098}
9099
9100/// Return true if the Expr is block type
9101static bool checkBlockType(Sema &S, const Expr *E) {
9102 if (E->getType()->isBlockPointerType()) {
9103 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
9104 return true;
9105 }
9106
9107 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9108 QualType Ty = CE->getCallee()->getType();
9109 if (Ty->isBlockPointerType()) {
9110 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
9111 return true;
9112 }
9113 }
9114 return false;
9115}
9116
9117/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9118/// In that case, LHS = cond.
9119/// C99 6.5.15
9122 ExprObjectKind &OK,
9123 SourceLocation QuestionLoc) {
9124
9125 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
9126 if (!LHSResult.isUsable()) return QualType();
9127 LHS = LHSResult;
9128
9129 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
9130 if (!RHSResult.isUsable()) return QualType();
9131 RHS = RHSResult;
9132
9133 // C++ is sufficiently different to merit its own checker.
9134 if (getLangOpts().CPlusPlus)
9135 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
9136
9137 VK = VK_PRValue;
9138 OK = OK_Ordinary;
9139
9140 if (Context.isDependenceAllowed() &&
9141 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
9142 RHS.get()->isTypeDependent())) {
9143 assert(!getLangOpts().CPlusPlus);
9144 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
9145 RHS.get()->containsErrors()) &&
9146 "should only occur in error-recovery path.");
9147 return Context.DependentTy;
9148 }
9149
9150 // The OpenCL operator with a vector condition is sufficiently
9151 // different to merit its own checker.
9152 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
9153 Cond.get()->getType()->isExtVectorType())
9154 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
9155
9156 // First, check the condition.
9157 Cond = UsualUnaryConversions(Cond.get());
9158 if (Cond.isInvalid())
9159 return QualType();
9160 if (checkCondition(*this, Cond.get(), QuestionLoc))
9161 return QualType();
9162
9163 // Handle vectors.
9164 if (LHS.get()->getType()->isVectorType() ||
9165 RHS.get()->getType()->isVectorType())
9166 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
9167 /*AllowBothBool*/ true,
9168 /*AllowBoolConversions*/ false,
9169 /*AllowBooleanOperation*/ false);
9170
9171 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
9173 if (LHS.isInvalid() || RHS.isInvalid())
9174 return QualType();
9175
9176 // WebAssembly tables are not allowed as conditional LHS or RHS.
9177 QualType LHSTy = LHS.get()->getType();
9178 QualType RHSTy = RHS.get()->getType();
9179 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
9180 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
9181 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9182 return QualType();
9183 }
9184
9185 // Diagnose attempts to convert between __ibm128, __float128 and long double
9186 // where such conversions currently can't be handled.
9187 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
9188 Diag(QuestionLoc,
9189 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
9190 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9191 return QualType();
9192 }
9193
9194 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9195 // selection operator (?:).
9196 if (getLangOpts().OpenCL &&
9197 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
9198 return QualType();
9199 }
9200
9201 // If both operands have arithmetic type, do the usual arithmetic conversions
9202 // to find a common type: C99 6.5.15p3,5.
9203 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
9204 // Disallow invalid arithmetic conversions, such as those between bit-
9205 // precise integers types of different sizes, or between a bit-precise
9206 // integer and another type.
9207 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9208 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9209 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9210 << RHS.get()->getSourceRange();
9211 return QualType();
9212 }
9213
9214 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
9215 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
9216
9217 return ResTy;
9218 }
9219
9220 // If both operands are the same structure or union type, the result is that
9221 // type.
9222 // FIXME: Type of conditional expression must be complete in C mode.
9223 if (LHSTy->isRecordType() &&
9224 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
9225 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
9226 RHSTy.getUnqualifiedType());
9227
9228 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9229 // The following || allows only one side to be void (a GCC-ism).
9230 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9231 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9232 // UsualArithmeticConversions already handled the case where both sides
9233 // are the same type.
9234 } else if (RHSTy->isVoidType()) {
9235 ResTy = RHSTy;
9236 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9237 << RHS.get()->getSourceRange();
9238 } else {
9239 ResTy = LHSTy;
9240 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9241 << LHS.get()->getSourceRange();
9242 }
9243 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
9244 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
9245 return ResTy;
9246 }
9247
9248 // C23 6.5.15p7:
9249 // ... if both the second and third operands have nullptr_t type, the
9250 // result also has that type.
9251 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
9252 return ResTy;
9253
9254 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9255 // the type of the other operand."
9256 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
9257 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
9258
9259 // All objective-c pointer type analysis is done here.
9260 QualType compositeType =
9261 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9262 if (LHS.isInvalid() || RHS.isInvalid())
9263 return QualType();
9264 if (!compositeType.isNull())
9265 return compositeType;
9266
9267
9268 // Handle block pointer types.
9269 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9270 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9271 QuestionLoc);
9272
9273 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9274 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9275 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9276 QuestionLoc);
9277
9278 // GCC compatibility: soften pointer/integer mismatch. Note that
9279 // null pointers have been filtered out by this point.
9280 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9281 /*IsIntFirstExpr=*/true))
9282 return RHSTy;
9283 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9284 /*IsIntFirstExpr=*/false))
9285 return LHSTy;
9286
9287 // Emit a better diagnostic if one of the expressions is a null pointer
9288 // constant and the other is not a pointer type. In this case, the user most
9289 // likely forgot to take the address of the other expression.
9290 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9291 return QualType();
9292
9293 // Finally, if the LHS and RHS types are canonically the same type, we can
9294 // use the common sugared type.
9295 if (Context.hasSameType(LHSTy, RHSTy))
9296 return Context.getCommonSugaredType(LHSTy, RHSTy);
9297
9298 // Otherwise, the operands are not compatible.
9299 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9300 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9301 << RHS.get()->getSourceRange();
9302 return QualType();
9303}
9304
9305/// SuggestParentheses - Emit a note with a fixit hint that wraps
9306/// ParenRange in parentheses.
9308 const PartialDiagnostic &Note,
9309 SourceRange ParenRange) {
9310 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9311 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9312 EndLoc.isValid()) {
9313 Self.Diag(Loc, Note)
9314 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9315 << FixItHint::CreateInsertion(EndLoc, ")");
9316 } else {
9317 // We can't display the parentheses, so just show the bare note.
9318 Self.Diag(Loc, Note) << ParenRange;
9319 }
9320}
9321
9323 return BinaryOperator::isAdditiveOp(Opc) ||
9325 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9326 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9327 // not any of the logical operators. Bitwise-xor is commonly used as a
9328 // logical-xor because there is no logical-xor operator. The logical
9329 // operators, including uses of xor, have a high false positive rate for
9330 // precedence warnings.
9331}
9332
9333/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9334/// expression, either using a built-in or overloaded operator,
9335/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9336/// expression.
9337static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9338 const Expr **RHSExprs) {
9339 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9340 E = E->IgnoreImpCasts();
9342 E = E->IgnoreImpCasts();
9343 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9344 E = MTE->getSubExpr();
9345 E = E->IgnoreImpCasts();
9346 }
9347
9348 // Built-in binary operator.
9349 if (const auto *OP = dyn_cast<BinaryOperator>(E);
9350 OP && IsArithmeticOp(OP->getOpcode())) {
9351 *Opcode = OP->getOpcode();
9352 *RHSExprs = OP->getRHS();
9353 return true;
9354 }
9355
9356 // Overloaded operator.
9357 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9358 if (Call->getNumArgs() != 2)
9359 return false;
9360
9361 // Make sure this is really a binary operator that is safe to pass into
9362 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9363 OverloadedOperatorKind OO = Call->getOperator();
9364 if (OO < OO_Plus || OO > OO_Arrow ||
9365 OO == OO_PlusPlus || OO == OO_MinusMinus)
9366 return false;
9367
9369 if (IsArithmeticOp(OpKind)) {
9370 *Opcode = OpKind;
9371 *RHSExprs = Call->getArg(1);
9372 return true;
9373 }
9374 }
9375
9376 return false;
9377}
9378
9379/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9380/// or is a logical expression such as (x==y) which has int type, but is
9381/// commonly interpreted as boolean.
9382static bool ExprLooksBoolean(const Expr *E) {
9383 E = E->IgnoreParenImpCasts();
9384
9385 if (E->getType()->isBooleanType())
9386 return true;
9387 if (const auto *OP = dyn_cast<BinaryOperator>(E))
9388 return OP->isComparisonOp() || OP->isLogicalOp();
9389 if (const auto *OP = dyn_cast<UnaryOperator>(E))
9390 return OP->getOpcode() == UO_LNot;
9391 if (E->getType()->isPointerType())
9392 return true;
9393 // FIXME: What about overloaded operator calls returning "unspecified boolean
9394 // type"s (commonly pointer-to-members)?
9395
9396 return false;
9397}
9398
9399/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9400/// and binary operator are mixed in a way that suggests the programmer assumed
9401/// the conditional operator has higher precedence, for example:
9402/// "int x = a + someBinaryCondition ? 1 : 2".
9404 Expr *Condition, const Expr *LHSExpr,
9405 const Expr *RHSExpr) {
9406 BinaryOperatorKind CondOpcode;
9407 const Expr *CondRHS;
9408
9409 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9410 return;
9411 if (!ExprLooksBoolean(CondRHS))
9412 return;
9413
9414 // The condition is an arithmetic binary expression, with a right-
9415 // hand side that looks boolean, so warn.
9416
9417 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9418 ? diag::warn_precedence_bitwise_conditional
9419 : diag::warn_precedence_conditional;
9420
9421 Self.Diag(OpLoc, DiagID)
9422 << Condition->getSourceRange()
9423 << BinaryOperator::getOpcodeStr(CondOpcode);
9424
9426 Self, OpLoc,
9427 Self.PDiag(diag::note_precedence_silence)
9428 << BinaryOperator::getOpcodeStr(CondOpcode),
9429 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9430
9431 SuggestParentheses(Self, OpLoc,
9432 Self.PDiag(diag::note_precedence_conditional_first),
9433 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9434}
9435
9436/// Compute the nullability of a conditional expression.
9438 QualType LHSTy, QualType RHSTy,
9439 ASTContext &Ctx) {
9440 if (!ResTy->isAnyPointerType())
9441 return ResTy;
9442
9443 auto GetNullability = [](QualType Ty) {
9444 NullabilityKindOrNone Kind = Ty->getNullability();
9445 if (Kind) {
9446 // For our purposes, treat _Nullable_result as _Nullable.
9449 return *Kind;
9450 }
9452 };
9453
9454 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9455 NullabilityKind MergedKind;
9456
9457 // Compute nullability of a binary conditional expression.
9458 if (IsBin) {
9459 if (LHSKind == NullabilityKind::NonNull)
9460 MergedKind = NullabilityKind::NonNull;
9461 else
9462 MergedKind = RHSKind;
9463 // Compute nullability of a normal conditional expression.
9464 } else {
9465 if (LHSKind == NullabilityKind::Nullable ||
9466 RHSKind == NullabilityKind::Nullable)
9467 MergedKind = NullabilityKind::Nullable;
9468 else if (LHSKind == NullabilityKind::NonNull)
9469 MergedKind = RHSKind;
9470 else if (RHSKind == NullabilityKind::NonNull)
9471 MergedKind = LHSKind;
9472 else
9473 MergedKind = NullabilityKind::Unspecified;
9474 }
9475
9476 // Return if ResTy already has the correct nullability.
9477 if (GetNullability(ResTy) == MergedKind)
9478 return ResTy;
9479
9480 // Strip all nullability from ResTy.
9481 while (ResTy->getNullability())
9482 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9483
9484 // Create a new AttributedType with the new nullability kind.
9485 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
9486}
9487
9489 SourceLocation ColonLoc,
9490 Expr *CondExpr, Expr *LHSExpr,
9491 Expr *RHSExpr) {
9492 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9493 // was the condition.
9494 OpaqueValueExpr *opaqueValue = nullptr;
9495 Expr *commonExpr = nullptr;
9496 if (!LHSExpr) {
9497 commonExpr = CondExpr;
9498 // Lower out placeholder types first. This is important so that we don't
9499 // try to capture a placeholder. This happens in few cases in C++; such
9500 // as Objective-C++'s dictionary subscripting syntax.
9501 if (commonExpr->hasPlaceholderType()) {
9502 ExprResult result = CheckPlaceholderExpr(commonExpr);
9503 if (!result.isUsable()) return ExprError();
9504 commonExpr = result.get();
9505 }
9506 // We usually want to apply unary conversions *before* saving, except
9507 // in the special case of a C++ l-value conditional.
9508 if (!(getLangOpts().CPlusPlus
9509 && !commonExpr->isTypeDependent()
9510 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9511 && commonExpr->isGLValue()
9512 && commonExpr->isOrdinaryOrBitFieldObject()
9513 && RHSExpr->isOrdinaryOrBitFieldObject()
9514 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9515 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9516 if (commonRes.isInvalid())
9517 return ExprError();
9518 commonExpr = commonRes.get();
9519 }
9520
9521 // If the common expression is a class or array prvalue, materialize it
9522 // so that we can safely refer to it multiple times.
9523 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9524 commonExpr->getType()->isArrayType())) {
9525 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9526 if (MatExpr.isInvalid())
9527 return ExprError();
9528 commonExpr = MatExpr.get();
9529 }
9530
9531 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9532 commonExpr->getType(),
9533 commonExpr->getValueKind(),
9534 commonExpr->getObjectKind(),
9535 commonExpr);
9536 LHSExpr = CondExpr = opaqueValue;
9537 }
9538
9539 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9542 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9543 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9544 VK, OK, QuestionLoc);
9545 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9546 RHS.isInvalid())
9547 return ExprError();
9548
9549 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9550 RHS.get());
9551
9552 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9553
9554 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9555 Context);
9556
9557 if (!commonExpr)
9558 return new (Context)
9559 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9560 RHS.get(), result, VK, OK);
9561
9563 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9564 ColonLoc, result, VK, OK);
9565}
9566
9568 unsigned FromAttributes = 0, ToAttributes = 0;
9569 if (const auto *FromFn =
9570 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9571 FromAttributes =
9572 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9573 if (const auto *ToFn =
9574 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9575 ToAttributes =
9576 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9577
9578 return FromAttributes != ToAttributes;
9579}
9580
9581// checkPointerTypesForAssignment - This is a very tricky routine (despite
9582// being closely modeled after the C99 spec:-). The odd characteristic of this
9583// routine is it effectively iqnores the qualifiers on the top level pointee.
9584// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9585// FIXME: add a couple examples in this comment.
9587 QualType LHSType,
9588 QualType RHSType,
9589 SourceLocation Loc) {
9590 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9591 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9592
9593 // get the "pointed to" type (ignoring qualifiers at the top level)
9594 const Type *lhptee, *rhptee;
9595 Qualifiers lhq, rhq;
9596 std::tie(lhptee, lhq) =
9597 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9598 std::tie(rhptee, rhq) =
9599 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9600
9602
9603 // C99 6.5.16.1p1: This following citation is common to constraints
9604 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9605 // qualifiers of the type *pointed to* by the right;
9606
9607 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9608 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9610 // Ignore lifetime for further calculation.
9611 lhq.removeObjCLifetime();
9612 rhq.removeObjCLifetime();
9613 }
9614
9615 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9616 // Treat address-space mismatches as fatal.
9617 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9619
9620 // It's okay to add or remove GC or lifetime qualifiers when converting to
9621 // and from void*.
9624 S.getASTContext()) &&
9625 (lhptee->isVoidType() || rhptee->isVoidType()))
9626 ; // keep old
9627
9628 // Treat lifetime mismatches as fatal.
9629 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9631
9632 // Treat pointer-auth mismatches as fatal.
9633 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9635
9636 // For GCC/MS compatibility, other qualifier mismatches are treated
9637 // as still compatible in C.
9638 else
9640 }
9641
9642 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9643 // incomplete type and the other is a pointer to a qualified or unqualified
9644 // version of void...
9645 if (lhptee->isVoidType()) {
9646 if (rhptee->isIncompleteOrObjectType())
9647 return ConvTy;
9648
9649 // As an extension, we allow cast to/from void* to function pointer.
9650 assert(rhptee->isFunctionType());
9652 }
9653
9654 if (rhptee->isVoidType()) {
9655 // In C, void * to another pointer type is compatible, but we want to note
9656 // that there will be an implicit conversion happening here.
9657 if (lhptee->isIncompleteOrObjectType())
9658 return ConvTy == AssignConvertType::Compatible &&
9659 !S.getLangOpts().CPlusPlus
9661 : ConvTy;
9662
9663 // As an extension, we allow cast to/from void* to function pointer.
9664 assert(lhptee->isFunctionType());
9666 }
9667
9668 if (!S.Diags.isIgnored(
9669 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9670 Loc) &&
9671 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9672 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9674
9675 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9676 // unqualified versions of compatible types, ...
9677 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9678
9679 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9680 if (!S.Context.hasSameType(ltrans, rtrans)) {
9681 QualType LUnderlying =
9682 ltrans->isOverflowBehaviorType()
9683 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9684 : ltrans;
9685 QualType RUnderlying =
9686 rtrans->isOverflowBehaviorType()
9687 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9688 : rtrans;
9689
9690 if (S.Context.hasSameType(LUnderlying, RUnderlying))
9692
9693 ltrans = LUnderlying;
9694 rtrans = RUnderlying;
9695 }
9696 }
9697
9698 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9699 // Check if the pointee types are compatible ignoring the sign.
9700 // We explicitly check for char so that we catch "char" vs
9701 // "unsigned char" on systems where "char" is unsigned.
9702 if (lhptee->isCharType())
9703 ltrans = S.Context.UnsignedCharTy;
9704 else if (lhptee->hasSignedIntegerRepresentation())
9705 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9706
9707 if (rhptee->isCharType())
9708 rtrans = S.Context.UnsignedCharTy;
9709 else if (rhptee->hasSignedIntegerRepresentation())
9710 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9711
9712 if (ltrans == rtrans) {
9713 // Types are compatible ignoring the sign. Qualifier incompatibility
9714 // takes priority over sign incompatibility because the sign
9715 // warning can be disabled.
9716 if (!S.IsAssignConvertCompatible(ConvTy))
9717 return ConvTy;
9718
9720 }
9721
9722 // If we are a multi-level pointer, it's possible that our issue is simply
9723 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9724 // the eventual target type is the same and the pointers have the same
9725 // level of indirection, this must be the issue.
9726 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9727 do {
9728 std::tie(lhptee, lhq) =
9729 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9730 std::tie(rhptee, rhq) =
9731 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9732
9733 // Inconsistent address spaces at this point is invalid, even if the
9734 // address spaces would be compatible.
9735 // FIXME: This doesn't catch address space mismatches for pointers of
9736 // different nesting levels, like:
9737 // __local int *** a;
9738 // int ** b = a;
9739 // It's not clear how to actually determine when such pointers are
9740 // invalidly incompatible.
9741 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9742 return AssignConvertType::
9743 IncompatibleNestedPointerAddressSpaceMismatch;
9744
9745 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9746
9747 if (lhptee == rhptee)
9749 }
9750
9751 // General pointer incompatibility takes priority over qualifiers.
9752 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9755 }
9756 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9757 // hasSameType, so we can skip further checks.
9758 const auto *LFT = ltrans->getAs<FunctionType>();
9759 const auto *RFT = rtrans->getAs<FunctionType>();
9760 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9761 // The invocation of IsFunctionConversion below will try to transform rtrans
9762 // to obtain an exact match for ltrans. This should not fail because of
9763 // mismatches in result type and parameter types, they were already checked
9764 // by typesAreCompatible above. So we will recreate rtrans (or where
9765 // appropriate ltrans) using the result type and parameter types from ltrans
9766 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9767 const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);
9768 const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);
9769 if (LFPT && RFPT) {
9770 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9771 LFPT->getParamTypes(),
9772 RFPT->getExtProtoInfo());
9773 } else if (LFPT) {
9775 EPI.ExtInfo = RFT->getExtInfo();
9776 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9777 LFPT->getParamTypes(), EPI);
9778 } else if (RFPT) {
9779 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9780 // all of its ExtProtoInfo. Transform ltrans instead.
9782 EPI.ExtInfo = LFT->getExtInfo();
9783 ltrans = S.Context.getFunctionType(RFPT->getReturnType(),
9784 RFPT->getParamTypes(), EPI);
9785 } else {
9786 rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),
9787 RFT->getExtInfo());
9788 }
9789 if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&
9790 !S.IsFunctionConversion(rtrans, ltrans))
9792 }
9793 return ConvTy;
9794}
9795
9796/// checkBlockPointerTypesForAssignment - This routine determines whether two
9797/// block pointer types are compatible or whether a block and normal pointer
9798/// are compatible. It is more restrict than comparing two function pointer
9799// types.
9801 QualType LHSType,
9802 QualType RHSType) {
9803 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9804 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9805
9806 QualType lhptee, rhptee;
9807
9808 // get the "pointed to" type (ignoring qualifiers at the top level)
9809 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9810 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9811
9812 // In C++, the types have to match exactly.
9813 if (S.getLangOpts().CPlusPlus)
9815
9817
9818 // For blocks we enforce that qualifiers are identical.
9819 Qualifiers LQuals = lhptee.getLocalQualifiers();
9820 Qualifiers RQuals = rhptee.getLocalQualifiers();
9821 if (S.getLangOpts().OpenCL) {
9822 LQuals.removeAddressSpace();
9823 RQuals.removeAddressSpace();
9824 }
9825 if (LQuals != RQuals)
9827
9828 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9829 // assignment.
9830 // The current behavior is similar to C++ lambdas. A block might be
9831 // assigned to a variable iff its return type and parameters are compatible
9832 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9833 // an assignment. Presumably it should behave in way that a function pointer
9834 // assignment does in C, so for each parameter and return type:
9835 // * CVR and address space of LHS should be a superset of CVR and address
9836 // space of RHS.
9837 // * unqualified types should be compatible.
9838 if (S.getLangOpts().OpenCL) {
9840 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9841 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9843 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9845
9846 return ConvTy;
9847}
9848
9849/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9850/// for assignment compatibility.
9852 QualType LHSType,
9853 QualType RHSType) {
9854 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9855 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9856
9857 if (LHSType->isObjCBuiltinType()) {
9858 // Class is not compatible with ObjC object pointers.
9859 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9860 !RHSType->isObjCQualifiedClassType())
9863 }
9864 if (RHSType->isObjCBuiltinType()) {
9865 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9866 !LHSType->isObjCQualifiedClassType())
9869 }
9870 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9871 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9872
9873 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9874 // make an exception for id<P>
9875 !LHSType->isObjCQualifiedIdType())
9877
9878 if (S.Context.typesAreCompatible(LHSType, RHSType))
9880 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9883}
9884
9886 QualType LHSType,
9887 QualType RHSType) {
9888 // Fake up an opaque expression. We don't actually care about what
9889 // cast operations are required, so if CheckAssignmentConstraints
9890 // adds casts to this they'll be wasted, but fortunately that doesn't
9891 // usually happen on valid code.
9892 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9893 ExprResult RHSPtr = &RHSExpr;
9894 CastKind K;
9895
9896 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9897}
9898
9899/// This helper function returns true if QT is a vector type that has element
9900/// type ElementType.
9901static bool isVector(QualType QT, QualType ElementType) {
9902 if (const VectorType *VT = QT->getAs<VectorType>())
9903 return VT->getElementType().getCanonicalType() == ElementType;
9904 return false;
9905}
9906
9907/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9908/// has code to accommodate several GCC extensions when type checking
9909/// pointers. Here are some objectionable examples that GCC considers warnings:
9910///
9911/// int a, *pint;
9912/// short *pshort;
9913/// struct foo *pfoo;
9914///
9915/// pint = pshort; // warning: assignment from incompatible pointer type
9916/// a = pint; // warning: assignment makes integer from pointer without a cast
9917/// pint = a; // warning: assignment makes pointer from integer without a cast
9918/// pint = pfoo; // warning: assignment from incompatible pointer type
9919///
9920/// As a result, the code for dealing with pointers is more complex than the
9921/// C99 spec dictates.
9922///
9923/// Sets 'Kind' for any result kind except Incompatible.
9925 ExprResult &RHS,
9926 CastKind &Kind,
9927 bool ConvertRHS) {
9928 QualType RHSType = RHS.get()->getType();
9929 QualType OrigLHSType = LHSType;
9930
9931 // Get canonical types. We're not formatting these types, just comparing
9932 // them.
9933 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9934 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9935
9936 // Common case: no conversion required.
9937 if (LHSType == RHSType) {
9938 Kind = CK_NoOp;
9940 }
9941
9942 // If the LHS has an __auto_type, there are no additional type constraints
9943 // to be worried about.
9944 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9945 if (AT->isGNUAutoType()) {
9946 Kind = CK_NoOp;
9948 }
9949 }
9950
9951 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHSType, RHSType);
9952 switch (OBTResult) {
9954 Kind = CK_NoOp;
9957 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9961 break;
9962 }
9963
9964 // Check for incompatible OBT types in pointer pointee types
9965 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9966 QualType LHSPointee = LHSType->getPointeeType();
9967 QualType RHSPointee = RHSType->getPointeeType();
9968 if ((LHSPointee->isOverflowBehaviorType() ||
9969 RHSPointee->isOverflowBehaviorType()) &&
9970 !Context.areCompatibleOverflowBehaviorTypes(LHSPointee, RHSPointee)) {
9971 Kind = CK_NoOp;
9973 }
9974 }
9975
9976 // If we have an atomic type, try a non-atomic assignment, then just add an
9977 // atomic qualification step.
9978 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9980 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9982 return Result;
9983 if (Kind != CK_NoOp && ConvertRHS)
9984 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9985 Kind = CK_NonAtomicToAtomic;
9986 return Result;
9987 }
9988
9989 // If the left-hand side is a reference type, then we are in a
9990 // (rare!) case where we've allowed the use of references in C,
9991 // e.g., as a parameter type in a built-in function. In this case,
9992 // just make sure that the type referenced is compatible with the
9993 // right-hand side type. The caller is responsible for adjusting
9994 // LHSType so that the resulting expression does not have reference
9995 // type.
9996 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9997 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9998 Kind = CK_LValueBitCast;
10000 }
10002 }
10003
10004 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
10005 // of an ExtVector type to the same ExtVector type.
10006 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
10007 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
10008 // Implicit conversions require the same number of elements.
10009 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
10011
10012 if (LHSType->isExtVectorBoolType() &&
10013 RHSExtType->getElementType()->isIntegerType()) {
10014 Kind = CK_IntegralToBoolean;
10016 }
10017 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
10018 if (Context.getLangOpts().OpenCL &&
10019 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10020 Kind = CK_BitCast;
10022 }
10024 }
10025 if (RHSType->isArithmeticType()) {
10026 // CK_VectorSplat does T -> vector T, so first cast to the element type.
10027 if (ConvertRHS)
10028 RHS = prepareVectorSplat(LHSType, RHS.get());
10029 Kind = CK_VectorSplat;
10031 }
10032 }
10033
10034 // Conversions to or from vector type.
10035 if (LHSType->isVectorType() || RHSType->isVectorType()) {
10036 if (LHSType->isVectorType() && RHSType->isVectorType()) {
10037 // Allow assignments of an AltiVec vector type to an equivalent GCC
10038 // vector type and vice versa
10039 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10040 Kind = CK_BitCast;
10042 }
10043
10044 // If we are allowing lax vector conversions, and LHS and RHS are both
10045 // vectors, the total size only needs to be the same. This is a bitcast;
10046 // no bits are changed but the result type is different.
10047 if (isLaxVectorConversion(RHSType, LHSType)) {
10048 // The default for lax vector conversions with Altivec vectors will
10049 // change, so if we are converting between vector types where
10050 // at least one is an Altivec vector, emit a warning.
10051 if (Context.getTargetInfo().getTriple().isPPC() &&
10052 anyAltivecTypes(RHSType, LHSType) &&
10053 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10054 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
10055 << RHSType << LHSType;
10056 Kind = CK_BitCast;
10058 }
10059 }
10060
10061 // When the RHS comes from another lax conversion (e.g. binops between
10062 // scalars and vectors) the result is canonicalized as a vector. When the
10063 // LHS is also a vector, the lax is allowed by the condition above. Handle
10064 // the case where LHS is a scalar.
10065 if (LHSType->isScalarType()) {
10066 const VectorType *VecType = RHSType->getAs<VectorType>();
10067 if (VecType && VecType->getNumElements() == 1 &&
10068 isLaxVectorConversion(RHSType, LHSType)) {
10069 if (Context.getTargetInfo().getTriple().isPPC() &&
10071 VecType->getVectorKind() == VectorKind::AltiVecBool ||
10073 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
10074 << RHSType << LHSType;
10075 ExprResult *VecExpr = &RHS;
10076 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
10077 Kind = CK_BitCast;
10079 }
10080 }
10081
10082 // Allow assignments between fixed-length and sizeless SVE vectors.
10083 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
10084 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
10085 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
10086 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
10087 Kind = CK_BitCast;
10089 }
10090
10091 // Allow assignments between fixed-length and sizeless RVV vectors.
10092 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
10093 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
10094 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
10095 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
10096 Kind = CK_BitCast;
10098 }
10099 }
10100
10102 }
10103
10104 // Diagnose attempts to convert between __ibm128, __float128 and long double
10105 // where such conversions currently can't be handled.
10106 if (unsupportedTypeConversion(*this, LHSType, RHSType))
10108
10109 // Disallow assigning a _Complex to a real type in C++ mode since it simply
10110 // discards the imaginary part.
10111 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
10112 !LHSType->getAs<ComplexType>())
10114
10115 // Arithmetic conversions.
10116 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
10117 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
10118 if (ConvertRHS)
10119 Kind = PrepareScalarCast(RHS, LHSType);
10121 }
10122
10123 // Conversions to normal pointers.
10124 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
10125 // U* -> T*
10126 if (isa<PointerType>(RHSType)) {
10127 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10128 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
10129 if (AddrSpaceL != AddrSpaceR)
10130 Kind = CK_AddressSpaceConversion;
10131 else if (Context.hasCvrSimilarType(RHSType, LHSType))
10132 Kind = CK_NoOp;
10133 else
10134 Kind = CK_BitCast;
10135 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
10136 RHS.get()->getBeginLoc());
10137 }
10138
10139 // int -> T*
10140 if (RHSType->isIntegerType()) {
10141 Kind = CK_IntegralToPointer; // FIXME: null?
10143 }
10144
10145 // C pointers are not compatible with ObjC object pointers,
10146 // with two exceptions:
10147 if (isa<ObjCObjectPointerType>(RHSType)) {
10148 // - conversions to void*
10149 if (LHSPointer->getPointeeType()->isVoidType()) {
10150 Kind = CK_BitCast;
10152 }
10153
10154 // - conversions from 'Class' to the redefinition type
10155 if (RHSType->isObjCClassType() &&
10156 Context.hasSameType(LHSType,
10157 Context.getObjCClassRedefinitionType())) {
10158 Kind = CK_BitCast;
10160 }
10161
10162 Kind = CK_BitCast;
10164 }
10165
10166 // U^ -> void*
10167 if (RHSType->getAs<BlockPointerType>()) {
10168 if (LHSPointer->getPointeeType()->isVoidType()) {
10169 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10170 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10171 ->getPointeeType()
10172 .getAddressSpace();
10173 Kind =
10174 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10176 }
10177 }
10178
10180 }
10181
10182 // Conversions to block pointers.
10183 if (isa<BlockPointerType>(LHSType)) {
10184 // U^ -> T^
10185 if (RHSType->isBlockPointerType()) {
10186 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10187 ->getPointeeType()
10188 .getAddressSpace();
10189 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10190 ->getPointeeType()
10191 .getAddressSpace();
10192 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10193 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
10194 }
10195
10196 // int or null -> T^
10197 if (RHSType->isIntegerType()) {
10198 Kind = CK_IntegralToPointer; // FIXME: null
10200 }
10201
10202 // id -> T^
10203 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10204 Kind = CK_AnyPointerToBlockPointerCast;
10206 }
10207
10208 // void* -> T^
10209 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10210 if (RHSPT->getPointeeType()->isVoidType()) {
10211 Kind = CK_AnyPointerToBlockPointerCast;
10213 }
10214
10216 }
10217
10218 // Conversions to Objective-C pointers.
10219 if (isa<ObjCObjectPointerType>(LHSType)) {
10220 // A* -> B*
10221 if (RHSType->isObjCObjectPointerType()) {
10222 Kind = CK_BitCast;
10223 AssignConvertType result =
10224 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
10225 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10227 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10229 return result;
10230 }
10231
10232 // int or null -> A*
10233 if (RHSType->isIntegerType()) {
10234 Kind = CK_IntegralToPointer; // FIXME: null
10236 }
10237
10238 // In general, C pointers are not compatible with ObjC object pointers,
10239 // with two exceptions:
10240 if (isa<PointerType>(RHSType)) {
10241 Kind = CK_CPointerToObjCPointerCast;
10242
10243 // - conversions from 'void*'
10244 if (RHSType->isVoidPointerType()) {
10246 }
10247
10248 // - conversions to 'Class' from its redefinition type
10249 if (LHSType->isObjCClassType() &&
10250 Context.hasSameType(RHSType,
10251 Context.getObjCClassRedefinitionType())) {
10253 }
10254
10256 }
10257
10258 // Only under strict condition T^ is compatible with an Objective-C pointer.
10259 if (RHSType->isBlockPointerType() &&
10261 if (ConvertRHS)
10263 Kind = CK_BlockPointerToObjCPointerCast;
10265 }
10266
10268 }
10269
10270 // Conversion to nullptr_t (C23 only)
10271 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10274 // null -> nullptr_t
10275 Kind = CK_NullToPointer;
10277 }
10278
10279 // Conversions from pointers that are not covered by the above.
10280 if (isa<PointerType>(RHSType)) {
10281 // T* -> _Bool
10282 if (LHSType == Context.BoolTy) {
10283 Kind = CK_PointerToBoolean;
10285 }
10286
10287 // T* -> int
10288 if (LHSType->isIntegerType()) {
10289 Kind = CK_PointerToIntegral;
10291 }
10292
10294 }
10295
10296 // Conversions from Objective-C pointers that are not covered by the above.
10297 if (isa<ObjCObjectPointerType>(RHSType)) {
10298 // T* -> _Bool
10299 if (LHSType == Context.BoolTy) {
10300 Kind = CK_PointerToBoolean;
10302 }
10303
10304 // T* -> int
10305 if (LHSType->isIntegerType()) {
10306 Kind = CK_PointerToIntegral;
10308 }
10309
10311 }
10312
10313 // struct A -> struct B
10314 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10315 if (Context.typesAreCompatible(LHSType, RHSType)) {
10316 Kind = CK_NoOp;
10318 }
10319 }
10320
10321 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10322 Kind = CK_IntToOCLSampler;
10324 }
10325
10327}
10328
10329/// Constructs a transparent union from an expression that is
10330/// used to initialize the transparent union.
10332 ExprResult &EResult, QualType UnionType,
10333 FieldDecl *Field) {
10334 // Build an initializer list that designates the appropriate member
10335 // of the transparent union.
10336 Expr *E = EResult.get();
10338 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10339 Initializer->setType(UnionType);
10340 Initializer->setInitializedFieldInUnion(Field);
10341
10342 // Build a compound literal constructing a value of the transparent
10343 // union type from this initializer list.
10344 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10345 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10346 VK_PRValue, Initializer, false);
10347}
10348
10351 ExprResult &RHS) {
10352 QualType RHSType = RHS.get()->getType();
10353
10354 // If the ArgType is a Union type, we want to handle a potential
10355 // transparent_union GCC extension.
10356 const RecordType *UT = ArgType->getAsUnionType();
10357 if (!UT)
10359
10360 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10361 if (!UD->hasAttr<TransparentUnionAttr>())
10363
10364 // The field to initialize within the transparent union.
10365 FieldDecl *InitField = nullptr;
10366 // It's compatible if the expression matches any of the fields.
10367 for (auto *it : UD->fields()) {
10368 if (it->getType()->isPointerType()) {
10369 // If the transparent union contains a pointer type, we allow:
10370 // 1) void pointer
10371 // 2) null pointer constant
10372 if (RHSType->isPointerType())
10373 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10374 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10375 InitField = it;
10376 break;
10377 }
10378
10381 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10382 CK_NullToPointer);
10383 InitField = it;
10384 break;
10385 }
10386 }
10387
10388 CastKind Kind;
10389 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
10391 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10392 InitField = it;
10393 break;
10394 }
10395 }
10396
10397 if (!InitField)
10399
10400 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10402}
10403
10405 ExprResult &CallerRHS,
10406 bool Diagnose,
10407 bool DiagnoseCFAudited,
10408 bool ConvertRHS) {
10409 // We need to be able to tell the caller whether we diagnosed a problem, if
10410 // they ask us to issue diagnostics.
10411 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10412
10413 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10414 // we can't avoid *all* modifications at the moment, so we need some somewhere
10415 // to put the updated value.
10416 ExprResult LocalRHS = CallerRHS;
10417 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10418
10419 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10420 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10421 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10422 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10423 Diag(RHS.get()->getExprLoc(),
10424 diag::warn_noderef_to_dereferenceable_pointer)
10425 << RHS.get()->getSourceRange();
10426 }
10427 }
10428 }
10429
10430 if (getLangOpts().CPlusPlus) {
10431 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10432 // C++ 5.17p3: If the left operand is not of class type, the
10433 // expression is implicitly converted (C++ 4) to the
10434 // cv-unqualified type of the left operand.
10435 QualType RHSType = RHS.get()->getType();
10436 if (Diagnose) {
10437 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10439 } else {
10442 /*SuppressUserConversions=*/false,
10443 AllowedExplicit::None,
10444 /*InOverloadResolution=*/false,
10445 /*CStyle=*/false,
10446 /*AllowObjCWritebackConversion=*/false);
10447 if (ICS.isFailure())
10449 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10451 }
10452 if (RHS.isInvalid())
10455 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10456 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10458
10459 // Check if OBT is being discarded during assignment
10460 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10461 if (RHSType->isOverflowBehaviorType() &&
10462 !LHSType->isOverflowBehaviorType()) {
10464 }
10465
10466 return result;
10467 }
10468
10469 // FIXME: Currently, we fall through and treat C++ classes like C
10470 // structures.
10471 // FIXME: We also fall through for atomics; not sure what should
10472 // happen there, though.
10473 } else if (RHS.get()->getType() == Context.OverloadTy) {
10474 // As a set of extensions to C, we support overloading on functions. These
10475 // functions need to be resolved here.
10476 DeclAccessPair DAP;
10478 RHS.get(), LHSType, /*Complain=*/false, DAP))
10479 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10480 else
10482 }
10483
10484 // For HLSL records, insert derived-to-base conversion if needed.
10485 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10486 QualType RHSType = RHS.get()->getType();
10487 if (!Context.hasSameUnqualifiedType(RHSType, LHSType)) {
10488 CXXBasePaths Paths;
10489 if (IsDerivedFrom(RHS.get()->getBeginLoc(), RHSType, LHSType, Paths)) {
10490 CXXCastPath CastPath;
10491 BuildBasePathArray(Paths, CastPath);
10492 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_DerivedToBase, VK_LValue,
10493 &CastPath);
10494 }
10495 }
10496 }
10497
10498 // This check seems unnatural, however it is necessary to ensure the proper
10499 // conversion of functions/arrays. If the conversion were done for all
10500 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10501 // expressions that suppress this implicit conversion (&, sizeof). This needs
10502 // to happen before we check for null pointer conversions because C does not
10503 // undergo the same implicit conversions as C++ does above (by the calls to
10504 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10505 // lvalue to rvalue cast before checking for null pointer constraints. This
10506 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10507 //
10508 // Suppress this for references: C++ 8.5.3p5.
10509 if (!LHSType->isReferenceType()) {
10510 // FIXME: We potentially allocate here even if ConvertRHS is false.
10512 if (RHS.isInvalid())
10514 }
10515
10516 // The constraints are expressed in terms of the atomic, qualified, or
10517 // unqualified type of the LHS.
10518 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10519
10520 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10521 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10522 if ((LHSTypeAfterConversion->isPointerType() ||
10523 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10524 LHSTypeAfterConversion->isBlockPointerType()) &&
10525 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10529 if (Diagnose || ConvertRHS) {
10530 CastKind Kind;
10531 CXXCastPath Path;
10532 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10533 /*IgnoreBaseAccess=*/false, Diagnose);
10534
10535 // If there is a conversion of some kind, check to see what kind of
10536 // pointer conversion happened so we can diagnose a C++ compatibility
10537 // diagnostic if the conversion is invalid. This only matters if the RHS
10538 // is some kind of void pointer. We have a carve-out when the RHS is from
10539 // a macro expansion because the use of a macro may indicate different
10540 // code between C and C++. Consider: char *s = NULL; where NULL is
10541 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10542 // C++, which is valid in C++. Ignore parentheses around the macro when
10543 // checking where the expression originates.
10544 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10545 !RHS.get()->IgnoreParens()->getBeginLoc().isMacroID()) {
10546 QualType CanRHS =
10548 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10549 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10550 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
10551 RHS.get()->getExprLoc());
10552 // Anything that's not considered perfectly compatible would be
10553 // incompatible in C++.
10556 }
10557 }
10558
10559 if (ConvertRHS)
10560 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10561 }
10562 return Ret;
10563 }
10564 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10565 // unqualified bool, and the right operand is a pointer or its type is
10566 // nullptr_t.
10567 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10568 RHS.get()->getType()->isNullPtrType()) {
10569 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10570 // only handles nullptr -> _Bool due to needing an extra conversion
10571 // step.
10572 // We model this by converting from nullptr -> void * and then let the
10573 // conversion from void * -> _Bool happen naturally.
10574 if (Diagnose || ConvertRHS) {
10575 CastKind Kind;
10576 CXXCastPath Path;
10577 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10578 /*IgnoreBaseAccess=*/false, Diagnose);
10579 if (ConvertRHS)
10580 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10581 &Path);
10582 }
10583 }
10584
10585 // OpenCL queue_t type assignment.
10586 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10588 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10590 }
10591
10592 CastKind Kind;
10593 AssignConvertType result =
10594 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10595
10596 // If assigning a void * created by an allocation function call to some other
10597 // type, check that the allocated size is sufficient for that type.
10598 if (result != AssignConvertType::Incompatible &&
10599 RHS.get()->getType()->isVoidPointerType())
10600 CheckSufficientAllocSize(*this, LHSType, RHS.get());
10601
10602 // C99 6.5.16.1p2: The value of the right operand is converted to the
10603 // type of the assignment expression.
10604 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10605 // so that we can use references in built-in functions even in C.
10606 // The getNonReferenceType() call makes sure that the resulting expression
10607 // does not have reference type.
10608 if (result != AssignConvertType::Incompatible &&
10609 RHS.get()->getType() != LHSType) {
10611 Expr *E = RHS.get();
10612
10613 // Check for various Objective-C errors. If we are not reporting
10614 // diagnostics and just checking for errors, e.g., during overload
10615 // resolution, return Incompatible to indicate the failure.
10616 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10617 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
10619 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10620 if (!Diagnose)
10622 }
10623 if (getLangOpts().ObjC &&
10624 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10625 E->getType(), E, Diagnose) ||
10626 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10627 if (!Diagnose)
10629 // Replace the expression with a corrected version and continue so we
10630 // can find further errors.
10631 RHS = E;
10633 }
10634
10635 if (ConvertRHS)
10636 RHS = ImpCastExprToType(E, Ty, Kind);
10637 }
10638
10639 return result;
10640}
10641
10642namespace {
10643/// The original operand to an operator, prior to the application of the usual
10644/// arithmetic conversions and converting the arguments of a builtin operator
10645/// candidate.
10646struct OriginalOperand {
10647 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10648 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10649 Op = MTE->getSubExpr();
10650 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10651 Op = BTE->getSubExpr();
10652 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10653 Orig = ICE->getSubExprAsWritten();
10654 Conversion = ICE->getConversionFunction();
10655 }
10656 }
10657
10658 QualType getType() const { return Orig->getType(); }
10659
10660 Expr *Orig;
10661 NamedDecl *Conversion;
10662};
10663}
10664
10666 ExprResult &RHS) {
10667 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10668
10669 Diag(Loc, diag::err_typecheck_invalid_operands)
10670 << OrigLHS.getType() << OrigRHS.getType()
10671 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10672
10673 // If a user-defined conversion was applied to either of the operands prior
10674 // to applying the built-in operator rules, tell the user about it.
10675 if (OrigLHS.Conversion) {
10676 Diag(OrigLHS.Conversion->getLocation(),
10677 diag::note_typecheck_invalid_operands_converted)
10678 << 0 << LHS.get()->getType();
10679 }
10680 if (OrigRHS.Conversion) {
10681 Diag(OrigRHS.Conversion->getLocation(),
10682 diag::note_typecheck_invalid_operands_converted)
10683 << 1 << RHS.get()->getType();
10684 }
10685
10686 return QualType();
10687}
10688
10690 ExprResult &RHS) {
10691 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10692 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10693
10694 bool LHSNatVec = LHSType->isVectorType();
10695 bool RHSNatVec = RHSType->isVectorType();
10696
10697 if (!(LHSNatVec && RHSNatVec)) {
10698 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10699 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10700 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10701 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10702 << Vector->getSourceRange();
10703 return QualType();
10704 }
10705
10706 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10707 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10708 << RHS.get()->getSourceRange();
10709
10710 return QualType();
10711}
10712
10713/// Try to convert a value of non-vector type to a vector type by converting
10714/// the type to the element type of the vector and then performing a splat.
10715/// If the language is OpenCL, we only use conversions that promote scalar
10716/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10717/// for float->int.
10718///
10719/// OpenCL V2.0 6.2.6.p2:
10720/// An error shall occur if any scalar operand type has greater rank
10721/// than the type of the vector element.
10722///
10723/// \param scalar - if non-null, actually perform the conversions
10724/// \return true if the operation fails (but without diagnosing the failure)
10726 QualType scalarTy,
10727 QualType vectorEltTy,
10728 QualType vectorTy,
10729 unsigned &DiagID) {
10730 // The conversion to apply to the scalar before splatting it,
10731 // if necessary.
10732 CastKind scalarCast = CK_NoOp;
10733
10734 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10735 scalarCast = CK_IntegralToBoolean;
10736 } else if (vectorEltTy->isIntegralType(S.Context)) {
10737 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10738 (scalarTy->isIntegerType() &&
10739 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10740 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10741 return true;
10742 }
10743 if (!scalarTy->isIntegralType(S.Context))
10744 return true;
10745 scalarCast = CK_IntegralCast;
10746 } else if (vectorEltTy->isRealFloatingType()) {
10747 if (scalarTy->isRealFloatingType()) {
10748 if (S.getLangOpts().OpenCL &&
10749 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10750 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10751 return true;
10752 }
10753 scalarCast = CK_FloatingCast;
10754 }
10755 else if (scalarTy->isIntegralType(S.Context))
10756 scalarCast = CK_IntegralToFloating;
10757 else
10758 return true;
10759 } else {
10760 return true;
10761 }
10762
10763 // Adjust scalar if desired.
10764 if (scalar) {
10765 if (scalarCast != CK_NoOp)
10766 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10767 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10768 }
10769 return false;
10770}
10771
10772/// Convert vector E to a vector with the same number of elements but different
10773/// element type.
10774static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10775 const auto *VecTy = E->getType()->getAs<VectorType>();
10776 assert(VecTy && "Expression E must be a vector");
10777 QualType NewVecTy =
10778 VecTy->isExtVectorType()
10779 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10780 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10781 VecTy->getVectorKind());
10782
10783 // Look through the implicit cast. Return the subexpression if its type is
10784 // NewVecTy.
10785 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10786 if (ICE->getSubExpr()->getType() == NewVecTy)
10787 return ICE->getSubExpr();
10788
10789 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10790 return S.ImpCastExprToType(E, NewVecTy, Cast);
10791}
10792
10793/// Test if a (constant) integer Int can be casted to another integer type
10794/// IntTy without losing precision.
10796 QualType OtherIntTy) {
10797 Expr *E = Int->get();
10799 return false;
10800
10801 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10802
10803 // Reject cases where the value of the Int is unknown as that would
10804 // possibly cause truncation, but accept cases where the scalar can be
10805 // demoted without loss of precision.
10806 Expr::EvalResult EVResult;
10807 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10808 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10809 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10810 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10811
10812 if (CstInt) {
10813 // If the scalar is constant and is of a higher order and has more active
10814 // bits that the vector element type, reject it.
10815 llvm::APSInt Result = EVResult.Val.getInt();
10816 unsigned NumBits = IntSigned
10817 ? (Result.isNegative() ? Result.getSignificantBits()
10818 : Result.getActiveBits())
10819 : Result.getActiveBits();
10820 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10821 return true;
10822
10823 // If the signedness of the scalar type and the vector element type
10824 // differs and the number of bits is greater than that of the vector
10825 // element reject it.
10826 return (IntSigned != OtherIntSigned &&
10827 NumBits > S.Context.getIntWidth(OtherIntTy));
10828 }
10829
10830 // Reject cases where the value of the scalar is not constant and it's
10831 // order is greater than that of the vector element type.
10832 return (Order < 0);
10833}
10834
10835/// Test if a (constant) integer Int can be casted to floating point type
10836/// FloatTy without losing precision.
10838 QualType FloatTy) {
10839 if (Int->get()->containsErrors())
10840 return false;
10841
10842 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10843
10844 // Determine if the integer constant can be expressed as a floating point
10845 // number of the appropriate type.
10846 Expr::EvalResult EVResult;
10847 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10848
10849 uint64_t Bits = 0;
10850 if (CstInt) {
10851 // Reject constants that would be truncated if they were converted to
10852 // the floating point type. Test by simple to/from conversion.
10853 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10854 // could be avoided if there was a convertFromAPInt method
10855 // which could signal back if implicit truncation occurred.
10856 llvm::APSInt Result = EVResult.Val.getInt();
10857 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10858 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10859 llvm::APFloat::rmTowardZero);
10860 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10862 bool Ignored = false;
10863 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10864 &Ignored);
10865 if (Result != ConvertBack)
10866 return true;
10867 } else {
10868 // Reject types that cannot be fully encoded into the mantissa of
10869 // the float.
10870 Bits = S.Context.getTypeSize(IntTy);
10871 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10872 S.Context.getFloatTypeSemantics(FloatTy));
10873 if (Bits > FloatPrec)
10874 return true;
10875 }
10876
10877 return false;
10878}
10879
10880/// Attempt to convert and splat Scalar into a vector whose types matches
10881/// Vector following GCC conversion rules. The rule is that implicit
10882/// conversion can occur when Scalar can be casted to match Vector's element
10883/// type without causing truncation of Scalar.
10885 ExprResult *Vector) {
10886 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10887 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10888 QualType VectorEltTy;
10889
10890 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10891 assert(!isa<ExtVectorType>(VT) &&
10892 "ExtVectorTypes should not be handled here!");
10893 VectorEltTy = VT->getElementType();
10894 } else if (VectorTy->isSveVLSBuiltinType()) {
10895 VectorEltTy =
10896 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10897 } else {
10898 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10899 }
10900
10901 // Reject cases where the vector element type or the scalar element type are
10902 // not integral or floating point types.
10903 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10904 return true;
10905
10906 // The conversion to apply to the scalar before splatting it,
10907 // if necessary.
10908 CastKind ScalarCast = CK_NoOp;
10909
10910 // Accept cases where the vector elements are integers and the scalar is
10911 // an integer.
10912 // FIXME: Notionally if the scalar was a floating point value with a precise
10913 // integral representation, we could cast it to an appropriate integer
10914 // type and then perform the rest of the checks here. GCC will perform
10915 // this conversion in some cases as determined by the input language.
10916 // We should accept it on a language independent basis.
10917 if (VectorEltTy->isIntegralType(S.Context) &&
10918 ScalarTy->isIntegralType(S.Context) &&
10919 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10920
10921 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10922 return true;
10923
10924 ScalarCast = CK_IntegralCast;
10925 } else if (VectorEltTy->isIntegralType(S.Context) &&
10926 ScalarTy->isRealFloatingType()) {
10927 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10928 ScalarCast = CK_FloatingToIntegral;
10929 else
10930 return true;
10931 } else if (VectorEltTy->isRealFloatingType()) {
10932 if (ScalarTy->isRealFloatingType()) {
10933
10934 // Reject cases where the scalar type is not a constant and has a higher
10935 // Order than the vector element type.
10936 llvm::APFloat Result(0.0);
10937
10938 // Determine whether this is a constant scalar. In the event that the
10939 // value is dependent (and thus cannot be evaluated by the constant
10940 // evaluator), skip the evaluation. This will then diagnose once the
10941 // expression is instantiated.
10942 bool CstScalar = Scalar->get()->isValueDependent() ||
10943 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10944 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10945 if (!CstScalar && Order < 0)
10946 return true;
10947
10948 // If the scalar cannot be safely casted to the vector element type,
10949 // reject it.
10950 if (CstScalar) {
10951 bool Truncated = false;
10952 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10953 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10954 if (Truncated)
10955 return true;
10956 }
10957
10958 ScalarCast = CK_FloatingCast;
10959 } else if (ScalarTy->isIntegralType(S.Context)) {
10960 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10961 return true;
10962
10963 ScalarCast = CK_IntegralToFloating;
10964 } else
10965 return true;
10966 } else if (ScalarTy->isEnumeralType())
10967 return true;
10968
10969 // Adjust scalar if desired.
10970 if (ScalarCast != CK_NoOp)
10971 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10972 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10973 return false;
10974}
10975
10977 SourceLocation Loc, bool IsCompAssign,
10978 bool AllowBothBool,
10979 bool AllowBoolConversions,
10980 bool AllowBoolOperation) {
10981 if (!IsCompAssign) {
10983 if (LHS.isInvalid())
10984 return QualType();
10985 }
10987 if (RHS.isInvalid())
10988 return QualType();
10989
10990 // For conversion purposes, we ignore any qualifiers.
10991 // For example, "const float" and "float" are equivalent.
10992 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10993 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10994
10995 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10996 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10997 assert(LHSVecType || RHSVecType);
10998
10999 if (getLangOpts().HLSL)
11000 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
11001 IsCompAssign);
11002
11003 // Any operation with MFloat8 type is only possible with C intrinsics
11004 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
11005 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
11006 return InvalidOperands(Loc, LHS, RHS);
11007
11008 // AltiVec-style "vector bool op vector bool" combinations are allowed
11009 // for some operators but not others.
11010 if (!AllowBothBool && LHSVecType &&
11011 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
11012 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11013 return InvalidOperands(Loc, LHS, RHS);
11014
11015 // This operation may not be performed on boolean vectors.
11016 if (!AllowBoolOperation &&
11017 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
11018 return InvalidOperands(Loc, LHS, RHS);
11019
11020 // If the vector types are identical, return.
11021 if (Context.hasSameType(LHSType, RHSType))
11022 return Context.getCommonSugaredType(LHSType, RHSType);
11023
11024 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
11025 if (LHSVecType && RHSVecType &&
11026 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
11027 if (isa<ExtVectorType>(LHSVecType)) {
11028 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11029 return LHSType;
11030 }
11031
11032 if (!IsCompAssign)
11033 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11034 return RHSType;
11035 }
11036
11037 // AllowBoolConversions says that bool and non-bool AltiVec vectors
11038 // can be mixed, with the result being the non-bool type. The non-bool
11039 // operand must have integer element type.
11040 if (AllowBoolConversions && LHSVecType && RHSVecType &&
11041 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
11042 (Context.getTypeSize(LHSVecType->getElementType()) ==
11043 Context.getTypeSize(RHSVecType->getElementType()))) {
11044 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
11045 LHSVecType->getElementType()->isIntegerType() &&
11046 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
11047 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11048 return LHSType;
11049 }
11050 if (!IsCompAssign &&
11051 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
11052 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
11053 RHSVecType->getElementType()->isIntegerType()) {
11054 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11055 return RHSType;
11056 }
11057 }
11058
11059 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
11060 // invalid since the ambiguity can affect the ABI.
11061 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
11062 unsigned &SVEorRVV) {
11063 const VectorType *VecType = SecondType->getAs<VectorType>();
11064 SVEorRVV = 0;
11065 if (FirstType->isSizelessBuiltinType() && VecType) {
11068 return true;
11069 if (isRVVFixedLengthVectorKind(VecType->getVectorKind())) {
11070 SVEorRVV = 1;
11071 return true;
11072 }
11073 }
11074
11075 return false;
11076 };
11077
11078 unsigned SVEorRVV;
11079 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
11080 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
11081 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
11082 << SVEorRVV << LHSType << RHSType;
11083 return QualType();
11084 }
11085
11086 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
11087 // invalid since the ambiguity can affect the ABI.
11088 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
11089 unsigned &SVEorRVV) {
11090 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
11091 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
11092
11093 SVEorRVV = 0;
11094 if (FirstVecType && SecondVecType) {
11095 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
11096 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
11097 SecondVecType->getVectorKind() ==
11099 return true;
11100 if (isRVVFixedLengthVectorKind(SecondVecType->getVectorKind())) {
11101 SVEorRVV = 1;
11102 return true;
11103 }
11104 }
11105 return false;
11106 }
11107
11108 if (SecondVecType &&
11109 SecondVecType->getVectorKind() == VectorKind::Generic) {
11110 if (FirstType->isSVESizelessBuiltinType())
11111 return true;
11112 if (FirstType->isRVVSizelessBuiltinType()) {
11113 SVEorRVV = 1;
11114 return true;
11115 }
11116 }
11117
11118 return false;
11119 };
11120
11121 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
11122 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
11123 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
11124 << SVEorRVV << LHSType << RHSType;
11125 return QualType();
11126 }
11127
11128 // If there's a vector type and a scalar, try to convert the scalar to
11129 // the vector element type and splat.
11130 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
11131 if (!RHSVecType) {
11132 if (isa<ExtVectorType>(LHSVecType)) {
11133 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
11134 LHSVecType->getElementType(), LHSType,
11135 DiagID))
11136 return LHSType;
11137 } else {
11138 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11139 return LHSType;
11140 }
11141 }
11142 if (!LHSVecType) {
11143 if (isa<ExtVectorType>(RHSVecType)) {
11144 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
11145 LHSType, RHSVecType->getElementType(),
11146 RHSType, DiagID))
11147 return RHSType;
11148 } else {
11149 if (LHS.get()->isLValue() ||
11150 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11151 return RHSType;
11152 }
11153 }
11154
11155 // FIXME: The code below also handles conversion between vectors and
11156 // non-scalars, we should break this down into fine grained specific checks
11157 // and emit proper diagnostics.
11158 QualType VecType = LHSVecType ? LHSType : RHSType;
11159 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
11160 QualType OtherType = LHSVecType ? RHSType : LHSType;
11161 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
11162 if (isLaxVectorConversion(OtherType, VecType)) {
11163 if (Context.getTargetInfo().getTriple().isPPC() &&
11164 anyAltivecTypes(RHSType, LHSType) &&
11165 !Context.areCompatibleVectorTypes(RHSType, LHSType))
11166 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
11167 // If we're allowing lax vector conversions, only the total (data) size
11168 // needs to be the same. For non compound assignment, if one of the types is
11169 // scalar, the result is always the vector type.
11170 if (!IsCompAssign) {
11171 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
11172 return VecType;
11173 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11174 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11175 // type. Note that this is already done by non-compound assignments in
11176 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11177 // <1 x T> -> T. The result is also a vector type.
11178 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
11179 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
11180 ExprResult *RHSExpr = &RHS;
11181 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
11182 return VecType;
11183 }
11184 }
11185
11186 // Okay, the expression is invalid.
11187
11188 // If there's a non-vector, non-real operand, diagnose that.
11189 if ((!RHSVecType && !RHSType->isRealType()) ||
11190 (!LHSVecType && !LHSType->isRealType())) {
11191 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11192 << LHSType << RHSType
11193 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11194 return QualType();
11195 }
11196
11197 // OpenCL V1.1 6.2.6.p1:
11198 // If the operands are of more than one vector type, then an error shall
11199 // occur. Implicit conversions between vector types are not permitted, per
11200 // section 6.2.1.
11201 if (getLangOpts().OpenCL &&
11202 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
11203 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
11204 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
11205 << RHSType;
11206 return QualType();
11207 }
11208
11209
11210 // If there is a vector type that is not a ExtVector and a scalar, we reach
11211 // this point if scalar could not be converted to the vector's element type
11212 // without truncation.
11213 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
11214 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
11215 QualType Scalar = LHSVecType ? RHSType : LHSType;
11216 QualType Vector = LHSVecType ? LHSType : RHSType;
11217 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11218 Diag(Loc,
11219 diag::err_typecheck_vector_not_convertable_implict_truncation)
11220 << ScalarOrVector << Scalar << Vector;
11221
11222 return QualType();
11223 }
11224
11225 // Otherwise, use the generic diagnostic.
11226 Diag(Loc, DiagID)
11227 << LHSType << RHSType
11228 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11229 return QualType();
11230}
11231
11233 SourceLocation Loc,
11234 bool IsCompAssign,
11235 ArithConvKind OperationKind) {
11236 if (!IsCompAssign) {
11238 if (LHS.isInvalid())
11239 return QualType();
11240 }
11242 if (RHS.isInvalid())
11243 return QualType();
11244
11245 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11246 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11247
11248 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11249 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11250
11251 unsigned DiagID = diag::err_typecheck_invalid_operands;
11252 if ((OperationKind == ArithConvKind::Arithmetic) &&
11253 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11254 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11255 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11256 << RHS.get()->getSourceRange();
11257 return QualType();
11258 }
11259
11260 if (Context.hasSameType(LHSType, RHSType))
11261 return LHSType;
11262
11263 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11264 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11265 return LHSType;
11266 }
11267 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11268 if (LHS.get()->isLValue() ||
11269 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11270 return RHSType;
11271 }
11272
11273 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11274 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11275 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11276 << LHSType << RHSType << LHS.get()->getSourceRange()
11277 << RHS.get()->getSourceRange();
11278 return QualType();
11279 }
11280
11281 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11282 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11283 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11284 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11285 << LHSType << RHSType << LHS.get()->getSourceRange()
11286 << RHS.get()->getSourceRange();
11287 return QualType();
11288 }
11289
11290 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11291 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11292 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11293 bool ScalarOrVector =
11294 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11295
11296 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11297 << ScalarOrVector << Scalar << Vector;
11298
11299 return QualType();
11300 }
11301
11302 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11303 << RHS.get()->getSourceRange();
11304 return QualType();
11305}
11306
11307// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11308// expression. These are mainly cases where the null pointer is used as an
11309// integer instead of a pointer.
11311 SourceLocation Loc, bool IsCompare) {
11312 // The canonical way to check for a GNU null is with isNullPointerConstant,
11313 // but we use a bit of a hack here for speed; this is a relatively
11314 // hot path, and isNullPointerConstant is slow.
11315 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11316 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11317
11318 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11319
11320 // Avoid analyzing cases where the result will either be invalid (and
11321 // diagnosed as such) or entirely valid and not something to warn about.
11322 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11323 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11324 return;
11325
11326 // Comparison operations would not make sense with a null pointer no matter
11327 // what the other expression is.
11328 if (!IsCompare) {
11329 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11330 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11331 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11332 return;
11333 }
11334
11335 // The rest of the operations only make sense with a null pointer
11336 // if the other expression is a pointer.
11337 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11338 NonNullType->canDecayToPointerType())
11339 return;
11340
11341 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11342 << LHSNull /* LHS is NULL */ << NonNullType
11343 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11344}
11345
11347 SourceLocation OpLoc) {
11348 // If the divisor is real, then this is real/real or complex/real division.
11349 // Either way there can be no precision loss.
11350 auto *CT = DivisorTy->getAs<ComplexType>();
11351 if (!CT)
11352 return;
11353
11354 QualType ElementType = CT->getElementType().getCanonicalType();
11355 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11357 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11358 return;
11359
11360 ASTContext &Ctx = S.getASTContext();
11361 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11362 const llvm::fltSemantics &ElementTypeSemantics =
11363 Ctx.getFloatTypeSemantics(ElementType);
11364 const llvm::fltSemantics &HigherElementTypeSemantics =
11365 Ctx.getFloatTypeSemantics(HigherElementType);
11366
11367 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11368 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11369 (HigherElementType == Ctx.LongDoubleTy &&
11370 !Ctx.getTargetInfo().hasLongDoubleType())) {
11371 // Retain the location of the first use of higher precision type.
11374 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11375 if (Type == HigherElementType) {
11376 Num++;
11377 return;
11378 }
11379 }
11380 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
11381 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
11382 }
11383}
11384
11386 SourceLocation Loc) {
11387 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11388 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11389 if (!LUE || !RUE)
11390 return;
11391 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11392 RUE->getKind() != UETT_SizeOf)
11393 return;
11394
11395 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11396 QualType LHSTy = LHSArg->getType();
11397 QualType RHSTy;
11398
11399 if (RUE->isArgumentType())
11400 RHSTy = RUE->getArgumentType().getNonReferenceType();
11401 else
11402 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11403
11404 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11405 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11406 return;
11407
11408 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11409 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11410 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11411 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11412 << LHSArgDecl;
11413 }
11414 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11415 QualType ArrayElemTy = ArrayTy->getElementType();
11416 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11417 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11418 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11419 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11420 return;
11421 S.Diag(Loc, diag::warn_division_sizeof_array)
11422 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11423 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11424 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11425 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11426 << LHSArgDecl;
11427 }
11428
11429 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11430 }
11431}
11432
11434 ExprResult &RHS,
11435 SourceLocation Loc, bool IsDiv) {
11436 // Check for division/remainder by zero.
11437 Expr::EvalResult RHSValue;
11438 if (!RHS.get()->isValueDependent() &&
11439 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11440 RHSValue.Val.getInt() == 0)
11441 S.DiagRuntimeBehavior(Loc, RHS.get(),
11442 S.PDiag(diag::warn_remainder_division_by_zero)
11443 << IsDiv << RHS.get()->getSourceRange());
11444}
11445
11446static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11447 const ExprResult &LHS, const ExprResult &RHS,
11448 BinaryOperatorKind Opc) {
11449 if (!LHS.isUsable() || !RHS.isUsable())
11450 return;
11451 const Expr *LHSExpr = LHS.get();
11452 const Expr *RHSExpr = RHS.get();
11453 const QualType LHSType = LHSExpr->getType();
11454 const QualType RHSType = RHSExpr->getType();
11455 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11456 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11457 if (!LHSIsScoped && !RHSIsScoped)
11458 return;
11459 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11460 return;
11461 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11462 return;
11463 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11464 return;
11465 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11466 SourceLocation BeginLoc = expr->getBeginLoc();
11467 QualType IntType = type->castAs<EnumType>()
11468 ->getDecl()
11469 ->getDefinitionOrSelf()
11470 ->getIntegerType();
11471 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11472 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
11473 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
11474 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
11475 };
11476 if (LHSIsScoped) {
11477 DiagnosticHelper(LHSExpr, LHSType);
11478 }
11479 if (RHSIsScoped) {
11480 DiagnosticHelper(RHSExpr, RHSType);
11481 }
11482}
11483
11485 SourceLocation Loc,
11486 BinaryOperatorKind Opc) {
11487 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11488 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11489
11490 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11491
11492 QualType LHSTy = LHS.get()->getType();
11493 QualType RHSTy = RHS.get()->getType();
11494 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11495 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11496 /*AllowBothBool*/ getLangOpts().AltiVec,
11497 /*AllowBoolConversions*/ false,
11498 /*AllowBooleanOperation*/ false);
11499 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11500 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11502 if (!IsDiv &&
11503 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11504 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11505 // For division, only matrix-by-scalar is supported. Other combinations with
11506 // matrix types are invalid.
11507 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11508 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11509
11511 LHS, RHS, Loc,
11513 if (LHS.isInvalid() || RHS.isInvalid())
11514 return QualType();
11515
11516 if (compType.isNull() || !compType->isArithmeticType()) {
11517 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11518 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11519 return ResultTy;
11520 }
11521 if (IsDiv) {
11522 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
11523 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11524 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11525 }
11526 return compType;
11527}
11528
11530 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11531 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11532
11533 // Note: This check is here to simplify the double exclusions of
11534 // scalar and vector HLSL checks. No getLangOpts().HLSL
11535 // is needed since all languages exlcude doubles.
11536 if (LHS.get()->getType()->isDoubleType() ||
11537 RHS.get()->getType()->isDoubleType() ||
11538 (LHS.get()->getType()->isVectorType() && LHS.get()
11539 ->getType()
11540 ->getAs<VectorType>()
11541 ->getElementType()
11542 ->isDoubleType()) ||
11543 (RHS.get()->getType()->isVectorType() && RHS.get()
11544 ->getType()
11545 ->getAs<VectorType>()
11546 ->getElementType()
11547 ->isDoubleType()))
11548 return InvalidOperands(Loc, LHS, RHS);
11549
11550 if (LHS.get()->getType()->isVectorType() ||
11551 RHS.get()->getType()->isVectorType()) {
11552 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11553 RHS.get()->getType()->hasIntegerRepresentation()) ||
11554 (getLangOpts().HLSL &&
11555 (LHS.get()->getType()->hasFloatingRepresentation() ||
11557 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11558 /*AllowBothBool*/ getLangOpts().AltiVec,
11559 /*AllowBoolConversions*/ false,
11560 /*AllowBooleanOperation*/ false);
11561 return InvalidOperands(Loc, LHS, RHS);
11562 }
11563
11564 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11565 RHS.get()->getType()->isSveVLSBuiltinType()) {
11566 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11568 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11570
11571 return InvalidOperands(Loc, LHS, RHS);
11572 }
11573
11575 LHS, RHS, Loc,
11577 if (LHS.isInvalid() || RHS.isInvalid())
11578 return QualType();
11579
11580 if (compType.isNull() ||
11581 (!compType->isIntegerType() &&
11582 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11583 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11584 diagnoseScopedEnums(*this, Loc, LHS, RHS,
11585 IsCompAssign ? BO_RemAssign : BO_Rem);
11586 return ResultTy;
11587 }
11588 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11589 return compType;
11590}
11591
11592/// Diagnose invalid arithmetic on two void pointers.
11594 Expr *LHSExpr, Expr *RHSExpr) {
11595 S.Diag(Loc, S.getLangOpts().CPlusPlus
11596 ? diag::err_typecheck_pointer_arith_void_type
11597 : diag::ext_gnu_void_ptr)
11598 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11599 << RHSExpr->getSourceRange();
11600}
11601
11602/// Diagnose invalid arithmetic on a void pointer.
11604 Expr *Pointer) {
11605 S.Diag(Loc, S.getLangOpts().CPlusPlus
11606 ? diag::err_typecheck_pointer_arith_void_type
11607 : diag::ext_gnu_void_ptr)
11608 << 0 /* one pointer */ << Pointer->getSourceRange();
11609}
11610
11611/// Diagnose invalid arithmetic on a null pointer.
11612///
11613/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11614/// idiom, which we recognize as a GNU extension.
11615///
11617 Expr *Pointer, bool IsGNUIdiom) {
11618 if (IsGNUIdiom)
11619 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11620 << Pointer->getSourceRange();
11621 else
11622 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11623 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11624}
11625
11626/// Diagnose invalid subraction on a null pointer.
11627///
11629 Expr *Pointer, bool BothNull) {
11630 // Null - null is valid in C++ [expr.add]p7
11631 if (BothNull && S.getLangOpts().CPlusPlus)
11632 return;
11633
11634 // Is this s a macro from a system header?
11636 return;
11637
11639 S.PDiag(diag::warn_pointer_sub_null_ptr)
11640 << S.getLangOpts().CPlusPlus
11641 << Pointer->getSourceRange());
11642}
11643
11644/// Diagnose invalid arithmetic on two function pointers.
11646 Expr *LHS, Expr *RHS) {
11647 assert(LHS->getType()->isAnyPointerType());
11648 assert(RHS->getType()->isAnyPointerType());
11649 S.Diag(Loc, S.getLangOpts().CPlusPlus
11650 ? diag::err_typecheck_pointer_arith_function_type
11651 : diag::ext_gnu_ptr_func_arith)
11652 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11653 // We only show the second type if it differs from the first.
11655 RHS->getType())
11656 << RHS->getType()->getPointeeType()
11657 << LHS->getSourceRange() << RHS->getSourceRange();
11658}
11659
11660/// Diagnose invalid arithmetic on a function pointer.
11662 Expr *Pointer) {
11663 assert(Pointer->getType()->isAnyPointerType());
11664 S.Diag(Loc, S.getLangOpts().CPlusPlus
11665 ? diag::err_typecheck_pointer_arith_function_type
11666 : diag::ext_gnu_ptr_func_arith)
11667 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11668 << 0 /* one pointer, so only one type */
11669 << Pointer->getSourceRange();
11670}
11671
11672/// Emit error if Operand is incomplete pointer type
11673///
11674/// \returns True if pointer has incomplete type
11676 Expr *Operand) {
11677 QualType ResType = Operand->getType();
11678 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11679 ResType = ResAtomicType->getValueType();
11680
11681 assert(ResType->isAnyPointerType());
11682 QualType PointeeTy = ResType->getPointeeType();
11683 return S.RequireCompleteSizedType(
11684 Loc, PointeeTy,
11685 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11686 Operand->getSourceRange());
11687}
11688
11689/// Check the validity of an arithmetic pointer operand.
11690///
11691/// If the operand has pointer type, this code will check for pointer types
11692/// which are invalid in arithmetic operations. These will be diagnosed
11693/// appropriately, including whether or not the use is supported as an
11694/// extension.
11695///
11696/// \returns True when the operand is valid to use (even if as an extension).
11698 Expr *Operand) {
11699 QualType ResType = Operand->getType();
11700 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11701 ResType = ResAtomicType->getValueType();
11702
11703 if (!ResType->isAnyPointerType()) return true;
11704
11705 QualType PointeeTy = ResType->getPointeeType();
11706 if (PointeeTy->isVoidType()) {
11707 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11708 return !S.getLangOpts().CPlusPlus;
11709 }
11710 if (PointeeTy->isFunctionType()) {
11711 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11712 return !S.getLangOpts().CPlusPlus;
11713 }
11714
11715 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11716
11717 return true;
11718}
11719
11720/// Check the validity of a binary arithmetic operation w.r.t. pointer
11721/// operands.
11722///
11723/// This routine will diagnose any invalid arithmetic on pointer operands much
11724/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11725/// for emitting a single diagnostic even for operations where both LHS and RHS
11726/// are (potentially problematic) pointers.
11727///
11728/// \returns True when the operand is valid to use (even if as an extension).
11730 Expr *LHSExpr, Expr *RHSExpr) {
11731 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11732 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11733 if (!isLHSPointer && !isRHSPointer) return true;
11734
11735 QualType LHSPointeeTy, RHSPointeeTy;
11736 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11737 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11738
11739 // if both are pointers check if operation is valid wrt address spaces
11740 if (isLHSPointer && isRHSPointer) {
11741 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11742 S.getASTContext())) {
11743 S.Diag(Loc,
11744 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11745 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11746 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11747 return false;
11748 }
11749 }
11750
11751 // Check for arithmetic on pointers to incomplete types.
11752 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11753 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11754 if (isLHSVoidPtr || isRHSVoidPtr) {
11755 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11756 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11757 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11758
11759 return !S.getLangOpts().CPlusPlus;
11760 }
11761
11762 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11763 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11764 if (isLHSFuncPtr || isRHSFuncPtr) {
11765 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11766 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11767 RHSExpr);
11768 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11769
11770 return !S.getLangOpts().CPlusPlus;
11771 }
11772
11773 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11774 return false;
11775 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11776 return false;
11777
11778 return true;
11779}
11780
11781/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11782/// literal.
11784 Expr *LHSExpr, Expr *RHSExpr) {
11785 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11786 Expr* IndexExpr = RHSExpr;
11787 if (!StrExpr) {
11788 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11789 IndexExpr = LHSExpr;
11790 }
11791
11792 bool IsStringPlusInt = StrExpr &&
11794 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11795 return;
11796
11797 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11798 Self.Diag(OpLoc, diag::warn_string_plus_int)
11799 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11800
11801 // Only print a fixit for "str" + int, not for int + "str".
11802 if (IndexExpr == RHSExpr) {
11803 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11804 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11805 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11807 << FixItHint::CreateInsertion(EndLoc, "]");
11808 } else
11809 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11810}
11811
11812/// Emit a warning when adding a char literal to a string.
11814 Expr *LHSExpr, Expr *RHSExpr) {
11815 const Expr *StringRefExpr = LHSExpr;
11816 const CharacterLiteral *CharExpr =
11817 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11818
11819 if (!CharExpr) {
11820 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11821 StringRefExpr = RHSExpr;
11822 }
11823
11824 if (!CharExpr || !StringRefExpr)
11825 return;
11826
11827 const QualType StringType = StringRefExpr->getType();
11828
11829 // Return if not a PointerType.
11830 if (!StringType->isAnyPointerType())
11831 return;
11832
11833 // Return if not a CharacterType.
11834 if (!StringType->getPointeeType()->isAnyCharacterType())
11835 return;
11836
11837 ASTContext &Ctx = Self.getASTContext();
11838 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11839
11840 const QualType CharType = CharExpr->getType();
11841 if (!CharType->isAnyCharacterType() &&
11842 CharType->isIntegerType() &&
11843 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11844 Self.Diag(OpLoc, diag::warn_string_plus_char)
11845 << DiagRange << Ctx.CharTy;
11846 } else {
11847 Self.Diag(OpLoc, diag::warn_string_plus_char)
11848 << DiagRange << CharExpr->getType();
11849 }
11850
11851 // Only print a fixit for str + char, not for char + str.
11852 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11853 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11854 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11855 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11857 << FixItHint::CreateInsertion(EndLoc, "]");
11858 } else {
11859 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11860 }
11861}
11862
11863/// Emit error when two pointers are incompatible.
11865 Expr *LHSExpr, Expr *RHSExpr) {
11866 assert(LHSExpr->getType()->isAnyPointerType());
11867 assert(RHSExpr->getType()->isAnyPointerType());
11868 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11869 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11870 << RHSExpr->getSourceRange();
11871}
11872
11873// C99 6.5.6
11876 QualType* CompLHSTy) {
11877 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11878
11879 if (LHS.get()->getType()->isVectorType() ||
11880 RHS.get()->getType()->isVectorType()) {
11881 QualType compType =
11882 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11883 /*AllowBothBool*/ getLangOpts().AltiVec,
11884 /*AllowBoolConversions*/ getLangOpts().ZVector,
11885 /*AllowBooleanOperation*/ false);
11886 if (CompLHSTy) *CompLHSTy = compType;
11887 return compType;
11888 }
11889
11890 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11891 RHS.get()->getType()->isSveVLSBuiltinType()) {
11892 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11894 if (CompLHSTy)
11895 *CompLHSTy = compType;
11896 return compType;
11897 }
11898
11899 if (LHS.get()->getType()->isConstantMatrixType() ||
11900 RHS.get()->getType()->isConstantMatrixType()) {
11901 QualType compType =
11902 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11903 if (CompLHSTy)
11904 *CompLHSTy = compType;
11905 return compType;
11906 }
11907
11909 LHS, RHS, Loc,
11911 if (LHS.isInvalid() || RHS.isInvalid())
11912 return QualType();
11913
11914 // Diagnose "string literal" '+' int and string '+' "char literal".
11915 if (Opc == BO_Add) {
11916 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11917 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11918 }
11919
11920 // handle the common case first (both operands are arithmetic).
11921 if (!compType.isNull() && compType->isArithmeticType()) {
11922 if (CompLHSTy) *CompLHSTy = compType;
11923 return compType;
11924 }
11925
11926 // Type-checking. Ultimately the pointer's going to be in PExp;
11927 // note that we bias towards the LHS being the pointer.
11928 Expr *PExp = LHS.get(), *IExp = RHS.get();
11929
11930 bool isObjCPointer;
11931 if (PExp->getType()->isPointerType()) {
11932 isObjCPointer = false;
11933 } else if (PExp->getType()->isObjCObjectPointerType()) {
11934 isObjCPointer = true;
11935 } else {
11936 std::swap(PExp, IExp);
11937 if (PExp->getType()->isPointerType()) {
11938 isObjCPointer = false;
11939 } else if (PExp->getType()->isObjCObjectPointerType()) {
11940 isObjCPointer = true;
11941 } else {
11942 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11943 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11944 return ResultTy;
11945 }
11946 }
11947 assert(PExp->getType()->isAnyPointerType());
11948
11949 if (!IExp->getType()->isIntegerType())
11950 return InvalidOperands(Loc, LHS, RHS);
11951
11952 // Adding to a null pointer results in undefined behavior.
11955 // In C++ adding zero to a null pointer is defined.
11956 Expr::EvalResult KnownVal;
11957 if (!getLangOpts().CPlusPlus ||
11958 (!IExp->isValueDependent() &&
11959 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11960 KnownVal.Val.getInt() != 0))) {
11961 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11963 Context, BO_Add, PExp, IExp);
11964 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11965 }
11966 }
11967
11968 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11969 return QualType();
11970
11971 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11972 return QualType();
11973
11974 // Arithmetic on label addresses is normally allowed, except when we add
11975 // a ptrauth signature to the addresses.
11976 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11977 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11978 << /*addition*/ 1;
11979 return QualType();
11980 }
11981
11982 // Check array bounds for pointer arithemtic
11983 CheckArrayAccess(PExp, IExp);
11984
11985 if (CompLHSTy) {
11986 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11987 if (LHSTy.isNull()) {
11988 LHSTy = LHS.get()->getType();
11989 if (Context.isPromotableIntegerType(LHSTy))
11990 LHSTy = Context.getPromotedIntegerType(LHSTy);
11991 }
11992 *CompLHSTy = LHSTy;
11993 }
11994
11995 return PExp->getType();
11996}
11997
11998/// Determine whether the size of \p T is provably zero: some array dimension
11999/// is provably zero or the base element type has zero size. A variable
12000/// dimension that does not fold to an integer constant is assumed nonzero.
12001static bool isProvablyZeroSize(const ASTContext &Ctx, QualType T) {
12002 while (const ArrayType *AT = Ctx.getAsArrayType(T)) {
12003 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
12004 if (CAT->isZeroSize())
12005 return true;
12006 } else if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
12007 if (const Expr *Bound = VAT->getSizeExpr())
12008 if (std::optional<llvm::APSInt> Size =
12009 Bound->getIntegerConstantExpr(Ctx))
12010 if (*Size == 0)
12011 return true;
12012 }
12013 T = AT->getElementType();
12014 }
12015 return !T->isIncompleteType() && Ctx.getTypeSizeInChars(T).isZero();
12016}
12017
12018// C99 6.5.6
12020 SourceLocation Loc,
12022 QualType *CompLHSTy) {
12023 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12024
12025 if (LHS.get()->getType()->isVectorType() ||
12026 RHS.get()->getType()->isVectorType()) {
12027 QualType compType =
12028 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
12029 /*AllowBothBool*/ getLangOpts().AltiVec,
12030 /*AllowBoolConversions*/ getLangOpts().ZVector,
12031 /*AllowBooleanOperation*/ false);
12032 if (CompLHSTy) *CompLHSTy = compType;
12033 return compType;
12034 }
12035
12036 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12037 RHS.get()->getType()->isSveVLSBuiltinType()) {
12038 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
12040 if (CompLHSTy)
12041 *CompLHSTy = compType;
12042 return compType;
12043 }
12044
12045 if (LHS.get()->getType()->isConstantMatrixType() ||
12046 RHS.get()->getType()->isConstantMatrixType()) {
12047 QualType compType =
12048 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
12049 if (CompLHSTy)
12050 *CompLHSTy = compType;
12051 return compType;
12052 }
12053
12055 LHS, RHS, Loc,
12057 if (LHS.isInvalid() || RHS.isInvalid())
12058 return QualType();
12059
12060 // Enforce type constraints: C99 6.5.6p3.
12061
12062 // Handle the common case first (both operands are arithmetic).
12063 if (!compType.isNull() && compType->isArithmeticType()) {
12064 if (CompLHSTy) *CompLHSTy = compType;
12065 return compType;
12066 }
12067
12068 // Either ptr - int or ptr - ptr.
12069 if (LHS.get()->getType()->isAnyPointerType()) {
12070 QualType lpointee = LHS.get()->getType()->getPointeeType();
12071
12072 // Diagnose bad cases where we step over interface counts.
12073 if (LHS.get()->getType()->isObjCObjectPointerType() &&
12074 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
12075 return QualType();
12076
12077 // Arithmetic on label addresses is normally allowed, except when we add
12078 // a ptrauth signature to the addresses.
12079 if (isa<AddrLabelExpr>(LHS.get()) &&
12080 getLangOpts().PointerAuthIndirectGotos) {
12081 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
12082 << /*subtraction*/ 0;
12083 return QualType();
12084 }
12085
12086 // The result type of a pointer-int computation is the pointer type.
12087 if (RHS.get()->getType()->isIntegerType()) {
12088 // Subtracting from a null pointer should produce a warning.
12089 // The last argument to the diagnose call says this doesn't match the
12090 // GNU int-to-pointer idiom.
12093 // In C++ adding zero to a null pointer is defined.
12094 Expr::EvalResult KnownVal;
12095 if (!getLangOpts().CPlusPlus ||
12096 (!RHS.get()->isValueDependent() &&
12097 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
12098 KnownVal.Val.getInt() != 0))) {
12099 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
12100 }
12101 }
12102
12103 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
12104 return QualType();
12105
12106 // Check array bounds for pointer arithemtic
12107 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
12108 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
12109
12110 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12111 return LHS.get()->getType();
12112 }
12113
12114 // Handle pointer-pointer subtractions.
12115 if (const PointerType *RHSPTy
12116 = RHS.get()->getType()->getAs<PointerType>()) {
12117 QualType rpointee = RHSPTy->getPointeeType();
12118
12119 if (getLangOpts().CPlusPlus) {
12120 // Pointee types must be the same: C++ [expr.add]
12121 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
12122 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
12123 }
12124 } else {
12125 // Pointee types must be compatible C99 6.5.6p3
12126 if (!Context.typesAreCompatible(
12127 Context.getCanonicalType(lpointee).getUnqualifiedType(),
12128 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
12129 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
12130 return QualType();
12131 }
12132 }
12133
12135 LHS.get(), RHS.get()))
12136 return QualType();
12137
12138 // For pointer subtraction, if the address spaces differ but overlap,
12139 // convert both pointers to the composite (superset) address space.
12140 // This is needed because address spaces may use different
12141 // representations, such as a private offset vs a flat address.
12142 LangAS LAddrSpace = lpointee.getAddressSpace();
12143 LangAS RAddrSpace = rpointee.getAddressSpace();
12144 if (LAddrSpace != RAddrSpace) {
12145 Qualifiers LQual = lpointee.getQualifiers();
12146 Qualifiers RQual = rpointee.getQualifiers();
12147 LangAS ResultAddrSpace = LQual.isAddressSpaceSupersetOf(RQual, Context)
12148 ? LAddrSpace
12149 : RAddrSpace;
12150
12151 if (LAddrSpace != ResultAddrSpace) {
12152 QualType NewPteTy = Context.getAddrSpaceQualType(
12153 lpointee.getUnqualifiedType(), ResultAddrSpace);
12154 QualType NewPtrTy = Context.getPointerType(NewPteTy);
12155 LHS =
12156 ImpCastExprToType(LHS.get(), NewPtrTy, CK_AddressSpaceConversion);
12157 }
12158 if (RAddrSpace != ResultAddrSpace) {
12159 QualType NewPteTy = Context.getAddrSpaceQualType(
12160 rpointee.getUnqualifiedType(), ResultAddrSpace);
12161 QualType NewPtrTy = Context.getPointerType(NewPteTy);
12162 RHS =
12163 ImpCastExprToType(RHS.get(), NewPtrTy, CK_AddressSpaceConversion);
12164 }
12165 }
12166
12167 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12169 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12171
12172 // Subtracting nullptr or from nullptr is suspect
12173 if (LHSIsNullPtr)
12174 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
12175 if (RHSIsNullPtr)
12176 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
12177
12178 // The pointee type may have zero size. As an extension, a structure or
12179 // union may have zero size or an array may have zero length. In this
12180 // case subtraction does not make sense. For a variably modified type,
12181 // warn only when the size is provably zero.
12182 if (!rpointee->isVoidType() && !rpointee->isFunctionType() &&
12183 isProvablyZeroSize(Context, rpointee))
12184 Diag(Loc, diag::warn_sub_ptr_zero_size_types)
12185 << rpointee.getUnqualifiedType() << LHS.get()->getSourceRange()
12186 << RHS.get()->getSourceRange();
12187
12188 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12189 return Context.getPointerDiffType();
12190 }
12191 }
12192
12193 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12194 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12195 return ResultTy;
12196}
12197
12199 if (const EnumType *ET = T->getAsCanonical<EnumType>())
12200 return ET->getDecl()->isScoped();
12201 return false;
12202}
12203
12206 QualType LHSType) {
12207 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
12208 // so skip remaining warnings as we don't want to modify values within Sema.
12209 if (S.getLangOpts().OpenCL)
12210 return;
12211
12212 if (Opc == BO_Shr &&
12214 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
12215
12216 // Check right/shifter operand
12217 Expr::EvalResult RHSResult;
12218 if (RHS.get()->isValueDependent() ||
12219 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
12220 return;
12221 llvm::APSInt Right = RHSResult.Val.getInt();
12222
12223 if (Right.isNegative()) {
12224 S.DiagRuntimeBehavior(Loc, RHS.get(),
12225 S.PDiag(diag::warn_shift_negative)
12226 << RHS.get()->getSourceRange());
12227 return;
12228 }
12229
12230 QualType LHSExprType = LHS.get()->getType();
12231 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
12232 if (LHSExprType->isBitIntType())
12233 LeftSize = S.Context.getIntWidth(LHSExprType);
12234 else if (LHSExprType->isFixedPointType()) {
12235 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
12236 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
12237 }
12238 if (Right.uge(LeftSize)) {
12239 S.DiagRuntimeBehavior(Loc, RHS.get(),
12240 S.PDiag(diag::warn_shift_gt_typewidth)
12241 << RHS.get()->getSourceRange());
12242 return;
12243 }
12244
12245 // FIXME: We probably need to handle fixed point types specially here.
12246 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12247 return;
12248
12249 // When left shifting an ICE which is signed, we can check for overflow which
12250 // according to C++ standards prior to C++2a has undefined behavior
12251 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12252 // more than the maximum value representable in the result type, so never
12253 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12254 // expression is still probably a bug.)
12255 Expr::EvalResult LHSResult;
12256 if (LHS.get()->isValueDependent() ||
12258 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
12259 return;
12260 llvm::APSInt Left = LHSResult.Val.getInt();
12261
12262 // Don't warn if signed overflow is defined, then all the rest of the
12263 // diagnostics will not be triggered because the behavior is defined.
12264 // Also don't warn in C++20 mode (and newer), as signed left shifts
12265 // always wrap and never overflow.
12266 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12267 return;
12268
12269 // If LHS does not have a non-negative value then, the
12270 // behavior is undefined before C++2a. Warn about it.
12271 if (Left.isNegative()) {
12272 S.DiagRuntimeBehavior(Loc, LHS.get(),
12273 S.PDiag(diag::warn_shift_lhs_negative)
12274 << LHS.get()->getSourceRange());
12275 return;
12276 }
12277
12278 llvm::APInt ResultBits =
12279 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12280 if (ResultBits.ule(LeftSize))
12281 return;
12282 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
12283 Result = Result.shl(Right);
12284
12285 // Print the bit representation of the signed integer as an unsigned
12286 // hexadecimal number.
12287 SmallString<40> HexResult;
12288 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
12289
12290 // If we are only missing a sign bit, this is less likely to result in actual
12291 // bugs -- if the result is cast back to an unsigned type, it will have the
12292 // expected value. Thus we place this behind a different warning that can be
12293 // turned off separately if needed.
12294 if (ResultBits - 1 == LeftSize) {
12295 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
12296 << HexResult << LHSType
12297 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12298 return;
12299 }
12300
12301 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
12302 << HexResult.str() << Result.getSignificantBits() << LHSType
12303 << Left.getBitWidth() << LHS.get()->getSourceRange()
12304 << RHS.get()->getSourceRange();
12305}
12306
12307/// Return the resulting type when a vector is shifted
12308/// by a scalar or vector shift amount.
12310 SourceLocation Loc, bool IsCompAssign) {
12311 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12312 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12313 !LHS.get()->getType()->isVectorType()) {
12314 S.Diag(Loc, diag::err_shift_rhs_only_vector)
12315 << RHS.get()->getType() << LHS.get()->getType()
12316 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12317 return QualType();
12318 }
12319
12320 if (!IsCompAssign) {
12321 LHS = S.UsualUnaryConversions(LHS.get());
12322 if (LHS.isInvalid()) return QualType();
12323 }
12324
12325 RHS = S.UsualUnaryConversions(RHS.get());
12326 if (RHS.isInvalid()) return QualType();
12327
12328 QualType LHSType = LHS.get()->getType();
12329 // Note that LHS might be a scalar because the routine calls not only in
12330 // OpenCL case.
12331 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12332 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12333
12334 // Note that RHS might not be a vector.
12335 QualType RHSType = RHS.get()->getType();
12336 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12337 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12338
12339 // Do not allow shifts for boolean vectors.
12340 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12341 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12342 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12343 << LHS.get()->getType() << RHS.get()->getType()
12344 << LHS.get()->getSourceRange();
12345 return QualType();
12346 }
12347
12348 // The operands need to be integers.
12349 if (!LHSEleType->isIntegerType()) {
12350 S.Diag(Loc, diag::err_typecheck_expect_int)
12351 << LHS.get()->getType() << LHS.get()->getSourceRange();
12352 return QualType();
12353 }
12354
12355 if (!RHSEleType->isIntegerType()) {
12356 S.Diag(Loc, diag::err_typecheck_expect_int)
12357 << RHS.get()->getType() << RHS.get()->getSourceRange();
12358 return QualType();
12359 }
12360
12361 if (!LHSVecTy) {
12362 assert(RHSVecTy);
12363 if (IsCompAssign)
12364 return RHSType;
12365 if (LHSEleType != RHSEleType) {
12366 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
12367 LHSEleType = RHSEleType;
12368 }
12369 QualType VecTy =
12370 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
12371 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
12372 LHSType = VecTy;
12373 } else if (RHSVecTy) {
12374 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12375 // are applied component-wise. So if RHS is a vector, then ensure
12376 // that the number of elements is the same as LHS...
12377 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12378 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12379 << LHS.get()->getType() << RHS.get()->getType()
12380 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12381 return QualType();
12382 }
12383 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12384 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12385 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12386 if (LHSBT != RHSBT &&
12387 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12388 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12389 << LHS.get()->getType() << RHS.get()->getType()
12390 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12391 }
12392 }
12393 } else {
12394 // ...else expand RHS to match the number of elements in LHS.
12395 QualType VecTy =
12396 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12397 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12398 }
12399
12400 return LHSType;
12401}
12402
12404 ExprResult &RHS, SourceLocation Loc,
12405 bool IsCompAssign) {
12406 if (!IsCompAssign) {
12407 LHS = S.UsualUnaryConversions(LHS.get());
12408 if (LHS.isInvalid())
12409 return QualType();
12410 }
12411
12412 RHS = S.UsualUnaryConversions(RHS.get());
12413 if (RHS.isInvalid())
12414 return QualType();
12415
12416 QualType LHSType = LHS.get()->getType();
12417 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12418 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12419 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12420 : LHSType;
12421
12422 // Note that RHS might not be a vector
12423 QualType RHSType = RHS.get()->getType();
12424 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12425 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12426 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12427 : RHSType;
12428
12429 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12430 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12431 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12432 << LHSType << RHSType << LHS.get()->getSourceRange();
12433 return QualType();
12434 }
12435
12436 if (!LHSEleType->isIntegerType()) {
12437 S.Diag(Loc, diag::err_typecheck_expect_int)
12438 << LHS.get()->getType() << LHS.get()->getSourceRange();
12439 return QualType();
12440 }
12441
12442 if (!RHSEleType->isIntegerType()) {
12443 S.Diag(Loc, diag::err_typecheck_expect_int)
12444 << RHS.get()->getType() << RHS.get()->getSourceRange();
12445 return QualType();
12446 }
12447
12448 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12449 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12450 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12451 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12452 << LHSType << RHSType << LHS.get()->getSourceRange()
12453 << RHS.get()->getSourceRange();
12454 return QualType();
12455 }
12456
12457 if (!LHSType->isSveVLSBuiltinType()) {
12458 assert(RHSType->isSveVLSBuiltinType());
12459 if (IsCompAssign)
12460 return RHSType;
12461 if (LHSEleType != RHSEleType) {
12462 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12463 LHSEleType = RHSEleType;
12464 }
12465 const llvm::ElementCount VecSize =
12466 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12467 QualType VecTy =
12468 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12469 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12470 LHSType = VecTy;
12471 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12472 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12473 S.Context.getTypeSize(LHSBuiltinTy)) {
12474 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12475 << LHSType << RHSType << LHS.get()->getSourceRange()
12476 << RHS.get()->getSourceRange();
12477 return QualType();
12478 }
12479 } else {
12480 const llvm::ElementCount VecSize =
12481 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12482 if (LHSEleType != RHSEleType) {
12483 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12484 RHSEleType = LHSEleType;
12485 }
12486 QualType VecTy =
12487 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12488 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12489 }
12490
12491 return LHSType;
12492}
12493
12494// C99 6.5.7
12497 bool IsCompAssign) {
12498 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12499
12500 // Vector shifts promote their scalar inputs to vector type.
12501 if (LHS.get()->getType()->isVectorType() ||
12502 RHS.get()->getType()->isVectorType()) {
12503 if (LangOpts.ZVector) {
12504 // The shift operators for the z vector extensions work basically
12505 // like general shifts, except that neither the LHS nor the RHS is
12506 // allowed to be a "vector bool".
12507 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12508 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12509 return InvalidOperands(Loc, LHS, RHS);
12510 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12511 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12512 return InvalidOperands(Loc, LHS, RHS);
12513 }
12514 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12515 }
12516
12517 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12518 RHS.get()->getType()->isSveVLSBuiltinType())
12519 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12520
12521 // Shifts don't perform usual arithmetic conversions, they just do integer
12522 // promotions on each operand. C99 6.5.7p3
12523
12524 // For the LHS, do usual unary conversions, but then reset them away
12525 // if this is a compound assignment.
12526 ExprResult OldLHS = LHS;
12527 LHS = UsualUnaryConversions(LHS.get());
12528 if (LHS.isInvalid())
12529 return QualType();
12530 QualType LHSType = LHS.get()->getType();
12531 if (IsCompAssign) LHS = OldLHS;
12532
12533 // The RHS is simpler.
12534 RHS = UsualUnaryConversions(RHS.get());
12535 if (RHS.isInvalid())
12536 return QualType();
12537 QualType RHSType = RHS.get()->getType();
12538
12539 // C99 6.5.7p2: Each of the operands shall have integer type.
12540 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12541 if ((!LHSType->isFixedPointOrIntegerType() &&
12542 !LHSType->hasIntegerRepresentation()) ||
12543 !RHSType->hasIntegerRepresentation()) {
12544 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12545 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12546 return ResultTy;
12547 }
12548
12549 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12550
12551 // "The type of the result is that of the promoted left operand."
12552 return LHSType;
12553}
12554
12555/// Diagnose bad pointer comparisons.
12557 ExprResult &LHS, ExprResult &RHS,
12558 bool IsError) {
12559 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12560 : diag::ext_typecheck_comparison_of_distinct_pointers)
12561 << LHS.get()->getType() << RHS.get()->getType()
12562 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12563}
12564
12565/// Returns false if the pointers are converted to a composite type,
12566/// true otherwise.
12568 ExprResult &LHS, ExprResult &RHS) {
12569 // C++ [expr.rel]p2:
12570 // [...] Pointer conversions (4.10) and qualification
12571 // conversions (4.4) are performed on pointer operands (or on
12572 // a pointer operand and a null pointer constant) to bring
12573 // them to their composite pointer type. [...]
12574 //
12575 // C++ [expr.eq]p1 uses the same notion for (in)equality
12576 // comparisons of pointers.
12577
12578 QualType LHSType = LHS.get()->getType();
12579 QualType RHSType = RHS.get()->getType();
12580 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12581 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12582
12583 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12584 if (T.isNull()) {
12585 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12586 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12587 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12588 else
12589 S.InvalidOperands(Loc, LHS, RHS);
12590 return true;
12591 }
12592
12593 return false;
12594}
12595
12597 ExprResult &LHS,
12598 ExprResult &RHS,
12599 bool IsError) {
12600 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12601 : diag::ext_typecheck_comparison_of_fptr_to_void)
12602 << LHS.get()->getType() << RHS.get()->getType()
12603 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12604}
12605
12607 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12608 case Stmt::ObjCArrayLiteralClass:
12609 case Stmt::ObjCDictionaryLiteralClass:
12610 case Stmt::ObjCStringLiteralClass:
12611 case Stmt::ObjCBoxedExprClass:
12612 return true;
12613 default:
12614 // Note that ObjCBoolLiteral is NOT an object literal!
12615 return false;
12616 }
12617}
12618
12619static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12622
12623 // If this is not actually an Objective-C object, bail out.
12624 if (!Type)
12625 return false;
12626
12627 // Get the LHS object's interface type.
12628 QualType InterfaceType = Type->getPointeeType();
12629
12630 // If the RHS isn't an Objective-C object, bail out.
12631 if (!RHS->getType()->isObjCObjectPointerType())
12632 return false;
12633
12634 // Try to find the -isEqual: method.
12635 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12636 ObjCMethodDecl *Method =
12637 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
12638 /*IsInstance=*/true);
12639 if (!Method) {
12640 if (Type->isObjCIdType()) {
12641 // For 'id', just check the global pool.
12642 Method =
12644 /*receiverId=*/true);
12645 } else {
12646 // Check protocols.
12647 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
12648 /*IsInstance=*/true);
12649 }
12650 }
12651
12652 if (!Method)
12653 return false;
12654
12655 QualType T = Method->parameters()[0]->getType();
12656 if (!T->isObjCObjectPointerType())
12657 return false;
12658
12659 QualType R = Method->getReturnType();
12660 if (!R->isScalarType())
12661 return false;
12662
12663 return true;
12664}
12665
12667 ExprResult &LHS, ExprResult &RHS,
12669 Expr *Literal;
12670 Expr *Other;
12671 if (isObjCObjectLiteral(LHS)) {
12672 Literal = LHS.get();
12673 Other = RHS.get();
12674 } else {
12675 Literal = RHS.get();
12676 Other = LHS.get();
12677 }
12678
12679 // Don't warn on comparisons against nil.
12680 Other = Other->IgnoreParenCasts();
12681 if (Other->isNullPointerConstant(S.getASTContext(),
12683 return;
12684
12685 // This should be kept in sync with warn_objc_literal_comparison.
12686 // LK_String should always be after the other literals, since it has its own
12687 // warning flag.
12688 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12689 assert(LiteralKind != SemaObjC::LK_Block);
12690 if (LiteralKind == SemaObjC::LK_None) {
12691 llvm_unreachable("Unknown Objective-C object literal kind");
12692 }
12693
12694 if (LiteralKind == SemaObjC::LK_String)
12695 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12696 << Literal->getSourceRange();
12697 else
12698 S.Diag(Loc, diag::warn_objc_literal_comparison)
12699 << LiteralKind << Literal->getSourceRange();
12700
12702 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12703 SourceLocation Start = LHS.get()->getBeginLoc();
12705 CharSourceRange OpRange =
12707
12708 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12709 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12710 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12711 << FixItHint::CreateInsertion(End, "]");
12712 }
12713}
12714
12715/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12717 ExprResult &RHS, SourceLocation Loc,
12718 BinaryOperatorKind Opc) {
12719 // Check that left hand side is !something.
12720 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12721 if (!UO || UO->getOpcode() != UO_LNot) return;
12722
12723 // Only check if the right hand side is non-bool arithmetic type.
12724 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12725
12726 // Make sure that the something in !something is not bool.
12727 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12728 if (SubExpr->isKnownToHaveBooleanValue()) return;
12729
12730 // Emit warning.
12731 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12732 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12733 << Loc << IsBitwiseOp;
12734
12735 // First note suggest !(x < y)
12736 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12737 SourceLocation FirstClose = RHS.get()->getEndLoc();
12738 FirstClose = S.getLocForEndOfToken(FirstClose);
12739 if (FirstClose.isInvalid())
12740 FirstOpen = SourceLocation();
12741 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12742 << IsBitwiseOp
12743 << FixItHint::CreateInsertion(FirstOpen, "(")
12744 << FixItHint::CreateInsertion(FirstClose, ")");
12745
12746 // Second note suggests (!x) < y
12747 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12748 SourceLocation SecondClose = LHS.get()->getEndLoc();
12749 SecondClose = S.getLocForEndOfToken(SecondClose);
12750 if (SecondClose.isInvalid())
12751 SecondOpen = SourceLocation();
12752 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12753 << FixItHint::CreateInsertion(SecondOpen, "(")
12754 << FixItHint::CreateInsertion(SecondClose, ")");
12755}
12756
12757// Returns true if E refers to a non-weak array.
12758static bool checkForArray(const Expr *E) {
12759 const ValueDecl *D = nullptr;
12760 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12761 D = DR->getDecl();
12762 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12763 if (Mem->isImplicitAccess())
12764 D = Mem->getMemberDecl();
12765 }
12766 if (!D)
12767 return false;
12768 return D->getType()->isArrayType() && !D->isWeak();
12769}
12770
12771/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12772/// pointer and size is an unsigned integer. Return whether the result is
12773/// always true/false.
12774static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12775 const Expr *RHS,
12776 BinaryOperatorKind Opc) {
12777 if (!LHS->getType()->isPointerType() ||
12778 S.getLangOpts().PointerOverflowDefined)
12779 return std::nullopt;
12780
12781 // Canonicalize to >= or < predicate.
12782 switch (Opc) {
12783 case BO_GE:
12784 case BO_LT:
12785 break;
12786 case BO_GT:
12787 std::swap(LHS, RHS);
12788 Opc = BO_LT;
12789 break;
12790 case BO_LE:
12791 std::swap(LHS, RHS);
12792 Opc = BO_GE;
12793 break;
12794 default:
12795 return std::nullopt;
12796 }
12797
12798 auto *BO = dyn_cast<BinaryOperator>(LHS);
12799 if (!BO || BO->getOpcode() != BO_Add)
12800 return std::nullopt;
12801
12802 Expr *Other;
12803 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12804 Other = BO->getRHS();
12805 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12806 Other = BO->getLHS();
12807 else
12808 return std::nullopt;
12809
12810 if (!Other->getType()->isUnsignedIntegerType())
12811 return std::nullopt;
12812
12813 return Opc == BO_GE;
12814}
12815
12816/// Diagnose some forms of syntactically-obvious tautological comparison.
12818 Expr *LHS, Expr *RHS,
12819 BinaryOperatorKind Opc) {
12820 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12821 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12822
12823 QualType LHSType = LHS->getType();
12824 QualType RHSType = RHS->getType();
12825 if (LHSType->hasFloatingRepresentation() ||
12826 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12828 return;
12829
12830 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12831 // Tautological diagnostics.
12832 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12833 return;
12834
12835 // Comparisons between two array types are ill-formed for operator<=>, so
12836 // we shouldn't emit any additional warnings about it.
12837 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12838 return;
12839
12840 // For non-floating point types, check for self-comparisons of the form
12841 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12842 // often indicate logic errors in the program.
12843 //
12844 // NOTE: Don't warn about comparison expressions resulting from macro
12845 // expansion. Also don't warn about comparisons which are only self
12846 // comparisons within a template instantiation. The warnings should catch
12847 // obvious cases in the definition of the template anyways. The idea is to
12848 // warn when the typed comparison operator will always evaluate to the same
12849 // result.
12850
12851 // Used for indexing into %select in warn_comparison_always
12852 enum {
12853 AlwaysConstant,
12854 AlwaysTrue,
12855 AlwaysFalse,
12856 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12857 };
12858
12859 // C++1a [array.comp]:
12860 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12861 // operands of array type.
12862 // C++2a [depr.array.comp]:
12863 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12864 // operands of array type are deprecated.
12865 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12866 RHSStripped->getType()->isArrayType()) {
12867 auto IsDeprArrayComparionIgnored =
12868 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12869 auto DiagID = S.getLangOpts().CPlusPlus26
12870 ? diag::warn_array_comparison_cxx26
12871 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12872 ? diag::warn_array_comparison
12873 : diag::warn_depr_array_comparison;
12874 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12875 << LHSStripped->getType() << RHSStripped->getType();
12876 // Carry on to produce the tautological comparison warning, if this
12877 // expression is potentially-evaluated, we can resolve the array to a
12878 // non-weak declaration, and so on.
12879 }
12880
12881 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12882 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12883 unsigned Result;
12884 switch (Opc) {
12885 case BO_EQ:
12886 case BO_LE:
12887 case BO_GE:
12888 Result = AlwaysTrue;
12889 break;
12890 case BO_NE:
12891 case BO_LT:
12892 case BO_GT:
12893 Result = AlwaysFalse;
12894 break;
12895 case BO_Cmp:
12896 Result = AlwaysEqual;
12897 break;
12898 default:
12899 Result = AlwaysConstant;
12900 break;
12901 }
12902 S.DiagRuntimeBehavior(Loc, nullptr,
12903 S.PDiag(diag::warn_comparison_always)
12904 << 0 /*self-comparison*/
12905 << Result);
12906 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12907 // What is it always going to evaluate to?
12908 unsigned Result;
12909 switch (Opc) {
12910 case BO_EQ: // e.g. array1 == array2
12911 Result = AlwaysFalse;
12912 break;
12913 case BO_NE: // e.g. array1 != array2
12914 Result = AlwaysTrue;
12915 break;
12916 default: // e.g. array1 <= array2
12917 // The best we can say is 'a constant'
12918 Result = AlwaysConstant;
12919 break;
12920 }
12921 S.DiagRuntimeBehavior(Loc, nullptr,
12922 S.PDiag(diag::warn_comparison_always)
12923 << 1 /*array comparison*/
12924 << Result);
12925 } else if (std::optional<bool> Res =
12926 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12927 S.DiagRuntimeBehavior(Loc, nullptr,
12928 S.PDiag(diag::warn_comparison_always)
12929 << 2 /*pointer comparison*/
12930 << (*Res ? AlwaysTrue : AlwaysFalse));
12931 }
12932 }
12933
12934 if (isa<CastExpr>(LHSStripped))
12935 LHSStripped = LHSStripped->IgnoreParenCasts();
12936 if (isa<CastExpr>(RHSStripped))
12937 RHSStripped = RHSStripped->IgnoreParenCasts();
12938
12939 // Warn about comparisons against a string constant (unless the other
12940 // operand is null); the user probably wants string comparison function.
12941 Expr *LiteralString = nullptr;
12942 Expr *LiteralStringStripped = nullptr;
12943 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12944 !RHSStripped->isNullPointerConstant(S.Context,
12946 LiteralString = LHS;
12947 LiteralStringStripped = LHSStripped;
12948 } else if ((isa<StringLiteral>(RHSStripped) ||
12949 isa<ObjCEncodeExpr>(RHSStripped)) &&
12950 !LHSStripped->isNullPointerConstant(S.Context,
12952 LiteralString = RHS;
12953 LiteralStringStripped = RHSStripped;
12954 }
12955
12956 if (LiteralString) {
12957 S.DiagRuntimeBehavior(Loc, nullptr,
12958 S.PDiag(diag::warn_stringcompare)
12959 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12960 << LiteralString->getSourceRange());
12961 }
12962}
12963
12965 switch (CK) {
12966 default: {
12967#ifndef NDEBUG
12968 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12969 << "\n";
12970#endif
12971 llvm_unreachable("unhandled cast kind");
12972 }
12973 case CK_UserDefinedConversion:
12974 return ICK_Identity;
12975 case CK_LValueToRValue:
12976 return ICK_Lvalue_To_Rvalue;
12977 case CK_ArrayToPointerDecay:
12978 return ICK_Array_To_Pointer;
12979 case CK_FunctionToPointerDecay:
12981 case CK_IntegralCast:
12983 case CK_FloatingCast:
12985 case CK_IntegralToFloating:
12986 case CK_FloatingToIntegral:
12987 return ICK_Floating_Integral;
12988 case CK_IntegralComplexCast:
12989 case CK_FloatingComplexCast:
12990 case CK_FloatingComplexToIntegralComplex:
12991 case CK_IntegralComplexToFloatingComplex:
12993 case CK_FloatingComplexToReal:
12994 case CK_FloatingRealToComplex:
12995 case CK_IntegralComplexToReal:
12996 case CK_IntegralRealToComplex:
12997 return ICK_Complex_Real;
12998 case CK_HLSLArrayRValue:
12999 return ICK_HLSL_Array_RValue;
13000 }
13001}
13002
13004 QualType FromType,
13005 SourceLocation Loc) {
13006 // Check for a narrowing implicit conversion.
13009 SCS.setToType(0, FromType);
13010 SCS.setToType(1, ToType);
13011 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
13012 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
13013
13014 APValue PreNarrowingValue;
13015 QualType PreNarrowingType;
13016 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
13017 PreNarrowingType,
13018 /*IgnoreFloatToIntegralConversion*/ true)) {
13020 // Implicit conversion to a narrower type, but the expression is
13021 // value-dependent so we can't tell whether it's actually narrowing.
13022 case NK_Not_Narrowing:
13023 return false;
13024
13026 // Implicit conversion to a narrower type, and the value is not a constant
13027 // expression.
13028 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
13029 << /*Constant*/ 1
13030 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
13031 return true;
13032
13034 // Implicit conversion to a narrower type, and the value is not a constant
13035 // expression.
13036 case NK_Type_Narrowing:
13037 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
13038 << /*Constant*/ 0 << FromType << ToType;
13039 // TODO: It's not a constant expression, but what if the user intended it
13040 // to be? Can we produce notes to help them figure out why it isn't?
13041 return true;
13042 }
13043 llvm_unreachable("unhandled case in switch");
13044}
13045
13047 ExprResult &LHS,
13048 ExprResult &RHS,
13049 SourceLocation Loc) {
13050 QualType LHSType = LHS.get()->getType();
13051 QualType RHSType = RHS.get()->getType();
13052 // Dig out the original argument type and expression before implicit casts
13053 // were applied. These are the types/expressions we need to check the
13054 // [expr.spaceship] requirements against.
13055 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
13056 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
13057 QualType LHSStrippedType = LHSStripped.get()->getType();
13058 QualType RHSStrippedType = RHSStripped.get()->getType();
13059
13060 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
13061 // other is not, the program is ill-formed.
13062 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
13063 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
13064 return QualType();
13065 }
13066
13067 // FIXME: Consider combining this with checkEnumArithmeticConversions.
13068 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
13069 RHSStrippedType->isEnumeralType();
13070 if (NumEnumArgs == 1) {
13071 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
13072 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
13073 if (OtherTy->hasFloatingRepresentation()) {
13074 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
13075 return QualType();
13076 }
13077 }
13078 if (NumEnumArgs == 2) {
13079 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
13080 // type E, the operator yields the result of converting the operands
13081 // to the underlying type of E and applying <=> to the converted operands.
13082 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
13083 S.InvalidOperands(Loc, LHS, RHS);
13084 return QualType();
13085 }
13086 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
13087 assert(IntType->isArithmeticType());
13088
13089 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
13090 // promote the boolean type, and all other promotable integer types, to
13091 // avoid this.
13092 if (S.Context.isPromotableIntegerType(IntType))
13093 IntType = S.Context.getPromotedIntegerType(IntType);
13094
13095 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
13096 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
13097 LHSType = RHSType = IntType;
13098 }
13099
13100 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
13101 // usual arithmetic conversions are applied to the operands.
13102 QualType Type =
13104 if (LHS.isInvalid() || RHS.isInvalid())
13105 return QualType();
13106 if (Type.isNull()) {
13107 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13108 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
13109 return ResultTy;
13110 }
13111
13112 std::optional<ComparisonCategoryType> CCT =
13114 if (!CCT)
13115 return S.InvalidOperands(Loc, LHS, RHS);
13116
13117 bool HasNarrowing = checkThreeWayNarrowingConversion(
13118 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
13119 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
13120 RHS.get()->getBeginLoc());
13121 if (HasNarrowing)
13122 return QualType();
13123
13124 assert(!Type.isNull() && "composite type for <=> has not been set");
13125
13128}
13129
13131 ExprResult &RHS,
13132 SourceLocation Loc,
13133 BinaryOperatorKind Opc) {
13134 if (Opc == BO_Cmp)
13135 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
13136
13137 // C99 6.5.8p3 / C99 6.5.9p4
13138 QualType Type =
13140 if (LHS.isInvalid() || RHS.isInvalid())
13141 return QualType();
13142 if (Type.isNull()) {
13143 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13144 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
13145 return ResultTy;
13146 }
13147 assert(Type->isArithmeticType() || Type->isEnumeralType());
13148
13150 return S.InvalidOperands(Loc, LHS, RHS);
13151
13152 // Check for comparisons of floating point operands using != and ==.
13154 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13155
13156 // The result of comparisons is 'bool' in C++, 'int' in C.
13158}
13159
13161 if (!NullE.get()->getType()->isAnyPointerType())
13162 return;
13163 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
13164 if (!E.get()->getType()->isAnyPointerType() &&
13168 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
13169 if (CL->getValue() == 0)
13170 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13171 << NullValue
13173 NullValue ? "NULL" : "(void *)0");
13174 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
13175 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
13176 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
13177 if (T == Context.CharTy)
13178 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13179 << NullValue
13181 NullValue ? "NULL" : "(void *)0");
13182 }
13183 }
13184}
13185
13186// C99 6.5.8, C++ [expr.rel]
13188 SourceLocation Loc,
13189 BinaryOperatorKind Opc) {
13190 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
13191 bool IsThreeWay = Opc == BO_Cmp;
13192 bool IsOrdered = IsRelational || IsThreeWay;
13193 auto IsAnyPointerType = [](ExprResult E) {
13194 QualType Ty = E.get()->getType();
13195 return Ty->isPointerType() || Ty->isMemberPointerType();
13196 };
13197
13198 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
13199 // type, array-to-pointer, ..., conversions are performed on both operands to
13200 // bring them to their composite type.
13201 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
13202 // any type-related checks.
13203 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
13205 if (LHS.isInvalid())
13206 return QualType();
13208 if (RHS.isInvalid())
13209 return QualType();
13210 } else {
13211 LHS = DefaultLvalueConversion(LHS.get());
13212 if (LHS.isInvalid())
13213 return QualType();
13214 RHS = DefaultLvalueConversion(RHS.get());
13215 if (RHS.isInvalid())
13216 return QualType();
13217 }
13218
13219 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
13223 }
13224
13225 if (getLangOpts().HLSL && (LHS.get()->getType()->isConstantMatrixType() ||
13226 RHS.get()->getType()->isConstantMatrixType()))
13227 return CheckMatrixCompareOperands(LHS, RHS, Loc, Opc);
13228
13229 // Handle vector comparisons separately.
13230 if (LHS.get()->getType()->isVectorType() ||
13231 RHS.get()->getType()->isVectorType())
13232 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
13233
13234 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13235 RHS.get()->getType()->isSveVLSBuiltinType())
13236 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
13237
13238 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13239 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13240
13241 QualType LHSType = LHS.get()->getType();
13242 QualType RHSType = RHS.get()->getType();
13243 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
13244 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13245 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
13246
13247 if ((LHSType->isPointerType() &&
13249 (RHSType->isPointerType() &&
13251 return InvalidOperands(Loc, LHS, RHS);
13252
13253 const Expr::NullPointerConstantKind LHSNullKind =
13255 const Expr::NullPointerConstantKind RHSNullKind =
13257 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13258 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13259
13260 auto computeResultTy = [&]() {
13261 if (Opc != BO_Cmp)
13262 return QualType(Context.getLogicalOperationType());
13263 assert(getLangOpts().CPlusPlus);
13264 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13265
13266 QualType CompositeTy = LHS.get()->getType();
13267 assert(!CompositeTy->isReferenceType());
13268
13269 std::optional<ComparisonCategoryType> CCT =
13271 if (!CCT)
13272 return InvalidOperands(Loc, LHS, RHS);
13273
13274 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13275 // P0946R0: Comparisons between a null pointer constant and an object
13276 // pointer result in std::strong_equality, which is ill-formed under
13277 // P1959R0.
13278 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13279 << (LHSIsNull ? LHS.get()->getSourceRange()
13280 : RHS.get()->getSourceRange());
13281 return QualType();
13282 }
13283
13286 };
13287
13288 if (LHSType->isMetaInfoType() && RHSType->isMetaInfoType()) {
13289 if (!BinaryOperator::isEqualityOp(Opc)) {
13290 return InvalidOperands(Loc, LHS, RHS);
13291 }
13292 return computeResultTy();
13293 }
13294
13295 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13296 bool IsEquality = Opc == BO_EQ;
13297 if (RHSIsNull)
13298 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
13299 RHS.get()->getSourceRange());
13300 else
13301 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
13302 LHS.get()->getSourceRange());
13303 }
13304
13305 if (IsOrdered && LHSType->isFunctionPointerType() &&
13306 RHSType->isFunctionPointerType()) {
13307 // Valid unless a relational comparison of function pointers
13308 bool IsError = Opc == BO_Cmp;
13309 auto DiagID =
13310 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13311 : getLangOpts().CPlusPlus
13312 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13313 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13314 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13315 << RHS.get()->getSourceRange();
13316 if (IsError)
13317 return QualType();
13318 }
13319
13320 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13321 (RHSType->isIntegerType() && !RHSIsNull)) {
13322 // Skip normal pointer conversion checks in this case; we have better
13323 // diagnostics for this below.
13324 } else if (getLangOpts().CPlusPlus) {
13325 // Equality comparison of a function pointer to a void pointer is invalid,
13326 // but we allow it as an extension.
13327 // FIXME: If we really want to allow this, should it be part of composite
13328 // pointer type computation so it works in conditionals too?
13329 if (!IsOrdered &&
13330 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13331 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13332 // This is a gcc extension compatibility comparison.
13333 // In a SFINAE context, we treat this as a hard error to maintain
13334 // conformance with the C++ standard.
13335 bool IsError = isSFINAEContext();
13336 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError);
13337
13338 if (IsError)
13339 return QualType();
13340
13341 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13342 return computeResultTy();
13343 }
13344
13345 // C++ [expr.eq]p2:
13346 // If at least one operand is a pointer [...] bring them to their
13347 // composite pointer type.
13348 // C++ [expr.spaceship]p6
13349 // If at least one of the operands is of pointer type, [...] bring them
13350 // to their composite pointer type.
13351 // C++ [expr.rel]p2:
13352 // If both operands are pointers, [...] bring them to their composite
13353 // pointer type.
13354 // For <=>, the only valid non-pointer types are arrays and functions, and
13355 // we already decayed those, so this is really the same as the relational
13356 // comparison rule.
13357 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13358 (IsOrdered ? 2 : 1) &&
13359 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13360 RHSType->isObjCObjectPointerType()))) {
13361 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13362 return QualType();
13363 return computeResultTy();
13364 }
13365 } else if (LHSType->isPointerType() &&
13366 RHSType->isPointerType()) { // C99 6.5.8p2
13367 // All of the following pointer-related warnings are GCC extensions, except
13368 // when handling null pointer constants.
13369 QualType LCanPointeeTy =
13371 QualType RCanPointeeTy =
13373
13374 // C99 6.5.9p2 and C99 6.5.8p2
13375 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
13376 RCanPointeeTy.getUnqualifiedType())) {
13377 if (IsRelational) {
13378 // Pointers both need to point to complete or incomplete types
13379 if ((LCanPointeeTy->isIncompleteType() !=
13380 RCanPointeeTy->isIncompleteType()) &&
13381 !getLangOpts().C11) {
13382 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13383 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13384 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13385 << RCanPointeeTy->isIncompleteType();
13386 }
13387 }
13388 } else if (!IsRelational &&
13389 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13390 // Valid unless comparison between non-null pointer and function pointer
13391 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13392 && !LHSIsNull && !RHSIsNull)
13393 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13394 /*isError*/false);
13395 } else {
13396 // Invalid
13397 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13398 }
13399 if (LCanPointeeTy != RCanPointeeTy) {
13400 // Treat NULL constant as a special case in OpenCL.
13401 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13402 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
13403 getASTContext())) {
13404 Diag(Loc,
13405 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13406 << LHSType << RHSType << 0 /* comparison */
13407 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13408 }
13409 }
13410 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13411 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13412 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13413 : CK_BitCast;
13414
13415 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13416 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13417 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13418 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13419 bool ChangingCFIUncheckedCallee =
13420 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13421
13422 if (LHSIsNull && !RHSIsNull)
13423 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13424 else if (!ChangingCFIUncheckedCallee)
13425 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13426 }
13427 return computeResultTy();
13428 }
13429
13430
13431 // C++ [expr.eq]p4:
13432 // Two operands of type std::nullptr_t or one operand of type
13433 // std::nullptr_t and the other a null pointer constant compare
13434 // equal.
13435 // C23 6.5.9p5:
13436 // If both operands have type nullptr_t or one operand has type nullptr_t
13437 // and the other is a null pointer constant, they compare equal if the
13438 // former is a null pointer.
13439 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13440 if (LHSType->isNullPtrType()) {
13441 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13442 return computeResultTy();
13443 }
13444 if (RHSType->isNullPtrType()) {
13445 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13446 return computeResultTy();
13447 }
13448 }
13449
13450 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13451 // C23 6.5.9p6:
13452 // Otherwise, at least one operand is a pointer. If one is a pointer and
13453 // the other is a null pointer constant or has type nullptr_t, they
13454 // compare equal
13455 if (LHSIsNull && RHSType->isPointerType()) {
13456 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13457 return computeResultTy();
13458 }
13459 if (RHSIsNull && LHSType->isPointerType()) {
13460 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13461 return computeResultTy();
13462 }
13463 }
13464
13465 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13466 // These aren't covered by the composite pointer type rules.
13467 if (!IsOrdered && RHSType->isNullPtrType() &&
13468 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13469 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13470 return computeResultTy();
13471 }
13472 if (!IsOrdered && LHSType->isNullPtrType() &&
13473 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13474 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13475 return computeResultTy();
13476 }
13477
13478 if (getLangOpts().CPlusPlus) {
13479 if (IsRelational &&
13480 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13481 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13482 // HACK: Relational comparison of nullptr_t against a pointer type is
13483 // invalid per DR583, but we allow it within std::less<> and friends,
13484 // since otherwise common uses of it break.
13485 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13486 // friends to have std::nullptr_t overload candidates.
13487 DeclContext *DC = CurContext;
13488 if (isa<FunctionDecl>(DC))
13489 DC = DC->getParent();
13490 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13491 if (CTSD->isInStdNamespace() &&
13492 llvm::StringSwitch<bool>(CTSD->getName())
13493 .Cases({"less", "less_equal", "greater", "greater_equal"}, true)
13494 .Default(false)) {
13495 if (RHSType->isNullPtrType())
13496 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13497 else
13498 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13499 return computeResultTy();
13500 }
13501 }
13502 }
13503
13504 // C++ [expr.eq]p2:
13505 // If at least one operand is a pointer to member, [...] bring them to
13506 // their composite pointer type.
13507 if (!IsOrdered &&
13508 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13509 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13510 return QualType();
13511 else
13512 return computeResultTy();
13513 }
13514 }
13515
13516 // Handle block pointer types.
13517 if (!IsOrdered && LHSType->isBlockPointerType() &&
13518 RHSType->isBlockPointerType()) {
13519 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13520 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13521
13522 if (!LHSIsNull && !RHSIsNull &&
13523 !Context.typesAreCompatible(lpointee, rpointee)) {
13524 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13525 << LHSType << RHSType << LHS.get()->getSourceRange()
13526 << RHS.get()->getSourceRange();
13527 }
13528 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13529 return computeResultTy();
13530 }
13531
13532 // Allow block pointers to be compared with null pointer constants.
13533 if (!IsOrdered
13534 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13535 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13536 if (!LHSIsNull && !RHSIsNull) {
13537 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13539 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13540 ->getPointeeType()->isVoidType())))
13541 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13542 << LHSType << RHSType << LHS.get()->getSourceRange()
13543 << RHS.get()->getSourceRange();
13544 }
13545 if (LHSIsNull && !RHSIsNull)
13546 LHS = ImpCastExprToType(LHS.get(), RHSType,
13547 RHSType->isPointerType() ? CK_BitCast
13548 : CK_AnyPointerToBlockPointerCast);
13549 else
13550 RHS = ImpCastExprToType(RHS.get(), LHSType,
13551 LHSType->isPointerType() ? CK_BitCast
13552 : CK_AnyPointerToBlockPointerCast);
13553 return computeResultTy();
13554 }
13555
13556 if (LHSType->isObjCObjectPointerType() ||
13557 RHSType->isObjCObjectPointerType()) {
13558 const PointerType *LPT = LHSType->getAs<PointerType>();
13559 const PointerType *RPT = RHSType->getAs<PointerType>();
13560 if (LPT || RPT) {
13561 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13562 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13563
13564 if (!LPtrToVoid && !RPtrToVoid &&
13565 !Context.typesAreCompatible(LHSType, RHSType)) {
13566 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13567 /*isError*/false);
13568 }
13569 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13570 // the RHS, but we have test coverage for this behavior.
13571 // FIXME: Consider using convertPointersToCompositeType in C++.
13572 if (LHSIsNull && !RHSIsNull) {
13573 Expr *E = LHS.get();
13574 if (getLangOpts().ObjCAutoRefCount)
13575 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
13577 LHS = ImpCastExprToType(E, RHSType,
13578 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13579 }
13580 else {
13581 Expr *E = RHS.get();
13582 if (getLangOpts().ObjCAutoRefCount)
13583 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
13585 /*Diagnose=*/true,
13586 /*DiagnoseCFAudited=*/false, Opc);
13587 RHS = ImpCastExprToType(E, LHSType,
13588 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13589 }
13590 return computeResultTy();
13591 }
13592 if (LHSType->isObjCObjectPointerType() &&
13593 RHSType->isObjCObjectPointerType()) {
13594 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13595 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13596 /*isError*/false);
13598 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13599
13600 if (LHSIsNull && !RHSIsNull)
13601 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13602 else
13603 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13604 return computeResultTy();
13605 }
13606
13607 if (!IsOrdered && LHSType->isBlockPointerType() &&
13609 LHS = ImpCastExprToType(LHS.get(), RHSType,
13610 CK_BlockPointerToObjCPointerCast);
13611 return computeResultTy();
13612 } else if (!IsOrdered &&
13614 RHSType->isBlockPointerType()) {
13615 RHS = ImpCastExprToType(RHS.get(), LHSType,
13616 CK_BlockPointerToObjCPointerCast);
13617 return computeResultTy();
13618 }
13619 }
13620 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13621 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13622 unsigned DiagID = 0;
13623 bool isError = false;
13624 if (LangOpts.DebuggerSupport) {
13625 // Under a debugger, allow the comparison of pointers to integers,
13626 // since users tend to want to compare addresses.
13627 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13628 (RHSIsNull && RHSType->isIntegerType())) {
13629 if (IsOrdered) {
13630 isError = getLangOpts().CPlusPlus;
13631 DiagID =
13632 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13633 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13634 }
13635 } else if (getLangOpts().CPlusPlus) {
13636 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13637 isError = true;
13638 } else if (IsOrdered)
13639 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13640 else
13641 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13642
13643 if (DiagID) {
13644 Diag(Loc, DiagID)
13645 << LHSType << RHSType << LHS.get()->getSourceRange()
13646 << RHS.get()->getSourceRange();
13647 if (isError)
13648 return QualType();
13649 }
13650
13651 if (LHSType->isIntegerType())
13652 LHS = ImpCastExprToType(LHS.get(), RHSType,
13653 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13654 else
13655 RHS = ImpCastExprToType(RHS.get(), LHSType,
13656 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13657 return computeResultTy();
13658 }
13659
13660 // Handle block pointers.
13661 if (!IsOrdered && RHSIsNull
13662 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13663 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13664 return computeResultTy();
13665 }
13666 if (!IsOrdered && LHSIsNull
13667 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13668 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13669 return computeResultTy();
13670 }
13671
13672 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13673 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13674 return computeResultTy();
13675 }
13676
13677 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13678 return computeResultTy();
13679 }
13680
13681 if (LHSIsNull && RHSType->isQueueT()) {
13682 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13683 return computeResultTy();
13684 }
13685
13686 if (LHSType->isQueueT() && RHSIsNull) {
13687 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13688 return computeResultTy();
13689 }
13690 }
13691
13692 return InvalidOperands(Loc, LHS, RHS);
13693}
13694
13696 const VectorType *VTy = V->castAs<VectorType>();
13697 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13698
13699 if (isa<ExtVectorType>(VTy)) {
13700 if (VTy->isExtVectorBoolType())
13701 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13702 if (TypeSize == Context.getTypeSize(Context.CharTy))
13703 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13704 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13705 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13706 if (TypeSize == Context.getTypeSize(Context.IntTy))
13707 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13708 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13709 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13710 if (TypeSize == Context.getTypeSize(Context.LongTy))
13711 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13712 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13713 return Context.getExtVectorType(Context.LongLongTy,
13714 VTy->getNumElements());
13715 const auto *BIT = VTy->getElementType()->castAs<BitIntType>();
13716 return Context.getExtVectorType(
13717 Context.getBitIntType(/*IsUnsigned=*/false, BIT->getNumBits()),
13718 VTy->getNumElements());
13719 }
13720
13721 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13722 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13724 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13725 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13727 if (TypeSize == Context.getTypeSize(Context.LongTy))
13728 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13730 if (TypeSize == Context.getTypeSize(Context.IntTy))
13731 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13733 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13734 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13736 if (TypeSize == Context.getTypeSize(Context.CharTy))
13737 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13739 const auto *BIT = VTy->getElementType()->castAs<BitIntType>();
13740 return Context.getVectorType(
13741 Context.getBitIntType(/*IsUnsigned=*/false, BIT->getNumBits()),
13743}
13744
13746 const BuiltinType *VTy = V->castAs<BuiltinType>();
13747 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13748
13749 const QualType ETy = V->getSveEltType(Context);
13750 const auto TypeSize = Context.getTypeSize(ETy);
13751
13752 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13753 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13754 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13755}
13756
13758 SourceLocation Loc,
13759 BinaryOperatorKind Opc) {
13760 if (Opc == BO_Cmp) {
13761 Diag(Loc, diag::err_three_way_vector_comparison);
13762 return QualType();
13763 }
13764
13765 // Check to make sure we're operating on vectors of the same type and width,
13766 // Allowing one side to be a scalar of element type.
13767 QualType vType =
13768 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13769 /*AllowBothBool*/ true,
13770 /*AllowBoolConversions*/ getLangOpts().ZVector,
13771 /*AllowBooleanOperation*/ true);
13772 if (vType.isNull())
13773 return vType;
13774
13775 QualType LHSType = LHS.get()->getType();
13776
13777 // Determine the return type of a vector compare. By default clang will return
13778 // a scalar for all vector compares except vector bool and vector pixel.
13779 // With the gcc compiler we will always return a vector type and with the xl
13780 // compiler we will always return a scalar type. This switch allows choosing
13781 // which behavior is prefered.
13782 if (getLangOpts().AltiVec) {
13783 switch (getLangOpts().getAltivecSrcCompat()) {
13785 // If AltiVec, the comparison results in a numeric type, i.e.
13786 // bool for C++, int for C
13787 if (vType->castAs<VectorType>()->getVectorKind() ==
13789 return Context.getLogicalOperationType();
13790 else
13791 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13792 break;
13794 // For GCC we always return the vector type.
13795 break;
13797 return Context.getLogicalOperationType();
13798 break;
13799 }
13800 }
13801
13802 // For non-floating point types, check for self-comparisons of the form
13803 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13804 // often indicate logic errors in the program.
13805 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13806
13807 // Check for comparisons of floating point operands using != and ==.
13808 if (LHSType->hasFloatingRepresentation()) {
13809 assert(RHS.get()->getType()->hasFloatingRepresentation());
13810 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13811 }
13812
13813 // Return a signed type for the vector.
13814 return GetSignedVectorType(vType);
13815}
13816
13818 SourceLocation Loc,
13819 BinaryOperatorKind Opc) {
13820 assert(getLangOpts().HLSL && "matrix comparisons are only supported in HLSL");
13821 assert(Opc != BO_Cmp && "three-way comparisons are not supported in HLSL");
13822
13823 QualType MatrixTy =
13824 CheckMatrixElementwiseOperands(LHS, RHS, Loc, /*IsCompAssign=*/false);
13825 if (MatrixTy.isNull())
13826 return QualType();
13827
13828 if (!LHS.get()->getType()->isMatrixType()) {
13829 LHS = prepareMatrixSplat(MatrixTy, LHS.get());
13830 if (LHS.isInvalid())
13831 return QualType();
13832 LHS = ImpCastExprToType(LHS.get(), MatrixTy, CK_HLSLAggregateSplatCast);
13833 }
13834 if (!RHS.get()->getType()->isMatrixType()) {
13835 RHS = prepareMatrixSplat(MatrixTy, RHS.get());
13836 if (RHS.isInvalid())
13837 return QualType();
13838 RHS = ImpCastExprToType(RHS.get(), MatrixTy, CK_HLSLAggregateSplatCast);
13839 }
13840
13841 const auto *MT = MatrixTy->castAs<ConstantMatrixType>();
13842 return Context.getConstantMatrixType(Context.BoolTy, MT->getNumRows(),
13843 MT->getNumColumns());
13844}
13845
13847 ExprResult &RHS,
13848 SourceLocation Loc,
13849 BinaryOperatorKind Opc) {
13850 if (Opc == BO_Cmp) {
13851 Diag(Loc, diag::err_three_way_vector_comparison);
13852 return QualType();
13853 }
13854
13855 // Check to make sure we're operating on vectors of the same type and width,
13856 // Allowing one side to be a scalar of element type.
13858 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13859
13860 if (vType.isNull())
13861 return vType;
13862
13863 QualType LHSType = LHS.get()->getType();
13864
13865 // For non-floating point types, check for self-comparisons of the form
13866 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13867 // often indicate logic errors in the program.
13868 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13869
13870 // Check for comparisons of floating point operands using != and ==.
13871 if (LHSType->hasFloatingRepresentation()) {
13872 assert(RHS.get()->getType()->hasFloatingRepresentation());
13873 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13874 }
13875
13876 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13877 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13878
13879 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13880 RHSBuiltinTy->isSVEBool())
13881 return LHSType;
13882
13883 // Return a signed type for the vector.
13884 return GetSignedSizelessVectorType(vType);
13885}
13886
13887static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13888 const ExprResult &XorRHS,
13889 const SourceLocation Loc) {
13890 // Do not diagnose macros.
13891 if (Loc.isMacroID())
13892 return;
13893
13894 // Do not diagnose if both LHS and RHS are macros.
13895 if (XorLHS.get()->getExprLoc().isMacroID() &&
13896 XorRHS.get()->getExprLoc().isMacroID())
13897 return;
13898
13899 bool Negative = false;
13900 bool ExplicitPlus = false;
13901 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13902 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13903
13904 if (!LHSInt)
13905 return;
13906 if (!RHSInt) {
13907 // Check negative literals.
13908 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13909 UnaryOperatorKind Opc = UO->getOpcode();
13910 if (Opc != UO_Minus && Opc != UO_Plus)
13911 return;
13912 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13913 if (!RHSInt)
13914 return;
13915 Negative = (Opc == UO_Minus);
13916 ExplicitPlus = !Negative;
13917 } else {
13918 return;
13919 }
13920 }
13921
13922 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13923 llvm::APInt RightSideValue = RHSInt->getValue();
13924 if (LeftSideValue != 2 && LeftSideValue != 10)
13925 return;
13926
13927 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13928 return;
13929
13931 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13932 llvm::StringRef ExprStr =
13934
13935 CharSourceRange XorRange =
13937 llvm::StringRef XorStr =
13939 // Do not diagnose if xor keyword/macro is used.
13940 if (XorStr == "xor")
13941 return;
13942
13943 std::string LHSStr = std::string(Lexer::getSourceText(
13944 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13945 S.getSourceManager(), S.getLangOpts()));
13946 std::string RHSStr = std::string(Lexer::getSourceText(
13947 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13948 S.getSourceManager(), S.getLangOpts()));
13949
13950 if (Negative) {
13951 RightSideValue = -RightSideValue;
13952 RHSStr = "-" + RHSStr;
13953 } else if (ExplicitPlus) {
13954 RHSStr = "+" + RHSStr;
13955 }
13956
13957 StringRef LHSStrRef = LHSStr;
13958 StringRef RHSStrRef = RHSStr;
13959 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13960 // literals.
13961 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13962 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13963 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13964 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13965 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13966 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13967 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13968 return;
13969
13970 bool SuggestXor =
13971 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13972 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13973 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13974 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13975 std::string SuggestedExpr = "1 << " + RHSStr;
13976 bool Overflow = false;
13977 llvm::APInt One = (LeftSideValue - 1);
13978 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13979 if (Overflow) {
13980 if (RightSideIntValue < 64)
13981 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13982 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13983 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13984 else if (RightSideIntValue == 64)
13985 S.Diag(Loc, diag::warn_xor_used_as_pow)
13986 << ExprStr << toString(XorValue, 10, true);
13987 else
13988 return;
13989 } else {
13990 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13991 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13992 << toString(PowValue, 10, true)
13994 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13995 }
13996
13997 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13998 << ("0x2 ^ " + RHSStr) << SuggestXor;
13999 } else if (LeftSideValue == 10) {
14000 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
14001 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
14002 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
14003 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
14004 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
14005 << ("0xA ^ " + RHSStr) << SuggestXor;
14006 }
14007}
14008
14010 SourceLocation Loc,
14011 BinaryOperatorKind Opc) {
14012 // Ensure that either both operands are of the same vector type, or
14013 // one operand is of a vector type and the other is of its element type.
14014 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
14015 /*AllowBothBool*/ true,
14016 /*AllowBoolConversions*/ false,
14017 /*AllowBooleanOperation*/ false);
14018 if (vType.isNull())
14019 return QualType();
14020 if (getLangOpts().OpenCL &&
14021 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
14023 return InvalidOperands(Loc, LHS, RHS);
14024 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
14025 // usage of the logical operators && and || with vectors in C. This
14026 // check could be notionally dropped.
14027 if (!getLangOpts().CPlusPlus &&
14028 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
14029 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
14030 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
14031 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
14032 // `select` functions.
14033 if (getLangOpts().HLSL &&
14034 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
14035 (void)InvalidOperands(Loc, LHS, RHS);
14036 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
14037 return QualType();
14038 }
14039
14040 return GetSignedVectorType(LHS.get()->getType());
14041}
14042
14044 SourceLocation Loc,
14045 BinaryOperatorKind Opc) {
14046
14047 if (!getLangOpts().HLSL) {
14048 SemaRef.Diag(Loc, diag::err_matrix_logical_operations_supported_for_hlsl);
14049 return QualType();
14050 }
14051
14052 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
14053 (void)InvalidOperands(Loc, LHS, RHS);
14054 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
14055 return QualType();
14056 }
14057 SemaRef.Diag(LHS.get()->getBeginLoc(), diag::err_hlsl_langstd_unimplemented)
14058 << getLangOpts().getHLSLVersion();
14059 return QualType();
14060}
14061
14063 SourceLocation Loc,
14064 bool IsCompAssign) {
14065 if (!IsCompAssign) {
14067 if (LHS.isInvalid())
14068 return QualType();
14069 }
14071 if (RHS.isInvalid())
14072 return QualType();
14073
14074 // For conversion purposes, we ignore any qualifiers.
14075 // For example, "const float" and "float" are equivalent.
14076 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
14077 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
14078
14079 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
14080 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
14081 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
14082
14083 if (Context.hasSameType(LHSType, RHSType))
14084 return Context.getCommonSugaredType(LHSType, RHSType);
14085
14086 // Type conversion may change LHS/RHS. Keep copies to the original results, in
14087 // case we have to return InvalidOperands.
14088 ExprResult OriginalLHS = LHS;
14089 ExprResult OriginalRHS = RHS;
14090 if (LHSMatType && !RHSMatType) {
14091 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
14092 if (!RHS.isInvalid())
14093 return LHSType;
14094
14095 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
14096 }
14097
14098 if (!LHSMatType && RHSMatType) {
14099 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
14100 if (!LHS.isInvalid())
14101 return RHSType;
14102 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
14103 }
14104
14105 return InvalidOperands(Loc, LHS, RHS);
14106}
14107
14109 SourceLocation Loc,
14110 bool IsCompAssign) {
14111 if (!IsCompAssign) {
14113 if (LHS.isInvalid())
14114 return QualType();
14115 }
14117 if (RHS.isInvalid())
14118 return QualType();
14119
14120 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
14121 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
14122 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
14123
14124 if (LHSMatType && RHSMatType) {
14125 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
14126 return InvalidOperands(Loc, LHS, RHS);
14127
14128 if (Context.hasSameType(LHSMatType, RHSMatType))
14129 return Context.getCommonSugaredType(
14130 LHS.get()->getType().getUnqualifiedType(),
14131 RHS.get()->getType().getUnqualifiedType());
14132
14133 QualType LHSELTy = LHSMatType->getElementType(),
14134 RHSELTy = RHSMatType->getElementType();
14135 if (!Context.hasSameType(LHSELTy, RHSELTy))
14136 return InvalidOperands(Loc, LHS, RHS);
14137
14138 return Context.getConstantMatrixType(
14139 Context.getCommonSugaredType(LHSELTy, RHSELTy),
14140 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
14141 }
14142 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
14143}
14144
14146 switch (Opc) {
14147 default:
14148 return false;
14149 case BO_And:
14150 case BO_AndAssign:
14151 case BO_Or:
14152 case BO_OrAssign:
14153 case BO_Xor:
14154 case BO_XorAssign:
14155 return true;
14156 }
14157}
14158
14160 SourceLocation Loc,
14161 BinaryOperatorKind Opc) {
14162 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
14163
14164 bool IsCompAssign =
14165 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
14166
14167 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
14168
14169 if (LHS.get()->getType()->isVectorType() ||
14170 RHS.get()->getType()->isVectorType()) {
14171 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14173 return CheckVectorOperands(
14174 LHS, RHS, Loc, IsCompAssign,
14175 /*AllowBothBool*/ true,
14176 /*AllowBoolConversions*/ getLangOpts().ZVector,
14177 /*AllowBooleanOperation*/ LegalBoolVecOperator);
14178 return InvalidOperands(Loc, LHS, RHS);
14179 }
14180
14181 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14182 RHS.get()->getType()->isSveVLSBuiltinType()) {
14183 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14185 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14187 return InvalidOperands(Loc, LHS, RHS);
14188 }
14189
14190 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14191 RHS.get()->getType()->isSveVLSBuiltinType()) {
14192 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14194 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14196 return InvalidOperands(Loc, LHS, RHS);
14197 }
14198
14199 if (Opc == BO_And)
14200 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
14201
14202 if (LHS.get()->getType()->hasFloatingRepresentation() ||
14204 return InvalidOperands(Loc, LHS, RHS);
14205
14206 ExprResult LHSResult = LHS, RHSResult = RHS;
14208 LHSResult, RHSResult, Loc,
14210 if (LHSResult.isInvalid() || RHSResult.isInvalid())
14211 return QualType();
14212 LHS = LHSResult.get();
14213 RHS = RHSResult.get();
14214
14215 if (Opc == BO_Xor)
14216 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
14217
14218 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
14219 return compType;
14220 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14221 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14222 return ResultTy;
14223}
14224
14225// C99 6.5.[13,14]
14227 SourceLocation Loc,
14228 BinaryOperatorKind Opc) {
14229 // Check vector operands differently.
14230 if (LHS.get()->getType()->isVectorType() ||
14231 RHS.get()->getType()->isVectorType())
14232 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
14233
14234 if (LHS.get()->getType()->isConstantMatrixType() ||
14235 RHS.get()->getType()->isConstantMatrixType())
14236 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
14237
14238 bool EnumConstantInBoolContext = false;
14239 for (const ExprResult &HS : {LHS, RHS}) {
14240 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
14241 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
14242 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
14243 EnumConstantInBoolContext = true;
14244 }
14245 }
14246
14247 if (EnumConstantInBoolContext)
14248 Diag(Loc, diag::warn_enum_constant_in_bool_context);
14249
14250 // WebAssembly tables can't be used with logical operators.
14251 QualType LHSTy = LHS.get()->getType();
14252 QualType RHSTy = RHS.get()->getType();
14253 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
14254 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
14255 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
14256 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
14257 return InvalidOperands(Loc, LHS, RHS);
14258 }
14259
14260 // Diagnose cases where the user write a logical and/or but probably meant a
14261 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
14262 // is a constant.
14263 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
14264 !LHS.get()->getType()->isBooleanType() &&
14265 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
14266 // Don't warn in macros or template instantiations.
14267 !Loc.isMacroID() && !inTemplateInstantiation()) {
14268 // If the RHS can be constant folded, and if it constant folds to something
14269 // that isn't 0 or 1 (which indicate a potential logical operation that
14270 // happened to fold to true/false) then warn.
14271 // Parens on the RHS are ignored.
14272 Expr::EvalResult EVResult;
14273 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
14274 llvm::APSInt Result = EVResult.Val.getInt();
14275 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
14276 !RHS.get()->getExprLoc().isMacroID()) ||
14277 (Result != 0 && Result != 1)) {
14278 Diag(Loc, diag::warn_logical_instead_of_bitwise)
14279 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
14280 // Suggest replacing the logical operator with the bitwise version
14281 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
14282 << (Opc == BO_LAnd ? "&" : "|")
14285 Opc == BO_LAnd ? "&" : "|");
14286 if (Opc == BO_LAnd)
14287 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14288 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
14291 RHS.get()->getEndLoc()));
14292 }
14293 }
14294 }
14295
14296 if (!Context.getLangOpts().CPlusPlus) {
14297 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14298 // not operate on the built-in scalar and vector float types.
14299 if (Context.getLangOpts().OpenCL &&
14300 Context.getLangOpts().OpenCLVersion < 120) {
14301 if (LHS.get()->getType()->isFloatingType() ||
14302 RHS.get()->getType()->isFloatingType())
14303 return InvalidOperands(Loc, LHS, RHS);
14304 }
14305
14306 LHS = UsualUnaryConversions(LHS.get());
14307 if (LHS.isInvalid())
14308 return QualType();
14309
14310 RHS = UsualUnaryConversions(RHS.get());
14311 if (RHS.isInvalid())
14312 return QualType();
14313
14314 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14316 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14318
14319 if (!LHS.get()->getType()->isScalarType() ||
14320 !RHS.get()->getType()->isScalarType())
14321 return InvalidOperands(Loc, LHS, RHS);
14322
14323 return Context.IntTy;
14324 }
14325
14326 // The following is safe because we only use this method for
14327 // non-overloadable operands.
14328
14329 // C++ [expr.log.and]p1
14330 // C++ [expr.log.or]p1
14331 // The operands are both contextually converted to type bool.
14333 if (LHSRes.isInvalid()) {
14334 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14335 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14336 return ResultTy;
14337 }
14338 LHS = LHSRes;
14339
14341 if (RHSRes.isInvalid()) {
14342 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14343 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14344 return ResultTy;
14345 }
14346 RHS = RHSRes;
14347
14348 // C++ [expr.log.and]p2
14349 // C++ [expr.log.or]p2
14350 // The result is a bool.
14351 return Context.BoolTy;
14352}
14353
14354static bool IsReadonlyMessage(Expr *E, Sema &S) {
14355 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14356 if (!ME) return false;
14357 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
14358 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14360 if (!Base) return false;
14361 return Base->getMethodDecl() != nullptr;
14362}
14363
14364/// Is the given expression (which must be 'const') a reference to a
14365/// variable which was originally non-const, but which has become
14366/// 'const' due to being captured within a block?
14369 assert(E->isLValue() && E->getType().isConstQualified());
14370 E = E->IgnoreParens();
14371
14372 // Must be a reference to a declaration from an enclosing scope.
14373 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14374 if (!DRE) return NCCK_None;
14376
14377 ValueDecl *Value = DRE->getDecl();
14378
14379 // The declaration must be a value which is not declared 'const'.
14381 return NCCK_None;
14382
14383 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
14384 if (Binding) {
14385 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14386 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14387 return NCCK_Lambda;
14388 }
14389
14390 VarDecl *Var = dyn_cast<VarDecl>(Value);
14391 if (!Var)
14392 return NCCK_None;
14393 if (Var->getType()->isReferenceType())
14394 return NCCK_None;
14395
14396 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14397
14398 // Decide whether the first capture was for a block or a lambda.
14399 DeclContext *DC = S.CurContext, *Prev = nullptr;
14400 // Decide whether the first capture was for a block or a lambda.
14401 while (DC) {
14402 // For init-capture, it is possible that the variable belongs to the
14403 // template pattern of the current context.
14404 if (auto *FD = dyn_cast<FunctionDecl>(DC))
14405 if (Var->isInitCapture() &&
14406 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14407 break;
14408 if (DC == Var->getDeclContext())
14409 break;
14410 Prev = DC;
14411 DC = DC->getParent();
14412 }
14413 // Unless we have an init-capture, we've gone one step too far.
14414 if (!Var->isInitCapture())
14415 DC = Prev;
14416 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
14417}
14418
14419static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14420 Ty = Ty.getNonReferenceType();
14421 if (IsDereference && Ty->isPointerType())
14422 Ty = Ty->getPointeeType();
14423 return !Ty.isConstQualified();
14424}
14425
14426// Update err_typecheck_assign_const and note_typecheck_assign_const
14427// when this enum is changed.
14428enum {
14433 ConstUnknown, // Keep as last element
14434};
14435
14436/// Emit the "read-only variable not assignable" error and print notes to give
14437/// more information about why the variable is not assignable, such as pointing
14438/// to the declaration of a const variable, showing that a method is const, or
14439/// that the function is returning a const reference.
14440static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14441 SourceLocation Loc) {
14442 SourceRange ExprRange = E->getSourceRange();
14443
14444 // Only emit one error on the first const found. All other consts will emit
14445 // a note to the error.
14446 bool DiagnosticEmitted = false;
14447
14448 // Track if the current expression is the result of a dereference, and if the
14449 // next checked expression is the result of a dereference.
14450 bool IsDereference = false;
14451 bool NextIsDereference = false;
14452
14453 // Loop to process MemberExpr chains.
14454 while (true) {
14455 IsDereference = NextIsDereference;
14456
14458 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14459 NextIsDereference = ME->isArrow();
14460 const ValueDecl *VD = ME->getMemberDecl();
14461 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14462 // Mutable fields can be modified even if the class is const.
14463 if (Field->isMutable()) {
14464 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14465 break;
14466 }
14467
14468 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14469 if (!DiagnosticEmitted) {
14470 S.Diag(Loc, diag::err_typecheck_assign_const)
14471 << ExprRange << ConstMember << false /*static*/ << Field
14472 << Field->getType();
14473 DiagnosticEmitted = true;
14474 }
14475 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14476 << ConstMember << false /*static*/ << Field << Field->getType()
14477 << Field->getSourceRange();
14478 }
14479 E = ME->getBase();
14480 continue;
14481 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14482 if (VDecl->getType().isConstQualified()) {
14483 if (!DiagnosticEmitted) {
14484 S.Diag(Loc, diag::err_typecheck_assign_const)
14485 << ExprRange << ConstMember << true /*static*/ << VDecl
14486 << VDecl->getType();
14487 DiagnosticEmitted = true;
14488 }
14489 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14490 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14491 << VDecl->getSourceRange();
14492 }
14493 // Static fields do not inherit constness from parents.
14494 break;
14495 }
14496 break; // End MemberExpr
14497 } else if (const ArraySubscriptExpr *ASE =
14498 dyn_cast<ArraySubscriptExpr>(E)) {
14499 E = ASE->getBase()->IgnoreParenImpCasts();
14500 continue;
14501 } else if (const ExtVectorElementExpr *EVE =
14502 dyn_cast<ExtVectorElementExpr>(E)) {
14503 E = EVE->getBase()->IgnoreParenImpCasts();
14504 continue;
14505 }
14506 break;
14507 }
14508
14509 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14510 // Function calls
14511 const FunctionDecl *FD = CE->getDirectCallee();
14512 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14513 if (!DiagnosticEmitted) {
14514 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14515 << ConstFunction << FD;
14516 DiagnosticEmitted = true;
14517 }
14519 diag::note_typecheck_assign_const)
14520 << ConstFunction << FD << FD->getReturnType()
14521 << FD->getReturnTypeSourceRange();
14522 }
14523 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14524 // Point to variable declaration.
14525 if (const ValueDecl *VD = DRE->getDecl()) {
14526 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14527 if (!DiagnosticEmitted) {
14528 S.Diag(Loc, diag::err_typecheck_assign_const)
14529 << ExprRange << ConstVariable << VD << VD->getType();
14530 DiagnosticEmitted = true;
14531 }
14532 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14533 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14534 }
14535 }
14536 } else if (isa<CXXThisExpr>(E)) {
14537 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14538 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14539 if (MD->isConst()) {
14540 if (!DiagnosticEmitted) {
14541 S.Diag(Loc, diag::err_typecheck_assign_const_method)
14542 << ExprRange << MD;
14543 DiagnosticEmitted = true;
14544 }
14545 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const_method)
14546 << MD << MD->getSourceRange();
14547 }
14548 }
14549 }
14550 }
14551
14552 if (DiagnosticEmitted)
14553 return;
14554
14555 // Can't determine a more specific message, so display the generic error.
14556 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14557}
14558
14564
14566 const RecordType *Ty,
14567 SourceLocation Loc, SourceRange Range,
14568 OriginalExprKind OEK,
14569 bool &DiagnosticEmitted) {
14570 std::vector<const RecordType *> RecordTypeList;
14571 RecordTypeList.push_back(Ty);
14572 unsigned NextToCheckIndex = 0;
14573 // We walk the record hierarchy breadth-first to ensure that we print
14574 // diagnostics in field nesting order.
14575 while (RecordTypeList.size() > NextToCheckIndex) {
14576 bool IsNested = NextToCheckIndex > 0;
14577 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14578 ->getDecl()
14579 ->getDefinitionOrSelf()
14580 ->fields()) {
14581 // First, check every field for constness.
14582 QualType FieldTy = Field->getType();
14583 if (FieldTy.isConstQualified()) {
14584 if (!DiagnosticEmitted) {
14585 S.Diag(Loc, diag::err_typecheck_assign_const)
14586 << Range << NestedConstMember << OEK << VD
14587 << IsNested << Field;
14588 DiagnosticEmitted = true;
14589 }
14590 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14591 << NestedConstMember << IsNested << Field
14592 << FieldTy << Field->getSourceRange();
14593 }
14594
14595 // Then we append it to the list to check next in order.
14596 FieldTy = FieldTy.getCanonicalType();
14597 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14598 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14599 RecordTypeList.push_back(FieldRecTy);
14600 }
14601 }
14602 ++NextToCheckIndex;
14603 }
14604}
14605
14606/// Emit an error for the case where a record we are trying to assign to has a
14607/// const-qualified field somewhere in its hierarchy.
14608static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14609 SourceLocation Loc) {
14610 QualType Ty = E->getType();
14611 assert(Ty->isRecordType() && "lvalue was not record?");
14612 SourceRange Range = E->getSourceRange();
14613 const auto *RTy = Ty->getAsCanonical<RecordType>();
14614 bool DiagEmitted = false;
14615
14616 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14617 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14618 Range, OEK_Member, DiagEmitted);
14619 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14620 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14621 Range, OEK_Variable, DiagEmitted);
14622 else
14623 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14624 Range, OEK_LValue, DiagEmitted);
14625 if (!DiagEmitted)
14626 DiagnoseConstAssignment(S, E, Loc);
14627}
14628
14629/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14630/// emit an error and return true. If so, return false.
14632 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14633
14635
14636 SourceLocation OrigLoc = Loc;
14638 &Loc);
14639 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14641 if (IsLV == Expr::MLV_Valid)
14642 return false;
14643
14644 unsigned DiagID = 0;
14645 bool NeedType = false;
14646 switch (IsLV) { // C99 6.5.16p2
14648 // Use a specialized diagnostic when we're assigning to an object
14649 // from an enclosing function or block.
14651 if (NCCK == NCCK_Block)
14652 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14653 else
14654 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14655 break;
14656 }
14657
14658 // In ARC, use some specialized diagnostics for occasions where we
14659 // infer 'const'. These are always pseudo-strong variables.
14660 if (S.getLangOpts().ObjCAutoRefCount) {
14661 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14662 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14663 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14664
14665 // Use the normal diagnostic if it's pseudo-__strong but the
14666 // user actually wrote 'const'.
14667 if (var->isARCPseudoStrong() &&
14668 (!var->getTypeSourceInfo() ||
14669 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14670 // There are three pseudo-strong cases:
14671 // - self
14672 ObjCMethodDecl *method = S.getCurMethodDecl();
14673 if (method && var == method->getSelfDecl()) {
14674 DiagID = method->isClassMethod()
14675 ? diag::err_typecheck_arc_assign_self_class_method
14676 : diag::err_typecheck_arc_assign_self;
14677
14678 // - Objective-C externally_retained attribute.
14679 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14680 isa<ParmVarDecl>(var)) {
14681 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14682
14683 // - fast enumeration variables
14684 } else {
14685 DiagID = diag::err_typecheck_arr_assign_enumeration;
14686 }
14687
14688 SourceRange Assign;
14689 if (Loc != OrigLoc)
14690 Assign = SourceRange(OrigLoc, OrigLoc);
14691 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14692 // We need to preserve the AST regardless, so migration tool
14693 // can do its job.
14694 return false;
14695 }
14696 }
14697 }
14698
14699 // If none of the special cases above are triggered, then this is a
14700 // simple const assignment.
14701 if (DiagID == 0) {
14702 DiagnoseConstAssignment(S, E, Loc);
14703 return true;
14704 }
14705
14706 break;
14708 DiagnoseConstAssignment(S, E, Loc);
14709 return true;
14712 return true;
14715 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14716 NeedType = true;
14717 break;
14719 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14720 NeedType = true;
14721 break;
14723 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14724 break;
14725 case Expr::MLV_Valid:
14726 llvm_unreachable("did not take early return for MLV_Valid");
14730 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E)) {
14731 const Expr *Op = UnaryOp->getSubExpr()->IgnoreParens();
14732 if (UnaryOp->getOpcode() == UO_Imag &&
14733 !Op->getType()->isAnyComplexType()) {
14734 DiagID = diag::err_typecheck_lvalue_imag_not_modifiable_lvalue;
14735 NeedType = true;
14736 break;
14737 }
14738 }
14739
14740 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14741 break;
14742 }
14745 return S.RequireCompleteType(Loc, E->getType(),
14746 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14748 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14749 break;
14751 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14752 break;
14754 llvm_unreachable("readonly properties should be processed differently");
14756 DiagID = diag::err_readonly_message_assignment;
14757 break;
14759 DiagID = diag::err_no_subobject_property_setting;
14760 break;
14761 }
14762
14763 SourceRange Assign;
14764 if (Loc != OrigLoc)
14765 Assign = SourceRange(OrigLoc, OrigLoc);
14766 if (NeedType)
14767 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14768 else
14769 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14770 return true;
14771}
14772
14773static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14774 SourceLocation Loc,
14775 Sema &Sema) {
14777 return;
14779 return;
14780 if (Loc.isInvalid() || Loc.isMacroID())
14781 return;
14782 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14783 return;
14784
14785 // C / C++ fields
14786 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14787 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14788 if (ML && MR) {
14789 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14790 return;
14791 const ValueDecl *LHSDecl =
14793 const ValueDecl *RHSDecl =
14795 if (LHSDecl != RHSDecl)
14796 return;
14797 if (LHSDecl->getType().isVolatileQualified())
14798 return;
14799 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14800 if (RefTy->getPointeeType().isVolatileQualified())
14801 return;
14802
14803 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14804 }
14805
14806 // Objective-C instance variables
14807 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14808 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14809 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14810 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14811 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14812 if (RL && RR && RL->getDecl() == RR->getDecl())
14813 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14814 }
14815}
14816
14817// C99 6.5.16.1
14819 SourceLocation Loc,
14820 QualType CompoundType,
14821 BinaryOperatorKind Opc) {
14822 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14823
14824 // Verify that LHS is a modifiable lvalue, and emit error if not.
14825 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14826 return QualType();
14827
14828 QualType LHSType = LHSExpr->getType();
14829 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14830 CompoundType;
14831
14832 if (RHS.isUsable()) {
14833 // Even if this check fails don't return early to allow the best
14834 // possible error recovery and to allow any subsequent diagnostics to
14835 // work.
14836 const ValueDecl *Assignee = nullptr;
14837 bool ShowFullyQualifiedAssigneeName = false;
14838 // In simple cases describe what is being assigned to
14839 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14840 Assignee = DR->getDecl();
14841 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14842 Assignee = ME->getMemberDecl();
14843 ShowFullyQualifiedAssigneeName = true;
14844 }
14845
14847 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14848 ShowFullyQualifiedAssigneeName);
14849 }
14850
14851 // OpenCL v1.2 s6.1.1.1 p2:
14852 // The half data type can only be used to declare a pointer to a buffer that
14853 // contains half values
14854 if (getLangOpts().OpenCL &&
14855 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14856 LHSType->isHalfType()) {
14857 Diag(Loc, diag::err_opencl_half_load_store) << 1
14858 << LHSType.getUnqualifiedType();
14859 return QualType();
14860 }
14861
14862 // WebAssembly tables can't be used on RHS of an assignment expression.
14863 if (RHSType->isWebAssemblyTableType()) {
14864 Diag(Loc, diag::err_wasm_table_art) << 0;
14865 return QualType();
14866 }
14867
14868 AssignConvertType ConvTy;
14869 if (CompoundType.isNull()) {
14870 Expr *RHSCheck = RHS.get();
14871
14872 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14873
14874 QualType LHSTy(LHSType);
14875 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14876 if (RHS.isInvalid())
14877 return QualType();
14878 // Special case of NSObject attributes on c-style pointer types.
14880 ((Context.isObjCNSObjectType(LHSType) &&
14881 RHSType->isObjCObjectPointerType()) ||
14882 (Context.isObjCNSObjectType(RHSType) &&
14883 LHSType->isObjCObjectPointerType())))
14885
14886 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14887 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14888
14889 // If the RHS is a unary plus or minus, check to see if they = and + are
14890 // right next to each other. If so, the user may have typo'd "x =+ 4"
14891 // instead of "x += 4".
14892 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14893 RHSCheck = ICE->getSubExpr();
14894 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14895 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14896 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14897 // Only if the two operators are exactly adjacent.
14898 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14899 // And there is a space or other character before the subexpr of the
14900 // unary +/-. We don't want to warn on "x=-1".
14901 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14902 UO->getSubExpr()->getBeginLoc().isFileID()) {
14903 Diag(Loc, diag::warn_not_compound_assign)
14904 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14905 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14906 }
14907 }
14908
14909 if (IsAssignConvertCompatible(ConvTy)) {
14910 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14911 // Warn about retain cycles where a block captures the LHS, but
14912 // not if the LHS is a simple variable into which the block is
14913 // being stored...unless that variable can be captured by reference!
14914 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14915 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14916 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14917 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14918 }
14919
14920 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14922 // It is safe to assign a weak reference into a strong variable.
14923 // Although this code can still have problems:
14924 // id x = self.weakProp;
14925 // id y = self.weakProp;
14926 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14927 // paths through the function. This should be revisited if
14928 // -Wrepeated-use-of-weak is made flow-sensitive.
14929 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14930 // variable, which will be valid for the current autorelease scope.
14931 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14932 RHS.get()->getBeginLoc()))
14934
14935 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14936 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14937 }
14938 }
14939 } else {
14940 // Compound assignment "x += y"
14941 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14942 }
14943
14944 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14946 return QualType();
14947
14948 CheckForNullPointerDereference(*this, LHSExpr);
14949
14950 AssignedEntity AE{LHSExpr};
14951 checkAssignmentLifetime(*this, AE, RHS.get());
14952
14953 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14954 if (CompoundType.isNull()) {
14955 // C++2a [expr.ass]p5:
14956 // A simple-assignment whose left operand is of a volatile-qualified
14957 // type is deprecated unless the assignment is either a discarded-value
14958 // expression or an unevaluated operand
14959 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14960 }
14961 }
14962
14963 // C11 6.5.16p3: The type of an assignment expression is the type of the
14964 // left operand would have after lvalue conversion.
14965 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14966 // qualified type, the value has the unqualified version of the type of the
14967 // lvalue; additionally, if the lvalue has atomic type, the value has the
14968 // non-atomic version of the type of the lvalue.
14969 // C++ 5.17p1: the type of the assignment expression is that of its left
14970 // operand.
14971 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14972}
14973
14974// Scenarios to ignore if expression E is:
14975// 1. an explicit cast expression into void
14976// 2. a function call expression that returns void
14977static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14978 E = E->IgnoreParens();
14979
14980 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14981 if (CE->getCastKind() == CK_ToVoid) {
14982 return true;
14983 }
14984
14985 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14986 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14987 CE->getSubExpr()->getType()->isDependentType()) {
14988 return true;
14989 }
14990 }
14991
14992 if (const auto *CE = dyn_cast<CallExpr>(E))
14993 return CE->getCallReturnType(Context)->isVoidType();
14994 return false;
14995}
14996
14998 // No warnings in macros
14999 if (Loc.isMacroID())
15000 return;
15001
15002 // Don't warn in template instantiations.
15004 return;
15005
15006 // Scope isn't fine-grained enough to explicitly list the specific cases, so
15007 // instead, skip more than needed, then call back into here with the
15008 // CommaVisitor in SemaStmt.cpp.
15009 // The listed locations are the initialization and increment portions
15010 // of a for loop. The additional checks are on the condition of
15011 // if statements, do/while loops, and for loops.
15012 if (getCurScope()->isControlScope())
15013 return;
15014
15015 // If there are multiple comma operators used together, get the RHS of the
15016 // of the comma operator as the LHS.
15017 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
15018 if (BO->getOpcode() != BO_Comma)
15019 break;
15020 LHS = BO->getRHS();
15021 }
15022
15023 // Only allow some expressions on LHS to not warn.
15024 if (IgnoreCommaOperand(LHS, Context))
15025 return;
15026
15027 Diag(Loc, diag::warn_comma_operator);
15028 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
15029 << LHS->getSourceRange()
15031 LangOpts.CPlusPlus ? "static_cast<void>("
15032 : "(void)(")
15033 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
15034 ")");
15035}
15036
15037// C99 6.5.17
15039 SourceLocation Loc) {
15040 LHS = S.CheckPlaceholderExpr(LHS.get());
15041 RHS = S.CheckPlaceholderExpr(RHS.get());
15042 if (LHS.isInvalid() || RHS.isInvalid())
15043 return QualType();
15044
15045 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
15046 // operands, but not unary promotions.
15047 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
15048
15049 // So we treat the LHS as a ignored value, and in C++ we allow the
15050 // containing site to determine what should be done with the RHS.
15051 LHS = S.IgnoredValueConversions(LHS.get());
15052 if (LHS.isInvalid())
15053 return QualType();
15054
15055 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
15056
15057 if (!S.getLangOpts().CPlusPlus) {
15059 if (RHS.isInvalid())
15060 return QualType();
15061 if (!RHS.get()->getType()->isVoidType())
15062 S.RequireCompleteType(Loc, RHS.get()->getType(),
15063 diag::err_incomplete_type);
15064 }
15065
15066 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
15067 S.DiagnoseCommaOperator(LHS.get(), Loc);
15068
15069 return RHS.get()->getType();
15070}
15071
15072/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
15073/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
15076 ExprObjectKind &OK,
15077 SourceLocation OpLoc, bool IsInc,
15078 bool IsPrefix) {
15079 QualType ResType = Op->getType();
15080 // Atomic types can be used for increment / decrement where the non-atomic
15081 // versions can, so ignore the _Atomic() specifier for the purpose of
15082 // checking.
15083 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
15084 ResType = ResAtomicType->getValueType();
15085
15086 assert(!ResType.isNull() && "no type for increment/decrement expression");
15087
15088 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
15089 // Decrement of bool is not allowed.
15090 if (!IsInc) {
15091 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
15092 return QualType();
15093 }
15094 // Increment of bool sets it to true, but is deprecated.
15095 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
15096 : diag::warn_increment_bool)
15097 << Op->getSourceRange();
15098 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
15099 // Error on enum increments and decrements in C++ mode
15100 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
15101 return QualType();
15102 } else if (ResType->isRealType()) {
15103 // OK!
15104 } else if (ResType->isPointerType()) {
15105 // C99 6.5.2.4p2, 6.5.6p2
15106 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
15107 return QualType();
15108 } else if (ResType->isOverflowBehaviorType()) {
15109 // OK!
15110 } else if (ResType->isObjCObjectPointerType()) {
15111 // On modern runtimes, ObjC pointer arithmetic is forbidden.
15112 // Otherwise, we just need a complete type.
15113 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
15114 checkArithmeticOnObjCPointer(S, OpLoc, Op))
15115 return QualType();
15116 } else if (ResType->isAnyComplexType()) {
15117 // C99 does not support ++/-- on complex types, we allow as an extension.
15118 S.DiagCompat(OpLoc, diag_compat::increment_complex)
15119 << IsInc << Op->getSourceRange();
15120 } else if (ResType->isPlaceholderType()) {
15122 if (PR.isInvalid()) return QualType();
15123 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
15124 IsInc, IsPrefix);
15125 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
15126 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
15127 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
15128 (ResType->castAs<VectorType>()->getVectorKind() !=
15130 // The z vector extensions allow ++ and -- for non-bool vectors.
15131 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
15132 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
15133 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
15134 } else {
15135 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
15136 << ResType << int(IsInc) << Op->getSourceRange();
15137 return QualType();
15138 }
15139 // At this point, we know we have a real, complex or pointer type.
15140 // Now make sure the operand is a modifiable lvalue.
15141 if (CheckForModifiableLvalue(Op, OpLoc, S))
15142 return QualType();
15143 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
15144 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
15145 // An operand with volatile-qualified type is deprecated
15146 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
15147 << IsInc << ResType;
15148 }
15149 // In C++, a prefix increment is the same type as the operand. Otherwise
15150 // (in C or with postfix), the increment is the unqualified type of the
15151 // operand.
15152 if (IsPrefix && S.getLangOpts().CPlusPlus) {
15153 VK = VK_LValue;
15154 OK = Op->getObjectKind();
15155 return ResType;
15156 } else {
15157 VK = VK_PRValue;
15158 return ResType.getUnqualifiedType();
15159 }
15160}
15161
15162/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
15163/// This routine allows us to typecheck complex/recursive expressions
15164/// where the declaration is needed for type checking. We only need to
15165/// handle cases when the expression references a function designator
15166/// or is an lvalue. Here are some examples:
15167/// - &(x) => x
15168/// - &*****f => f for f a function designator.
15169/// - &s.xx => s
15170/// - &s.zz[1].yy -> s, if zz is an array
15171/// - *(x + 1) -> x, if x is an array
15172/// - &"123"[2] -> 0
15173/// - & __real__ x -> x
15174///
15175/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
15176/// members.
15178 switch (E->getStmtClass()) {
15179 case Stmt::DeclRefExprClass:
15180 return cast<DeclRefExpr>(E)->getDecl();
15181 case Stmt::MemberExprClass:
15182 // If this is an arrow operator, the address is an offset from
15183 // the base's value, so the object the base refers to is
15184 // irrelevant.
15185 if (cast<MemberExpr>(E)->isArrow())
15186 return nullptr;
15187 // Otherwise, the expression refers to a part of the base
15188 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
15189 case Stmt::ArraySubscriptExprClass: {
15190 // FIXME: This code shouldn't be necessary! We should catch the implicit
15191 // promotion of register arrays earlier.
15192 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
15193 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
15194 if (ICE->getSubExpr()->getType()->isArrayType())
15195 return getPrimaryDecl(ICE->getSubExpr());
15196 }
15197 return nullptr;
15198 }
15199 case Stmt::UnaryOperatorClass: {
15201
15202 switch(UO->getOpcode()) {
15203 case UO_Real:
15204 case UO_Imag:
15205 case UO_Extension:
15206 return getPrimaryDecl(UO->getSubExpr());
15207 default:
15208 return nullptr;
15209 }
15210 }
15211 case Stmt::ParenExprClass:
15212 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
15213 case Stmt::ImplicitCastExprClass:
15214 // If the result of an implicit cast is an l-value, we care about
15215 // the sub-expression; otherwise, the result here doesn't matter.
15216 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
15217 case Stmt::CXXUuidofExprClass:
15218 return cast<CXXUuidofExpr>(E)->getGuidDecl();
15219 default:
15220 return nullptr;
15221 }
15222}
15223
15224namespace {
15225enum {
15226 AO_Bit_Field = 0,
15227 AO_Vector_Element = 1,
15228 AO_Property_Expansion = 2,
15229 AO_Register_Variable = 3,
15230 AO_Matrix_Element = 4,
15231 AO_No_Error = 5
15232};
15233}
15234/// Diagnose invalid operand for address of operations.
15235///
15236/// \param Type The type of operand which cannot have its address taken.
15238 Expr *E, unsigned Type) {
15239 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
15240}
15241
15243 const Expr *Op,
15244 const CXXMethodDecl *MD) {
15245 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
15246
15247 if (Op != DRE)
15248 return Diag(OpLoc, diag::err_parens_pointer_member_function)
15249 << Op->getSourceRange();
15250
15251 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
15252 if (isa<CXXDestructorDecl>(MD))
15253 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
15254 << DRE->getSourceRange();
15255
15256 if (DRE->getQualifier())
15257 return false;
15258
15259 if (MD->getParent()->getName().empty())
15260 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15261 << DRE->getSourceRange();
15262
15263 SmallString<32> Str;
15264 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
15265 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15266 << DRE->getSourceRange()
15267 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
15268}
15269
15271 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
15272 if (PTy->getKind() == BuiltinType::Overload) {
15273 Expr *E = OrigOp.get()->IgnoreParens();
15274 if (!isa<OverloadExpr>(E)) {
15275 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
15276 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
15277 << OrigOp.get()->getSourceRange();
15278 return QualType();
15279 }
15280
15284 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15285 << OrigOp.get()->getSourceRange();
15286 return QualType();
15287 }
15288
15289 return Context.OverloadTy;
15290 }
15291
15292 if (PTy->getKind() == BuiltinType::UnknownAny)
15293 return Context.UnknownAnyTy;
15294
15295 if (PTy->getKind() == BuiltinType::BoundMember) {
15296 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15297 << OrigOp.get()->getSourceRange();
15298 return QualType();
15299 }
15300
15301 OrigOp = CheckPlaceholderExpr(OrigOp.get());
15302 if (OrigOp.isInvalid()) return QualType();
15303 }
15304
15305 if (OrigOp.get()->isTypeDependent())
15306 return Context.DependentTy;
15307
15308 assert(!OrigOp.get()->hasPlaceholderType());
15309
15310 // Make sure to ignore parentheses in subsequent checks
15311 Expr *op = OrigOp.get()->IgnoreParens();
15312
15313 // In OpenCL captures for blocks called as lambda functions
15314 // are located in the private address space. Blocks used in
15315 // enqueue_kernel can be located in a different address space
15316 // depending on a vendor implementation. Thus preventing
15317 // taking an address of the capture to avoid invalid AS casts.
15318 if (LangOpts.OpenCL) {
15319 auto* VarRef = dyn_cast<DeclRefExpr>(op);
15320 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15321 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
15322 return QualType();
15323 }
15324 }
15325
15326 if (getLangOpts().C99) {
15327 // Implement C99-only parts of addressof rules.
15328 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
15329 if (uOp->getOpcode() == UO_Deref)
15330 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15331 // (assuming the deref expression is valid).
15332 return uOp->getSubExpr()->getType();
15333 }
15334 // Technically, there should be a check for array subscript
15335 // expressions here, but the result of one is always an lvalue anyway.
15336 }
15337 ValueDecl *dcl = getPrimaryDecl(op);
15338
15339 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
15340 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15341 op->getBeginLoc()))
15342 return QualType();
15343
15345 unsigned AddressOfError = AO_No_Error;
15346
15347 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15348 bool IsError = isSFINAEContext();
15349 Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary
15350 : diag::ext_typecheck_addrof_temporary)
15351 << op->getType() << op->getSourceRange();
15352 if (IsError)
15353 return QualType();
15354 // Materialize the temporary as an lvalue so that we can take its address.
15355 OrigOp = op =
15356 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
15357 } else if (isa<ObjCSelectorExpr>(op)) {
15358 return Context.getPointerType(op->getType());
15359 } else if (lval == Expr::LV_MemberFunction) {
15360 // If it's an instance method, make a member pointer.
15361 // The expression must have exactly the form &A::foo.
15362
15363 // If the underlying expression isn't a decl ref, give up.
15364 if (!isa<DeclRefExpr>(op)) {
15365 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15366 << OrigOp.get()->getSourceRange();
15367 return QualType();
15368 }
15369 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
15371
15372 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15373 QualType MPTy = Context.getMemberPointerType(
15374 op->getType(), DRE->getQualifier(), MD->getParent());
15375
15376 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15377 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15378 // When pointer authentication is enabled, argument and return types of
15379 // vitual member functions must be complete. This is because vitrual
15380 // member function pointers are implemented using virtual dispatch
15381 // thunks and the thunks cannot be emitted if the argument or return
15382 // types are incomplete.
15383 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15384 SourceLocation DeclRefLoc,
15385 SourceLocation RetArgTypeLoc) {
15386 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
15387 Diag(DeclRefLoc,
15388 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15389 Diag(RetArgTypeLoc,
15390 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15391 << T;
15392 return true;
15393 }
15394 return false;
15395 };
15396 QualType RetTy = MD->getReturnType();
15397 bool IsIncomplete =
15398 !RetTy->isVoidType() &&
15399 ReturnOrParamTypeIsIncomplete(
15400 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15401 for (auto *PVD : MD->parameters())
15402 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15403 PVD->getBeginLoc());
15404 if (IsIncomplete)
15405 return QualType();
15406 }
15407
15408 // Under the MS ABI, lock down the inheritance model now.
15409 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15410 (void)isCompleteType(OpLoc, MPTy);
15411 return MPTy;
15412 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15413 // C99 6.5.3.2p1
15414 // The operand must be either an l-value or a function designator
15415 if (!op->getType()->isFunctionType()) {
15416 // Use a special diagnostic for loads from property references.
15417 if (isa<PseudoObjectExpr>(op)) {
15418 AddressOfError = AO_Property_Expansion;
15419 } else {
15420 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15421 << op->getType() << op->getSourceRange();
15422 return QualType();
15423 }
15424 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
15425 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
15426 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15427 }
15428
15429 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15430 // The operand cannot be a bit-field
15431 AddressOfError = AO_Bit_Field;
15432 } else if (op->getObjectKind() == OK_VectorComponent) {
15433 // The operand cannot be an element of a vector
15434 AddressOfError = AO_Vector_Element;
15435 } else if (op->getObjectKind() == OK_MatrixComponent) {
15436 // The operand cannot be an element of a matrix.
15437 AddressOfError = AO_Matrix_Element;
15438 } else if (dcl) { // C99 6.5.3.2p1
15439 // We have an lvalue with a decl. Make sure the decl is not declared
15440 // with the register storage-class specifier.
15441 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15442 // in C++ it is not error to take address of a register
15443 // variable (c++03 7.1.1P3)
15444 if (vd->getStorageClass() == SC_Register &&
15446 AddressOfError = AO_Register_Variable;
15447 }
15448 } else if (isa<MSPropertyDecl>(dcl)) {
15449 AddressOfError = AO_Property_Expansion;
15450 } else if (isa<FunctionTemplateDecl>(dcl)) {
15451 return Context.OverloadTy;
15452 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15453 // Okay: we can take the address of a field.
15454 // Could be a pointer to member, though, if there is an explicit
15455 // scope qualifier for the class.
15456
15457 // [C++26] [expr.prim.id.general]
15458 // If an id-expression E denotes a non-static non-type member
15459 // of some class C [...] and if E is a qualified-id, E is
15460 // not the un-parenthesized operand of the unary & operator [...]
15461 // the id-expression is transformed into a class member access expression.
15462 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
15463 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
15464 DeclContext *Ctx = dcl->getDeclContext();
15465 if (Ctx && Ctx->isRecord()) {
15466 if (dcl->getType()->isReferenceType()) {
15467 Diag(OpLoc,
15468 diag::err_cannot_form_pointer_to_member_of_reference_type)
15469 << dcl->getDeclName() << dcl->getType();
15470 return QualType();
15471 }
15472
15473 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15474 Ctx = Ctx->getParent();
15475
15476 QualType MPTy = Context.getMemberPointerType(
15477 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
15478 // Under the MS ABI, lock down the inheritance model now.
15479 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15480 (void)isCompleteType(OpLoc, MPTy);
15481 return MPTy;
15482 }
15483 }
15487 llvm_unreachable("Unknown/unexpected decl type");
15488 }
15489
15490 if (AddressOfError != AO_No_Error) {
15491 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15492 return QualType();
15493 }
15494
15495 if (lval == Expr::LV_IncompleteVoidType) {
15496 // Taking the address of a void variable is technically illegal, but we
15497 // allow it in cases which are otherwise valid.
15498 // Example: "extern void x; void* y = &x;".
15499 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15500 }
15501
15502 // If the operand has type "type", the result has type "pointer to type".
15503 if (op->getType()->isObjCObjectType())
15504 return Context.getObjCObjectPointerType(op->getType());
15505
15506 // Cannot take the address of WebAssembly references or tables.
15507 if (Context.getTargetInfo().getTriple().isWasm()) {
15508 QualType OpTy = op->getType();
15509 if (OpTy.isWebAssemblyReferenceType()) {
15510 Diag(OpLoc, diag::err_wasm_ca_reference)
15511 << 1 << OrigOp.get()->getSourceRange();
15512 return QualType();
15513 }
15514 if (OpTy->isWebAssemblyTableType()) {
15515 Diag(OpLoc, diag::err_wasm_table_pr)
15516 << 1 << OrigOp.get()->getSourceRange();
15517 return QualType();
15518 }
15519 }
15520
15521 CheckAddressOfPackedMember(op);
15522
15523 return Context.getPointerType(op->getType());
15524}
15525
15526static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15527 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15528 if (!DRE)
15529 return;
15530 const Decl *D = DRE->getDecl();
15531 if (!D)
15532 return;
15533 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15534 if (!Param)
15535 return;
15536 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15537 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15538 return;
15539 if (FunctionScopeInfo *FD = S.getCurFunction())
15540 FD->ModifiedNonNullParams.insert(Param);
15541}
15542
15543/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15545 SourceLocation OpLoc,
15546 bool IsAfterAmp = false) {
15547 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15548 if (ConvResult.isInvalid())
15549 return QualType();
15550 Op = ConvResult.get();
15551 QualType OpTy = Op->getType();
15553
15555 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15556 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15557 Op->getSourceRange());
15558 }
15559
15560 if (const PointerType *PT = OpTy->getAs<PointerType>())
15561 {
15562 Result = PT->getPointeeType();
15563 }
15564 else if (const ObjCObjectPointerType *OPT =
15566 Result = OPT->getPointeeType();
15567 else {
15569 if (PR.isInvalid()) return QualType();
15570 if (PR.get() != Op)
15571 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15572 }
15573
15574 if (Result.isNull()) {
15575 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15576 << OpTy << Op->getSourceRange();
15577 return QualType();
15578 }
15579
15580 if (Result->isVoidType()) {
15581 // C++ [expr.unary.op]p1:
15582 // [...] the expression to which [the unary * operator] is applied shall
15583 // be a pointer to an object type, or a pointer to a function type
15584 LangOptions LO = S.getLangOpts();
15585 if (LO.CPlusPlus)
15586 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15587 << OpTy << Op->getSourceRange();
15588 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15589 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15590 << OpTy << Op->getSourceRange();
15591 }
15592
15593 // HLX has no vector pair loads or stores.
15594 if (S.Hexagon().isHLXVectorType(Result) &&
15596 S.Diag(OpLoc, diag::err_typecheck_indirection_hlx_vectorpair_pointer)
15597 << OpTy << Op->getSourceRange();
15598
15599 // Dereferences are usually l-values...
15600 VK = VK_LValue;
15601
15602 // ...except that certain expressions are never l-values in C.
15603 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15604 VK = VK_PRValue;
15605
15606 return Result;
15607}
15608
15609BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15611 switch (Kind) {
15612 default: llvm_unreachable("Unknown binop!");
15613 case tok::periodstar: Opc = BO_PtrMemD; break;
15614 case tok::arrowstar: Opc = BO_PtrMemI; break;
15615 case tok::star: Opc = BO_Mul; break;
15616 case tok::slash: Opc = BO_Div; break;
15617 case tok::percent: Opc = BO_Rem; break;
15618 case tok::plus: Opc = BO_Add; break;
15619 case tok::minus: Opc = BO_Sub; break;
15620 case tok::lessless: Opc = BO_Shl; break;
15621 case tok::greatergreater: Opc = BO_Shr; break;
15622 case tok::lessequal: Opc = BO_LE; break;
15623 case tok::less: Opc = BO_LT; break;
15624 case tok::greaterequal: Opc = BO_GE; break;
15625 case tok::greater: Opc = BO_GT; break;
15626 case tok::exclaimequal: Opc = BO_NE; break;
15627 case tok::equalequal: Opc = BO_EQ; break;
15628 case tok::spaceship: Opc = BO_Cmp; break;
15629 case tok::amp: Opc = BO_And; break;
15630 case tok::caret: Opc = BO_Xor; break;
15631 case tok::pipe: Opc = BO_Or; break;
15632 case tok::ampamp: Opc = BO_LAnd; break;
15633 case tok::pipepipe: Opc = BO_LOr; break;
15634 case tok::equal: Opc = BO_Assign; break;
15635 case tok::starequal: Opc = BO_MulAssign; break;
15636 case tok::slashequal: Opc = BO_DivAssign; break;
15637 case tok::percentequal: Opc = BO_RemAssign; break;
15638 case tok::plusequal: Opc = BO_AddAssign; break;
15639 case tok::minusequal: Opc = BO_SubAssign; break;
15640 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15641 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15642 case tok::ampequal: Opc = BO_AndAssign; break;
15643 case tok::caretequal: Opc = BO_XorAssign; break;
15644 case tok::pipeequal: Opc = BO_OrAssign; break;
15645 case tok::comma: Opc = BO_Comma; break;
15646 }
15647 return Opc;
15648}
15649
15651 tok::TokenKind Kind) {
15653 switch (Kind) {
15654 default: llvm_unreachable("Unknown unary op!");
15655 case tok::plusplus: Opc = UO_PreInc; break;
15656 case tok::minusminus: Opc = UO_PreDec; break;
15657 case tok::amp: Opc = UO_AddrOf; break;
15658 case tok::star: Opc = UO_Deref; break;
15659 case tok::plus: Opc = UO_Plus; break;
15660 case tok::minus: Opc = UO_Minus; break;
15661 case tok::tilde: Opc = UO_Not; break;
15662 case tok::exclaim: Opc = UO_LNot; break;
15663 case tok::kw___real: Opc = UO_Real; break;
15664 case tok::kw___imag: Opc = UO_Imag; break;
15665 case tok::kw___extension__: Opc = UO_Extension; break;
15666 }
15667 return Opc;
15668}
15669
15670const FieldDecl *
15672 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15673 // common for setters.
15674 // struct A {
15675 // int X;
15676 // -void setX(int X) { X = X; }
15677 // +void setX(int X) { this->X = X; }
15678 // };
15679
15680 // Only consider parameters for self assignment fixes.
15681 if (!isa<ParmVarDecl>(SelfAssigned))
15682 return nullptr;
15683 const auto *Method =
15684 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15685 if (!Method)
15686 return nullptr;
15687
15688 const CXXRecordDecl *Parent = Method->getParent();
15689 // In theory this is fixable if the lambda explicitly captures this, but
15690 // that's added complexity that's rarely going to be used.
15691 if (Parent->isLambda())
15692 return nullptr;
15693
15694 // FIXME: Use an actual Lookup operation instead of just traversing fields
15695 // in order to get base class fields.
15696 auto Field =
15697 llvm::find_if(Parent->fields(),
15698 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15699 return F->getDeclName() == Name;
15700 });
15701 return (Field != Parent->field_end()) ? *Field : nullptr;
15702}
15703
15704/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15705/// This warning suppressed in the event of macro expansions.
15706static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15707 SourceLocation OpLoc, bool IsBuiltin) {
15709 return;
15710 if (S.isUnevaluatedContext())
15711 return;
15712 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15713 return;
15714 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15715 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15716 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15717 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15718 if (!LHSDeclRef || !RHSDeclRef ||
15719 LHSDeclRef->getLocation().isMacroID() ||
15720 RHSDeclRef->getLocation().isMacroID())
15721 return;
15722 const ValueDecl *LHSDecl =
15723 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15724 const ValueDecl *RHSDecl =
15725 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15726 if (LHSDecl != RHSDecl)
15727 return;
15728 if (LHSDecl->getType().isVolatileQualified())
15729 return;
15730 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15731 if (RefTy->getPointeeType().isVolatileQualified())
15732 return;
15733
15734 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15735 : diag::warn_self_assignment_overloaded)
15736 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15737 << RHSExpr->getSourceRange();
15738 if (const FieldDecl *SelfAssignField =
15740 Diag << 1 << SelfAssignField
15741 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15742 else
15743 Diag << 0;
15744}
15745
15746/// Check if a bitwise-& is performed on an Objective-C pointer. This
15747/// is usually indicative of introspection within the Objective-C pointer.
15749 SourceLocation OpLoc) {
15750 if (!S.getLangOpts().ObjC)
15751 return;
15752
15753 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15754 const Expr *LHS = L.get();
15755 const Expr *RHS = R.get();
15756
15758 ObjCPointerExpr = LHS;
15759 OtherExpr = RHS;
15760 }
15761 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15762 ObjCPointerExpr = RHS;
15763 OtherExpr = LHS;
15764 }
15765
15766 // This warning is deliberately made very specific to reduce false
15767 // positives with logic that uses '&' for hashing. This logic mainly
15768 // looks for code trying to introspect into tagged pointers, which
15769 // code should generally never do.
15770 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15771 unsigned Diag = diag::warn_objc_pointer_masking;
15772 // Determine if we are introspecting the result of performSelectorXXX.
15773 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15774 // Special case messages to -performSelector and friends, which
15775 // can return non-pointer values boxed in a pointer value.
15776 // Some clients may wish to silence warnings in this subcase.
15777 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15778 Selector S = ME->getSelector();
15779 StringRef SelArg0 = S.getNameForSlot(0);
15780 if (SelArg0.starts_with("performSelector"))
15781 Diag = diag::warn_objc_pointer_masking_performSelector;
15782 }
15783
15784 S.Diag(OpLoc, Diag)
15785 << ObjCPointerExpr->getSourceRange();
15786 }
15787}
15788
15789// This helper function promotes a binary operator's operands (which are of a
15790// half vector type) to a vector of floats and then truncates the result to
15791// a vector of either half or short.
15793 BinaryOperatorKind Opc, QualType ResultTy,
15795 bool IsCompAssign, SourceLocation OpLoc,
15796 FPOptionsOverride FPFeatures) {
15797 auto &Context = S.getASTContext();
15798 assert((isVector(ResultTy, Context.HalfTy) ||
15799 isVector(ResultTy, Context.ShortTy)) &&
15800 "Result must be a vector of half or short");
15801 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15802 isVector(RHS.get()->getType(), Context.HalfTy) &&
15803 "both operands expected to be a half vector");
15804
15805 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15806 QualType BinOpResTy = RHS.get()->getType();
15807
15808 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15809 // change BinOpResTy to a vector of ints.
15810 if (isVector(ResultTy, Context.ShortTy))
15811 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15812
15813 if (IsCompAssign)
15814 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15815 ResultTy, VK, OK, OpLoc, FPFeatures,
15816 BinOpResTy, BinOpResTy);
15817
15818 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15819 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15820 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15821 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15822}
15823
15824/// Returns true if conversion between vectors of halfs and vectors of floats
15825/// is needed.
15826static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15827 QualType ResultTy, Expr *E0,
15828 Expr *E1 = nullptr) {
15829 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType)
15830 return false;
15831
15832 // The conversion truncates the result to a half/short vector, so it shouldn't
15833 // apply when the result is not that type (e.g. HLSL comparisons).
15834 if (ResultTy->isVectorType() && !isVector(ResultTy, Ctx.HalfTy) &&
15835 !isVector(ResultTy, Ctx.ShortTy))
15836 return false;
15837
15838 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15839 QualType Ty = E->IgnoreImplicit()->getType();
15840
15841 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15842 // to vectors of floats. Although the element type of the vectors is __fp16,
15843 // the vectors shouldn't be treated as storage-only types. See the
15844 // discussion here: https://reviews.llvm.org/rG825235c140e7
15845 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15846 if (VT->getVectorKind() == VectorKind::Neon)
15847 return false;
15848 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15849 }
15850 return false;
15851 };
15852
15853 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15854}
15855
15857 BinaryOperatorKind Opc, Expr *LHSExpr,
15858 Expr *RHSExpr, bool ForFoldExpression) {
15859 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15860 // The syntax only allows initializer lists on the RHS of assignment,
15861 // so we don't need to worry about accepting invalid code for
15862 // non-assignment operators.
15863 // C++11 5.17p9:
15864 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15865 // of x = {} is x = T().
15867 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15868 InitializedEntity Entity =
15870 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15871 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15872 if (Init.isInvalid())
15873 return Init;
15874 RHSExpr = Init.get();
15875 }
15876
15877 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15878 QualType ResultTy; // Result type of the binary operator.
15879 // The following two variables are used for compound assignment operators
15880 QualType CompLHSTy; // Type of LHS after promotions for computation
15881 QualType CompResultTy; // Type of computation result
15884 bool ConvertHalfVec = false;
15885
15886 if (!LHS.isUsable() || !RHS.isUsable())
15887 return ExprError();
15888
15889 if (getLangOpts().OpenCL) {
15890 QualType LHSTy = LHSExpr->getType();
15891 QualType RHSTy = RHSExpr->getType();
15892 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15893 // the ATOMIC_VAR_INIT macro.
15894 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15895 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15896 if (BO_Assign == Opc)
15897 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15898 else
15899 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15900 return ExprError();
15901 }
15902
15903 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15904 // only with a builtin functions and therefore should be disallowed here.
15905 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15906 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15907 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15908 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15909 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15910 return ExprError();
15911 }
15912 }
15913
15914 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15915 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15916
15917 switch (Opc) {
15918 case BO_Assign:
15919 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15920 if (getLangOpts().CPlusPlus &&
15921 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15922 VK = LHS.get()->getValueKind();
15923 OK = LHS.get()->getObjectKind();
15924 }
15925 if (!ResultTy.isNull()) {
15926 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15927 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15928
15929 // Avoid copying a block to the heap if the block is assigned to a local
15930 // auto variable that is declared in the same scope as the block. This
15931 // optimization is unsafe if the local variable is declared in an outer
15932 // scope. For example:
15933 //
15934 // BlockTy b;
15935 // {
15936 // b = ^{...};
15937 // }
15938 // // It is unsafe to invoke the block here if it wasn't copied to the
15939 // // heap.
15940 // b();
15941
15942 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15943 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15944 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15945 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15946 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15947
15949 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15951 }
15952 RecordModifiableNonNullParam(*this, LHS.get());
15953 break;
15954 case BO_PtrMemD:
15955 case BO_PtrMemI:
15956 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15957 Opc == BO_PtrMemI);
15958 break;
15959 case BO_Mul:
15960 case BO_Div:
15961 ConvertHalfVec = true;
15962 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15963 break;
15964 case BO_Rem:
15965 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15966 break;
15967 case BO_Add:
15968 ConvertHalfVec = true;
15969 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15970 break;
15971 case BO_Sub:
15972 ConvertHalfVec = true;
15973 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15974 break;
15975 case BO_Shl:
15976 case BO_Shr:
15977 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15978 break;
15979 case BO_LE:
15980 case BO_LT:
15981 case BO_GE:
15982 case BO_GT:
15983 ConvertHalfVec = true;
15984 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15985
15986 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15987 !ForFoldExpression && BI && BI->isComparisonOp())
15988 Diag(OpLoc, diag::warn_consecutive_comparison)
15989 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15990
15991 break;
15992 case BO_EQ:
15993 case BO_NE:
15994 ConvertHalfVec = true;
15995 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15996 break;
15997 case BO_Cmp:
15998 ConvertHalfVec = true;
15999 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
16000 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
16001 break;
16002 case BO_And:
16003 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
16004 [[fallthrough]];
16005 case BO_Xor:
16006 case BO_Or:
16007 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
16008 break;
16009 case BO_LAnd:
16010 case BO_LOr:
16011 ConvertHalfVec = true;
16012 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
16013 break;
16014 case BO_MulAssign:
16015 case BO_DivAssign:
16016 ConvertHalfVec = true;
16017 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
16018 CompLHSTy = CompResultTy;
16019 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
16020 ResultTy =
16021 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
16022 break;
16023 case BO_RemAssign:
16024 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
16025 CompLHSTy = CompResultTy;
16026 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
16027 ResultTy =
16028 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
16029 break;
16030 case BO_AddAssign:
16031 ConvertHalfVec = true;
16032 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
16033 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
16034 ResultTy =
16035 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
16036 break;
16037 case BO_SubAssign:
16038 ConvertHalfVec = true;
16039 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
16040 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
16041 ResultTy =
16042 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
16043 break;
16044 case BO_ShlAssign:
16045 case BO_ShrAssign:
16046 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
16047 CompLHSTy = CompResultTy;
16048 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
16049 ResultTy =
16050 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
16051 break;
16052 case BO_AndAssign:
16053 case BO_OrAssign: // fallthrough
16054 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
16055 [[fallthrough]];
16056 case BO_XorAssign:
16057 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
16058 CompLHSTy = CompResultTy;
16059 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
16060 ResultTy =
16061 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
16062 break;
16063 case BO_Comma:
16064 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
16065 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
16066 VK = RHS.get()->getValueKind();
16067 OK = RHS.get()->getObjectKind();
16068 }
16069 break;
16070 }
16071 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
16072 return ExprError();
16073
16074 // Some of the binary operations require promoting operands of half vector to
16075 // float vectors and truncating the result back to half vector. For now, we do
16076 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
16077 // arm64).
16078 assert(
16079 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
16080 isVector(LHS.get()->getType(), Context.HalfTy)) &&
16081 "both sides are half vectors or neither sides are");
16082 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, ResultTy,
16083 LHS.get(), RHS.get());
16084
16085 // Check for array bounds violations for both sides of the BinaryOperator
16086 CheckArrayAccess(LHS.get());
16087 CheckArrayAccess(RHS.get());
16088
16089 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
16090 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
16091 &Context.Idents.get("object_setClass"),
16093 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
16094 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
16095 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
16097 "object_setClass(")
16098 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
16099 ",")
16100 << FixItHint::CreateInsertion(RHSLocEnd, ")");
16101 }
16102 else
16103 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
16104 }
16105 else if (const ObjCIvarRefExpr *OIRE =
16106 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
16107 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
16108
16109 // Opc is not a compound assignment if CompResultTy is null.
16110 if (CompResultTy.isNull()) {
16111 if (ConvertHalfVec)
16112 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
16113 OpLoc, CurFPFeatureOverrides());
16114 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
16115 VK, OK, OpLoc, CurFPFeatureOverrides());
16116 }
16117
16118 // Handle compound assignments.
16119 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
16121 VK = VK_LValue;
16122 OK = LHS.get()->getObjectKind();
16123 }
16124
16125 // The LHS is not converted to the result type for fixed-point compound
16126 // assignment as the common type is computed on demand. Reset the CompLHSTy
16127 // to the LHS type we would have gotten after unary conversions.
16128 if (CompResultTy->isFixedPointType())
16129 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
16130
16131 if (ConvertHalfVec)
16132 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
16133 OpLoc, CurFPFeatureOverrides());
16134
16136 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
16137 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
16138}
16139
16140/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
16141/// operators are mixed in a way that suggests that the programmer forgot that
16142/// comparison operators have higher precedence. The most typical example of
16143/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
16145 SourceLocation OpLoc, Expr *LHSExpr,
16146 Expr *RHSExpr) {
16147 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
16148 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
16149
16150 // Check that one of the sides is a comparison operator and the other isn't.
16151 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
16152 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
16153 if (isLeftComp == isRightComp)
16154 return;
16155
16156 // Bitwise operations are sometimes used as eager logical ops.
16157 // Don't diagnose this.
16158 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
16159 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
16160 if (isLeftBitwise || isRightBitwise)
16161 return;
16162
16163 SourceRange DiagRange = isLeftComp
16164 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
16165 : SourceRange(OpLoc, RHSExpr->getEndLoc());
16166 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
16167 SourceRange ParensRange =
16168 isLeftComp
16169 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
16170 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
16171
16172 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
16173 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
16174 SuggestParentheses(Self, OpLoc,
16175 Self.PDiag(diag::note_precedence_silence) << OpStr,
16176 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
16177 SuggestParentheses(Self, OpLoc,
16178 Self.PDiag(diag::note_precedence_bitwise_first)
16180 ParensRange);
16181}
16182
16183/// It accepts a '&&' expr that is inside a '||' one.
16184/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
16185/// in parentheses.
16186static void
16188 BinaryOperator *Bop) {
16189 assert(Bop->getOpcode() == BO_LAnd);
16190 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
16191 << Bop->getSourceRange() << OpLoc;
16193 Self.PDiag(diag::note_precedence_silence)
16194 << Bop->getOpcodeStr(),
16195 Bop->getSourceRange());
16196}
16197
16198/// Look for '&&' in the left hand of a '||' expr.
16200 Expr *LHSExpr, Expr *RHSExpr) {
16201 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
16202 if (Bop->getOpcode() == BO_LAnd) {
16203 // If it's "string_literal && a || b" don't warn since the precedence
16204 // doesn't matter.
16205 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
16206 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
16207 } else if (Bop->getOpcode() == BO_LOr) {
16208 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
16209 // If it's "a || b && string_literal || c" we didn't warn earlier for
16210 // "a || b && string_literal", but warn now.
16211 if (RBop->getOpcode() == BO_LAnd &&
16212 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
16213 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
16214 }
16215 }
16216 }
16217}
16218
16219/// Look for '&&' in the right hand of a '||' expr.
16221 Expr *LHSExpr, Expr *RHSExpr) {
16222 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
16223 if (Bop->getOpcode() == BO_LAnd) {
16224 // If it's "a || b && string_literal" don't warn since the precedence
16225 // doesn't matter.
16226 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
16227 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
16228 }
16229 }
16230}
16231
16232/// Look for bitwise op in the left or right hand of a bitwise op with
16233/// lower precedence and emit a diagnostic together with a fixit hint that wraps
16234/// the '&' expression in parentheses.
16236 SourceLocation OpLoc, Expr *SubExpr) {
16237 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
16238 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
16239 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
16240 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
16241 << Bop->getSourceRange() << OpLoc;
16242 SuggestParentheses(S, Bop->getOperatorLoc(),
16243 S.PDiag(diag::note_precedence_silence)
16244 << Bop->getOpcodeStr(),
16245 Bop->getSourceRange());
16246 }
16247 }
16248}
16249
16251 Expr *SubExpr, StringRef Shift) {
16252 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
16253 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
16254 StringRef Op = Bop->getOpcodeStr();
16255 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
16256 << Bop->getSourceRange() << OpLoc << Shift << Op;
16257 SuggestParentheses(S, Bop->getOperatorLoc(),
16258 S.PDiag(diag::note_precedence_silence) << Op,
16259 Bop->getSourceRange());
16260 }
16261 }
16262}
16263
16265 Expr *LHSExpr, Expr *RHSExpr) {
16266 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
16267 if (!OCE)
16268 return;
16269
16270 FunctionDecl *FD = OCE->getDirectCallee();
16271 if (!FD || !FD->isOverloadedOperator())
16272 return;
16273
16275 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
16276 return;
16277
16278 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
16279 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
16280 << (Kind == OO_LessLess);
16282 S.PDiag(diag::note_precedence_silence)
16283 << (Kind == OO_LessLess ? "<<" : ">>"),
16284 OCE->getSourceRange());
16286 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
16287 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
16288}
16289
16290/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
16291/// precedence.
16293 SourceLocation OpLoc, Expr *LHSExpr,
16294 Expr *RHSExpr){
16295 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
16297 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
16298
16299 // Diagnose "arg1 & arg2 | arg3"
16300 if ((Opc == BO_Or || Opc == BO_Xor) &&
16301 !OpLoc.isMacroID()/* Don't warn in macros. */) {
16302 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
16303 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
16304 }
16305
16306 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16307 // We don't warn for 'assert(a || b && "bad")' since this is safe.
16308 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
16309 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
16310 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
16311 }
16312
16313 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
16314 || Opc == BO_Shr) {
16315 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
16316 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
16317 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
16318 }
16319
16320 // Warn on overloaded shift operators and comparisons, such as:
16321 // cout << 5 == 4;
16323 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
16324}
16325
16327 tok::TokenKind Kind,
16328 Expr *LHSExpr, Expr *RHSExpr) {
16329 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16330 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16331 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16332
16333 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16334 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
16335
16339
16340 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
16341 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
16342
16343 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
16344}
16345
16347 UnresolvedSetImpl &Functions) {
16349 if (OverOp != OO_None && OverOp != OO_Equal)
16350 LookupOverloadedOperatorName(OverOp, S, Functions);
16351
16352 // In C++20 onwards, we may have a second operator to look up.
16353 if (getLangOpts().CPlusPlus20) {
16355 LookupOverloadedOperatorName(ExtraOp, S, Functions);
16356 }
16357}
16358
16359/// Build an overloaded binary operator expression in the given scope.
16362 Expr *LHS, Expr *RHS) {
16363 switch (Opc) {
16364 case BO_Assign:
16365 // In the non-overloaded case, we warn about self-assignment (x = x) for
16366 // both simple assignment and certain compound assignments where algebra
16367 // tells us the operation yields a constant result. When the operator is
16368 // overloaded, we can't do the latter because we don't want to assume that
16369 // those algebraic identities still apply; for example, a path-building
16370 // library might use operator/= to append paths. But it's still reasonable
16371 // to assume that simple assignment is just moving/copying values around
16372 // and so self-assignment is likely a bug.
16373 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
16374 [[fallthrough]];
16375 case BO_DivAssign:
16376 case BO_RemAssign:
16377 case BO_SubAssign:
16378 case BO_AndAssign:
16379 case BO_OrAssign:
16380 case BO_XorAssign:
16381 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
16382 break;
16383 default:
16384 break;
16385 }
16386
16387 // Find all of the overloaded operators visible from this point.
16388 UnresolvedSet<16> Functions;
16389 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
16390
16391 // Build the (potentially-overloaded, potentially-dependent)
16392 // binary operation.
16393 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16394}
16395
16397 BinaryOperatorKind Opc, Expr *LHSExpr,
16398 Expr *RHSExpr, bool ForFoldExpression) {
16399 if (!LHSExpr || !RHSExpr)
16400 return ExprError();
16401
16402 // We want to end up calling one of SemaPseudoObject::checkAssignment
16403 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16404 // both expressions are overloadable or either is type-dependent),
16405 // or CreateBuiltinBinOp (in any other case). We also want to get
16406 // any placeholder types out of the way.
16407
16408 // Handle pseudo-objects in the LHS.
16409 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16410 // Assignments with a pseudo-object l-value need special analysis.
16411 if (pty->getKind() == BuiltinType::PseudoObject &&
16413 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16414
16415 // Don't resolve overloads if the other type is overloadable.
16416 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16417 // We can't actually test that if we still have a placeholder,
16418 // though. Fortunately, none of the exceptions we see in that
16419 // code below are valid when the LHS is an overload set. Note
16420 // that an overload set can be dependently-typed, but it never
16421 // instantiates to having an overloadable type.
16422 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16423 if (resolvedRHS.isInvalid()) return ExprError();
16424 RHSExpr = resolvedRHS.get();
16425
16426 if (RHSExpr->isTypeDependent() ||
16427 RHSExpr->getType()->isOverloadableType())
16428 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16429 }
16430
16431 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16432 // template, diagnose the missing 'template' keyword instead of diagnosing
16433 // an invalid use of a bound member function.
16434 //
16435 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16436 // to C++1z [over.over]/1.4, but we already checked for that case above.
16437 if (Opc == BO_LT && inTemplateInstantiation() &&
16438 (pty->getKind() == BuiltinType::BoundMember ||
16439 pty->getKind() == BuiltinType::Overload)) {
16440 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16441 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16442 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16443 return isa<FunctionTemplateDecl>(ND);
16444 })) {
16445 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16446 : OE->getNameLoc(),
16447 diag::err_template_kw_missing)
16448 << OE->getName().getAsIdentifierInfo();
16449 return ExprError();
16450 }
16451 }
16452
16453 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16454 if (LHS.isInvalid()) return ExprError();
16455 LHSExpr = LHS.get();
16456 }
16457
16458 // Handle pseudo-objects in the RHS.
16459 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16460 // An overload in the RHS can potentially be resolved by the type
16461 // being assigned to.
16462 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16463 if (getLangOpts().CPlusPlus &&
16464 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16465 LHSExpr->getType()->isOverloadableType()))
16466 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16467
16468 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16469 ForFoldExpression);
16470 }
16471
16472 // Don't resolve overloads if the other type is overloadable.
16473 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16474 LHSExpr->getType()->isOverloadableType())
16475 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16476
16477 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16478 if (!resolvedRHS.isUsable()) return ExprError();
16479 RHSExpr = resolvedRHS.get();
16480 }
16481
16482 if (getLangOpts().HLSL) {
16483 if (LHSExpr->getType()->isHLSLResourceRecord() ||
16484 LHSExpr->getType()->isHLSLResourceRecordArray()) {
16485 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
16486 return ExprError();
16487 } else if (RHSExpr->getType()->isHLSLResourceRecord()) {
16488 std::optional<ExprResult> ConvRHS =
16490 if (ConvRHS && Context.hasSameUnqualifiedType(
16491 LHSExpr->getType(), ConvRHS->get()->getType())) {
16492 assert(!ConvRHS->isInvalid());
16493 RHSExpr = ConvRHS->get();
16494 }
16495 }
16496 }
16497
16498 if (getLangOpts().CPlusPlus) {
16499 bool CanOverloadBinOp =
16500 !getLangOpts().HLSL ||
16501 HLSL().canHaveOverloadedBinOp(LHSExpr->getType(), Opc) ||
16502 HLSL().canHaveOverloadedBinOp(RHSExpr->getType(), Opc);
16503 bool TypeDependent =
16504 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16505 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16506 RHSExpr->getType()->isOverloadableType();
16507 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16508 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16509 }
16510
16511 if (getLangOpts().RecoveryAST &&
16512 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16513 assert(!getLangOpts().CPlusPlus);
16514 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16515 "Should only occur in error-recovery path.");
16517 // C [6.15.16] p3:
16518 // An assignment expression has the value of the left operand after the
16519 // assignment, but is not an lvalue.
16521 Context, LHSExpr, RHSExpr, Opc,
16523 OpLoc, CurFPFeatureOverrides());
16524 QualType ResultType;
16525 switch (Opc) {
16526 case BO_Assign:
16527 ResultType = LHSExpr->getType().getUnqualifiedType();
16528 break;
16529 case BO_LT:
16530 case BO_GT:
16531 case BO_LE:
16532 case BO_GE:
16533 case BO_EQ:
16534 case BO_NE:
16535 case BO_LAnd:
16536 case BO_LOr:
16537 // These operators have a fixed result type regardless of operands.
16538 ResultType = Context.IntTy;
16539 break;
16540 case BO_Comma:
16541 ResultType = RHSExpr->getType();
16542 break;
16543 default:
16544 ResultType = Context.DependentTy;
16545 break;
16546 }
16547 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16548 VK_PRValue, OK_Ordinary, OpLoc,
16550 }
16551
16552 // Build a built-in binary operation.
16553 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16554}
16555
16557 if (T.isNull() || T->isDependentType())
16558 return false;
16559
16560 if (!Ctx.isPromotableIntegerType(T))
16561 return true;
16562
16563 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16564}
16565
16567 UnaryOperatorKind Opc, Expr *InputExpr,
16568 bool IsAfterAmp) {
16569 ExprResult Input = InputExpr;
16572 QualType resultType;
16573 bool CanOverflow = false;
16574
16575 bool ConvertHalfVec = false;
16576 if (getLangOpts().OpenCL) {
16577 QualType Ty = InputExpr->getType();
16578 // The only legal unary operation for atomics is '&'.
16579 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16580 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16581 // only with a builtin functions and therefore should be disallowed here.
16582 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16583 || Ty->isBlockPointerType())) {
16584 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16585 << InputExpr->getType()
16586 << Input.get()->getSourceRange());
16587 }
16588 }
16589
16590 if (getLangOpts().HLSL && OpLoc.isValid()) {
16591 if (Opc == UO_AddrOf)
16592 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16593 if (Opc == UO_Deref)
16594 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16595 }
16596
16597 if (InputExpr->isTypeDependent() &&
16598 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
16599 resultType = Context.DependentTy;
16600 } else {
16601 switch (Opc) {
16602 case UO_PreInc:
16603 case UO_PreDec:
16604 case UO_PostInc:
16605 case UO_PostDec:
16606 resultType =
16607 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
16608 Opc == UO_PreInc || Opc == UO_PostInc,
16609 Opc == UO_PreInc || Opc == UO_PreDec);
16610 CanOverflow = isOverflowingIntegerType(Context, resultType);
16611 break;
16612 case UO_AddrOf:
16613 resultType = CheckAddressOfOperand(Input, OpLoc);
16614 CheckAddressOfNoDeref(InputExpr);
16615 RecordModifiableNonNullParam(*this, InputExpr);
16616 break;
16617 case UO_Deref: {
16619 if (Input.isInvalid())
16620 return ExprError();
16621 resultType =
16622 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16623 break;
16624 }
16625 case UO_Plus:
16626 case UO_Minus:
16627 CanOverflow = Opc == UO_Minus &&
16629 Input = UsualUnaryConversions(Input.get());
16630 if (Input.isInvalid())
16631 return ExprError();
16632 // Unary plus and minus require promoting an operand of half vector to a
16633 // float vector and truncating the result back to a half vector. For now,
16634 // we do this only when HalfArgsAndReturns is set (that is, when the
16635 // target is arm or arm64).
16636 ConvertHalfVec = needsConversionOfHalfVec(
16637 true, Context, Input.get()->getType(), Input.get());
16638
16639 // If the operand is a half vector, promote it to a float vector.
16640 if (ConvertHalfVec)
16641 Input = convertVector(Input.get(), Context.FloatTy, *this);
16642 resultType = Input.get()->getType();
16643 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16644 break;
16645 else if (resultType->isVectorType() &&
16646 // The z vector extensions don't allow + or - with bool vectors.
16647 (!Context.getLangOpts().ZVector ||
16648 resultType->castAs<VectorType>()->getVectorKind() !=
16650 break;
16651 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16652 break;
16653 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16654 Opc == UO_Plus && resultType->isPointerType())
16655 break;
16656
16657 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16658 << resultType << Input.get()->getSourceRange());
16659
16660 case UO_Not: // bitwise complement
16661 Input = UsualUnaryConversions(Input.get());
16662 if (Input.isInvalid())
16663 return ExprError();
16664 resultType = Input.get()->getType();
16665 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16666 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16667 // C99 does not support '~' for complex conjugation.
16668 Diag(OpLoc, diag::ext_integer_complement_complex)
16669 << resultType << Input.get()->getSourceRange();
16670 else if (resultType->hasIntegerRepresentation())
16671 break;
16672 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16673 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16674 // on vector float types.
16675 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16676 if (!T->isIntegerType())
16677 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16678 << resultType << Input.get()->getSourceRange());
16679 } else {
16680 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16681 << resultType << Input.get()->getSourceRange());
16682 }
16683 break;
16684
16685 case UO_LNot: // logical negation
16686 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16688 if (Input.isInvalid())
16689 return ExprError();
16690 resultType = Input.get()->getType();
16691
16692 // Though we still have to promote half FP to float...
16693 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16694 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16695 .get();
16696 resultType = Context.FloatTy;
16697 }
16698
16699 // WebAsembly tables can't be used in unary expressions.
16700 if (resultType->isPointerType() &&
16702 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16703 << resultType << Input.get()->getSourceRange());
16704 }
16705
16706 if (resultType->isScalarType() && !isScopedEnumerationType(resultType) &&
16707 !resultType->isMetaInfoType()) {
16708 // Before C++26, scalar types are contextually converted to bool,
16709 // std::meta::info is a scalar type but not an arithmetic type.
16710
16711 // C99 6.5.3.3p1: ok, fallthrough;
16712 if (Context.getLangOpts().CPlusPlus) {
16713 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16714 // operand contextually converted to bool.
16715 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16716 ScalarTypeToBooleanCastKind(resultType));
16717 } else if (Context.getLangOpts().OpenCL &&
16718 Context.getLangOpts().OpenCLVersion < 120) {
16719 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16720 // operate on scalar float types.
16721 if (!resultType->isIntegerType() && !resultType->isPointerType())
16722 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16723 << resultType << Input.get()->getSourceRange());
16724 }
16725 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16726 !resultType->hasBooleanRepresentation()) {
16727 // HLSL unary logical 'not' behaves like C++, which states that the
16728 // operand is converted to bool and the result is bool, however HLSL
16729 // extends this property to vectors.
16730 const VectorType *VTy = resultType->castAs<VectorType>();
16731 resultType =
16732 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16733
16734 Input = ImpCastExprToType(
16735 Input.get(), resultType,
16737 .get();
16738 break;
16739 } else if (resultType->isExtVectorType()) {
16740 if (Context.getLangOpts().OpenCL &&
16741 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16742 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16743 // operate on vector float types.
16744 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16745 if (!T->isIntegerType())
16746 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16747 << resultType << Input.get()->getSourceRange());
16748 }
16749 // Vector logical not returns the signed variant of the operand type.
16750 resultType = GetSignedVectorType(resultType);
16751 break;
16752 } else if (Context.getLangOpts().CPlusPlus &&
16753 resultType->isVectorType()) {
16754 const VectorType *VTy = resultType->castAs<VectorType>();
16755 if (VTy->getVectorKind() != VectorKind::Generic)
16756 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16757 << resultType << Input.get()->getSourceRange());
16758
16759 // Vector logical not returns the signed variant of the operand type.
16760 resultType = GetSignedVectorType(resultType);
16761 break;
16762 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16763 resultType = Context.getLogicalOperationType();
16764 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(InputExpr);
16765 break;
16766 } else {
16767 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16768 << resultType << Input.get()->getSourceRange());
16769 }
16770
16771 // LNot always has type int. C99 6.5.3.3p5.
16772 // In C++, it's bool. C++ 5.3.1p8
16773 resultType = Context.getLogicalOperationType();
16774 break;
16775 case UO_Real:
16776 case UO_Imag:
16777 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16778 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16779 // ordinary complex l-values to ordinary l-values and all other values to
16780 // r-values.
16781 if (Input.isInvalid())
16782 return ExprError();
16783 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16784 if (Input.get()->isGLValue() &&
16785 Input.get()->getObjectKind() == OK_Ordinary)
16786 VK = Input.get()->getValueKind();
16787 } else if (!getLangOpts().CPlusPlus) {
16788 // In C, a volatile scalar is read by __imag. In C++, it is not.
16789 Input = DefaultLvalueConversion(Input.get());
16790 }
16791 break;
16792 case UO_Extension:
16793 resultType = Input.get()->getType();
16794 VK = Input.get()->getValueKind();
16795 OK = Input.get()->getObjectKind();
16796 break;
16797 case UO_Coawait:
16798 // It's unnecessary to represent the pass-through operator co_await in the
16799 // AST; just return the input expression instead.
16800 assert(!Input.get()->getType()->isDependentType() &&
16801 "the co_await expression must be non-dependant before "
16802 "building operator co_await");
16803 return Input;
16804 }
16805 }
16806 if (resultType.isNull() || Input.isInvalid())
16807 return ExprError();
16808
16809 // Check for array bounds violations in the operand of the UnaryOperator,
16810 // except for the '*' and '&' operators that have to be handled specially
16811 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16812 // that are explicitly defined as valid by the standard).
16813 if (Opc != UO_AddrOf && Opc != UO_Deref)
16814 CheckArrayAccess(Input.get());
16815
16816 auto *UO =
16817 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16818 OpLoc, CanOverflow, CurFPFeatureOverrides());
16819
16820 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16821 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16823 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16824
16825 // Convert the result back to a half vector.
16826 if (ConvertHalfVec)
16827 return convertVector(UO, Context.HalfTy, *this);
16828 return UO;
16829}
16830
16832 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16833 if (!DRE->getQualifier())
16834 return false;
16835
16836 ValueDecl *VD = DRE->getDecl();
16837 if (!VD->isCXXClassMember())
16838 return false;
16839
16841 return true;
16842 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16843 return Method->isImplicitObjectMemberFunction();
16844
16845 return false;
16846 }
16847
16848 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16849 if (!ULE->getQualifier())
16850 return false;
16851
16852 for (NamedDecl *D : ULE->decls()) {
16853 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16854 if (Method->isImplicitObjectMemberFunction())
16855 return true;
16856 } else {
16857 // Overload set does not contain methods.
16858 break;
16859 }
16860 }
16861
16862 return false;
16863 }
16864
16865 return false;
16866}
16867
16869 UnaryOperatorKind Opc, Expr *Input,
16870 bool IsAfterAmp) {
16871 // First things first: handle placeholders so that the
16872 // overloaded-operator check considers the right type.
16873 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16874 // Increment and decrement of pseudo-object references.
16875 if (pty->getKind() == BuiltinType::PseudoObject &&
16877 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16878
16879 // extension is always a builtin operator.
16880 if (Opc == UO_Extension)
16881 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16882
16883 // & gets special logic for several kinds of placeholder.
16884 // The builtin code knows what to do.
16885 if (Opc == UO_AddrOf &&
16886 (pty->getKind() == BuiltinType::Overload ||
16887 pty->getKind() == BuiltinType::UnknownAny ||
16888 pty->getKind() == BuiltinType::BoundMember))
16889 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16890
16891 // Anything else needs to be handled now.
16893 if (Result.isInvalid()) return ExprError();
16894 Input = Result.get();
16895 }
16896
16897 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16899 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16900 // Find all of the overloaded operators visible from this point.
16901 UnresolvedSet<16> Functions;
16903 if (S && OverOp != OO_None)
16904 LookupOverloadedOperatorName(OverOp, S, Functions);
16905
16906 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16907 }
16908
16909 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16910}
16911
16913 Expr *Input, bool IsAfterAmp) {
16914 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16915 IsAfterAmp);
16916}
16917
16919 LabelDecl *TheDecl) {
16920 TheDecl->markUsed(Context);
16921 // Create the AST node. The address of a label always has type 'void*'.
16922 auto *Res = new (Context) AddrLabelExpr(
16923 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16924
16925 if (getCurFunction())
16926 getCurFunction()->AddrLabels.push_back(Res);
16927
16928 return Res;
16929}
16930
16933 // Make sure we diagnose jumping into a statement expression.
16935}
16936
16938 // Note that function is also called by TreeTransform when leaving a
16939 // StmtExpr scope without rebuilding anything.
16940
16943}
16944
16946 SourceLocation RPLoc) {
16947 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16948}
16949
16951 SourceLocation RPLoc, unsigned TemplateDepth) {
16952 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16953 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16954
16957 assert(!Cleanup.exprNeedsCleanups() &&
16958 "cleanups within StmtExpr not correctly bound!");
16960
16961 // FIXME: there are a variety of strange constraints to enforce here, for
16962 // example, it is not possible to goto into a stmt expression apparently.
16963 // More semantic analysis is needed.
16964
16965 // If there are sub-stmts in the compound stmt, take the type of the last one
16966 // as the type of the stmtexpr.
16967 QualType Ty = Context.VoidTy;
16968 bool StmtExprMayBindToTemp = false;
16969 if (!Compound->body_empty()) {
16970 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16971 if (const Expr *Value = LastStmt->getExprStmt()) {
16972 StmtExprMayBindToTemp = true;
16973 Ty = Value->getType();
16974 }
16975 }
16976 }
16977
16978 // FIXME: Check that expression type is complete/non-abstract; statement
16979 // expressions are not lvalues.
16980 Expr *ResStmtExpr =
16981 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16982 if (StmtExprMayBindToTemp)
16983 return MaybeBindToTemporary(ResStmtExpr);
16984 return ResStmtExpr;
16985}
16986
16988 if (ER.isInvalid())
16989 return ExprError();
16990
16991 // Do function/array conversion on the last expression, but not
16992 // lvalue-to-rvalue. However, initialize an unqualified type.
16994 if (ER.isInvalid())
16995 return ExprError();
16996 Expr *E = ER.get();
16997
16998 if (E->isTypeDependent())
16999 return E;
17000
17001 // In ARC, if the final expression ends in a consume, splice
17002 // the consume out and bind it later. In the alternate case
17003 // (when dealing with a retainable type), the result
17004 // initialization will create a produce. In both cases the
17005 // result will be +1, and we'll need to balance that out with
17006 // a bind.
17007 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
17008 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
17009 return Cast->getSubExpr();
17010
17011 // FIXME: Provide a better location for the initialization.
17015 SourceLocation(), E);
17016}
17017
17019 TypeSourceInfo *TInfo,
17020 const Designation &Desig,
17021 SourceLocation RParenLoc) {
17022 QualType ArgTy = TInfo->getType();
17023 bool Dependent = ArgTy->isDependentType();
17024 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
17025
17026 // We must have at least one component that refers to the type, and the first
17027 // one is known to be a field designator. Verify that the ArgTy represents
17028 // a struct/union/class.
17029 if (!Dependent && !ArgTy->isRecordType())
17030 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
17031 << ArgTy << TypeRange);
17032
17033 // Type must be complete per C99 7.17p3 because a declaring a variable
17034 // with an incomplete type would be ill-formed.
17035 if (!Dependent
17036 && RequireCompleteType(BuiltinLoc, ArgTy,
17037 diag::err_offsetof_incomplete_type, TypeRange))
17038 return ExprError();
17039
17040 bool DidWarnAboutNonPOD = false;
17041 QualType CurrentType = ArgTy;
17044 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
17045 const Designator &D = Desig.getDesignator(I);
17046 assert(!D.isArrayRangeDesignator());
17047 if (D.isArrayDesignator()) {
17048 // Offset of an array sub-field. TODO: Should we allow vector elements?
17049 if (!CurrentType->isDependentType()) {
17050 const ArrayType *AT = Context.getAsArrayType(CurrentType);
17051 if(!AT)
17052 return ExprError(Diag(D.getEndLoc(), diag::err_offsetof_array_type)
17053 << CurrentType);
17054 CurrentType = AT->getElementType();
17055 } else
17056 CurrentType = Context.DependentTy;
17057
17059 if (IdxRval.isInvalid())
17060 return ExprError();
17061 Expr *Idx = IdxRval.get();
17062
17063 // The expression must be an integral expression.
17064 // FIXME: An integral constant expression?
17065 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
17066 !Idx->getType()->isIntegerType())
17067 return ExprError(
17068 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
17069 << Idx->getSourceRange());
17070
17071 // Record this array index.
17072 Comps.push_back(
17073 OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
17074 Exprs.push_back(Idx);
17075 continue;
17076 }
17077
17078 assert(D.isFieldDesignator());
17079 const IdentifierInfo *Name = D.getFieldDecl();
17080
17081 // Offset of a field.
17082 if (CurrentType->isDependentType()) {
17083 // We have the offset of a field, but we can't look into the dependent
17084 // type. Just record the identifier of the field.
17085 Comps.push_back(OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
17086 CurrentType = Context.DependentTy;
17087 continue;
17088 }
17089
17090 // We need to have a complete type to look into.
17091 if (RequireCompleteType(D.getBeginLoc(), CurrentType,
17092 diag::err_offsetof_incomplete_type))
17093 return ExprError();
17094
17095 // Look for the designated field.
17096 auto *RD = CurrentType->getAsRecordDecl();
17097 if (!RD)
17098 return ExprError(Diag(D.getEndLoc(), diag::err_offsetof_record_type)
17099 << CurrentType);
17100
17101 // C++ [lib.support.types]p5:
17102 // The macro offsetof accepts a restricted set of type arguments in this
17103 // International Standard. type shall be a POD structure or a POD union
17104 // (clause 9).
17105 // C++11 [support.types]p4:
17106 // If type is not a standard-layout class (Clause 9), the results are
17107 // undefined.
17108 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
17109 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
17110 unsigned DiagID =
17111 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
17112 : diag::ext_offsetof_non_pod_type;
17113
17114 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
17115 Diag(BuiltinLoc, DiagID)
17117 << CurrentType;
17118 DidWarnAboutNonPOD = true;
17119 }
17120 }
17121
17122 // Look for the field.
17123 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
17124 LookupQualifiedName(R, RD);
17125 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
17126 IndirectFieldDecl *IndirectMemberDecl = nullptr;
17127 if (!MemberDecl) {
17128 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
17129 MemberDecl = IndirectMemberDecl->getAnonField();
17130 }
17131
17132 if (!MemberDecl) {
17133 // Lookup could be ambiguous when looking up a placeholder variable
17134 // __builtin_offsetof(S, _).
17135 // In that case we would already have emitted a diagnostic
17136 if (!R.isAmbiguous())
17137 Diag(BuiltinLoc, diag::err_no_member)
17138 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
17139 return ExprError();
17140 }
17141
17142 // C99 7.17p3:
17143 // (If the specified member is a bit-field, the behavior is undefined.)
17144 //
17145 // We diagnose this as an error.
17146 if (MemberDecl->isBitField()) {
17147 Diag(D.getEndLoc(), diag::err_offsetof_bitfield)
17148 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17149 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
17150 return ExprError();
17151 }
17152
17153 RecordDecl *Parent = MemberDecl->getParent();
17154 if (IndirectMemberDecl)
17155 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
17156
17157 // If the member was found in a base class, introduce OffsetOfNodes for
17158 // the base class indirections.
17159 CXXBasePaths Paths;
17160 if (IsDerivedFrom(D.getBeginLoc(), CurrentType,
17161 Context.getCanonicalTagType(Parent), Paths)) {
17162 if (Paths.getDetectedVirtual()) {
17163 Diag(D.getEndLoc(), diag::err_offsetof_field_of_virtual_base)
17164 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17165 return ExprError();
17166 }
17167
17168 CXXBasePath &Path = Paths.front();
17169 for (const CXXBasePathElement &B : Path)
17170 Comps.push_back(OffsetOfNode(B.Base));
17171 }
17172
17173 if (IndirectMemberDecl) {
17174 for (auto *FI : IndirectMemberDecl->chain()) {
17175 assert(isa<FieldDecl>(FI));
17176 Comps.push_back(
17178 }
17179 } else
17180 Comps.push_back(OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
17181
17182 CurrentType = MemberDecl->getType().getNonReferenceType();
17183 }
17184
17185 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
17186 Comps, Exprs, RParenLoc);
17187}
17188
17191 ParsedType ParsedArgTy,
17192 const Designation &Desig,
17193 SourceLocation RParenLoc) {
17194
17195 TypeSourceInfo *ArgTInfo;
17196 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
17197 if (ArgTy.isNull())
17198 return ExprError();
17199
17200 if (!ArgTInfo)
17201 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
17202
17203 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Desig, RParenLoc);
17204}
17205
17207 Expr *CondExpr,
17208 Expr *LHSExpr, Expr *RHSExpr,
17209 SourceLocation RPLoc) {
17210 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
17211
17214 QualType resType;
17215 bool CondIsTrue = false;
17216 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
17217 resType = Context.DependentTy;
17218 } else {
17219 // The conditional expression is required to be a constant expression.
17220 llvm::APSInt condEval(32);
17222 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
17223 if (CondICE.isInvalid())
17224 return ExprError();
17225 CondExpr = CondICE.get();
17226 CondIsTrue = condEval.getZExtValue();
17227
17228 // If the condition is > zero, then the AST type is the same as the LHSExpr.
17229 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
17230
17231 resType = ActiveExpr->getType();
17232 VK = ActiveExpr->getValueKind();
17233 OK = ActiveExpr->getObjectKind();
17234 }
17235
17236 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
17237 resType, VK, OK, RPLoc, CondIsTrue);
17238}
17239
17240//===----------------------------------------------------------------------===//
17241// Clang Extensions.
17242//===----------------------------------------------------------------------===//
17243
17244void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
17246
17247 if (LangOpts.CPlusPlus) {
17249 Decl *ManglingContextDecl;
17250 std::tie(MCtx, ManglingContextDecl) =
17251 getCurrentMangleNumberContext(Block->getDeclContext());
17252 if (MCtx) {
17253 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
17254 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
17255 }
17256 }
17257
17258 PushBlockScope(CurScope, Block);
17259 CurContext->addDecl(Block);
17260 if (CurScope)
17261 PushDeclContext(CurScope, Block);
17262 else
17263 CurContext = Block;
17264
17266
17267 // Enter a new evaluation context to insulate the block from any
17268 // cleanups from the enclosing full-expression.
17271}
17272
17274 Scope *CurScope) {
17275 assert(ParamInfo.getIdentifier() == nullptr &&
17276 "block-id should have no identifier!");
17277 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
17278 BlockScopeInfo *CurBlock = getCurBlock();
17279
17280 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
17281 QualType T = Sig->getType();
17283
17284 // GetTypeForDeclarator always produces a function type for a block
17285 // literal signature. Furthermore, it is always a FunctionProtoType
17286 // unless the function was written with a typedef.
17287 assert(T->isFunctionType() &&
17288 "GetTypeForDeclarator made a non-function block signature");
17289
17290 // Look for an explicit signature in that function type.
17291 FunctionProtoTypeLoc ExplicitSignature;
17292
17293 if ((ExplicitSignature = Sig->getTypeLoc()
17295
17296 // Check whether that explicit signature was synthesized by
17297 // GetTypeForDeclarator. If so, don't save that as part of the
17298 // written signature.
17299 if (ExplicitSignature.getLocalRangeBegin() ==
17300 ExplicitSignature.getLocalRangeEnd()) {
17301 // This would be much cheaper if we stored TypeLocs instead of
17302 // TypeSourceInfos.
17303 TypeLoc Result = ExplicitSignature.getReturnLoc();
17304 unsigned Size = Result.getFullDataSize();
17305 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
17306 Sig->getTypeLoc().initializeFullCopy(Result, Size);
17307
17308 ExplicitSignature = FunctionProtoTypeLoc();
17309 }
17310 }
17311
17312 CurBlock->TheDecl->setSignatureAsWritten(Sig);
17313 CurBlock->FunctionType = T;
17314
17315 const auto *Fn = T->castAs<FunctionType>();
17316 QualType RetTy = Fn->getReturnType();
17317 bool isVariadic =
17318 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
17319
17320 CurBlock->TheDecl->setIsVariadic(isVariadic);
17321
17322 // Context.DependentTy is used as a placeholder for a missing block
17323 // return type. TODO: what should we do with declarators like:
17324 // ^ * { ... }
17325 // If the answer is "apply template argument deduction"....
17326 if (RetTy != Context.DependentTy) {
17327 CurBlock->ReturnType = RetTy;
17328 CurBlock->TheDecl->setBlockMissingReturnType(false);
17329 CurBlock->HasImplicitReturnType = false;
17330 }
17331
17332 // Push block parameters from the declarator if we had them.
17334 if (ExplicitSignature) {
17335 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17336 ParmVarDecl *Param = ExplicitSignature.getParam(I);
17337 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17338 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17339 // Diagnose this as an extension in C17 and earlier.
17340 if (!getLangOpts().C23)
17341 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
17342 }
17343 Params.push_back(Param);
17344 }
17345
17346 // Fake up parameter variables if we have a typedef, like
17347 // ^ fntype { ... }
17348 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17349 for (const auto &I : Fn->param_types()) {
17351 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
17352 Params.push_back(Param);
17353 }
17354 }
17355
17356 // Set the parameters on the block decl.
17357 if (!Params.empty()) {
17358 CurBlock->TheDecl->setParams(Params);
17360 /*CheckParameterNames=*/false);
17361 }
17362
17363 // Finally we can process decl attributes.
17364 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
17365
17366 // Put the parameter variables in scope.
17367 for (auto *AI : CurBlock->TheDecl->parameters()) {
17368 AI->setOwningFunction(CurBlock->TheDecl);
17369
17370 // If this has an identifier, add it to the scope stack.
17371 if (AI->getIdentifier()) {
17372 CheckShadow(CurBlock->TheScope, AI);
17373
17374 PushOnScopeChains(AI, CurBlock->TheScope);
17375 }
17376
17377 if (AI->isInvalidDecl())
17378 CurBlock->TheDecl->setInvalidDecl();
17379 }
17380}
17381
17382void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17383 // Leave the expression-evaluation context.
17386
17387 // Pop off CurBlock, handle nested blocks.
17390}
17391
17393 Stmt *Body, Scope *CurScope) {
17394 // If blocks are disabled, emit an error.
17395 if (!LangOpts.Blocks)
17396 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
17397
17398 // Leave the expression-evaluation context.
17401 assert(!Cleanup.exprNeedsCleanups() &&
17402 "cleanups within block not correctly bound!");
17404
17406 BlockDecl *BD = BSI->TheDecl;
17407
17409
17410 if (BSI->HasImplicitReturnType)
17412
17413 QualType RetTy = Context.VoidTy;
17414 if (!BSI->ReturnType.isNull())
17415 RetTy = BSI->ReturnType;
17416
17417 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17418 QualType BlockTy;
17419
17420 // If the user wrote a function type in some form, try to use that.
17421 if (!BSI->FunctionType.isNull()) {
17422 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17423
17424 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17425 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17426
17427 // Turn protoless block types into nullary block types.
17428 if (isa<FunctionNoProtoType>(FTy)) {
17430 EPI.ExtInfo = Ext;
17431 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17432
17433 // Otherwise, if we don't need to change anything about the function type,
17434 // preserve its sugar structure.
17435 } else if (FTy->getReturnType() == RetTy &&
17436 (!NoReturn || FTy->getNoReturnAttr())) {
17437 BlockTy = BSI->FunctionType;
17438
17439 // Otherwise, make the minimal modifications to the function type.
17440 } else {
17443 EPI.TypeQuals = Qualifiers();
17444 EPI.ExtInfo = Ext;
17445 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17446 }
17447
17448 // If we don't have a function type, just build one from nothing.
17449 } else {
17451 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17452 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17453 }
17454
17456 BlockTy = Context.getBlockPointerType(BlockTy);
17457
17458 // If needed, diagnose invalid gotos and switches in the block.
17459 if (getCurFunction()->NeedsScopeChecking() &&
17460 !PP.isCodeCompletionEnabled())
17462
17463 BD->setBody(cast<CompoundStmt>(Body));
17464
17465 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17467
17468 // Try to apply the named return value optimization. We have to check again
17469 // if we can do this, though, because blocks keep return statements around
17470 // to deduce an implicit return type.
17471 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17472 !BD->isDependentContext())
17473 computeNRVO(Body, BSI);
17474
17480
17482
17483 // Set the captured variables on the block.
17485 for (Capture &Cap : BSI->Captures) {
17486 if (Cap.isInvalid() || Cap.isThisCapture())
17487 continue;
17488 // Cap.getVariable() is always a VarDecl because
17489 // blocks cannot capture structured bindings or other ValueDecl kinds.
17490 auto *Var = cast<VarDecl>(Cap.getVariable());
17491 Expr *CopyExpr = nullptr;
17492 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17493 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17494 // The capture logic needs the destructor, so make sure we mark it.
17495 // Usually this is unnecessary because most local variables have
17496 // their destructors marked at declaration time, but parameters are
17497 // an exception because it's technically only the call site that
17498 // actually requires the destructor.
17499 if (isa<ParmVarDecl>(Var))
17501
17502 // Enter a separate potentially-evaluated context while building block
17503 // initializers to isolate their cleanups from those of the block
17504 // itself.
17505 // FIXME: Is this appropriate even when the block itself occurs in an
17506 // unevaluated operand?
17509
17510 SourceLocation Loc = Cap.getLocation();
17511
17513 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17514
17515 // According to the blocks spec, the capture of a variable from
17516 // the stack requires a const copy constructor. This is not true
17517 // of the copy/move done to move a __block variable to the heap.
17518 if (!Result.isInvalid() &&
17519 !Result.get()->getType().isConstQualified()) {
17521 Result.get()->getType().withConst(),
17522 CK_NoOp, VK_LValue);
17523 }
17524
17525 if (!Result.isInvalid()) {
17527 InitializedEntity::InitializeBlock(Var->getLocation(),
17528 Cap.getCaptureType()),
17529 Loc, Result.get());
17530 }
17531
17532 // Build a full-expression copy expression if initialization
17533 // succeeded and used a non-trivial constructor. Recover from
17534 // errors by pretending that the copy isn't necessary.
17535 if (!Result.isInvalid() &&
17536 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17537 ->isTrivial()) {
17539 CopyExpr = Result.get();
17540 }
17541 }
17542 }
17543
17544 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17545 CopyExpr);
17546 Captures.push_back(NewCap);
17547 }
17548 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17549
17550 // Pop the block scope now but keep it alive to the end of this function.
17552 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
17553 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17554
17555 BlockExpr *Result = new (Context)
17556 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17557
17558 // If the block isn't obviously global, i.e. it captures anything at
17559 // all, then we need to do a few things in the surrounding context:
17560 if (Result->getBlockDecl()->hasCaptures()) {
17561 // First, this expression has a new cleanup object.
17562 ExprCleanupObjects.push_back(Result->getBlockDecl());
17563 Cleanup.setExprNeedsCleanups(true);
17564
17565 // It also gets a branch-protected scope if any of the captured
17566 // variables needs destruction.
17567 for (const auto &CI : Result->getBlockDecl()->captures()) {
17568 const VarDecl *var = CI.getVariable();
17569 if (var->getType().isDestructedType() != QualType::DK_none) {
17571 break;
17572 }
17573 }
17574 }
17575
17576 if (getCurFunction())
17577 getCurFunction()->addBlock(BD);
17578
17579 // This can happen if the block's return type is deduced, but
17580 // the return expression is invalid.
17581 if (BD->isInvalidDecl())
17582 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17583 {Result}, Result->getType());
17584 return Result;
17585}
17586
17588 SourceLocation RPLoc) {
17589 TypeSourceInfo *TInfo;
17590 GetTypeFromParser(Ty, &TInfo);
17591 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17592}
17593
17595 Expr *E, TypeSourceInfo *TInfo,
17596 SourceLocation RPLoc) {
17597 Expr *OrigExpr = E;
17599
17600 // CUDA device global function does not support varargs.
17601 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17602 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17605 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17606 }
17607 }
17608
17609 // NVPTX does not support va_arg expression.
17610 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17611 Context.getTargetInfo().getTriple().isNVPTX())
17612 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17613
17614 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17615 // as Microsoft ABI on an actual Microsoft platform, where
17616 // __builtin_ms_va_list and __builtin_va_list are the same.)
17617 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17618 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17619 QualType MSVaListType = Context.getBuiltinMSVaListType();
17620 if (Context.hasSameType(MSVaListType, E->getType())) {
17621 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17622 return ExprError();
17623 VAKind = VAArgExpr::VA_MS;
17624 }
17625 }
17626
17627 // Get the va_list type
17628 QualType VaListType = Context.getBuiltinVaListType();
17629
17630 // It might be a __builtin_zos_va_list!
17631 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinZOSVaList()) {
17632 // E->getType() can be:
17633 // - va_list: equal to array (char*)[2] (inside function)
17634 // - char **: decayed array (va_list passed as parameter)
17635 // We need to check for both cases.
17636 QualType ZOSVaListType = Context.getBuiltinZOSVaListType();
17637 assert(ZOSVaListType->isArrayType() &&
17638 "__builtin_zos_va_list must be an array type");
17639 QualType DecayedType = Context.getArrayDecayedType(ZOSVaListType);
17640 if (Context.hasSameType(ZOSVaListType, E->getType()) ||
17641 Context.hasSameType(DecayedType, E->getType())) {
17642 VAKind = VAArgExpr::VA_ZOS;
17643 VaListType = ZOSVaListType;
17644 }
17645 }
17646
17647 if (VAKind != VAArgExpr::VA_MS) {
17648 if (VaListType->isArrayType()) {
17649 // Deal with implicit array decay; for example, on x86-64,
17650 // va_list is an array, but it's supposed to decay to
17651 // a pointer for va_arg.
17652 VaListType = Context.getArrayDecayedType(VaListType);
17653 // Make sure the input expression also decays appropriately.
17655 if (Result.isInvalid())
17656 return ExprError();
17657 E = Result.get();
17658 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17659 // If va_list is a record type and we are compiling in C++ mode,
17660 // check the argument using reference binding.
17662 Context, Context.getLValueReferenceType(VaListType), false);
17664 if (Init.isInvalid())
17665 return ExprError();
17666 E = Init.getAs<Expr>();
17667 } else {
17668 // Otherwise, the va_list argument must be an l-value because
17669 // it is modified by va_arg.
17670 if (!E->isTypeDependent() &&
17671 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17672 return ExprError();
17673 }
17674 }
17675
17676 if ((VAKind != VAArgExpr::VA_MS) && !E->isTypeDependent() &&
17677 !Context.hasSameType(VaListType, E->getType()))
17678 return ExprError(
17679 Diag(E->getBeginLoc(),
17680 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17681 << OrigExpr->getType() << E->getSourceRange());
17682
17683 if (!TInfo->getType()->isDependentType()) {
17684 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17685 diag::err_second_parameter_to_va_arg_incomplete,
17686 TInfo->getTypeLoc()))
17687 return ExprError();
17688
17690 TInfo->getType(),
17691 diag::err_second_parameter_to_va_arg_abstract,
17692 TInfo->getTypeLoc()))
17693 return ExprError();
17694
17695 if (!TInfo->getType().isPODType(Context)) {
17696 Diag(TInfo->getTypeLoc().getBeginLoc(),
17697 TInfo->getType()->isObjCLifetimeType()
17698 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17699 : diag::warn_second_parameter_to_va_arg_not_pod)
17700 << TInfo->getType()
17701 << TInfo->getTypeLoc().getSourceRange();
17702 }
17703
17704 if (TInfo->getType()->isArrayType()) {
17706 PDiag(diag::warn_second_parameter_to_va_arg_array)
17707 << TInfo->getType()
17708 << TInfo->getTypeLoc().getSourceRange());
17709 }
17710
17711 // Check for va_arg where arguments of the given type will be promoted
17712 // (i.e. this va_arg is guaranteed to have undefined behavior).
17713 QualType PromoteType;
17714 if (Context.isPromotableIntegerType(TInfo->getType())) {
17715 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17716 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17717 // and C23 7.16.1.1p2 says, in part:
17718 // If type is not compatible with the type of the actual next argument
17719 // (as promoted according to the default argument promotions), the
17720 // behavior is undefined, except for the following cases:
17721 // - both types are pointers to qualified or unqualified versions of
17722 // compatible types;
17723 // - one type is compatible with a signed integer type, the other
17724 // type is compatible with the corresponding unsigned integer type,
17725 // and the value is representable in both types;
17726 // - one type is pointer to qualified or unqualified void and the
17727 // other is a pointer to a qualified or unqualified character type;
17728 // - or, the type of the next argument is nullptr_t and type is a
17729 // pointer type that has the same representation and alignment
17730 // requirements as a pointer to a character type.
17731 // Given that type compatibility is the primary requirement (ignoring
17732 // qualifications), you would think we could call typesAreCompatible()
17733 // directly to test this. However, in C++, that checks for *same type*,
17734 // which causes false positives when passing an enumeration type to
17735 // va_arg. Instead, get the underlying type of the enumeration and pass
17736 // that.
17737 QualType UnderlyingType = TInfo->getType();
17738 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17739 UnderlyingType = ED->getIntegerType();
17740 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17741 /*CompareUnqualified*/ true))
17742 PromoteType = QualType();
17743
17744 // If the types are still not compatible, we need to test whether the
17745 // promoted type and the underlying type are the same except for
17746 // signedness. Ask the AST for the correctly corresponding type and see
17747 // if that's compatible.
17748 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17749 PromoteType->isUnsignedIntegerType() !=
17750 UnderlyingType->isUnsignedIntegerType()) {
17751 UnderlyingType =
17752 UnderlyingType->isUnsignedIntegerType()
17753 ? Context.getCorrespondingSignedType(UnderlyingType)
17754 : Context.getCorrespondingUnsignedType(UnderlyingType);
17755 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17756 /*CompareUnqualified*/ true))
17757 PromoteType = QualType();
17758 }
17759 }
17760 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17761 PromoteType = Context.DoubleTy;
17762 if (!PromoteType.isNull())
17764 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17765 << TInfo->getType()
17766 << PromoteType
17767 << TInfo->getTypeLoc().getSourceRange());
17768 }
17769
17771 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, VAKind);
17772}
17773
17775 // The type of __null will be int or long, depending on the size of
17776 // pointers on the target.
17777 QualType Ty;
17778 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17779 if (pw == Context.getTargetInfo().getIntWidth())
17780 Ty = Context.IntTy;
17781 else if (pw == Context.getTargetInfo().getLongWidth())
17782 Ty = Context.LongTy;
17783 else if (pw == Context.getTargetInfo().getLongLongWidth())
17784 Ty = Context.LongLongTy;
17785 else {
17786 llvm_unreachable("I don't know size of pointer!");
17787 }
17788
17789 return new (Context) GNUNullExpr(Ty, TokenLoc);
17790}
17791
17793 CXXRecordDecl *ImplDecl = nullptr;
17794
17795 // Fetch the std::source_location::__impl decl.
17796 if (NamespaceDecl *Std = S.getStdNamespace()) {
17797 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17799 if (S.LookupQualifiedName(ResultSL, Std)) {
17800 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17801 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17803 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17804 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17805 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17806 }
17807 }
17808 }
17809 }
17810
17811 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17812 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17813 return nullptr;
17814 }
17815
17816 // Verify that __impl is a trivial struct type, with no base classes, and with
17817 // only the four expected fields.
17818 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17819 ImplDecl->getNumBases() != 0) {
17820 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17821 return nullptr;
17822 }
17823
17824 unsigned Count = 0;
17825 for (FieldDecl *F : ImplDecl->fields()) {
17826 StringRef Name = F->getName();
17827
17828 if (Name == "_M_file_name") {
17829 if (F->getType() !=
17831 break;
17832 Count++;
17833 } else if (Name == "_M_function_name") {
17834 if (F->getType() !=
17836 break;
17837 Count++;
17838 } else if (Name == "_M_line") {
17839 if (!F->getType()->isIntegerType())
17840 break;
17841 Count++;
17842 } else if (Name == "_M_column") {
17843 if (!F->getType()->isIntegerType())
17844 break;
17845 Count++;
17846 } else {
17847 Count = 100; // invalid
17848 break;
17849 }
17850 }
17851 if (Count != 4) {
17852 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17853 return nullptr;
17854 }
17855
17856 return ImplDecl;
17857}
17858
17860 SourceLocation BuiltinLoc,
17861 SourceLocation RPLoc) {
17862 QualType ResultTy;
17863 switch (Kind) {
17868 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17869 ResultTy =
17870 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17871 break;
17872 }
17875 ResultTy = Context.UnsignedIntTy;
17876 break;
17880 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17882 return ExprError();
17883 }
17884 ResultTy = Context.getPointerType(
17885 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17886 break;
17887 }
17888
17889 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17890}
17891
17893 SourceLocation BuiltinLoc,
17894 SourceLocation RPLoc,
17895 DeclContext *ParentContext) {
17896 return new (Context)
17897 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17898}
17899
17901 StringLiteral *BinaryData, StringRef FileName) {
17903 Data->BinaryData = BinaryData;
17904 Data->FileName = FileName;
17905 return new (Context)
17906 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17907 Data->getDataElementCount());
17908}
17909
17911 const Expr *SrcExpr) {
17912 if (!DstType->isFunctionPointerType() ||
17913 !SrcExpr->getType()->isFunctionType())
17914 return false;
17915
17916 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17917 if (!DRE)
17918 return false;
17919
17920 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17921 if (!FD)
17922 return false;
17923
17925 /*Complain=*/true,
17926 SrcExpr->getBeginLoc());
17927}
17928
17930 SourceLocation Loc,
17931 QualType DstType, QualType SrcType,
17932 Expr *SrcExpr, AssignmentAction Action,
17933 bool *Complained) {
17934 if (Complained)
17935 *Complained = false;
17936
17937 // Decode the result (notice that AST's are still created for extensions).
17938 bool CheckInferredResultType = false;
17939 bool isInvalid = false;
17940 unsigned DiagKind = 0;
17941 ConversionFixItGenerator ConvHints;
17942 bool MayHaveConvFixit = false;
17943 bool MayHaveFunctionDiff = false;
17944 const ObjCInterfaceDecl *IFace = nullptr;
17945 const ObjCProtocolDecl *PDecl = nullptr;
17946
17947 switch (ConvTy) {
17949 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17950 return false;
17952 // Still a valid conversion, but we may want to diagnose for C++
17953 // compatibility reasons.
17954 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17955 break;
17957 if (getLangOpts().CPlusPlus) {
17958 DiagKind = diag::err_typecheck_convert_pointer_int;
17959 isInvalid = true;
17960 } else {
17961 DiagKind = diag::ext_typecheck_convert_pointer_int;
17962 }
17963 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17964 MayHaveConvFixit = true;
17965 break;
17967 if (getLangOpts().CPlusPlus) {
17968 DiagKind = diag::err_typecheck_convert_int_pointer;
17969 isInvalid = true;
17970 } else {
17971 DiagKind = diag::ext_typecheck_convert_int_pointer;
17972 }
17973 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17974 MayHaveConvFixit = true;
17975 break;
17977 DiagKind =
17978 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17979 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17980 MayHaveConvFixit = true;
17981 break;
17983 if (getLangOpts().CPlusPlus) {
17984 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17985 isInvalid = true;
17986 } else {
17987 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17988 }
17989 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17990 MayHaveConvFixit = true;
17991 break;
17994 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17995 } else if (getLangOpts().CPlusPlus) {
17996 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17997 isInvalid = true;
17998 } else {
17999 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
18000 }
18001 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
18002 SrcType->isObjCObjectPointerType();
18003 if (CheckInferredResultType) {
18004 SrcType = SrcType.getUnqualifiedType();
18005 DstType = DstType.getUnqualifiedType();
18006 } else {
18007 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
18008 }
18009 MayHaveConvFixit = true;
18010 break;
18012 if (getLangOpts().CPlusPlus) {
18013 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
18014 isInvalid = true;
18015 } else {
18016 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
18017 }
18018 break;
18020 if (getLangOpts().CPlusPlus) {
18021 DiagKind = diag::err_typecheck_convert_pointer_void_func;
18022 isInvalid = true;
18023 } else {
18024 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
18025 }
18026 break;
18028 // Perform decay if necessary.
18029 if (SrcType->canDecayToPointerType())
18030 SrcType = Context.getDecayedType(SrcType);
18031
18032 isInvalid = true;
18033
18034 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
18035 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
18036 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
18037 DiagKind = diag::err_typecheck_incompatible_address_space;
18038 break;
18039 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
18040 DiagKind = diag::err_typecheck_incompatible_ownership;
18041 break;
18042 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
18043 DiagKind = diag::err_typecheck_incompatible_ptrauth;
18044 break;
18045 }
18046
18047 llvm_unreachable("unknown error case for discarding qualifiers!");
18048 // fallthrough
18049 }
18051 if (SrcType->isArrayType())
18052 SrcType = Context.getArrayDecayedType(SrcType);
18053
18054 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
18055 break;
18057 // If the qualifiers lost were because we were applying the
18058 // (deprecated) C++ conversion from a string literal to a char*
18059 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
18060 // Ideally, this check would be performed in
18061 // checkPointerTypesForAssignment. However, that would require a
18062 // bit of refactoring (so that the second argument is an
18063 // expression, rather than a type), which should be done as part
18064 // of a larger effort to fix checkPointerTypesForAssignment for
18065 // C++ semantics.
18066 if (getLangOpts().CPlusPlus &&
18068 return false;
18069 if (getLangOpts().CPlusPlus) {
18070 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
18071 isInvalid = true;
18072 } else {
18073 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
18074 }
18075
18076 break;
18078 if (getLangOpts().CPlusPlus) {
18079 isInvalid = true;
18080 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
18081 } else {
18082 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
18083 }
18084 break;
18086 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
18087 isInvalid = true;
18088 break;
18090 DiagKind = diag::err_int_to_block_pointer;
18091 isInvalid = true;
18092 break;
18094 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
18095 isInvalid = true;
18096 break;
18098 if (SrcType->isObjCQualifiedIdType()) {
18099 const ObjCObjectPointerType *srcOPT =
18100 SrcType->castAs<ObjCObjectPointerType>();
18101 for (auto *srcProto : srcOPT->quals()) {
18102 PDecl = srcProto;
18103 break;
18104 }
18105 if (const ObjCInterfaceType *IFaceT =
18107 IFace = IFaceT->getDecl();
18108 }
18109 else if (DstType->isObjCQualifiedIdType()) {
18110 const ObjCObjectPointerType *dstOPT =
18111 DstType->castAs<ObjCObjectPointerType>();
18112 for (auto *dstProto : dstOPT->quals()) {
18113 PDecl = dstProto;
18114 break;
18115 }
18116 if (const ObjCInterfaceType *IFaceT =
18118 IFace = IFaceT->getDecl();
18119 }
18120 if (getLangOpts().CPlusPlus) {
18121 DiagKind = diag::err_incompatible_qualified_id;
18122 isInvalid = true;
18123 } else {
18124 DiagKind = diag::warn_incompatible_qualified_id;
18125 }
18126 break;
18127 }
18129 if (getLangOpts().CPlusPlus) {
18130 DiagKind = diag::err_incompatible_vectors;
18131 isInvalid = true;
18132 } else {
18133 DiagKind = diag::warn_incompatible_vectors;
18134 }
18135 break;
18137 DiagKind = diag::err_arc_weak_unavailable_assign;
18138 isInvalid = true;
18139 break;
18141 return false;
18143 assert(!SrcType->isFunctionType() &&
18144 "Unexpected function type found in IncompatibleOBTKinds assignment");
18145 if (SrcType->canDecayToPointerType())
18146 SrcType = Context.getDecayedType(SrcType);
18147
18148 auto getOBTKindName = [](QualType Ty) -> StringRef {
18149 if (Ty->isPointerType())
18150 Ty = Ty->getPointeeType();
18151 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
18152 return OBT->getBehaviorKind() ==
18153 OverflowBehaviorType::OverflowBehaviorKind::Trap
18154 ? "__ob_trap"
18155 : "__ob_wrap";
18156 }
18157 llvm_unreachable("OBT kind unhandled");
18158 };
18159
18160 Diag(Loc, diag::err_incompatible_obt_kinds_assignment)
18161 << DstType << SrcType << getOBTKindName(DstType)
18162 << getOBTKindName(SrcType);
18163 isInvalid = true;
18164 return true;
18165 }
18167 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
18168 if (Complained)
18169 *Complained = true;
18170 return true;
18171 }
18172
18173 DiagKind = diag::err_typecheck_convert_incompatible;
18174 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
18175 MayHaveConvFixit = true;
18176 isInvalid = true;
18177 MayHaveFunctionDiff = true;
18178 break;
18179 }
18180
18181 QualType FirstType, SecondType;
18182 switch (Action) {
18185 // The destination type comes first.
18186 FirstType = DstType;
18187 SecondType = SrcType;
18188 break;
18189
18196 // The source type comes first.
18197 FirstType = SrcType;
18198 SecondType = DstType;
18199 break;
18200 }
18201
18202 PartialDiagnostic FDiag = PDiag(DiagKind);
18203 AssignmentAction ActionForDiag = Action;
18205 ActionForDiag = AssignmentAction::Passing;
18206
18207 FDiag << FirstType << SecondType << ActionForDiag
18208 << SrcExpr->getSourceRange();
18209
18210 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
18211 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
18212 auto isPlainChar = [](const clang::Type *Type) {
18213 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
18214 Type->isSpecificBuiltinType(BuiltinType::Char_U);
18215 };
18216 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
18217 isPlainChar(SecondType->getPointeeOrArrayElementType()));
18218 }
18219
18220 // If we can fix the conversion, suggest the FixIts.
18221 if (!ConvHints.isNull()) {
18222 for (FixItHint &H : ConvHints.Hints)
18223 FDiag << H;
18224 }
18225
18226 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
18227
18228 if (MayHaveFunctionDiff)
18229 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
18230
18231 Diag(Loc, FDiag);
18232 if ((DiagKind == diag::warn_incompatible_qualified_id ||
18233 DiagKind == diag::err_incompatible_qualified_id) &&
18234 PDecl && IFace && !IFace->hasDefinition())
18235 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
18236 << IFace << PDecl;
18237
18238 if (SecondType == Context.OverloadTy)
18240 FirstType, /*TakingAddress=*/true);
18241
18242 if (CheckInferredResultType)
18244
18245 if (Action == AssignmentAction::Returning &&
18248
18249 if (Complained)
18250 *Complained = true;
18251 return isInvalid;
18252}
18253
18255 llvm::APSInt *Result,
18256 AllowFoldKind CanFold) {
18257 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
18258 public:
18259 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
18260 QualType T) override {
18261 return S.Diag(Loc, diag::err_ice_not_integral)
18262 << T << S.LangOpts.CPlusPlus;
18263 }
18264 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18265 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
18266 }
18267 } Diagnoser;
18268
18269 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18270}
18271
18273 llvm::APSInt *Result,
18274 unsigned DiagID,
18275 AllowFoldKind CanFold) {
18276 class IDDiagnoser : public VerifyICEDiagnoser {
18277 unsigned DiagID;
18278
18279 public:
18280 IDDiagnoser(unsigned DiagID)
18281 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
18282
18283 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18284 return S.Diag(Loc, DiagID);
18285 }
18286 } Diagnoser(DiagID);
18287
18288 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18289}
18290
18296
18299 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
18300}
18301
18304 VerifyICEDiagnoser &Diagnoser,
18305 AllowFoldKind CanFold) {
18306 SourceLocation DiagLoc = E->getBeginLoc();
18307
18308 if (getLangOpts().CPlusPlus11) {
18309 // C++11 [expr.const]p5:
18310 // If an expression of literal class type is used in a context where an
18311 // integral constant expression is required, then that class type shall
18312 // have a single non-explicit conversion function to an integral or
18313 // unscoped enumeration type
18314 ExprResult Converted;
18315 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
18316 VerifyICEDiagnoser &BaseDiagnoser;
18317 public:
18318 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
18319 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18320 BaseDiagnoser.Suppress, true),
18321 BaseDiagnoser(BaseDiagnoser) {}
18322
18323 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18324 QualType T) override {
18325 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18326 }
18327
18328 SemaDiagnosticBuilder diagnoseIncomplete(
18329 Sema &S, SourceLocation Loc, QualType T) override {
18330 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
18331 }
18332
18333 SemaDiagnosticBuilder diagnoseExplicitConv(
18334 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18335 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
18336 }
18337
18338 SemaDiagnosticBuilder noteExplicitConv(
18339 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18340 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18341 << ConvTy->isEnumeralType() << ConvTy;
18342 }
18343
18344 SemaDiagnosticBuilder diagnoseAmbiguous(
18345 Sema &S, SourceLocation Loc, QualType T) override {
18346 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
18347 }
18348
18349 SemaDiagnosticBuilder noteAmbiguous(
18350 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18351 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18352 << ConvTy->isEnumeralType() << ConvTy;
18353 }
18354
18355 SemaDiagnosticBuilder diagnoseConversion(
18356 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18357 llvm_unreachable("conversion functions are permitted");
18358 }
18359 } ConvertDiagnoser(Diagnoser);
18360
18361 Converted = PerformContextualImplicitConversion(DiagLoc, E,
18362 ConvertDiagnoser);
18363 if (Converted.isInvalid())
18364 return Converted;
18365 E = Converted.get();
18366 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
18367 // don't try to evaluate it later. We also don't want to return the
18368 // RecoveryExpr here, as it results in this call succeeding, thus callers of
18369 // this function will attempt to use 'Value'.
18370 if (isa<RecoveryExpr>(E))
18371 return ExprError();
18373 return ExprError();
18374 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18375 // An ICE must be of integral or unscoped enumeration type.
18376 if (!Diagnoser.Suppress)
18377 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
18378 << E->getSourceRange();
18379 return ExprError();
18380 }
18381
18382 ExprResult RValueExpr = DefaultLvalueConversion(E);
18383 if (RValueExpr.isInvalid())
18384 return ExprError();
18385
18386 E = RValueExpr.get();
18387
18388 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18389 // in the non-ICE case.
18391
18392 if (!Result)
18393 return E;
18394
18397 if (!isa<ConstantExpr>(E))
18399
18400 if (Notes.empty())
18401 return E;
18402
18403 // If our only note is the usual "invalid subexpression" note, just point
18404 // the caret at its location rather than producing an essentially
18405 // redundant note.
18406 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18407 diag::note_invalid_subexpr_in_const_expr) {
18408 DiagLoc = Notes[0].first;
18409 Notes.clear();
18410 }
18411
18412 if (getLangOpts().CPlusPlus) {
18413 if (!Diagnoser.Suppress) {
18414 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18415 for (const PartialDiagnosticAt &Note : Notes)
18416 Diag(Note.first, Note.second);
18417 }
18418 return ExprError();
18419 }
18420
18421 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18422 for (const PartialDiagnosticAt &Note : Notes)
18423 Diag(Note.first, Note.second);
18424
18425 return E;
18426 }
18427
18428 Expr::EvalResult EvalResult;
18431 EvalResult.Diag = &Notes;
18432 EvalResult.ExtendedDiag = &MSWarning;
18433
18434 // Try to evaluate the expression, and produce diagnostics explaining why it's
18435 // not a constant expression as a side-effect.
18436 EvalProxy SProxy(*this);
18437 bool Folded =
18438 (getLangOpts().CPlusPlus
18439 ? E->EvaluateAsMandatedConstantRValue(EvalResult, Context, SProxy)
18440 : E->EvaluateAsRValue(EvalResult, Context,
18441 /*isConstantContext=*/true)) &&
18442 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18443 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18444
18445 if (Folded && !isa<ConstantExpr>(E))
18446 E = ConstantExpr::Create(Context, E, EvalResult.Val);
18447
18448 // For -fms-compatibility mode we relax some requirements
18449 // for constant folding in non-SFINAE contexts
18450 if (!MSWarning.empty()) {
18451 if (isSFINAEContext()) {
18452 Folded = false;
18453 } else {
18454 for (auto &Info : MSWarning)
18455 Diag(Info.first, Info.second);
18456 }
18457 }
18458
18459 // In C++11, we can rely on diagnostics being produced for any expression
18460 // which is not a constant expression. If no diagnostics were produced, then
18461 // this is a constant expression.
18462 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18463 if (Result)
18464 *Result = EvalResult.Val.getInt();
18465 return E;
18466 }
18467
18468 // If our only note is the usual "invalid subexpression" note, just point
18469 // the caret at its location rather than producing an essentially
18470 // redundant note.
18471 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18472 diag::note_invalid_subexpr_in_const_expr) {
18473 DiagLoc = Notes[0].first;
18474 Notes.clear();
18475 }
18476
18477 if (!Folded || CanFold == AllowFoldKind::No) {
18478 if (!Diagnoser.Suppress) {
18479 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18480 for (const PartialDiagnosticAt &Note : Notes)
18481 Diag(Note.first, Note.second);
18482 }
18483
18484 return ExprError();
18485 }
18486
18487 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18488 for (const PartialDiagnosticAt &Note : Notes)
18489 Diag(Note.first, Note.second);
18490
18491 if (Result)
18492 *Result = EvalResult.Val.getInt();
18493 return E;
18494}
18495
18496namespace {
18497 // Handle the case where we conclude a expression which we speculatively
18498 // considered to be unevaluated is actually evaluated.
18499 class TransformToPE : public TreeTransform<TransformToPE> {
18500 typedef TreeTransform<TransformToPE> BaseTransform;
18501
18502 public:
18503 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18504
18505 // Make sure we redo semantic analysis
18506 bool AlwaysRebuild() { return true; }
18507 bool ReplacingOriginal() { return true; }
18508
18509 // We need to special-case DeclRefExprs referring to FieldDecls which
18510 // are not part of a member pointer formation; normal TreeTransforming
18511 // doesn't catch this case because of the way we represent them in the AST.
18512 // FIXME: This is a bit ugly; is it really the best way to handle this
18513 // case?
18514 //
18515 // Error on DeclRefExprs referring to FieldDecls.
18516 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18517 if (isa<FieldDecl>(E->getDecl()) &&
18518 !SemaRef.isUnevaluatedContext())
18519 return SemaRef.Diag(E->getLocation(),
18520 diag::err_invalid_non_static_member_use)
18521 << E->getDecl() << E->getSourceRange();
18522
18523 return BaseTransform::TransformDeclRefExpr(E);
18524 }
18525
18526 // Exception: filter out member pointer formation
18527 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18528 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18529 return E;
18530
18531 return BaseTransform::TransformUnaryOperator(E);
18532 }
18533
18534 // The body of a lambda-expression is in a separate expression evaluation
18535 // context so never needs to be transformed.
18536 // FIXME: Ideally we wouldn't transform the closure type either, and would
18537 // just recreate the capture expressions and lambda expression.
18538 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18539 return SkipLambdaBody(E, Body);
18540 }
18541 };
18542}
18543
18545 assert(isUnevaluatedContext() &&
18546 "Should only transform unevaluated expressions");
18547 ExprEvalContexts.back().Context =
18548 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18550 return E;
18551 return TransformToPE(*this).TransformExpr(E);
18552}
18553
18555 assert(isUnevaluatedContext() &&
18556 "Should only transform unevaluated expressions");
18559 return TInfo;
18560 return TransformToPE(*this).TransformType(TInfo);
18561}
18562
18563void
18565 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18567 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18568 LambdaContextDecl, ExprContext);
18569
18570 // Discarded statements and immediate contexts nested in other
18571 // discarded statements or immediate context are themselves
18572 // a discarded statement or an immediate context, respectively.
18573 ExprEvalContexts.back().InDiscardedStatement =
18575
18576 // C++23 [expr.const]/p15
18577 // An expression or conversion is in an immediate function context if [...]
18578 // it is a subexpression of a manifestly constant-evaluated expression or
18579 // conversion.
18580 const auto &Prev = parentEvaluationContext();
18581 ExprEvalContexts.back().InImmediateFunctionContext =
18582 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18583
18584 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18585 Prev.InImmediateEscalatingFunctionContext;
18586
18587 Cleanup.reset();
18588 if (!MaybeODRUseExprs.empty())
18589 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18590}
18591
18592void
18596 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18597 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18598}
18599
18601 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18602 // [expr.const]/p14.1
18603 // An expression or conversion is in an immediate function context if it is
18604 // potentially evaluated and either: its innermost enclosing non-block scope
18605 // is a function parameter scope of an immediate function.
18607 FD && FD->isConsteval()
18609 : NewContext);
18613
18614 Current.InDiscardedStatement = false;
18615
18616 if (FD) {
18617
18618 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18619 // context is nested in an immediate function context, so smaller contexts
18620 // that appear inside immediate functions (like variable initializers) are
18621 // considered to be inside an immediate function context even though by
18622 // themselves they are not immediate function contexts. But when a new
18623 // function is entered, we need to reset this tracking, since the entered
18624 // function might be not an immediate function.
18625
18627 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18628
18629 if (isLambdaMethod(FD) && !isLambdaCallOperator(FD))
18630 Current.InImmediateFunctionContext = FD->isConsteval() ||
18631 Parent.isConstantEvaluated() ||
18633 else
18635 }
18636}
18637
18639 TypeSourceInfo *TSI) {
18640 return BuildCXXReflectExpr(CaretCaretLoc, TSI);
18641}
18642
18644 TypeSourceInfo *TSI) {
18645 return CXXReflectExpr::Create(Context, CaretCaretLoc, TSI);
18646}
18647
18648namespace {
18649
18650const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18651 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18652 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18653 if (E->getOpcode() == UO_Deref)
18654 return CheckPossibleDeref(S, E->getSubExpr());
18655 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18656 return CheckPossibleDeref(S, E->getBase());
18657 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18658 return CheckPossibleDeref(S, E->getBase());
18659 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18660 QualType Inner;
18661 QualType Ty = E->getType();
18662 if (const auto *Ptr = Ty->getAs<PointerType>())
18663 Inner = Ptr->getPointeeType();
18664 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18665 Inner = Arr->getElementType();
18666 else
18667 return nullptr;
18668
18669 if (Inner->hasAttr(attr::NoDeref))
18670 return E;
18671 }
18672 return nullptr;
18673}
18674
18675} // namespace
18676
18678 for (const Expr *E : Rec.PossibleDerefs) {
18679 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18680 if (DeclRef) {
18681 const ValueDecl *Decl = DeclRef->getDecl();
18682 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18683 << Decl->getName() << E->getSourceRange();
18684 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18685 } else {
18686 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18687 << E->getSourceRange();
18688 }
18689 }
18690 Rec.PossibleDerefs.clear();
18691}
18692
18695 return;
18696
18697 // Note: ignoring parens here is not justified by the standard rules, but
18698 // ignoring parentheses seems like a more reasonable approach, and this only
18699 // drives a deprecation warning so doesn't affect conformance.
18700 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18701 if (BO->getOpcode() == BO_Assign) {
18702 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18703 llvm::erase(LHSs, BO->getLHS());
18704 }
18705 }
18706}
18707
18709 assert(getLangOpts().CPlusPlus20 &&
18710 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18711 "Cannot mark an immediate escalating expression outside of an "
18712 "immediate escalating context");
18713 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18714 Call && Call->getCallee()) {
18715 if (auto *DeclRef =
18716 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18717 DeclRef->setIsImmediateEscalating(true);
18718 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18719 Ctr->setIsImmediateEscalating(true);
18720 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18721 DeclRef->setIsImmediateEscalating(true);
18722 } else {
18723 assert(false && "expected an immediately escalating expression");
18724 }
18726 FI->FoundImmediateEscalatingExpression = true;
18727}
18728
18730 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18731 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18734 return E;
18735
18736 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18737 /// It's OK if this fails; we'll also remove this in
18738 /// HandleImmediateInvocations, but catching it here allows us to avoid
18739 /// walking the AST looking for it in simple cases.
18740 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18741 if (auto *DeclRef =
18742 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18743 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18744
18745 // C++23 [expr.const]/p16
18746 // An expression or conversion is immediate-escalating if it is not initially
18747 // in an immediate function context and it is [...] an immediate invocation
18748 // that is not a constant expression and is not a subexpression of an
18749 // immediate invocation.
18750 APValue Cached;
18751 auto CheckConstantExpressionAndKeepResult = [&]() {
18752 Expr::EvalResult Eval;
18753 EvalProxy SProxy(*this);
18754 bool Res = E.get()->EvaluateAsMandatedConstantExpr(
18755 Eval, getASTContext(), SProxy, ConstantExprKind::ImmediateInvocation);
18756 if (Res && !Eval.DiagEmitted) {
18757 Cached = std::move(Eval.Val);
18758 return true;
18759 }
18760 return false;
18761 };
18762
18763 if (!E.get()->isValueDependent() &&
18764 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18765 !CheckConstantExpressionAndKeepResult()) {
18767 return E;
18768 }
18769
18770 if (Cleanup.exprNeedsCleanups()) {
18771 // Since an immediate invocation is a full expression itself - it requires
18772 // an additional ExprWithCleanups node, but it can participate to a bigger
18773 // full expression which actually requires cleanups to be run after so
18774 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18775 // may discard cleanups for outer expression too early.
18776
18777 // Note that ExprWithCleanups created here must always have empty cleanup
18778 // objects:
18779 // - compound literals do not create cleanup objects in C++ and immediate
18780 // invocations are C++-only.
18781 // - blocks are not allowed inside constant expressions and compiler will
18782 // issue an error if they appear there.
18783 //
18784 // Hence, in correct code any cleanup objects created inside current
18785 // evaluation context must be outside the immediate invocation.
18787 Cleanup.cleanupsHaveSideEffects(), {});
18788 }
18789
18791 getASTContext(), E.get(),
18792 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18793 getASTContext()),
18794 /*IsImmediateInvocation*/ true);
18795 if (Cached.hasValue())
18796 Res->MoveIntoResult(Cached, getASTContext());
18797 /// Value-dependent constant expressions should not be immediately
18798 /// evaluated until they are instantiated.
18799 if (!Res->isValueDependent())
18800 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18801 return Res;
18802}
18803
18807 Expr::EvalResult Eval;
18808 Eval.Diag = &Notes;
18809 ConstantExpr *CE = Candidate.getPointer();
18810 EvalProxy SProxy(SemaRef);
18811 bool Result =
18813 ConstantExprKind::ImmediateInvocation);
18814 if (!Result || !Notes.empty()) {
18816 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18817 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18818 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18819 FunctionDecl *FD = nullptr;
18820 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18821 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18822 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18823 FD = Call->getConstructor();
18824 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18825 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18826
18827 assert(FD && FD->isImmediateFunction() &&
18828 "could not find an immediate function in this expression");
18829 if (FD->isInvalidDecl())
18830 return;
18831 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18832 << FD << FD->isConsteval();
18833 if (auto Context =
18835 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18836 << Context->Decl;
18837 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18838 }
18839 if (!FD->isConsteval())
18841 for (auto &Note : Notes)
18842 SemaRef.Diag(Note.first, Note.second);
18843 return;
18844 }
18846}
18847
18851 struct ComplexRemove : TreeTransform<ComplexRemove> {
18853 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18856 CurrentII;
18857 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18860 4>::reverse_iterator Current)
18861 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18862 void RemoveImmediateInvocation(ConstantExpr* E) {
18863 auto It = std::find_if(CurrentII, IISet.rend(),
18865 return Elem.getPointer() == E;
18866 });
18867 // It is possible that some subexpression of the current immediate
18868 // invocation was handled from another expression evaluation context. Do
18869 // not handle the current immediate invocation if some of its
18870 // subexpressions failed before.
18871 if (It == IISet.rend()) {
18872 if (SemaRef.FailedImmediateInvocations.contains(E))
18873 CurrentII->setInt(1);
18874 } else {
18875 It->setInt(1); // Mark as deleted
18876 }
18877 }
18878 ExprResult TransformConstantExpr(ConstantExpr *E) {
18879 if (!E->isImmediateInvocation())
18880 return Base::TransformConstantExpr(E);
18881 RemoveImmediateInvocation(E);
18882 return Base::TransformExpr(E->getSubExpr());
18883 }
18884 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18885 /// we need to remove its DeclRefExpr from the DRSet.
18886 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18887 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18888 return Base::TransformCXXOperatorCallExpr(E);
18889 }
18890 /// Base::TransformUserDefinedLiteral doesn't preserve the
18891 /// UserDefinedLiteral node.
18892 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18893 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18894 /// here.
18895 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18896 if (!Init)
18897 return Init;
18898
18899 // We cannot use IgnoreImpCasts because we need to preserve
18900 // full expressions.
18901 while (true) {
18902 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18903 Init = ICE->getSubExpr();
18904 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18905 Init = ICE->getSubExpr();
18906 else
18907 break;
18908 }
18909 /// ConstantExprs are the first layer of implicit node to be removed so if
18910 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18911 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18912 CE && CE->isImmediateInvocation())
18913 RemoveImmediateInvocation(CE);
18914 return Base::TransformInitializer(Init, NotCopyInit);
18915 }
18916 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18917 DRSet.erase(E);
18918 return E;
18919 }
18920 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18921 // Do not rebuild lambdas to avoid creating a new type.
18922 // Lambdas have already been processed inside their eval contexts.
18923 return E;
18924 }
18925
18926 // We do not have enough information to transform opaque expressions and
18927 // assume they do not contain immediate subexpressions.
18928 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18929
18930 bool AlwaysRebuild() { return false; }
18931 bool ReplacingOriginal() { return true; }
18932 bool AllowSkippingCXXConstructExpr() {
18933 bool Res = AllowSkippingFirstCXXConstructExpr;
18934 AllowSkippingFirstCXXConstructExpr = true;
18935 return Res;
18936 }
18937 bool AllowSkippingFirstCXXConstructExpr = true;
18938 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18940
18941 /// CXXConstructExpr with a single argument are getting skipped by
18942 /// TreeTransform in some situtation because they could be implicit. This
18943 /// can only occur for the top-level CXXConstructExpr because it is used
18944 /// nowhere in the expression being transformed therefore will not be rebuilt.
18945 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18946 /// skipping the first CXXConstructExpr.
18947 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18948 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18949
18950 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18951 // The result may not be usable in case of previous compilation errors.
18952 // In this case evaluation of the expression may result in crash so just
18953 // don't do anything further with the result.
18954 if (Res.isUsable()) {
18956 It->getPointer()->setSubExpr(Res.get());
18957 }
18958}
18959
18960static void
18963 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18964 Rec.ReferenceToConsteval.size() == 0) ||
18966 return;
18967
18968 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18969 // [...]
18970 // - the initializer of a variable that is usable in constant expressions or
18971 // has constant initialization.
18972 if (SemaRef.getLangOpts().CPlusPlus23 &&
18973 Rec.ExprContext ==
18975 auto *VD = dyn_cast<VarDecl>(Rec.ManglingContextDecl);
18976 if (VD && (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18977 VD->hasConstantInitialization())) {
18978 // An expression or conversion is in an 'immediate function context' if it
18979 // is potentially evaluated and either:
18980 // [...]
18981 // - it is a subexpression of a manifestly constant-evaluated expression
18982 // or conversion.
18983 return;
18984 }
18985 }
18986
18987 /// When we have more than 1 ImmediateInvocationCandidates or previously
18988 /// failed immediate invocations, we need to check for nested
18989 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18990 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18991 /// invocation.
18992 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18994
18995 /// Prevent sema calls during the tree transform from adding pointers that
18996 /// are already in the sets.
18997 llvm::SaveAndRestore DisableIITracking(
18999
19000 /// Prevent diagnostic during tree transfrom as they are duplicates
19002
19003 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
19004 It != Rec.ImmediateInvocationCandidates.rend(); It++)
19005 if (!It->getInt())
19007 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
19008 Rec.ReferenceToConsteval.size()) {
19009 struct SimpleRemove : DynamicRecursiveASTVisitor {
19010 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
19011 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
19012 bool VisitDeclRefExpr(DeclRefExpr *E) override {
19013 DRSet.erase(E);
19014 return DRSet.size();
19015 }
19016 } Visitor(Rec.ReferenceToConsteval);
19017 Visitor.TraverseStmt(
19018 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
19019 }
19020 for (auto CE : Rec.ImmediateInvocationCandidates)
19021 if (!CE.getInt())
19023 for (auto *DR : Rec.ReferenceToConsteval) {
19024 // If the expression is immediate escalating, it is not an error;
19025 // The outer context itself becomes immediate and further errors,
19026 // if any, will be handled by DiagnoseImmediateEscalatingReason.
19027 if (DR->isImmediateEscalating())
19028 continue;
19029 auto *FD = cast<FunctionDecl>(DR->getDecl());
19030 const NamedDecl *ND = FD;
19031 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
19032 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
19033 ND = MD->getParent();
19034
19035 // C++23 [expr.const]/p16
19036 // An expression or conversion is immediate-escalating if it is not
19037 // initially in an immediate function context and it is [...] a
19038 // potentially-evaluated id-expression that denotes an immediate function
19039 // that is not a subexpression of an immediate invocation.
19040 bool ImmediateEscalating = false;
19041 bool IsPotentiallyEvaluated =
19042 Rec.Context ==
19044 Rec.Context ==
19046 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
19047 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
19048
19050 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
19051 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
19052 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
19053 if (!FD->getBuiltinID())
19054 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
19055 if (auto Context =
19057 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
19058 << Context->Decl;
19059 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
19060 }
19061 if (FD->isImmediateEscalating() && !FD->isConsteval())
19063
19064 } else {
19066 }
19067 }
19068}
19069
19072 if (!Rec.Lambdas.empty()) {
19074 if (!getLangOpts().CPlusPlus20 &&
19075 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
19076 Rec.isUnevaluated() ||
19078 unsigned D;
19079 if (Rec.isUnevaluated()) {
19080 // C++11 [expr.prim.lambda]p2:
19081 // A lambda-expression shall not appear in an unevaluated operand
19082 // (Clause 5).
19083 D = diag::err_lambda_unevaluated_operand;
19084 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
19085 // C++1y [expr.const]p2:
19086 // A conditional-expression e is a core constant expression unless the
19087 // evaluation of e, following the rules of the abstract machine, would
19088 // evaluate [...] a lambda-expression.
19089 D = diag::err_lambda_in_constant_expression;
19090 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
19091 // C++17 [expr.prim.lamda]p2:
19092 // A lambda-expression shall not appear [...] in a template-argument.
19093 D = diag::err_lambda_in_invalid_context;
19094 } else
19095 llvm_unreachable("Couldn't infer lambda error message.");
19096
19097 for (const auto *L : Rec.Lambdas)
19098 Diag(L->getBeginLoc(), D);
19099 }
19100 }
19101
19102 // Append the collected materialized temporaries into previous context before
19103 // exit if the previous also is a lifetime extending context.
19105 parentEvaluationContext().InLifetimeExtendingContext &&
19106 !Rec.ForRangeLifetimeExtendTemps.empty()) {
19109 }
19110
19112 HandleImmediateInvocations(*this, Rec);
19113
19114 // Warn on any volatile-qualified simple-assignments that are not discarded-
19115 // value expressions nor unevaluated operands (those cases get removed from
19116 // this list by CheckUnusedVolatileAssignment).
19117 for (auto *BO : Rec.VolatileAssignmentLHSs)
19118 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
19119 << BO->getType();
19120
19121 // When are coming out of an unevaluated context, clear out any
19122 // temporaries that we may have created as part of the evaluation of
19123 // the expression in that context: they aren't relevant because they
19124 // will never be constructed.
19125 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
19127 ExprCleanupObjects.end());
19128 Cleanup = Rec.ParentCleanup;
19131 // Otherwise, merge the contexts together.
19132 } else {
19133 Cleanup.mergeFrom(Rec.ParentCleanup);
19134 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
19135 }
19136
19138
19139 // Pop the current expression evaluation context off the stack.
19140 ExprEvalContexts.pop_back();
19141}
19142
19144 ExprCleanupObjects.erase(
19145 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
19146 ExprCleanupObjects.end());
19147 Cleanup.reset();
19148 MaybeODRUseExprs.clear();
19149}
19150
19153 if (Result.isInvalid())
19154 return ExprError();
19155 E = Result.get();
19156 if (!E->getType()->isVariablyModifiedType())
19157 return E;
19159}
19160
19161/// Are we in a context that is potentially constant evaluated per C++20
19162/// [expr.const]p12?
19164 /// C++2a [expr.const]p12:
19165 // An expression or conversion is potentially constant evaluated if it is
19166 switch (SemaRef.ExprEvalContexts.back().Context) {
19169
19170 // -- a manifestly constant-evaluated expression,
19174 // -- a potentially-evaluated expression,
19176 // -- an immediate subexpression of a braced-init-list,
19177
19178 // -- [FIXME] an expression of the form & cast-expression that occurs
19179 // within a templated entity
19180 // -- a subexpression of one of the above that is not a subexpression of
19181 // a nested unevaluated operand.
19182 return true;
19183
19186 // Expressions in this context are never evaluated.
19187 return false;
19188 }
19189 llvm_unreachable("Invalid context");
19190}
19191
19192/// Return true if this function has a calling convention that requires mangling
19193/// in the size of the parameter pack.
19195 // These manglings are only applicable for targets whcih use Microsoft
19196 // mangling scheme for C.
19198 return false;
19199
19200 // If this is C++ and this isn't an extern "C" function, parameters do not
19201 // need to be complete. In this case, C++ mangling will apply, which doesn't
19202 // use the size of the parameters.
19203 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
19204 return false;
19205
19206 // Stdcall, fastcall, and vectorcall need this special treatment.
19207 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19208 switch (CC) {
19209 case CC_X86StdCall:
19210 case CC_X86FastCall:
19211 case CC_X86VectorCall:
19212 return true;
19213 default:
19214 break;
19215 }
19216 return false;
19217}
19218
19219/// Require that all of the parameter types of function be complete. Normally,
19220/// parameter types are only required to be complete when a function is called
19221/// or defined, but to mangle functions with certain calling conventions, the
19222/// mangler needs to know the size of the parameter list. In this situation,
19223/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
19224/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
19225/// result in a linker error. Clang doesn't implement this behavior, and instead
19226/// attempts to error at compile time.
19228 SourceLocation Loc) {
19229 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
19230 FunctionDecl *FD;
19231 ParmVarDecl *Param;
19232
19233 public:
19234 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
19235 : FD(FD), Param(Param) {}
19236
19237 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19238 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19239 StringRef CCName;
19240 switch (CC) {
19241 case CC_X86StdCall:
19242 CCName = "stdcall";
19243 break;
19244 case CC_X86FastCall:
19245 CCName = "fastcall";
19246 break;
19247 case CC_X86VectorCall:
19248 CCName = "vectorcall";
19249 break;
19250 default:
19251 llvm_unreachable("CC does not need mangling");
19252 }
19253
19254 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
19255 << Param->getDeclName() << FD->getDeclName() << CCName;
19256 }
19257 };
19258
19259 for (ParmVarDecl *Param : FD->parameters()) {
19260 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
19261 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
19262 }
19263}
19264
19265namespace {
19266enum class OdrUseContext {
19267 /// Declarations in this context are not odr-used.
19268 None,
19269 /// Declarations in this context are formally odr-used, but this is a
19270 /// dependent context.
19271 Dependent,
19272 /// Declarations in this context are odr-used but not actually used (yet).
19273 FormallyOdrUsed,
19274 /// Declarations in this context are used.
19275 Used
19276};
19277}
19278
19279/// Are we within a context in which references to resolved functions or to
19280/// variables result in odr-use?
19281static OdrUseContext isOdrUseContext(Sema &SemaRef) {
19284
19285 if (Context.isUnevaluated())
19286 return OdrUseContext::None;
19287
19289 return OdrUseContext::Dependent;
19290
19291 if (Context.isDiscardedStatementContext())
19292 return OdrUseContext::FormallyOdrUsed;
19293
19294 else if (Context.Context ==
19296 return OdrUseContext::FormallyOdrUsed;
19297
19298 return OdrUseContext::Used;
19299}
19300
19302 if (!Func->isConstexpr())
19303 return false;
19304
19305 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
19306 return true;
19307
19308 // Lambda conversion operators are never user provided.
19309 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
19310 return isLambdaConversionOperator(Conv);
19311
19312 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
19313 return CCD && CCD->getInheritedConstructor();
19314}
19315
19317 bool MightBeOdrUse) {
19318 assert(Func && "No function?");
19319
19320 Func->setReferenced();
19321
19322 // Recursive functions aren't really used until they're used from some other
19323 // context.
19324 bool IsRecursiveCall = CurContext == Func;
19325
19326 // C++11 [basic.def.odr]p3:
19327 // A function whose name appears as a potentially-evaluated expression is
19328 // odr-used if it is the unique lookup result or the selected member of a
19329 // set of overloaded functions [...].
19330 //
19331 // We (incorrectly) mark overload resolution as an unevaluated context, so we
19332 // can just check that here.
19333 OdrUseContext OdrUse =
19334 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
19335 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
19336 OdrUse = OdrUseContext::FormallyOdrUsed;
19337
19338 // Trivial default constructors and destructors are never actually used.
19339 // FIXME: What about other special members?
19340 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
19341 OdrUse == OdrUseContext::Used) {
19342 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
19343 if (Constructor->isDefaultConstructor())
19344 OdrUse = OdrUseContext::FormallyOdrUsed;
19346 OdrUse = OdrUseContext::FormallyOdrUsed;
19347 }
19348
19349 // C++20 [expr.const]p12:
19350 // A function [...] is needed for constant evaluation if it is [...] a
19351 // constexpr function that is named by an expression that is potentially
19352 // constant evaluated
19353 bool NeededForConstantEvaluation =
19356
19357 // Determine whether we require a function definition to exist, per
19358 // C++11 [temp.inst]p3:
19359 // Unless a function template specialization has been explicitly
19360 // instantiated or explicitly specialized, the function template
19361 // specialization is implicitly instantiated when the specialization is
19362 // referenced in a context that requires a function definition to exist.
19363 // C++20 [temp.inst]p7:
19364 // The existence of a definition of a [...] function is considered to
19365 // affect the semantics of the program if the [...] function is needed for
19366 // constant evaluation by an expression
19367 // C++20 [basic.def.odr]p10:
19368 // Every program shall contain exactly one definition of every non-inline
19369 // function or variable that is odr-used in that program outside of a
19370 // discarded statement
19371 // C++20 [special]p1:
19372 // The implementation will implicitly define [defaulted special members]
19373 // if they are odr-used or needed for constant evaluation.
19374 //
19375 // Note that we skip the implicit instantiation of templates that are only
19376 // used in unused default arguments or by recursive calls to themselves.
19377 // This is formally non-conforming, but seems reasonable in practice.
19378 bool NeedDefinition =
19379 !IsRecursiveCall &&
19380 (OdrUse == OdrUseContext::Used ||
19381 (NeededForConstantEvaluation && !Func->isPureVirtual()));
19382
19383 // C++14 [temp.expl.spec]p6:
19384 // If a template [...] is explicitly specialized then that specialization
19385 // shall be declared before the first use of that specialization that would
19386 // cause an implicit instantiation to take place, in every translation unit
19387 // in which such a use occurs
19388 if (NeedDefinition &&
19389 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
19390 Func->getMemberSpecializationInfo()))
19392
19393 if (getLangOpts().CUDA)
19394 CUDA().CheckCall(Loc, Func);
19395
19396 // If we need a definition, try to create one.
19397 if (NeedDefinition && !Func->getBody()) {
19400 dyn_cast<CXXConstructorDecl>(Func)) {
19402 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19403 if (Constructor->isDefaultConstructor()) {
19404 if (Constructor->isTrivial() &&
19405 !Constructor->hasAttr<DLLExportAttr>())
19406 return;
19408 } else if (Constructor->isCopyConstructor()) {
19410 } else if (Constructor->isMoveConstructor()) {
19412 }
19413 } else if (Constructor->getInheritedConstructor()) {
19415 }
19416 } else if (CXXDestructorDecl *Destructor =
19417 dyn_cast<CXXDestructorDecl>(Func)) {
19419 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19420 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19421 return;
19423 }
19424 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19425 MarkVTableUsed(Loc, Destructor->getParent());
19426 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
19427 if (MethodDecl->isOverloadedOperator() &&
19428 MethodDecl->getOverloadedOperator() == OO_Equal) {
19429 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
19430 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19431 if (MethodDecl->isCopyAssignmentOperator())
19432 DefineImplicitCopyAssignment(Loc, MethodDecl);
19433 else if (MethodDecl->isMoveAssignmentOperator())
19434 DefineImplicitMoveAssignment(Loc, MethodDecl);
19435 }
19436 } else if (isa<CXXConversionDecl>(MethodDecl) &&
19437 MethodDecl->getParent()->isLambda()) {
19438 CXXConversionDecl *Conversion =
19439 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
19440 if (Conversion->isLambdaToBlockPointerConversion())
19442 else
19444 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19445 MarkVTableUsed(Loc, MethodDecl->getParent());
19446 }
19447
19448 if (Func->isDefaulted() && !Func->isDeleted()) {
19450 Func->getDefaultedFunctionKind();
19451 if (DFK.isComparison())
19453 else if (DFK.isPostfixOperator())
19455 }
19456
19457 // Implicit instantiation of function templates and member functions of
19458 // class templates.
19459 if (Func->isImplicitlyInstantiable()) {
19461 Func->getTemplateSpecializationKindForInstantiation();
19462 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19463 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19464 if (FirstInstantiation) {
19465 PointOfInstantiation = Loc;
19466 if (auto *MSI = Func->getMemberSpecializationInfo())
19467 MSI->setPointOfInstantiation(Loc);
19468 // FIXME: Notify listener.
19469 else
19470 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19471 } else if (TSK != TSK_ImplicitInstantiation) {
19472 // Use the point of use as the point of instantiation, instead of the
19473 // point of explicit instantiation (which we track as the actual point
19474 // of instantiation). This gives better backtraces in diagnostics.
19475 PointOfInstantiation = Loc;
19476 }
19477
19478 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19479 Func->isConstexpr()) {
19480 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19481 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19482 CodeSynthesisContexts.size())
19484 std::make_pair(Func, PointOfInstantiation));
19485 else if (Func->isConstexpr())
19486 // Do not defer instantiations of constexpr functions, to avoid the
19487 // expression evaluator needing to call back into Sema if it sees a
19488 // call to such a function.
19489 InstantiateFunctionDefinition(PointOfInstantiation, Func);
19490 else {
19491 Func->setInstantiationIsPending(true);
19492 PendingInstantiations.push_back(
19493 std::make_pair(Func, PointOfInstantiation));
19494 if (llvm::isTimeTraceVerbose()) {
19495 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
19496 std::string Name;
19497 llvm::raw_string_ostream OS(Name);
19498 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
19499 /*Qualified=*/true);
19500 return Name;
19501 });
19502 }
19503 // Notify the consumer that a function was implicitly instantiated.
19504 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
19505 }
19506 }
19507 } else {
19508 // Walk redefinitions, as some of them may be instantiable.
19509 for (auto *i : Func->redecls()) {
19510 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19511 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19512 }
19513 }
19514 });
19515 }
19516
19517 // If a constructor was defined in the context of a default parameter
19518 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19519 // context), its initializers may not be referenced yet.
19520 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19522 *this,
19523 Constructor->isImmediateFunction()
19526 Constructor);
19527 for (CXXCtorInitializer *Init : Constructor->inits()) {
19528 if (Init->isInClassMemberInitializer())
19529 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19530 MarkDeclarationsReferencedInExpr(Init->getInit());
19531 });
19532 }
19533 }
19534
19535 // C++14 [except.spec]p17:
19536 // An exception-specification is considered to be needed when:
19537 // - the function is odr-used or, if it appears in an unevaluated operand,
19538 // would be odr-used if the expression were potentially-evaluated;
19539 //
19540 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19541 // function is a pure virtual function we're calling, and in that case the
19542 // function was selected by overload resolution and we need to resolve its
19543 // exception specification for a different reason.
19544 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19546 ResolveExceptionSpec(Loc, FPT);
19547
19548 // A callee could be called by a host function then by a device function.
19549 // If we only try recording once, we will miss recording the use on device
19550 // side. Therefore keep trying until it is recorded.
19551 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19552 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19554
19555 // If this is the first "real" use, act on that.
19556 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19557 // Keep track of used but undefined functions.
19558 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19559 if (mightHaveNonExternalLinkage(Func))
19560 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19561 else if (Func->getMostRecentDecl()->isInlined() &&
19562 !LangOpts.GNUInline &&
19563 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19564 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19566 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19567 }
19568
19569 // Some x86 Windows calling conventions mangle the size of the parameter
19570 // pack into the name. Computing the size of the parameters requires the
19571 // parameter types to be complete. Check that now.
19574
19575 // In the MS C++ ABI, the compiler emits destructor variants where they are
19576 // used. If the destructor is used here but defined elsewhere, mark the
19577 // virtual base destructors referenced. If those virtual base destructors
19578 // are inline, this will ensure they are defined when emitting the complete
19579 // destructor variant. This checking may be redundant if the destructor is
19580 // provided later in this TU.
19581 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19582 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19583 CXXRecordDecl *Parent = Dtor->getParent();
19584 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19586 }
19587 }
19588
19589 Func->markUsed(Context);
19590 }
19591}
19592
19593/// Directly mark a variable odr-used. Given a choice, prefer to use
19594/// MarkVariableReferenced since it does additional checks and then
19595/// calls MarkVarDeclODRUsed.
19596/// If the variable must be captured:
19597/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19598/// - else capture it in the DeclContext that maps to the
19599/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19600static void
19602 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19603 // Keep track of used but undefined variables.
19604 // FIXME: We shouldn't suppress this warning for static data members.
19605 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19606 assert(Var && "expected a capturable variable");
19607
19609 (!Var->isExternallyVisible() || Var->isInline() ||
19611 !(Var->isStaticDataMember() && Var->hasInit())) {
19613 if (old.isInvalid())
19614 old = Loc;
19615 }
19616 QualType CaptureType, DeclRefType;
19617 if (SemaRef.LangOpts.OpenMP)
19620 /*EllipsisLoc*/ SourceLocation(),
19621 /*BuildAndDiagnose*/ true, CaptureType,
19622 DeclRefType, FunctionScopeIndexToStopAt);
19623
19624 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19625 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19626 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
19627 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
19628 if (VarTarget == SemaCUDA::CVT_Host &&
19629 (UserTarget == CUDAFunctionTarget::Device ||
19630 UserTarget == CUDAFunctionTarget::HostDevice ||
19631 UserTarget == CUDAFunctionTarget::Global)) {
19632 // Diagnose ODR-use of host global variables in device functions.
19633 // Reference of device global variables in host functions is allowed
19634 // through shadow variables therefore it is not diagnosed.
19635 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19636 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19637 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19639 Var->getType().isConstQualified()
19640 ? diag::note_cuda_const_var_unpromoted
19641 : diag::note_cuda_host_var);
19642 }
19643 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19644 // Also capture __device__ const variables, which are classified
19645 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19646 // an explicit CUDADeviceAttr to distinguish them from plain
19647 // const variables (no __device__), which also get CVT_Both but
19648 // only have an implicit CUDADeviceAttr.
19649 (VarTarget == SemaCUDA::CVT_Both &&
19650 Var->hasAttr<CUDADeviceAttr>() &&
19651 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19652 !Var->hasAttr<CUDASharedAttr>() &&
19653 (UserTarget == CUDAFunctionTarget::Host ||
19654 UserTarget == CUDAFunctionTarget::HostDevice)) {
19655 // Record a CUDA/HIP device side variable if it is ODR-used
19656 // by host code. This is done conservatively, when the variable is
19657 // referenced in any of the following contexts:
19658 // - a non-function context
19659 // - a host function
19660 // - a host device function
19661 // This makes the ODR-use of the device side variable by host code to
19662 // be visible in the device compilation for the compiler to be able to
19663 // emit template variables instantiated by host code only and to
19664 // externalize the static device side variable ODR-used by host code.
19665 if (!Var->hasExternalStorage())
19667 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19668 (!FD || (!FD->getDescribedFunctionTemplate() &&
19672 }
19673 }
19674
19675 V->markUsed(SemaRef.Context);
19676}
19677
19679 SourceLocation Loc,
19680 unsigned CapturingScopeIndex) {
19681 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19682}
19683
19685 SourceLocation loc,
19686 ValueDecl *var) {
19687 DeclContext *VarDC =
19688 var->getDeclContext()->getEnclosingNonExpansionStatementContext();
19689
19690 // If the parameter still belongs to the translation unit, then
19691 // we're actually just using one parameter in the declaration of
19692 // the next.
19693 if (isa<ParmVarDecl>(var) &&
19695 return;
19696
19697 // For C code, don't diagnose about capture if we're not actually in code
19698 // right now; it's impossible to write a non-constant expression outside of
19699 // function context, so we'll get other (more useful) diagnostics later.
19700 //
19701 // For C++, things get a bit more nasty... it would be nice to suppress this
19702 // diagnostic for certain cases like using a local variable in an array bound
19703 // for a member of a local class, but the correct predicate is not obvious.
19704 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19705 return;
19706
19707 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19708 unsigned ContextKind = 3; // unknown
19709 if (isa<CXXMethodDecl>(VarDC) &&
19710 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19711 ContextKind = 2;
19712 } else if (isa<FunctionDecl>(VarDC)) {
19713 ContextKind = 0;
19714 } else if (isa<BlockDecl>(VarDC)) {
19715 ContextKind = 1;
19716 }
19717
19718 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19719 << var << ValueKind << ContextKind << VarDC;
19720 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19721 << var;
19722
19723 // FIXME: Add additional diagnostic info about class etc. which prevents
19724 // capture.
19725}
19726
19728 ValueDecl *Var,
19729 bool &SubCapturesAreNested,
19730 QualType &CaptureType,
19731 QualType &DeclRefType) {
19732 // Check whether we've already captured it.
19733 if (CSI->CaptureMap.count(Var)) {
19734 // If we found a capture, any subcaptures are nested.
19735 SubCapturesAreNested = true;
19736
19737 // Retrieve the capture type for this variable.
19738 CaptureType = CSI->getCapture(Var).getCaptureType();
19739
19740 // Compute the type of an expression that refers to this variable.
19741 DeclRefType = CaptureType.getNonReferenceType();
19742
19743 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19744 // are mutable in the sense that user can change their value - they are
19745 // private instances of the captured declarations.
19746 const Capture &Cap = CSI->getCapture(Var);
19747 // C++ [expr.prim.lambda]p10:
19748 // The type of such a data member is [...] an lvalue reference to the
19749 // referenced function type if the entity is a reference to a function.
19750 // [...]
19751 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19752 !(isa<LambdaScopeInfo>(CSI) &&
19753 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19755 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19756 DeclRefType.addConst();
19757 return true;
19758 }
19759 return false;
19760}
19761
19762// Only block literals, captured statements, and lambda expressions can
19763// capture; other scopes don't work.
19765 ValueDecl *Var,
19766 SourceLocation Loc,
19767 const bool Diagnose,
19768 Sema &S) {
19771
19772 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19773 if (Underlying) {
19774 if (Underlying->hasLocalStorage() && Diagnose)
19776 }
19777 return nullptr;
19778}
19779
19780// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19781// certain types of variables (unnamed, variably modified types etc.)
19782// so check for eligibility.
19784 SourceLocation Loc, const bool Diagnose,
19785 Sema &S) {
19786
19787 assert((isa<VarDecl, BindingDecl>(Var)) &&
19788 "Only variables and structured bindings can be captured");
19789
19790 bool IsBlock = isa<BlockScopeInfo>(CSI);
19791 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19792
19793 // Reject bindings referenced from a lambda or block that wraps an OpenMP
19794 // region.
19795 if ((IsLambda || IsBlock) && S.getLangOpts().OpenMP &&
19797 if (Diagnose)
19798 S.Diag(Loc, diag::err_omp_unsupported_on_binding) << 3;
19799 return false;
19800 }
19801
19802 // Lambdas are not allowed to capture unnamed variables
19803 // (e.g. anonymous unions).
19804 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19805 // assuming that's the intent.
19806 if (IsLambda && !Var->getDeclName()) {
19807 if (Diagnose) {
19808 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19809 S.Diag(Var->getLocation(), diag::note_declared_at);
19810 }
19811 return false;
19812 }
19813
19814 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19815 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19816 if (Diagnose) {
19817 S.Diag(Loc, diag::err_ref_vm_type);
19818 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19819 }
19820 return false;
19821 }
19822 // Prohibit structs with flexible array members too.
19823 // We cannot capture what is in the tail end of the struct.
19824 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19825 VTD && VTD->hasFlexibleArrayMember()) {
19826 if (Diagnose) {
19827 if (IsBlock)
19828 S.Diag(Loc, diag::err_ref_flexarray_type);
19829 else
19830 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19831 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19832 }
19833 return false;
19834 }
19835 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19836 // Lambdas and captured statements are not allowed to capture __block
19837 // variables; they don't support the expected semantics.
19838 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19839 if (Diagnose) {
19840 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19841 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19842 }
19843 return false;
19844 }
19845 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19846 if (S.getLangOpts().OpenCL && IsBlock &&
19847 Var->getType()->isBlockPointerType()) {
19848 if (Diagnose)
19849 S.Diag(Loc, diag::err_opencl_block_ref_block);
19850 return false;
19851 }
19852
19853 if (auto *BD = dyn_cast<BindingDecl>(Var)) {
19854 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19855 if (RSI->CapRegionKind == CR_OpenMP) {
19856 if (BD->getHoldingVar()) {
19857 if (Diagnose) {
19858 S.Diag(Loc, diag::err_capture_tuple_binding_openmp) << Var;
19859 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19860 }
19861 return false;
19862 }
19863 if (Diagnose && S.getLangOpts().CPlusPlus) {
19864 S.DiagCompat(Loc, diag_compat::capture_binding) << Var;
19865 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19866 }
19867 return true;
19868 }
19869 }
19870 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19871 if (Diagnose)
19873 return false;
19874 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19875 S.DiagCompat(Loc, diag_compat::capture_binding) << Var;
19876 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19877 }
19878 }
19879
19880 return true;
19881}
19882
19883// Returns true if the capture by block was successful.
19885 SourceLocation Loc, const bool BuildAndDiagnose,
19886 QualType &CaptureType, QualType &DeclRefType,
19887 const bool Nested, Sema &S, bool Invalid) {
19888 bool ByRef = false;
19889
19890 // Blocks are not allowed to capture arrays, excepting OpenCL.
19891 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19892 // (decayed to pointers).
19893 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19894 if (BuildAndDiagnose) {
19895 S.Diag(Loc, diag::err_ref_array_type);
19896 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19897 Invalid = true;
19898 } else {
19899 return false;
19900 }
19901 }
19902
19903 // Forbid the block-capture of autoreleasing variables.
19904 if (!Invalid &&
19906 if (BuildAndDiagnose) {
19907 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19908 << /*block*/ 0;
19909 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19910 Invalid = true;
19911 } else {
19912 return false;
19913 }
19914 }
19915
19916 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19917 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19918 QualType PointeeTy = PT->getPointeeType();
19919
19920 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19922 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19923 if (BuildAndDiagnose) {
19924 SourceLocation VarLoc = Var->getLocation();
19925 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19926 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19927 }
19928 }
19929 }
19930
19931 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19932 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19933 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19934 // Block capture by reference does not change the capture or
19935 // declaration reference types.
19936 ByRef = true;
19937 } else {
19938 // Block capture by copy introduces 'const'.
19939 CaptureType = CaptureType.getNonReferenceType().withConst();
19940 DeclRefType = CaptureType;
19941 }
19942
19943 // Actually capture the variable.
19944 if (BuildAndDiagnose)
19945 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19946 CaptureType, Invalid);
19947
19948 return !Invalid;
19949}
19950
19951/// Capture the given variable in the captured region.
19954 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19955 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19956 Sema &S, bool Invalid) {
19957 // By default, capture variables by reference.
19958 bool ByRef = true;
19959 bool IsBindingDecl = isa<BindingDecl>(Var);
19960 ValueDecl *DSAVar = Var;
19961 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19962 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19963 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19964 // Using an LValue reference type is consistent with Lambdas (see below).
19965 if (VarDecl *VD = S.OpenMP().isOpenMPCapturedDecl(Var)) {
19966 Var = VD; // Capture the DecompositionDecl.
19967 bool HasConst = DeclRefType.isConstQualified();
19968 // Note: DeclRefType should remain the BindingDecl's type (e.g., int),
19969 // not the DecompositionDecl's type (e.g., Point). The variable being
19970 // captured is the DecompositionDecl, but expressions still reference
19971 // the individual binding's type.
19972 DeclRefType = DeclRefType.getUnqualifiedType();
19973 // Don't lose diagnostics about assignments to const.
19974 if (HasConst)
19975 DeclRefType.addConst();
19976 }
19977 // Do not capture firstprivates in tasks. For bindings the DSA is on the
19978 // binding, not on the DecompositionDecl; the task firstprivate path still
19979 // needs the DecompositionDecl capture, so skip only private.
19981 IsBindingDecl ? DSAVar : Var, RSI->OpenMPLevel,
19982 RSI->OpenMPCaptureLevel);
19983 if (IsBindingDecl ? PrivateKind == OMPC_private
19984 : PrivateKind != OMPC_unknown)
19985 return true;
19986 ByRef = S.OpenMP().isOpenMPCapturedByRef(DSAVar, RSI->OpenMPLevel,
19987 RSI->OpenMPCaptureLevel);
19988 // Bindings share the DecompositionDecl storage; a second capture with
19989 // a different capture kind is not representable.
19990 if (BuildAndDiagnose && IsBindingDecl) {
19991 unsigned Idx = RSI->CaptureMap.lookup(Var);
19992 if (Idx != 0 && RSI->Captures[Idx - 1].isReferenceCapture() != ByRef) {
19993 S.Diag(Loc,
19994 diag::err_omp_decomposition_bindings_different_capture_kinds)
19995 << DSAVar;
19996 return false;
19997 }
19998 }
19999 }
20000
20001 if (ByRef)
20002 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
20003 else
20004 CaptureType = DeclRefType;
20005
20006 // Actually capture the variable.
20007 if (BuildAndDiagnose)
20008 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
20009 Loc, SourceLocation(), CaptureType, Invalid);
20010
20011 if (BuildAndDiagnose && IsBindingDecl)
20012 // Key the binding to its own capture entry so repeated uses hit the
20013 // already-captured path.
20014 RSI->CaptureMap[DSAVar] = RSI->Captures.size();
20015
20016 return !Invalid;
20017}
20018
20019/// Capture the given variable in the lambda.
20021 SourceLocation Loc, const bool BuildAndDiagnose,
20022 QualType &CaptureType, QualType &DeclRefType,
20023 const bool RefersToCapturedVariable,
20024 const TryCaptureKind Kind,
20025 SourceLocation EllipsisLoc, const bool IsTopScope,
20026 Sema &S, bool Invalid) {
20027 // Determine whether we are capturing by reference or by value.
20028 bool ByRef = false;
20029 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
20030 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
20031 } else {
20032 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
20033 }
20034
20035 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
20037 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
20038 Invalid = true;
20039 }
20040
20041 // Compute the type of the field that will capture this variable.
20042 if (ByRef) {
20043 // C++11 [expr.prim.lambda]p15:
20044 // An entity is captured by reference if it is implicitly or
20045 // explicitly captured but not captured by copy. It is
20046 // unspecified whether additional unnamed non-static data
20047 // members are declared in the closure type for entities
20048 // captured by reference.
20049 //
20050 // FIXME: It is not clear whether we want to build an lvalue reference
20051 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
20052 // to do the former, while EDG does the latter. Core issue 1249 will
20053 // clarify, but for now we follow GCC because it's a more permissive and
20054 // easily defensible position.
20055 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
20056 } else {
20057 // C++11 [expr.prim.lambda]p14:
20058 // For each entity captured by copy, an unnamed non-static
20059 // data member is declared in the closure type. The
20060 // declaration order of these members is unspecified. The type
20061 // of such a data member is the type of the corresponding
20062 // captured entity if the entity is not a reference to an
20063 // object, or the referenced type otherwise. [Note: If the
20064 // captured entity is a reference to a function, the
20065 // corresponding data member is also a reference to a
20066 // function. - end note ]
20067 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
20068 if (!RefType->getPointeeType()->isFunctionType())
20069 CaptureType = RefType->getPointeeType();
20070 }
20071
20072 // Forbid the lambda copy-capture of autoreleasing variables.
20073 if (!Invalid &&
20075 if (BuildAndDiagnose) {
20076 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
20077 S.Diag(Var->getLocation(), diag::note_previous_decl)
20078 << Var->getDeclName();
20079 Invalid = true;
20080 } else {
20081 return false;
20082 }
20083 }
20084
20085 // Make sure that by-copy captures are of a complete and non-abstract type.
20086 if (!Invalid && BuildAndDiagnose) {
20087 if (!CaptureType->isDependentType() &&
20089 Loc, CaptureType,
20090 diag::err_capture_of_incomplete_or_sizeless_type,
20091 Var->getDeclName()))
20092 Invalid = true;
20093 else if (S.RequireNonAbstractType(Loc, CaptureType,
20094 diag::err_capture_of_abstract_type))
20095 Invalid = true;
20096 }
20097 }
20098
20099 // Compute the type of a reference to this captured variable.
20100 if (ByRef)
20101 DeclRefType = CaptureType.getNonReferenceType();
20102 else {
20103 // C++ [expr.prim.lambda]p5:
20104 // The closure type for a lambda-expression has a public inline
20105 // function call operator [...]. This function call operator is
20106 // declared const (9.3.1) if and only if the lambda-expression's
20107 // parameter-declaration-clause is not followed by mutable.
20108 DeclRefType = CaptureType.getNonReferenceType();
20109 bool Const = LSI->lambdaCaptureShouldBeConst();
20110 // C++ [expr.prim.lambda]p10:
20111 // The type of such a data member is [...] an lvalue reference to the
20112 // referenced function type if the entity is a reference to a function.
20113 // [...]
20114 if (Const && !CaptureType->isReferenceType() &&
20115 !DeclRefType->isFunctionType())
20116 DeclRefType.addConst();
20117 }
20118
20119 // Add the capture.
20120 if (BuildAndDiagnose)
20121 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
20122 Loc, EllipsisLoc, CaptureType, Invalid);
20123
20124 return !Invalid;
20125}
20126
20128 const ASTContext &Context) {
20129 // Offer a Copy fix even if the type is dependent.
20130 if (Var->getType()->isDependentType())
20131 return true;
20133 if (T.isTriviallyCopyableType(Context))
20134 return true;
20135 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
20136
20137 if (!(RD = RD->getDefinition()))
20138 return false;
20139 if (RD->hasSimpleCopyConstructor())
20140 return true;
20141 if (RD->hasUserDeclaredCopyConstructor())
20142 for (CXXConstructorDecl *Ctor : RD->ctors())
20143 if (Ctor->isCopyConstructor())
20144 return !Ctor->isDeleted();
20145 }
20146 return false;
20147}
20148
20149/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
20150/// default capture. Fixes may be omitted if they aren't allowed by the
20151/// standard, for example we can't emit a default copy capture fix-it if we
20152/// already explicitly copy capture capture another variable.
20154 ValueDecl *Var) {
20156 // Don't offer Capture by copy of default capture by copy fixes if Var is
20157 // known not to be copy constructible.
20158 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
20159
20160 SmallString<32> FixBuffer;
20161 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
20162 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
20163 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
20164 if (ShouldOfferCopyFix) {
20165 // Offer fixes to insert an explicit capture for the variable.
20166 // [] -> [VarName]
20167 // [OtherCapture] -> [OtherCapture, VarName]
20168 FixBuffer.assign({Separator, Var->getName()});
20169 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
20170 << Var << /*value*/ 0
20171 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
20172 }
20173 // As above but capture by reference.
20174 FixBuffer.assign({Separator, "&", Var->getName()});
20175 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
20176 << Var << /*reference*/ 1
20177 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
20178 }
20179
20180 // Only try to offer default capture if there are no captures excluding this
20181 // and init captures.
20182 // [this]: OK.
20183 // [X = Y]: OK.
20184 // [&A, &B]: Don't offer.
20185 // [A, B]: Don't offer.
20186 if (llvm::any_of(LSI->Captures, [](Capture &C) {
20187 return !C.isThisCapture() && !C.isInitCapture();
20188 }))
20189 return;
20190
20191 // The default capture specifiers, '=' or '&', must appear first in the
20192 // capture body.
20193 SourceLocation DefaultInsertLoc =
20195
20196 if (ShouldOfferCopyFix) {
20197 bool CanDefaultCopyCapture = true;
20198 // [=, *this] OK since c++17
20199 // [=, this] OK since c++20
20200 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
20201 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
20203 : false;
20204 // We can't use default capture by copy if any captures already specified
20205 // capture by copy.
20206 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
20207 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
20208 })) {
20209 FixBuffer.assign({"=", Separator});
20210 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
20211 << /*value*/ 0
20212 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
20213 }
20214 }
20215
20216 // We can't use default capture by reference if any captures already specified
20217 // capture by reference.
20218 if (llvm::none_of(LSI->Captures, [](Capture &C) {
20219 return !C.isInitCapture() && C.isReferenceCapture() &&
20220 !C.isThisCapture();
20221 })) {
20222 FixBuffer.assign({"&", Separator});
20223 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
20224 << /*reference*/ 1
20225 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
20226 }
20227}
20228
20230 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
20231 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
20232 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
20233 // An init-capture is notionally from the context surrounding its
20234 // declaration, but its parent DC is the lambda class.
20235 DeclContext *VarDC =
20237 DeclContext *DC = CurContext;
20238
20239 // Skip past RequiresExprBodys because they don't constitute function scopes.
20240 while (DC->isRequiresExprBody() || DC->isExpansionStmt())
20241 DC = DC->getParent();
20242
20243 // tryCaptureVariable is called every time a DeclRef is formed,
20244 // it can therefore have non-negigible impact on performances.
20245 // For local variables and when there is no capturing scope,
20246 // we can bailout early.
20247 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
20248 return true;
20249
20250 // Exception: Function parameters are not tied to the function's DeclContext
20251 // until we enter the function definition. Capturing them anyway would result
20252 // in an out-of-bounds error while traversing DC and its parents.
20253 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
20254 return true;
20255
20256 const auto *VD = dyn_cast<VarDecl>(Var);
20257 if (VD) {
20258 if (VD->isInitCapture())
20259 VarDC = VarDC->getParent();
20260 } else {
20262 }
20263 assert(VD && "Cannot capture a null variable");
20264
20265 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
20266 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
20267 // We need to sync up the Declaration Context with the
20268 // FunctionScopeIndexToStopAt
20269 if (FunctionScopeIndexToStopAt) {
20270 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
20271 unsigned FSIndex = FunctionScopes.size() - 1;
20272 // When we're parsing the lambda parameter list, the current DeclContext is
20273 // NOT the lambda but its parent. So move away the current LSI before
20274 // aligning DC and FunctionScopeIndexToStopAt.
20275 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
20276 FSIndex && LSI && !LSI->AfterParameterList)
20277 --FSIndex;
20278 assert(MaxFunctionScopesIndex <= FSIndex &&
20279 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
20280 "FunctionScopes.");
20281 while (FSIndex != MaxFunctionScopesIndex) {
20283 --FSIndex;
20284 }
20285 }
20286
20287 // Capture global variables if it is required to use private copy of this
20288 // variable.
20289 bool IsGlobal = !VD->hasLocalStorage();
20290 if (IsGlobal && !(LangOpts.OpenMP &&
20291 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
20292 MaxFunctionScopesIndex)))
20293 return true;
20294
20295 if (isa<VarDecl>(Var))
20296 Var = cast<VarDecl>(Var->getCanonicalDecl());
20297
20298 // Walk up the stack to determine whether we can capture the variable,
20299 // performing the "simple" checks that don't depend on type. We stop when
20300 // we've either hit the declared scope of the variable or find an existing
20301 // capture of that variable. We start from the innermost capturing-entity
20302 // (the DC) and ensure that all intervening capturing-entities
20303 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
20304 // declcontext can either capture the variable or have already captured
20305 // the variable.
20306 CaptureType = Var->getType();
20307 DeclRefType = CaptureType.getNonReferenceType();
20308 bool Nested = false;
20309 bool Explicit = (Kind != TryCaptureKind::Implicit);
20310 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
20311 do {
20312
20313 LambdaScopeInfo *LSI = nullptr;
20314 if (!FunctionScopes.empty())
20315 LSI = dyn_cast_or_null<LambdaScopeInfo>(
20316 FunctionScopes[FunctionScopesIndex]);
20317
20318 bool IsInScopeDeclarationContext =
20319 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
20320
20321 if (LSI && !LSI->AfterParameterList) {
20322 // This allows capturing parameters from a default value which does not
20323 // seems correct
20324 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
20325 return true;
20326 }
20327 // If the variable is declared in the current context, there is no need to
20328 // capture it.
20329 if (IsInScopeDeclarationContext &&
20330 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
20331 return true;
20332
20333 // Only block literals, captured statements, and lambda expressions can
20334 // capture; other scopes don't work.
20335 DeclContext *ParentDC =
20336 !IsInScopeDeclarationContext
20337 ? DC->getParent()
20338 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
20339 BuildAndDiagnose, *this);
20340 // We need to check for the parent *first* because, if we *have*
20341 // private-captured a global variable, we need to recursively capture it in
20342 // intermediate blocks, lambdas, etc.
20343 if (!ParentDC) {
20344 if (IsGlobal) {
20345 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
20346 break;
20347 }
20348 return true;
20349 }
20350
20351 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
20353
20354 // Check whether we've already captured it.
20355 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
20356 DeclRefType)) {
20357 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
20358 break;
20359 }
20360
20361 // When evaluating some attributes (like enable_if) we might refer to a
20362 // function parameter appertaining to the same declaration as that
20363 // attribute.
20364 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
20365 Parm && Parm->getDeclContext() == DC)
20366 return true;
20367
20368 // If we are instantiating a generic lambda call operator body,
20369 // we do not want to capture new variables. What was captured
20370 // during either a lambdas transformation or initial parsing
20371 // should be used.
20373 if (BuildAndDiagnose) {
20376 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
20377 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
20378 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
20379 buildLambdaCaptureFixit(*this, LSI, Var);
20380 } else
20382 }
20383 return true;
20384 }
20385
20386 // Try to capture variable-length arrays types.
20387 if (Var->getType()->isVariablyModifiedType()) {
20388 // We're going to walk down into the type and look for VLA
20389 // expressions.
20390 QualType QTy = Var->getType();
20391 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
20392 QTy = PVD->getOriginalType();
20394 }
20395
20396 if (getLangOpts().OpenMP) {
20397 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20398 // OpenMP private variables should not be captured in outer scope, so
20399 // just break here. Similarly, global variables that are captured in a
20400 // target region should not be captured outside the scope of the region.
20401 if (RSI->CapRegionKind == CR_OpenMP) {
20402 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
20403 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
20404 // If the variable is private (i.e. not captured) and has variably
20405 // modified type, we still need to capture the type for correct
20406 // codegen in all regions, associated with the construct. Currently,
20407 // it is captured in the innermost captured region only.
20408 if (IsOpenMPPrivateDecl != OMPC_unknown &&
20409 Var->getType()->isVariablyModifiedType()) {
20410 QualType QTy = Var->getType();
20411 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
20412 QTy = PVD->getOriginalType();
20413 for (int I = 1,
20414 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
20415 I < E; ++I) {
20416 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
20417 FunctionScopes[FunctionScopesIndex - I]);
20418 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
20419 "Wrong number of captured regions associated with the "
20420 "OpenMP construct.");
20421 captureVariablyModifiedType(Context, QTy, OuterRSI);
20422 }
20423 }
20424 bool IsTargetCap =
20425 IsOpenMPPrivateDecl != OMPC_private &&
20426 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
20427 RSI->OpenMPCaptureLevel);
20428 // Do not capture global if it is not privatized in outer regions.
20429 bool IsGlobalCap =
20430 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
20431 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
20432
20433 // When we detect target captures we are looking from inside the
20434 // target region, therefore we need to propagate the capture from the
20435 // enclosing region. Therefore, the capture is not initially nested.
20436 if (IsTargetCap)
20437 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
20438 RSI->OpenMPLevel);
20439
20440 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
20441 (IsGlobal && !IsGlobalCap)) {
20442 Nested = !IsTargetCap;
20443 bool HasConst = DeclRefType.isConstQualified();
20444 DeclRefType = DeclRefType.getUnqualifiedType();
20445 // Don't lose diagnostics about assignments to const.
20446 if (HasConst)
20447 DeclRefType.addConst();
20448 CaptureType = Context.getLValueReferenceType(DeclRefType);
20449 break;
20450 }
20451 }
20452 }
20453 }
20455 // No capture-default, and this is not an explicit capture
20456 // so cannot capture this variable.
20457 if (BuildAndDiagnose) {
20458 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
20459 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
20460 auto *LSI = cast<LambdaScopeInfo>(CSI);
20461 if (LSI->Lambda) {
20462 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
20463 buildLambdaCaptureFixit(*this, LSI, Var);
20464 }
20465 // FIXME: If we error out because an outer lambda can not implicitly
20466 // capture a variable that an inner lambda explicitly captures, we
20467 // should have the inner lambda do the explicit capture - because
20468 // it makes for cleaner diagnostics later. This would purely be done
20469 // so that the diagnostic does not misleadingly claim that a variable
20470 // can not be captured by a lambda implicitly even though it is captured
20471 // explicitly. Suggestion:
20472 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20473 // at the function head
20474 // - cache the StartingDeclContext - this must be a lambda
20475 // - captureInLambda in the innermost lambda the variable.
20476 }
20477 return true;
20478 }
20479 Explicit = false;
20480 FunctionScopesIndex--;
20481 if (IsInScopeDeclarationContext)
20482 DC = ParentDC;
20483 } while (!VarDC->Equals(DC));
20484
20485 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20486 // computing the type of the capture at each step, checking type-specific
20487 // requirements, and adding captures if requested.
20488 // If the variable had already been captured previously, we start capturing
20489 // at the lambda nested within that one.
20490 bool Invalid = false;
20491 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20492 ++I) {
20494
20495 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20496 // certain types of variables (unnamed, variably modified types etc.)
20497 // so check for eligibility.
20498 if (!Invalid)
20499 Invalid =
20500 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
20501
20502 // After encountering an error, if we're actually supposed to capture, keep
20503 // capturing in nested contexts to suppress any follow-on diagnostics.
20504 if (Invalid && !BuildAndDiagnose)
20505 return true;
20506
20507 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
20508 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20509 DeclRefType, Nested, *this, Invalid);
20510 Nested = true;
20511 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20513 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
20514 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
20515 Nested = true;
20516 } else {
20518 Invalid =
20519 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20520 DeclRefType, Nested, Kind, EllipsisLoc,
20521 /*IsTopScope*/ I == N - 1, *this, Invalid);
20522 Nested = true;
20523 }
20524
20525 if (Invalid && !BuildAndDiagnose)
20526 return true;
20527 }
20528 return Invalid;
20529}
20530
20532 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20533 QualType CaptureType;
20534 QualType DeclRefType;
20535 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
20536 /*BuildAndDiagnose=*/true, CaptureType,
20537 DeclRefType, nullptr);
20538}
20539
20541 QualType CaptureType;
20542 QualType DeclRefType;
20543 return !tryCaptureVariable(
20545 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
20546}
20547
20549 assert(Var && "Null value cannot be captured");
20550
20551 QualType CaptureType;
20552 QualType DeclRefType;
20553
20554 // Determine whether we can capture this variable.
20556 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20557 nullptr))
20558 return QualType();
20559
20560 return DeclRefType;
20561}
20562
20563namespace {
20564// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20565// The produced TemplateArgumentListInfo* points to data stored within this
20566// object, so should only be used in contexts where the pointer will not be
20567// used after the CopiedTemplateArgs object is destroyed.
20568class CopiedTemplateArgs {
20569 bool HasArgs;
20570 TemplateArgumentListInfo TemplateArgStorage;
20571public:
20572 template<typename RefExpr>
20573 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20574 if (HasArgs)
20575 E->copyTemplateArgumentsInto(TemplateArgStorage);
20576 }
20577 operator TemplateArgumentListInfo*()
20578#ifdef __has_cpp_attribute
20579#if __has_cpp_attribute(clang::lifetimebound)
20580 [[clang::lifetimebound]]
20581#endif
20582#endif
20583 {
20584 return HasArgs ? &TemplateArgStorage : nullptr;
20585 }
20586};
20587}
20588
20589/// Walk the set of potential results of an expression and mark them all as
20590/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20591///
20592/// \return A new expression if we found any potential results, ExprEmpty() if
20593/// not, and ExprError() if we diagnosed an error.
20595 NonOdrUseReason NOUR) {
20596 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20597 // an object that satisfies the requirements for appearing in a
20598 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20599 // is immediately applied." This function handles the lvalue-to-rvalue
20600 // conversion part.
20601 //
20602 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20603 // transform it into the relevant kind of non-odr-use node and rebuild the
20604 // tree of nodes leading to it.
20605 //
20606 // This is a mini-TreeTransform that only transforms a restricted subset of
20607 // nodes (and only certain operands of them).
20608
20609 // Rebuild a subexpression.
20610 auto Rebuild = [&](Expr *Sub) {
20611 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20612 };
20613
20614 // Check whether a potential result satisfies the requirements of NOUR.
20615 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20616 // Any entity other than a VarDecl is always odr-used whenever it's named
20617 // in a potentially-evaluated expression.
20618 auto *VD = dyn_cast<VarDecl>(D);
20619 if (!VD)
20620 return true;
20621
20622 // C++2a [basic.def.odr]p4:
20623 // A variable x whose name appears as a potentially-evalauted expression
20624 // e is odr-used by e unless
20625 // -- x is a reference that is usable in constant expressions, or
20626 // -- x is a variable of non-reference type that is usable in constant
20627 // expressions and has no mutable subobjects, and e is an element of
20628 // the set of potential results of an expression of
20629 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20630 // conversion is applied, or
20631 // -- x is a variable of non-reference type, and e is an element of the
20632 // set of potential results of a discarded-value expression to which
20633 // the lvalue-to-rvalue conversion is not applied
20634 //
20635 // We check the first bullet and the "potentially-evaluated" condition in
20636 // BuildDeclRefExpr. We check the type requirements in the second bullet
20637 // in CheckLValueToRValueConversionOperand below.
20638 switch (NOUR) {
20639 case NOUR_None:
20640 case NOUR_Unevaluated:
20641 llvm_unreachable("unexpected non-odr-use-reason");
20642
20643 case NOUR_Constant:
20644 // Constant references were handled when they were built.
20645 if (VD->getType()->isReferenceType())
20646 return true;
20647 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20648 if (RD->hasDefinition() && RD->hasMutableFields())
20649 return true;
20650 if (!VD->isUsableInConstantExpressions(S.Context))
20651 return true;
20652 break;
20653
20654 case NOUR_Discarded:
20655 if (VD->getType()->isReferenceType())
20656 return true;
20657 break;
20658 }
20659 return false;
20660 };
20661
20662 // Check whether this expression may be odr-used in CUDA/HIP.
20663 auto MaybeCUDAODRUsed = [&]() -> bool {
20664 if (!S.LangOpts.CUDA)
20665 return false;
20666 LambdaScopeInfo *LSI = S.getCurLambda();
20667 if (!LSI)
20668 return false;
20669 auto *DRE = dyn_cast<DeclRefExpr>(E);
20670 if (!DRE)
20671 return false;
20672 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
20673 if (!VD)
20674 return false;
20675 return LSI->CUDAPotentialODRUsedVars.count(VD);
20676 };
20677
20678 // Mark that this expression does not constitute an odr-use.
20679 auto MarkNotOdrUsed = [&] {
20680 if (!MaybeCUDAODRUsed()) {
20681 S.MaybeODRUseExprs.remove(E);
20682 if (LambdaScopeInfo *LSI = S.getCurLambda())
20683 LSI->markVariableExprAsNonODRUsed(E);
20684 }
20685 };
20686
20687 // C++2a [basic.def.odr]p2:
20688 // The set of potential results of an expression e is defined as follows:
20689 switch (E->getStmtClass()) {
20690 // -- If e is an id-expression, ...
20691 case Expr::DeclRefExprClass: {
20692 auto *DRE = cast<DeclRefExpr>(E);
20693 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20694 break;
20695
20696 // Rebuild as a non-odr-use DeclRefExpr.
20697 MarkNotOdrUsed();
20698 return DeclRefExpr::Create(
20699 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20700 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20701 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20702 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20703 }
20704
20705 case Expr::FunctionParmPackExprClass: {
20706 auto *FPPE = cast<FunctionParmPackExpr>(E);
20707 // If any of the declarations in the pack is odr-used, then the expression
20708 // as a whole constitutes an odr-use.
20709 for (ValueDecl *D : *FPPE)
20710 if (IsPotentialResultOdrUsed(D))
20711 return ExprEmpty();
20712
20713 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20714 // nothing cares about whether we marked this as an odr-use, but it might
20715 // be useful for non-compiler tools.
20716 MarkNotOdrUsed();
20717 break;
20718 }
20719
20720 // -- If e is a subscripting operation with an array operand...
20721 case Expr::ArraySubscriptExprClass: {
20722 auto *ASE = cast<ArraySubscriptExpr>(E);
20723 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20724 if (!OldBase->getType()->isArrayType())
20725 break;
20726 ExprResult Base = Rebuild(OldBase);
20727 if (!Base.isUsable())
20728 return Base;
20729 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20730 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20731 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20732 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20733 ASE->getRBracketLoc());
20734 }
20735
20736 case Expr::MemberExprClass: {
20737 auto *ME = cast<MemberExpr>(E);
20738 // -- If e is a class member access expression [...] naming a non-static
20739 // data member...
20740 if (isa<FieldDecl>(ME->getMemberDecl())) {
20741 ExprResult Base = Rebuild(ME->getBase());
20742 if (!Base.isUsable())
20743 return Base;
20744 return MemberExpr::Create(
20745 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20746 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20747 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20748 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20749 ME->getObjectKind(), ME->isNonOdrUse());
20750 }
20751
20752 if (ME->getMemberDecl()->isCXXInstanceMember())
20753 break;
20754
20755 // -- If e is a class member access expression naming a static data member,
20756 // ...
20757 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20758 break;
20759
20760 // Rebuild as a non-odr-use MemberExpr.
20761 MarkNotOdrUsed();
20762 return MemberExpr::Create(
20763 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20764 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20765 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20766 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20767 }
20768
20769 case Expr::BinaryOperatorClass: {
20770 auto *BO = cast<BinaryOperator>(E);
20771 Expr *LHS = BO->getLHS();
20772 Expr *RHS = BO->getRHS();
20773 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20774 if (BO->getOpcode() == BO_PtrMemD) {
20775 ExprResult Sub = Rebuild(LHS);
20776 if (!Sub.isUsable())
20777 return Sub;
20778 BO->setLHS(Sub.get());
20779 // -- If e is a comma expression, ...
20780 } else if (BO->getOpcode() == BO_Comma) {
20781 ExprResult Sub = Rebuild(RHS);
20782 if (!Sub.isUsable())
20783 return Sub;
20784 BO->setRHS(Sub.get());
20785 } else {
20786 break;
20787 }
20788 return ExprResult(BO);
20789 }
20790
20791 // -- If e has the form (e1)...
20792 case Expr::ParenExprClass: {
20793 auto *PE = cast<ParenExpr>(E);
20794 ExprResult Sub = Rebuild(PE->getSubExpr());
20795 if (!Sub.isUsable())
20796 return Sub;
20797 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20798 }
20799
20800 // -- If e is a glvalue conditional expression, ...
20801 // We don't apply this to a binary conditional operator. FIXME: Should we?
20802 case Expr::ConditionalOperatorClass: {
20803 auto *CO = cast<ConditionalOperator>(E);
20804 ExprResult LHS = Rebuild(CO->getLHS());
20805 if (LHS.isInvalid())
20806 return ExprError();
20807 ExprResult RHS = Rebuild(CO->getRHS());
20808 if (RHS.isInvalid())
20809 return ExprError();
20810 if (!LHS.isUsable() && !RHS.isUsable())
20811 return ExprEmpty();
20812 if (!LHS.isUsable())
20813 LHS = CO->getLHS();
20814 if (!RHS.isUsable())
20815 RHS = CO->getRHS();
20816 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20817 CO->getCond(), LHS.get(), RHS.get());
20818 }
20819
20820 // [Clang extension]
20821 // -- If e has the form __extension__ e1...
20822 case Expr::UnaryOperatorClass: {
20823 auto *UO = cast<UnaryOperator>(E);
20824 if (UO->getOpcode() != UO_Extension)
20825 break;
20826 ExprResult Sub = Rebuild(UO->getSubExpr());
20827 if (!Sub.isUsable())
20828 return Sub;
20829 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20830 Sub.get());
20831 }
20832
20833 // [Clang extension]
20834 // -- If e has the form _Generic(...), the set of potential results is the
20835 // union of the sets of potential results of the associated expressions.
20836 case Expr::GenericSelectionExprClass: {
20837 auto *GSE = cast<GenericSelectionExpr>(E);
20838
20839 SmallVector<Expr *, 4> AssocExprs;
20840 bool AnyChanged = false;
20841 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20842 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20843 if (AssocExpr.isInvalid())
20844 return ExprError();
20845 if (AssocExpr.isUsable()) {
20846 AssocExprs.push_back(AssocExpr.get());
20847 AnyChanged = true;
20848 } else {
20849 AssocExprs.push_back(OrigAssocExpr);
20850 }
20851 }
20852
20853 void *ExOrTy = nullptr;
20854 bool IsExpr = GSE->isExprPredicate();
20855 if (IsExpr)
20856 ExOrTy = GSE->getControllingExpr();
20857 else
20858 ExOrTy = GSE->getControllingType();
20859 return AnyChanged ? S.CreateGenericSelectionExpr(
20860 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20861 GSE->getRParenLoc(), IsExpr, ExOrTy,
20862 GSE->getAssocTypeSourceInfos(), AssocExprs)
20863 : ExprEmpty();
20864 }
20865
20866 // [Clang extension]
20867 // -- If e has the form __builtin_choose_expr(...), the set of potential
20868 // results is the union of the sets of potential results of the
20869 // second and third subexpressions.
20870 case Expr::ChooseExprClass: {
20871 auto *CE = cast<ChooseExpr>(E);
20872
20873 ExprResult LHS = Rebuild(CE->getLHS());
20874 if (LHS.isInvalid())
20875 return ExprError();
20876
20877 ExprResult RHS = Rebuild(CE->getLHS());
20878 if (RHS.isInvalid())
20879 return ExprError();
20880
20881 if (!LHS.get() && !RHS.get())
20882 return ExprEmpty();
20883 if (!LHS.isUsable())
20884 LHS = CE->getLHS();
20885 if (!RHS.isUsable())
20886 RHS = CE->getRHS();
20887
20888 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20889 RHS.get(), CE->getRParenLoc());
20890 }
20891
20892 // Step through non-syntactic nodes.
20893 case Expr::ConstantExprClass: {
20894 auto *CE = cast<ConstantExpr>(E);
20895 ExprResult Sub = Rebuild(CE->getSubExpr());
20896 if (!Sub.isUsable())
20897 return Sub;
20898 return ConstantExpr::Create(S.Context, Sub.get());
20899 }
20900
20901 // We could mostly rely on the recursive rebuilding to rebuild implicit
20902 // casts, but not at the top level, so rebuild them here.
20903 case Expr::ImplicitCastExprClass: {
20904 auto *ICE = cast<ImplicitCastExpr>(E);
20905 // Only step through the narrow set of cast kinds we expect to encounter.
20906 // Anything else suggests we've left the region in which potential results
20907 // can be found.
20908 switch (ICE->getCastKind()) {
20909 case CK_NoOp:
20910 case CK_DerivedToBase:
20911 case CK_UncheckedDerivedToBase: {
20912 ExprResult Sub = Rebuild(ICE->getSubExpr());
20913 if (!Sub.isUsable())
20914 return Sub;
20915 CXXCastPath Path(ICE->path());
20916 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20917 ICE->getValueKind(), &Path);
20918 }
20919
20920 default:
20921 break;
20922 }
20923 break;
20924 }
20925
20926 default:
20927 break;
20928 }
20929
20930 // Can't traverse through this node. Nothing to do.
20931 return ExprEmpty();
20932}
20933
20935 // Check whether the operand is or contains an object of non-trivial C union
20936 // type.
20937 if (E->getType().isVolatileQualified() &&
20943
20944 // C++2a [basic.def.odr]p4:
20945 // [...] an expression of non-volatile-qualified non-class type to which
20946 // the lvalue-to-rvalue conversion is applied [...]
20947 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20948 return E;
20949
20952 if (Result.isInvalid())
20953 return ExprError();
20954 return Result.get() ? Result : E;
20955}
20956
20958 if (!Res.isUsable())
20959 return Res;
20960
20961 // If a constant-expression is a reference to a variable where we delay
20962 // deciding whether it is an odr-use, just assume we will apply the
20963 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20964 // (a non-type template argument), we have special handling anyway.
20966}
20967
20969 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20970 // call.
20971 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20972 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20973
20974 for (Expr *E : LocalMaybeODRUseExprs) {
20975 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20976 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20977 DRE->getLocation(), *this);
20978 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20979 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20980 *this);
20981 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20982 for (ValueDecl *VD : *FP)
20983 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20984 } else {
20985 llvm_unreachable("Unexpected expression");
20986 }
20987 }
20988
20989 assert(MaybeODRUseExprs.empty() &&
20990 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20991}
20992
20994 ValueDecl *Var, Expr *E) {
20996 if (!VD)
20997 return;
20998
20999 const bool RefersToEnclosingScope =
21000 (SemaRef.CurContext != VD->getDeclContext() &&
21002 if (RefersToEnclosingScope) {
21003 LambdaScopeInfo *const LSI =
21004 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
21005 if (LSI && (!LSI->CallOperator ||
21006 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
21007 // If a variable could potentially be odr-used, defer marking it so
21008 // until we finish analyzing the full expression for any
21009 // lvalue-to-rvalue
21010 // or discarded value conversions that would obviate odr-use.
21011 // Add it to the list of potential captures that will be analyzed
21012 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
21013 // unless the variable is a reference that was initialized by a constant
21014 // expression (this will never need to be captured or odr-used).
21015 //
21016 // FIXME: We can simplify this a lot after implementing P0588R1.
21017 assert(E && "Capture variable should be used in an expression.");
21018 if (!Var->getType()->isReferenceType() ||
21021 }
21022 }
21023}
21024
21026 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
21027 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
21028 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
21030 "Invalid Expr argument to DoMarkVarDeclReferenced");
21031 Var->setReferenced();
21032
21033 if (Var->isInvalidDecl())
21034 return;
21035
21036 auto *MSI = Var->getMemberSpecializationInfo();
21037 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
21039
21040 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
21041 bool UsableInConstantExpr =
21043
21044 // Only track variables with internal linkage or local scope.
21045 // Use canonical decl so in-class declarations and out-of-class definitions
21046 // of static data members in anonymous namespaces are tracked as a single
21047 // entry.
21048 const VarDecl *CanonVar = Var->getCanonicalDecl();
21049 if ((CanonVar->isLocalVarDeclOrParm() ||
21050 CanonVar->isInternalLinkageFileVar()) &&
21051 !CanonVar->hasExternalStorage()) {
21052 RefsMinusAssignments.insert({CanonVar, 0}).first->getSecond()++;
21053 }
21054
21055 // C++20 [expr.const]p12:
21056 // A variable [...] is needed for constant evaluation if it is [...] a
21057 // variable whose name appears as a potentially constant evaluated
21058 // expression that is either a contexpr variable or is of non-volatile
21059 // const-qualified integral type or of reference type
21060 bool NeededForConstantEvaluation =
21061 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
21062
21063 bool NeedDefinition =
21064 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
21065 (TSK != clang::TSK_Undeclared && Var->getType()->isUndeducedType());
21066
21068 "Can't instantiate a partial template specialization.");
21069
21070 // If this might be a member specialization of a static data member, check
21071 // the specialization is visible. We already did the checks for variable
21072 // template specializations when we created them.
21073 if (NeedDefinition && TSK != TSK_Undeclared &&
21076
21077 // Perform implicit instantiation of static data members, static data member
21078 // templates of class templates, and variable template specializations. Delay
21079 // instantiations of variable templates, except for those that could be used
21080 // in a constant expression.
21081 if (NeedDefinition && isTemplateInstantiation(TSK)) {
21082 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
21083 // instantiation declaration if a variable is usable in a constant
21084 // expression (among other cases).
21085 bool TryInstantiating =
21087 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
21088
21089 if (TryInstantiating) {
21090 SourceLocation PointOfInstantiation =
21091 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
21092 bool FirstInstantiation = PointOfInstantiation.isInvalid();
21093 if (FirstInstantiation) {
21094 PointOfInstantiation = Loc;
21095 if (MSI)
21096 MSI->setPointOfInstantiation(PointOfInstantiation);
21097 // FIXME: Notify listener.
21098 else
21099 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
21100 }
21101
21102 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
21103 // Do not defer instantiations of variables that could be used in a
21104 // constant expression.
21105 // The type deduction also needs a complete initializer.
21106 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
21107 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
21108 });
21109
21110 // The size of an incomplete array type can be updated by
21111 // instantiating the initializer. The DeclRefExpr's type should be
21112 // updated accordingly too, or users of it would be confused!
21113 if (E)
21115
21116 // Re-set the member to trigger a recomputation of the dependence bits
21117 // for the expression.
21118 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
21119 DRE->setDecl(DRE->getDecl());
21120 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
21121 ME->setMemberDecl(ME->getMemberDecl());
21122 } else if (FirstInstantiation) {
21124 .push_back(std::make_pair(Var, PointOfInstantiation));
21125 } else {
21126 bool Inserted = false;
21127 for (auto &I : SemaRef.SavedPendingInstantiations) {
21128 auto Iter = llvm::find_if(
21129 I, [Var](const Sema::PendingImplicitInstantiation &P) {
21130 return P.first == Var;
21131 });
21132 if (Iter != I.end()) {
21133 SemaRef.PendingInstantiations.push_back(*Iter);
21134 I.erase(Iter);
21135 Inserted = true;
21136 break;
21137 }
21138 }
21139
21140 // FIXME: For a specialization of a variable template, we don't
21141 // distinguish between "declaration and type implicitly instantiated"
21142 // and "implicit instantiation of definition requested", so we have
21143 // no direct way to avoid enqueueing the pending instantiation
21144 // multiple times.
21145 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
21147 .push_back(std::make_pair(Var, PointOfInstantiation));
21148 }
21149 }
21150 }
21151
21152 // C++2a [basic.def.odr]p4:
21153 // A variable x whose name appears as a potentially-evaluated expression e
21154 // is odr-used by e unless
21155 // -- x is a reference that is usable in constant expressions
21156 // -- x is a variable of non-reference type that is usable in constant
21157 // expressions and has no mutable subobjects [FIXME], and e is an
21158 // element of the set of potential results of an expression of
21159 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
21160 // conversion is applied
21161 // -- x is a variable of non-reference type, and e is an element of the set
21162 // of potential results of a discarded-value expression to which the
21163 // lvalue-to-rvalue conversion is not applied [FIXME]
21164 //
21165 // We check the first part of the second bullet here, and
21166 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
21167 // FIXME: To get the third bullet right, we need to delay this even for
21168 // variables that are not usable in constant expressions.
21169
21170 // If we already know this isn't an odr-use, there's nothing more to do.
21171 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
21172 if (DRE->isNonOdrUse())
21173 return;
21174 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
21175 if (ME->isNonOdrUse())
21176 return;
21177
21178 switch (OdrUse) {
21179 case OdrUseContext::None:
21180 // In some cases, a variable may not have been marked unevaluated, if it
21181 // appears in a defaukt initializer.
21182 assert((!E || isa<FunctionParmPackExpr>(E) ||
21184 "missing non-odr-use marking for unevaluated decl ref");
21185 break;
21186
21187 case OdrUseContext::FormallyOdrUsed:
21188 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
21189 // behavior.
21190 break;
21191
21192 case OdrUseContext::Used:
21193 // If we might later find that this expression isn't actually an odr-use,
21194 // delay the marking.
21196 SemaRef.MaybeODRUseExprs.insert(E);
21197 else
21198 MarkVarDeclODRUsed(Var, Loc, SemaRef);
21199 break;
21200
21201 case OdrUseContext::Dependent:
21202 // If this is a dependent context, we don't need to mark variables as
21203 // odr-used, but we may still need to track them for lambda capture.
21204 // FIXME: Do we also need to do this inside dependent typeid expressions
21205 // (which are modeled as unevaluated at this point)?
21206 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
21207 break;
21208 }
21209}
21210
21212 BindingDecl *BD, Expr *E) {
21213 BD->setReferenced();
21214
21215 if (BD->isInvalidDecl())
21216 return;
21217
21218 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
21219 if (OdrUse == OdrUseContext::Used) {
21220 QualType CaptureType, DeclRefType;
21222 /*EllipsisLoc*/ SourceLocation(),
21223 /*BuildAndDiagnose*/ true, CaptureType,
21224 DeclRefType,
21225 /*FunctionScopeIndexToStopAt*/ nullptr);
21226 } else if (OdrUse == OdrUseContext::Dependent) {
21227 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
21228 }
21229}
21230
21232 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
21233}
21234
21235// C++ [temp.dep.expr]p3:
21236// An id-expression is type-dependent if it contains:
21237// - an identifier associated by name lookup with an entity captured by copy
21238// in a lambda-expression that has an explicit object parameter whose type
21239// is dependent ([dcl.fct]),
21241 Sema &SemaRef, ValueDecl *D, Expr *E) {
21242 auto *ID = dyn_cast<DeclRefExpr>(E);
21243 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
21244 return;
21245
21246 // If any enclosing lambda with a dependent explicit object parameter either
21247 // explicitly captures the variable by value, or has a capture default of '='
21248 // and does not capture the variable by reference, then the type of the DRE
21249 // is dependent on the type of that lambda's explicit object parameter.
21250 auto IsDependent = [&]() {
21251 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
21252 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
21253 if (!LSI)
21254 continue;
21255
21256 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
21257 LSI->AfterParameterList)
21258 return false;
21259
21260 const auto *MD = LSI->CallOperator;
21261 if (MD->getType().isNull())
21262 continue;
21263
21264 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
21265 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
21266 !Ty->getParamType(0)->isDependentType())
21267 continue;
21268
21269 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
21270 if (C->isCopyCapture())
21271 return true;
21272 continue;
21273 }
21274
21275 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
21276 return true;
21277 }
21278 return false;
21279 }();
21280
21281 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
21282 IsDependent, SemaRef.getASTContext());
21283}
21284
21285static void
21287 bool MightBeOdrUse,
21288 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
21291
21292 if (SemaRef.getLangOpts().OpenACC)
21293 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
21294
21295 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
21297 if (SemaRef.getLangOpts().CPlusPlus)
21299 Var, E);
21300 return;
21301 }
21302
21303 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
21305 if (SemaRef.getLangOpts().CPlusPlus)
21307 Decl, E);
21308 return;
21309 }
21310 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
21311
21312 // If this is a call to a method via a cast, also mark the method in the
21313 // derived class used in case codegen can devirtualize the call.
21314 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
21315 if (!ME)
21316 return;
21317 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
21318 if (!MD)
21319 return;
21320 // Only attempt to devirtualize if this is truly a virtual call.
21321 bool IsVirtualCall = MD->isVirtual() &&
21323 if (!IsVirtualCall)
21324 return;
21325
21326 // If it's possible to devirtualize the call, mark the called function
21327 // referenced.
21329 ME->getBase(), SemaRef.getLangOpts().AppleKext);
21330 if (DM)
21331 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
21332}
21333
21335 // [basic.def.odr] (CWG 1614)
21336 // A function is named by an expression or conversion [...]
21337 // unless it is a pure virtual function and either the expression is not an
21338 // id-expression naming the function with an explicitly qualified name or
21339 // the expression forms a pointer to member
21340 bool OdrUse = true;
21341 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
21342 if (Method->isVirtual() &&
21343 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
21344 OdrUse = false;
21345
21346 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
21350 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
21351 !FD->isDependentContext())
21352 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
21353 }
21354 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
21356}
21357
21359 // C++11 [basic.def.odr]p2:
21360 // A non-overloaded function whose name appears as a potentially-evaluated
21361 // expression or a member of a set of candidate functions, if selected by
21362 // overload resolution when referred to from a potentially-evaluated
21363 // expression, is odr-used, unless it is a pure virtual function and its
21364 // name is not explicitly qualified.
21365 bool MightBeOdrUse = true;
21367 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
21368 if (Method->isPureVirtual())
21369 MightBeOdrUse = false;
21370 }
21371 SourceLocation Loc =
21372 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
21373 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
21375}
21376
21382
21383/// Perform marking for a reference to an arbitrary declaration. It
21384/// marks the declaration referenced, and performs odr-use checking for
21385/// functions and variables. This method should not be used when building a
21386/// normal expression which refers to a variable.
21388 bool MightBeOdrUse) {
21389 if (MightBeOdrUse) {
21390 if (auto *VD = dyn_cast<VarDecl>(D)) {
21391 MarkVariableReferenced(Loc, VD);
21392 return;
21393 }
21394 }
21395 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
21396 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
21397 return;
21398 }
21399 D->setReferenced();
21400}
21401
21402namespace {
21403 // Mark all of the declarations used by a type as referenced.
21404 // FIXME: Not fully implemented yet! We need to have a better understanding
21405 // of when we're entering a context we should not recurse into.
21406 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
21407 // TreeTransforms rebuilding the type in a new context. Rather than
21408 // duplicating the TreeTransform logic, we should consider reusing it here.
21409 // Currently that causes problems when rebuilding LambdaExprs.
21410class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
21411 Sema &S;
21412 SourceLocation Loc;
21413
21414public:
21415 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
21416
21417 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
21418};
21419}
21420
21421bool MarkReferencedDecls::TraverseTemplateArgument(
21422 const TemplateArgument &Arg) {
21423 {
21424 // A non-type template argument is a constant-evaluated context.
21425 EnterExpressionEvaluationContext Evaluated(
21428 if (Decl *D = Arg.getAsDecl())
21429 S.MarkAnyDeclReferenced(Loc, D, true);
21430 } else if (Arg.getKind() == TemplateArgument::Expression) {
21432 }
21433 }
21434
21436}
21437
21439 MarkReferencedDecls Marker(*this, Loc);
21440 Marker.TraverseType(T);
21441}
21442
21443namespace {
21444/// Helper class that marks all of the declarations referenced by
21445/// potentially-evaluated subexpressions as "referenced".
21446class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21447public:
21448 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21449 bool SkipLocalVariables;
21451
21452 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21454 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21455
21456 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21458 }
21459
21460 void Visit(Expr *E) {
21461 if (llvm::is_contained(StopAt, E))
21462 return;
21463 Inherited::Visit(E);
21464 }
21465
21466 void VisitConstantExpr(ConstantExpr *E) {
21467 // Don't mark declarations within a ConstantExpression, as this expression
21468 // will be evaluated and folded to a value.
21469 }
21470
21471 void VisitDeclRefExpr(DeclRefExpr *E) {
21472 // If we were asked not to visit local variables, don't.
21473 if (SkipLocalVariables) {
21474 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
21475 if (VD->hasLocalStorage())
21476 return;
21477 }
21478
21479 // FIXME: This can trigger the instantiation of the initializer of a
21480 // variable, which can cause the expression to become value-dependent
21481 // or error-dependent. Do we need to propagate the new dependence bits?
21483 }
21484
21485 void VisitMemberExpr(MemberExpr *E) {
21487 Visit(E->getBase());
21488 }
21489};
21490} // namespace
21491
21493 bool SkipLocalVariables,
21494 ArrayRef<const Expr*> StopAt) {
21495 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21496}
21497
21498/// Emit a diagnostic when statements are reachable.
21500 const PartialDiagnostic &PD) {
21501 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21502 // The initializer of a constexpr variable or of the first declaration of a
21503 // static data member is not syntactically a constant evaluated constant,
21504 // but nonetheless is always required to be a constant expression, so we
21505 // can skip diagnosing.
21506 if (Decl &&
21507 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21508 Decl->isFirstDecl() && !Decl->isInline())))
21509 return false;
21510
21511 if (Stmts.empty()) {
21512 Diag(Loc, PD);
21513 return true;
21514 }
21515
21516 if (getCurFunction()) {
21517 // This queue flushes after the function is analyzed, by which time an
21518 // ignore-all-warnings region live here is gone, so sample it now. A note
21519 // is not error-class either, so this also drops the notes that accompany a
21520 // skipped warning. They arrive on their own call, out of reach of the
21521 // engine's rule that drops a note whose warning was ignored.
21522 if (Diags.getIgnoreAllWarnings() &&
21523 Diags.getDiagnosticIDs()->isWarningOrExtension(PD.getDiagID()))
21524 return false;
21525 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21526 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21527 return true;
21528 }
21529
21530 // For non-constexpr file-scope variables with reachability context (non-empty
21531 // Stmts), build a CFG for the initializer and check whether the context in
21532 // question is reachable.
21533 if (Decl && Decl->isFileVarDecl()) {
21534 AnalysisWarnings.registerVarDeclWarning(
21535 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21536 return true;
21537 }
21538
21539 Diag(Loc, PD);
21540 return true;
21541}
21542
21543/// Emit a diagnostic that describes an effect on the run-time behavior
21544/// of the program being compiled.
21545///
21546/// This routine emits the given diagnostic when the code currently being
21547/// type-checked is "potentially evaluated", meaning that there is a
21548/// possibility that the code will actually be executable. Code in sizeof()
21549/// expressions, code used only during overload resolution, etc., are not
21550/// potentially evaluated. This routine will suppress such diagnostics or,
21551/// in the absolutely nutty case of potentially potentially evaluated
21552/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21553/// later.
21554///
21555/// This routine should be used for all diagnostics that describe the run-time
21556/// behavior of a program, such as passing a non-POD value through an ellipsis.
21557/// Failure to do so will likely result in spurious diagnostics or failures
21558/// during overload resolution or within sizeof/alignof/typeof/typeid.
21560 const PartialDiagnostic &PD) {
21561
21562 if (ExprEvalContexts.back().isDiscardedStatementContext())
21563 return false;
21564
21565 switch (ExprEvalContexts.back().Context) {
21570 // The argument will never be evaluated, so don't complain.
21571 break;
21572
21575 // Relevant diagnostics should be produced by constant evaluation.
21576 break;
21577
21580 return DiagIfReachable(Loc, Stmts, PD);
21581 }
21582
21583 return false;
21584}
21585
21587 const PartialDiagnostic &PD) {
21588 return DiagRuntimeBehavior(
21589 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21590 PD);
21591}
21592
21594 CallExpr *CE, FunctionDecl *FD) {
21595 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21596 return false;
21597
21598 // If we're inside a decltype's expression, don't check for a valid return
21599 // type or construct temporaries until we know whether this is the last call.
21600 if (ExprEvalContexts.back().ExprContext ==
21602 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21603 return false;
21604 }
21605
21606 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21607 FunctionDecl *FD;
21608 CallExpr *CE;
21609
21610 public:
21611 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21612 : FD(FD), CE(CE) { }
21613
21614 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21615 if (!FD) {
21616 S.Diag(Loc, diag::err_call_incomplete_return)
21617 << T << CE->getSourceRange();
21618 return;
21619 }
21620
21621 S.Diag(Loc, diag::err_call_function_incomplete_return)
21622 << CE->getSourceRange() << FD << T;
21623 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21624 << FD->getDeclName();
21625 }
21626 } Diagnoser(FD, CE);
21627
21628 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21629 return true;
21630
21631 return false;
21632}
21633
21634// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21635// will prevent this condition from triggering, which is what we want.
21637 SourceLocation Loc;
21638
21639 unsigned diagnostic = diag::warn_condition_is_assignment;
21640 bool IsOrAssign = false;
21641
21642 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21643 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21644 return;
21645
21646 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21647
21648 // Greylist some idioms by putting them into a warning subcategory.
21649 if (ObjCMessageExpr *ME
21650 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21651 Selector Sel = ME->getSelector();
21652
21653 // self = [<foo> init...]
21654 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21655 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21656
21657 // <foo> = [<bar> nextObject]
21658 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21659 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21660 }
21661
21662 Loc = Op->getOperatorLoc();
21663 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21664 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21665 return;
21666
21667 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21668 Loc = Op->getOperatorLoc();
21669 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21670 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21671 else {
21672 // Not an assignment.
21673 return;
21674 }
21675
21676 Diag(Loc, diagnostic) << E->getSourceRange();
21677
21680 Diag(Loc, diag::note_condition_assign_silence)
21682 << FixItHint::CreateInsertion(Close, ")");
21683
21684 if (IsOrAssign)
21685 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21686 << FixItHint::CreateReplacement(Loc, "!=");
21687 else
21688 Diag(Loc, diag::note_condition_assign_to_comparison)
21689 << FixItHint::CreateReplacement(Loc, "==");
21690}
21691
21693 // Don't warn if the parens came from a macro.
21694 SourceLocation parenLoc = ParenE->getBeginLoc();
21695 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21696 return;
21697 // Don't warn for dependent expressions.
21698 if (ParenE->isTypeDependent())
21699 return;
21700
21701 Expr *E = ParenE->IgnoreParens();
21702 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21703 return;
21704
21705 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21706 if (opE->getOpcode() == BO_EQ &&
21707 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21708 == Expr::MLV_Valid) {
21709 SourceLocation Loc = opE->getOperatorLoc();
21710
21711 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21712 SourceRange ParenERange = ParenE->getSourceRange();
21713 Diag(Loc, diag::note_equality_comparison_silence)
21714 << FixItHint::CreateRemoval(ParenERange.getBegin())
21715 << FixItHint::CreateRemoval(ParenERange.getEnd());
21716 Diag(Loc, diag::note_equality_comparison_to_assign)
21717 << FixItHint::CreateReplacement(Loc, "=");
21718 }
21719}
21720
21722 bool IsConstexpr) {
21724 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21726
21727 ExprResult result = CheckPlaceholderExpr(E);
21728 if (result.isInvalid()) return ExprError();
21729 E = result.get();
21730
21731 if (!E->isTypeDependent()) {
21732 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21734
21735 if (getLangOpts().CPlusPlus)
21736 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21737
21739 if (ERes.isInvalid())
21740 return ExprError();
21741 E = ERes.get();
21742
21743 QualType T = E->getType();
21744 if (!T->isScalarType()) { // C99 6.8.4.1p1
21745 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21746 << T << E->getSourceRange();
21747 return ExprError();
21748 }
21749 CheckBoolLikeConversion(E, Loc);
21750 }
21751
21752 return E;
21753}
21754
21756 Expr *SubExpr, ConditionKind CK,
21757 bool MissingOK) {
21758 // MissingOK indicates whether having no condition expression is valid
21759 // (for loop) or invalid (e.g. while loop).
21760 if (!SubExpr)
21761 return MissingOK ? ConditionResult() : ConditionError();
21762
21763 ExprResult Cond;
21764 switch (CK) {
21766 Cond = CheckBooleanCondition(Loc, SubExpr);
21767 break;
21768
21770 // Note: this might produce a FullExpr
21771 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21772 break;
21773
21775 Cond = CheckSwitchCondition(Loc, SubExpr);
21776 break;
21777 }
21778 if (Cond.isInvalid()) {
21779 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21780 {SubExpr}, PreferredConditionType(CK));
21781 if (!Cond.get())
21782 return ConditionError();
21783 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
21784 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
21785
21786 if (!Cond.isUsable())
21787 return ConditionError();
21788
21789 return ConditionResult(*this, nullptr, Cond,
21791}
21792
21793namespace {
21794 /// A visitor for rebuilding a call to an __unknown_any expression
21795 /// to have an appropriate type.
21796 struct RebuildUnknownAnyFunction
21797 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21798
21799 Sema &S;
21800
21801 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21802
21803 ExprResult VisitStmt(Stmt *S) {
21804 llvm_unreachable("unexpected statement!");
21805 }
21806
21807 ExprResult VisitExpr(Expr *E) {
21808 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21809 << E->getSourceRange();
21810 return ExprError();
21811 }
21812
21813 /// Rebuild an expression which simply semantically wraps another
21814 /// expression which it shares the type and value kind of.
21815 template <class T> ExprResult rebuildSugarExpr(T *E) {
21816 ExprResult SubResult = Visit(E->getSubExpr());
21817 if (SubResult.isInvalid()) return ExprError();
21818
21819 Expr *SubExpr = SubResult.get();
21820 E->setSubExpr(SubExpr);
21821 E->setType(SubExpr->getType());
21822 E->setValueKind(SubExpr->getValueKind());
21823 assert(E->getObjectKind() == OK_Ordinary);
21824 return E;
21825 }
21826
21827 ExprResult VisitParenExpr(ParenExpr *E) {
21828 return rebuildSugarExpr(E);
21829 }
21830
21831 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21832 return rebuildSugarExpr(E);
21833 }
21834
21835 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21836 ExprResult SubResult = Visit(E->getSubExpr());
21837 if (SubResult.isInvalid()) return ExprError();
21838
21839 Expr *SubExpr = SubResult.get();
21840 E->setSubExpr(SubExpr);
21841 E->setType(S.Context.getPointerType(SubExpr->getType()));
21842 assert(E->isPRValue());
21843 assert(E->getObjectKind() == OK_Ordinary);
21844 return E;
21845 }
21846
21847 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21848 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21849
21850 E->setType(VD->getType());
21851
21852 assert(E->isPRValue());
21853 if (S.getLangOpts().CPlusPlus &&
21854 !(isa<CXXMethodDecl>(VD) &&
21855 cast<CXXMethodDecl>(VD)->isInstance()))
21857
21858 return E;
21859 }
21860
21861 ExprResult VisitMemberExpr(MemberExpr *E) {
21862 return resolveDecl(E, E->getMemberDecl());
21863 }
21864
21865 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21866 return resolveDecl(E, E->getDecl());
21867 }
21868 };
21869}
21870
21871/// Given a function expression of unknown-any type, try to rebuild it
21872/// to have a function type.
21874 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21875 if (Result.isInvalid()) return ExprError();
21876 return S.DefaultFunctionArrayConversion(Result.get());
21877}
21878
21879namespace {
21880 /// A visitor for rebuilding an expression of type __unknown_anytype
21881 /// into one which resolves the type directly on the referring
21882 /// expression. Strict preservation of the original source
21883 /// structure is not a goal.
21884 struct RebuildUnknownAnyExpr
21885 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21886
21887 Sema &S;
21888
21889 /// The current destination type.
21890 QualType DestType;
21891
21892 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21893 : S(S), DestType(CastType) {}
21894
21895 ExprResult VisitStmt(Stmt *S) {
21896 llvm_unreachable("unexpected statement!");
21897 }
21898
21899 ExprResult VisitExpr(Expr *E) {
21900 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21901 << E->getSourceRange();
21902 return ExprError();
21903 }
21904
21905 ExprResult VisitCallExpr(CallExpr *E);
21906 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21907
21908 /// Rebuild an expression which simply semantically wraps another
21909 /// expression which it shares the type and value kind of.
21910 template <class T> ExprResult rebuildSugarExpr(T *E) {
21911 ExprResult SubResult = Visit(E->getSubExpr());
21912 if (SubResult.isInvalid()) return ExprError();
21913 Expr *SubExpr = SubResult.get();
21914 E->setSubExpr(SubExpr);
21915 E->setType(SubExpr->getType());
21916 E->setValueKind(SubExpr->getValueKind());
21917 assert(E->getObjectKind() == OK_Ordinary);
21918 return E;
21919 }
21920
21921 ExprResult VisitParenExpr(ParenExpr *E) {
21922 return rebuildSugarExpr(E);
21923 }
21924
21925 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21926 return rebuildSugarExpr(E);
21927 }
21928
21929 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21930 const PointerType *Ptr = DestType->getAs<PointerType>();
21931 if (!Ptr) {
21932 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21933 << E->getSourceRange();
21934 return ExprError();
21935 }
21936
21937 if (isa<CallExpr>(E->getSubExpr())) {
21938 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21939 << E->getSourceRange();
21940 return ExprError();
21941 }
21942
21943 assert(E->isPRValue());
21944 assert(E->getObjectKind() == OK_Ordinary);
21945 E->setType(DestType);
21946
21947 // Build the sub-expression as if it were an object of the pointee type.
21948 DestType = Ptr->getPointeeType();
21949 ExprResult SubResult = Visit(E->getSubExpr());
21950 if (SubResult.isInvalid()) return ExprError();
21951 E->setSubExpr(SubResult.get());
21952 return E;
21953 }
21954
21955 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21956
21957 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21958
21959 ExprResult VisitMemberExpr(MemberExpr *E) {
21960 return resolveDecl(E, E->getMemberDecl());
21961 }
21962
21963 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21964 return resolveDecl(E, E->getDecl());
21965 }
21966 };
21967}
21968
21969/// Rebuilds a call expression which yielded __unknown_anytype.
21970ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21971 Expr *CalleeExpr = E->getCallee();
21972
21973 enum FnKind {
21974 FK_MemberFunction,
21975 FK_FunctionPointer,
21976 FK_BlockPointer
21977 };
21978
21979 FnKind Kind;
21980 QualType CalleeType = CalleeExpr->getType();
21981 if (CalleeType == S.Context.BoundMemberTy) {
21983 Kind = FK_MemberFunction;
21984 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21985 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21986 CalleeType = Ptr->getPointeeType();
21987 Kind = FK_FunctionPointer;
21988 } else {
21989 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21990 Kind = FK_BlockPointer;
21991 }
21992 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21993
21994 // Verify that this is a legal result type of a function.
21995 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21996 DestType->isFunctionType()) {
21997 unsigned diagID = diag::err_func_returning_array_function;
21998 if (Kind == FK_BlockPointer)
21999 diagID = diag::err_block_returning_array_function;
22000
22001 S.Diag(E->getExprLoc(), diagID)
22002 << DestType->isFunctionType() << DestType;
22003 return ExprError();
22004 }
22005
22006 // Otherwise, go ahead and set DestType as the call's result.
22007 E->setType(DestType.getNonLValueExprType(S.Context));
22009 assert(E->getObjectKind() == OK_Ordinary);
22010
22011 // Rebuild the function type, replacing the result type with DestType.
22012 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
22013 if (Proto) {
22014 // __unknown_anytype(...) is a special case used by the debugger when
22015 // it has no idea what a function's signature is.
22016 //
22017 // We want to build this call essentially under the K&R
22018 // unprototyped rules, but making a FunctionNoProtoType in C++
22019 // would foul up all sorts of assumptions. However, we cannot
22020 // simply pass all arguments as variadic arguments, nor can we
22021 // portably just call the function under a non-variadic type; see
22022 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
22023 // However, it turns out that in practice it is generally safe to
22024 // call a function declared as "A foo(B,C,D);" under the prototype
22025 // "A foo(B,C,D,...);". The only known exception is with the
22026 // Windows ABI, where any variadic function is implicitly cdecl
22027 // regardless of its normal CC. Therefore we change the parameter
22028 // types to match the types of the arguments.
22029 //
22030 // This is a hack, but it is far superior to moving the
22031 // corresponding target-specific code from IR-gen to Sema/AST.
22032
22033 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
22034 SmallVector<QualType, 8> ArgTypes;
22035 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
22036 ArgTypes.reserve(E->getNumArgs());
22037 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
22038 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
22039 }
22040 ParamTypes = ArgTypes;
22041 }
22042 DestType = S.Context.getFunctionType(DestType, ParamTypes,
22043 Proto->getExtProtoInfo());
22044 } else {
22045 DestType = S.Context.getFunctionNoProtoType(DestType,
22046 FnType->getExtInfo());
22047 }
22048
22049 // Rebuild the appropriate pointer-to-function type.
22050 switch (Kind) {
22051 case FK_MemberFunction:
22052 // Nothing to do.
22053 break;
22054
22055 case FK_FunctionPointer:
22056 DestType = S.Context.getPointerType(DestType);
22057 break;
22058
22059 case FK_BlockPointer:
22060 DestType = S.Context.getBlockPointerType(DestType);
22061 break;
22062 }
22063
22064 // Finally, we can recurse.
22065 ExprResult CalleeResult = Visit(CalleeExpr);
22066 if (!CalleeResult.isUsable()) return ExprError();
22067 E->setCallee(CalleeResult.get());
22068
22069 // Bind a temporary if necessary.
22070 return S.MaybeBindToTemporary(E);
22071}
22072
22073ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
22074 // Verify that this is a legal result type of a call.
22075 if (DestType->isArrayType() || DestType->isFunctionType()) {
22076 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
22077 << DestType->isFunctionType() << DestType;
22078 return ExprError();
22079 }
22080
22081 // Rewrite the method result type if available.
22082 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
22083 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
22084 Method->setReturnType(DestType);
22085 }
22086
22087 // Change the type of the message.
22088 E->setType(DestType.getNonReferenceType());
22090
22091 return S.MaybeBindToTemporary(E);
22092}
22093
22094ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
22095 // The only case we should ever see here is a function-to-pointer decay.
22096 if (E->getCastKind() == CK_FunctionToPointerDecay) {
22097 assert(E->isPRValue());
22098 assert(E->getObjectKind() == OK_Ordinary);
22099
22100 E->setType(DestType);
22101
22102 // Rebuild the sub-expression as the pointee (function) type.
22103 DestType = DestType->castAs<PointerType>()->getPointeeType();
22104
22105 ExprResult Result = Visit(E->getSubExpr());
22106 if (!Result.isUsable()) return ExprError();
22107
22108 E->setSubExpr(Result.get());
22109 return E;
22110 } else if (E->getCastKind() == CK_LValueToRValue) {
22111 assert(E->isPRValue());
22112 assert(E->getObjectKind() == OK_Ordinary);
22113
22114 assert(isa<BlockPointerType>(E->getType()));
22115
22116 E->setType(DestType);
22117
22118 // The sub-expression has to be a lvalue reference, so rebuild it as such.
22119 DestType = S.Context.getLValueReferenceType(DestType);
22120
22121 ExprResult Result = Visit(E->getSubExpr());
22122 if (!Result.isUsable()) return ExprError();
22123
22124 E->setSubExpr(Result.get());
22125 return E;
22126 } else {
22127 llvm_unreachable("Unhandled cast type!");
22128 }
22129}
22130
22131ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
22132 ExprValueKind ValueKind = VK_LValue;
22133 QualType Type = DestType;
22134
22135 // We know how to make this work for certain kinds of decls:
22136
22137 // - functions
22138 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
22139 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
22140 DestType = Ptr->getPointeeType();
22141 ExprResult Result = resolveDecl(E, VD);
22142 if (Result.isInvalid()) return ExprError();
22143 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
22144 VK_PRValue);
22145 }
22146
22147 if (!Type->isFunctionType()) {
22148 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
22149 << VD << E->getSourceRange();
22150 return ExprError();
22151 }
22152 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
22153 // We must match the FunctionDecl's type to the hack introduced in
22154 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
22155 // type. See the lengthy commentary in that routine.
22156 QualType FDT = FD->getType();
22157 const FunctionType *FnType = FDT->castAs<FunctionType>();
22158 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
22159 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
22160 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
22161 SourceLocation Loc = FD->getLocation();
22162 FunctionDecl *NewFD = FunctionDecl::Create(
22163 S.Context, FD->getDeclContext(), Loc, Loc,
22164 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
22166 false /*isInlineSpecified*/, FD->hasPrototype(),
22167 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
22168
22169 if (FD->getQualifier())
22170 NewFD->setQualifierInfo(FD->getQualifierLoc());
22171
22172 SmallVector<ParmVarDecl*, 16> Params;
22173 for (const auto &AI : FT->param_types()) {
22174 ParmVarDecl *Param =
22175 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
22176 Param->setScopeInfo(0, Params.size());
22177 Params.push_back(Param);
22178 }
22179 NewFD->setParams(Params);
22180 DRE->setDecl(NewFD);
22181 VD = DRE->getDecl();
22182 }
22183 }
22184
22185 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
22186 if (MD->isInstance()) {
22187 ValueKind = VK_PRValue;
22189 }
22190
22191 // Function references aren't l-values in C.
22192 if (!S.getLangOpts().CPlusPlus)
22193 ValueKind = VK_PRValue;
22194
22195 // - variables
22196 } else if (isa<VarDecl>(VD)) {
22197 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
22198 Type = RefTy->getPointeeType();
22199 } else if (Type->isFunctionType()) {
22200 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
22201 << VD << E->getSourceRange();
22202 return ExprError();
22203 }
22204
22205 // - nothing else
22206 } else {
22207 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
22208 << VD << E->getSourceRange();
22209 return ExprError();
22210 }
22211
22212 // Modifying the declaration like this is friendly to IR-gen but
22213 // also really dangerous.
22214 VD->setType(DestType);
22215 E->setType(Type);
22216 E->setValueKind(ValueKind);
22217 return E;
22218}
22219
22222 ExprValueKind &VK, CXXCastPath &Path) {
22223 // The type we're casting to must be either void or complete.
22224 if (!CastType->isVoidType() &&
22226 diag::err_typecheck_cast_to_incomplete))
22227 return ExprError();
22228
22229 // Rewrite the casted expression from scratch.
22230 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
22231 if (!result.isUsable()) return ExprError();
22232
22233 CastExpr = result.get();
22235 CastKind = CK_NoOp;
22236
22237 return CastExpr;
22238}
22239
22241 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
22242}
22243
22245 Expr *arg, QualType &paramType) {
22246 // If the syntactic form of the argument is not an explicit cast of
22247 // any sort, just do default argument promotion.
22248 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
22249 if (!castArg) {
22251 if (result.isInvalid()) return ExprError();
22252 paramType = result.get()->getType();
22253 return result;
22254 }
22255
22256 // Otherwise, use the type that was written in the explicit cast.
22257 assert(!arg->hasPlaceholderType());
22258 paramType = castArg->getTypeAsWritten();
22259
22260 // Copy-initialize a parameter of that type.
22261 InitializedEntity entity =
22263 /*consumed*/ false);
22264 return PerformCopyInitialization(entity, callLoc, arg);
22265}
22266
22268 Expr *orig = E;
22269 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
22270 while (true) {
22271 E = E->IgnoreParenImpCasts();
22272 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
22273 E = call->getCallee();
22274 diagID = diag::err_uncasted_call_of_unknown_any;
22275 } else {
22276 break;
22277 }
22278 }
22279
22280 SourceLocation loc;
22281 NamedDecl *d;
22282 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
22283 loc = ref->getLocation();
22284 d = ref->getDecl();
22285 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
22286 loc = mem->getMemberLoc();
22287 d = mem->getMemberDecl();
22288 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
22289 diagID = diag::err_uncasted_call_of_unknown_any;
22290 loc = msg->getSelectorStartLoc();
22291 d = msg->getMethodDecl();
22292 if (!d) {
22293 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
22294 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
22295 << orig->getSourceRange();
22296 return ExprError();
22297 }
22298 } else {
22299 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
22300 << E->getSourceRange();
22301 return ExprError();
22302 }
22303
22304 S.Diag(loc, diagID) << d << orig->getSourceRange();
22305
22306 // Never recoverable.
22307 return ExprError();
22308}
22309
22311 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
22312 if (!placeholderType) return E;
22313
22314 switch (placeholderType->getKind()) {
22315 case BuiltinType::UnresolvedTemplate: {
22316 auto *ULE = cast<UnresolvedLookupExpr>(E->IgnoreParens());
22317 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
22318 // There's only one FoundDecl for UnresolvedTemplate type. See
22319 // BuildTemplateIdExpr.
22320 NamedDecl *Temp = *ULE->decls_begin();
22321 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
22322
22323 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
22324 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
22325 // as it models only the unqualified-id case, where this case can clearly be
22326 // qualified. Thus we can't just qualify an assumed template.
22327 TemplateName TN;
22328 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
22329 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
22330 TemplateName(TD));
22331 else
22332 TN = Context.getAssumedTemplateName(NameInfo.getName());
22333
22334 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
22335 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
22336 Diag(Temp->getLocation(), diag::note_referenced_type_template)
22337 << IsTypeAliasTemplateDecl;
22338
22339 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
22340 bool HasAnyDependentTA = false;
22341 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
22342 HasAnyDependentTA |= Arg.getArgument().isDependent();
22343 TAL.addArgument(Arg);
22344 }
22345
22346 QualType TST;
22347 {
22348 SFINAETrap Trap(*this);
22349 TST = CheckTemplateIdType(
22350 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
22351 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
22352 }
22353 if (TST.isNull())
22354 TST = Context.getTemplateSpecializationType(
22355 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
22356 /*CanonicalArgs=*/{},
22357 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
22358 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
22359 TST);
22360 }
22361
22362 // Overloaded expressions.
22363 case BuiltinType::Overload: {
22364 // Try to resolve a single function template specialization.
22365 // This is obligatory.
22366 ExprResult Result = E;
22368 return Result;
22369
22370 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
22371 // leaves Result unchanged on failure.
22372 Result = E;
22374 return Result;
22375
22376 // If that failed, try to recover with a call.
22377 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
22378 /*complain*/ true);
22379 return Result;
22380 }
22381
22382 // Bound member functions.
22383 case BuiltinType::BoundMember: {
22384 ExprResult result = E;
22385 const Expr *BME = E->IgnoreParens();
22386 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
22387 // Try to give a nicer diagnostic if it is a bound member that we recognize.
22389 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
22390 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
22391 if (ME->getMemberNameInfo().getName().getNameKind() ==
22393 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
22394 }
22395 tryToRecoverWithCall(result, PD,
22396 /*complain*/ true);
22397 return result;
22398 }
22399
22400 // ARC unbridged casts.
22401 case BuiltinType::ARCUnbridgedCast: {
22402 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
22403 ObjC().diagnoseARCUnbridgedCast(realCast);
22404 return realCast;
22405 }
22406
22407 // Expressions of unknown type.
22408 case BuiltinType::UnknownAny:
22409 return diagnoseUnknownAnyExpr(*this, E);
22410
22411 // Pseudo-objects.
22412 case BuiltinType::PseudoObject:
22413 return PseudoObject().checkRValue(E);
22414
22415 case BuiltinType::BuiltinFn: {
22416 // Accept __noop without parens by implicitly converting it to a call expr.
22417 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
22418 if (DRE) {
22419 auto *FD = cast<FunctionDecl>(DRE->getDecl());
22420 unsigned BuiltinID = FD->getBuiltinID();
22421 if (BuiltinID == Builtin::BI__noop) {
22422 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
22423 CK_BuiltinFnToFnPtr)
22424 .get();
22425 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
22428 }
22429
22430 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
22431 // Any use of these other than a direct call is ill-formed as of C++20,
22432 // because they are not addressable functions. In earlier language
22433 // modes, warn and force an instantiation of the real body.
22434 Diag(E->getBeginLoc(),
22436 ? diag::err_use_of_unaddressable_function
22437 : diag::warn_cxx20_compat_use_of_unaddressable_function);
22438 if (FD->isImplicitlyInstantiable()) {
22439 // Require a definition here because a normal attempt at
22440 // instantiation for a builtin will be ignored, and we won't try
22441 // again later. We assume that the definition of the template
22442 // precedes this use.
22444 /*Recursive=*/false,
22445 /*DefinitionRequired=*/true,
22446 /*AtEndOfTU=*/false);
22447 }
22448 // Produce a properly-typed reference to the function.
22449 CXXScopeSpec SS;
22450 SS.Adopt(DRE->getQualifierLoc());
22451 TemplateArgumentListInfo TemplateArgs;
22452 DRE->copyTemplateArgumentsInto(TemplateArgs);
22453 return BuildDeclRefExpr(
22454 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
22455 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
22456 DRE->getTemplateKeywordLoc(),
22457 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22458 }
22459 }
22460
22461 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
22462 return ExprError();
22463 }
22464
22465 case BuiltinType::IncompleteMatrixIdx: {
22466 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
22467 // At this point, we know there was no second [] to complete the operator.
22468 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22469 if (getLangOpts().HLSL) {
22471 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
22472 }
22473 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
22474 return ExprError();
22475 }
22476
22477 // Expressions of unknown type.
22478 case BuiltinType::ArraySection:
22479 // If we've already diagnosed something on the array section type, we
22480 // shouldn't need to do any further diagnostic here.
22481 if (!E->containsErrors())
22482 Diag(E->getBeginLoc(), diag::err_array_section_use)
22483 << cast<ArraySectionExpr>(E->IgnoreParens())->isOMPArraySection();
22484 return ExprError();
22485
22486 // Expressions of unknown type.
22487 case BuiltinType::OMPArrayShaping:
22488 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
22489
22490 case BuiltinType::OMPIterator:
22491 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
22492
22493 // Everything else should be impossible.
22494#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22495 case BuiltinType::Id:
22496#include "clang/Basic/OpenCLImageTypes.def"
22497#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22498 case BuiltinType::Id:
22499#include "clang/Basic/OpenCLExtensionTypes.def"
22500#define SVE_TYPE(Name, Id, SingletonId) \
22501 case BuiltinType::Id:
22502#include "clang/Basic/AArch64ACLETypes.def"
22503#define PPC_VECTOR_TYPE(Name, Id, Size) \
22504 case BuiltinType::Id:
22505#include "clang/Basic/PPCTypes.def"
22506#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22507#include "clang/Basic/RISCVVTypes.def"
22508#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22509#include "clang/Basic/WebAssemblyReferenceTypes.def"
22510#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22511#include "clang/Basic/AMDGPUTypes.def"
22512#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22513#include "clang/Basic/HLSLIntangibleTypes.def"
22514#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22515#include "clang/Basic/HLSLPackedTypes.def"
22516#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22517#include "clang/Basic/SPIRVTypes.def"
22518#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22519#define PLACEHOLDER_TYPE(Id, SingletonId)
22520#include "clang/AST/BuiltinTypes.def"
22521 break;
22522 }
22523
22524 llvm_unreachable("invalid placeholder type!");
22525}
22526
22528 if (E->isTypeDependent())
22529 return true;
22531 return E->getType()->isIntegralOrEnumerationType();
22532 return false;
22533}
22534
22536 ArrayRef<Expr *> SubExprs, QualType T) {
22537 if (!Context.getLangOpts().RecoveryAST)
22538 return ExprError();
22539
22540 if (isSFINAEContext())
22541 return ExprError();
22542
22543 if (T.isNull() || T->isUndeducedType() ||
22544 !Context.getLangOpts().RecoveryASTType)
22545 // We don't know the concrete type, fallback to dependent type.
22546 T = Context.DependentTy;
22547
22548 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
22549}
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
static bool isObjCPointer(const MemRegion *R)
Defines enumerations for traits support.
Defines enum values for all the target-independent builtin functions.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
Token Tok
The Token.
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static QualType getUnderlyingType(const SubRegion *R)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:51
static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy, SourceLocation OpLoc)
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, QualType FloatTy)
Test if a (constant) integer Int can be casted to floating point type FloatTy without losing precisio...
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison operators are mixed in a way t...
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
static Decl * getPredefinedExprDecl(Sema &S, DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, const Expr *LHSExpr, const Expr *RHSExpr)
DiagnoseConditionalPrecedence - Emit a warning when a conditional operator and binary operator are mi...
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Return the resulting type for the conditional operator in OpenCL (aka "ternary selection operator",...
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
@ NCCK_Block
@ NCCK_None
@ NCCK_Lambda
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, QualType scalarTy, QualType vectorEltTy, QualType vectorTy, unsigned &DiagID)
Try to convert a value of non-vector type to a vector type by converting the type to the element type...
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes,...
static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
static void SuggestParentheses(Sema &Self, SourceLocation Loc, const PartialDiagnostic &Note, SourceRange ParenRange)
SuggestParentheses - Emit a note with a fixit hint that wraps ParenRange in parentheses.
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
static bool checkForArray(const Expr *E)
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T, QualType U)
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool MayBeFunctionType(const ASTContext &Context, const Expr *E)
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type.
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, const Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
@ ConstUnknown
@ ConstVariable
@ NestedConstMember
@ ConstMember
@ ConstFunction
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union.
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn't need to call Usual...
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, const Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition SemaExpr.cpp:153
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, const TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the lambda.
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, QualType RHSType)
Diagnose attempts to convert between __float128, __ibm128 and long double if there is no support for ...
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, const NamedDecl *D, SourceLocation Loc)
Check whether we're in an extern inline function and referring to a variable or function with interna...
Definition SemaExpr.cpp:169
static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD)
Return true if this function has a calling convention that requires mangling in the size of the param...
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
static AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, ExprResult *Vector)
Attempt to convert and splat Scalar into a vector whose types matches Vector following GCC conversion...
static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc, const ExprResult &LHS, const ExprResult &RHS, BinaryOperatorKind Opc)
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition SemaExpr.cpp:568
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void CheckSufficientAllocSize(Sema &S, QualType DestType, const Expr *E)
Check that a call to alloc_size function specifies sufficient space for the destination type.
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
OriginalExprKind
@ OEK_Variable
@ OEK_LValue
@ OEK_Member
static bool diagnoseFunctionLikeMacro(Sema &SemaRef, DeclarationName Name, SourceLocation TypoLoc)
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
static FieldDecl * FindFieldDeclInstantiationPattern(const ASTContext &Ctx, FieldDecl *Field)
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
static bool IsReadonlyMessage(Expr *E, Sema &S)
static std::optional< bool > isTautologicalBoundsCheck(Sema &S, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opc)
Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a pointer and size is an unsigne...
static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, ValueDecl *Var)
Create up to 4 fix-its for explicit reference and value capture of Var or default capture.
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the captured region.
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer,...
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
static bool IsArithmeticOp(BinaryOperatorKind Opc)
static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Convert complex integers to complex floats and real integers to real floats as required for complex a...
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition SemaExpr.cpp:593
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type.
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, FunctionDecl *FDecl, MultiExprArg ArgExprs)
If a builtin function has a pointer argument with no explicit address space, then it should be able t...
static bool isProvablyZeroSize(const ASTContext &Ctx, QualType T)
Determine whether the size of T is provably zero: some array dimension is provably zero or the base e...
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition SemaExpr.cpp:115
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, QualType ResultTy, Expr *E0, Expr *E1=nullptr)
Returns true if conversion between vectors of halfs and vectors of floats is needed.
static bool isObjCObjectLiteral(ExprResult &E)
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, QualType OtherIntTy)
Test if a (constant) integer Int can be casted to another integer type IntTy without losing precision...
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, NonOdrUseReason NOUR)
Walk the set of potential results of an expression and mark them all as non-odr-uses if they satisfy ...
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
static bool isScopedEnumerationType(QualType T)
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis for expressions involving.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
@ Open
The standard open() call: int open(const char *path, int oflag, ...);.
a trap message and trap category.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
APSInt & getInt()
Definition APValue.h:573
bool hasValue() const
Definition APValue.h:547
bool isInt() const
Definition APValue.h:549
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:1099
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:856
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CanQualType LongDoubleTy
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:852
const LangOptions & getLangOpts() const
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:974
bool typesAreBlockPointerCompatible(QualType, QualType)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType getCorrespondingSaturatedType(QualType Ty) const
CanQualType BoundMemberTy
CanQualType CharTy
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnknownAnyTy
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType ShortTy
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:971
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
QualType getCorrespondingUnsignedType(QualType T) const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
unsigned getTargetAddressSpace(LangAS AS) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
CanQualType HalfTy
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4619
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2845
Wrapper for source info for arrays.
Definition TypeLoc.h:1808
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3834
QualType getElementType() const
Definition TypeBase.h:3832
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition Expr.h:6819
Attr - This represents one attribute.
Definition Attr.h:47
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4522
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
Expr * getLHS() const
Definition Expr.h:4157
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4201
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2217
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4207
StringRef getOpcodeStr() const
Definition Expr.h:4173
bool isRelationalOp() const
Definition Expr.h:4202
SourceLocation getOperatorLoc() const
Definition Expr.h:4149
bool isMultiplicativeOp() const
Definition Expr.h:4192
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2170
bool isShiftOp() const
Definition Expr.h:4196
Expr * getRHS() const
Definition Expr.h:4159
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5144
bool isBitwiseOp() const
Definition Expr.h:4199
bool isAdditiveOp() const
Definition Expr.h:4194
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4243
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4248
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, const Expr *LHS, const Expr *RHS)
Return true if a binary operator using the specified opcode and operands would match the 'p = (i8*)nu...
Definition Expr.cpp:2242
Opcode getOpcode() const
Definition Expr.h:4152
bool isAssignmentOp() const
Definition Expr.h:4246
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2179
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4204
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4198
BinaryOperatorKind Opcode
Definition Expr.h:4112
A binding in a decomposition declaration.
Definition DeclCXX.h:4232
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8436
A class which contains all the information about a particular captured value.
Definition Decl.h:4864
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4858
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.cpp:5582
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition Decl.h:4940
void setBlockMissingReturnType(bool val=true)
Definition Decl.h:4997
void setIsVariadic(bool value)
Definition Decl.h:4934
SourceLocation getCaretLocation() const
Definition Decl.h:4931
void setBody(CompoundStmt *B)
Definition Decl.h:4938
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4944
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition Decl.cpp:5593
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5786
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6758
Pointer to a block type.
Definition TypeBase.h:3653
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
bool isSVEBool() const
Definition TypeBase.h:3328
Kind getKind() const
Definition TypeBase.h:3299
static CUDAKernelCallExpr * Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:2007
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const RecordType * getDetectedVirtual() const
The virtual base discovered on the path (if we are merely detecting virtuals).
CXXBasePath & front()
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2994
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition DeclCXX.cpp:3297
Represents a C++ base or member initializer.
Definition DeclCXX.h:2410
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1275
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition ExprCXX.cpp:1071
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1382
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext, Expr *RewrittenInitExpr)
Field is the non-static data member whose default initializer is used by this expression.
Definition ExprCXX.cpp:1125
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1137
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1581
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
bool isVirtual() const
Definition DeclCXX.h:2208
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
CXXMethodDecl * getDevirtualizedMethod(const Expr *Base, bool IsAppleKext)
If it's possible to devirtualize a call to this method, return the called function.
Definition DeclCXX.cpp:2524
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:86
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:157
SourceRange getSourceRange() const
Definition ExprCXX.h:169
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:2038
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2750
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1235
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:606
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1028
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:2087
bool hasDefinition() const
Definition DeclCXX.h:562
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:523
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:624
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
static CXXReflectExpr * Create(ASTContext &C, SourceLocation OperatorLoc, const TypeSourceInfo *TSI)
Definition ExprCXX.cpp:1983
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:184
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:189
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:83
SourceLocation getBeginLoc() const
Definition DeclSpec.h:87
bool isSet() const
Deprecated.
Definition DeclSpec.h:202
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:98
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:187
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:182
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Represents the this expression in C++.
Definition ExprCXX.h:1159
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3229
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition Expr.cpp:1549
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
Expr * getCallee()
Definition Expr.h:3159
void computeDependence()
Compute and set dependence bits.
Definition Expr.h:3235
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
void setCallee(Expr *F)
Definition Expr.h:3161
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
CastKind getCastKind() const
Definition Expr.h:3789
const char * getCastKindName() const
Definition Expr.h:3793
void setSubExpr(Expr *E)
Definition Expr.h:3797
Expr * getSubExpr()
Definition Expr.h:3795
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
unsigned getValue() const
Definition Expr.h:1674
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4917
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
QualType getElementType() const
Definition TypeBase.h:3372
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition Expr.cpp:5166
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3674
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1751
bool body_empty() const
Definition Stmt.h:1795
Stmt * body_back()
Definition Stmt.h:1819
ConditionalOperator - The ?
Definition Expr.h:4460
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3934
An expression that occurs in a constant context and the result of evaluating the expression.
Definition Expr.h:1127
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition Expr.cpp:308
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition Expr.cpp:384
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1177
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
bool isImmediateInvocation() const
Definition Expr.h:1199
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4622
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4644
std::optional< LayoutKind > getLayout() const
Definition TypeBase.h:4646
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4641
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
void setTypoName(const IdentifierInfo *II)
void setTypoNNS(NestedNameSpecifier NNS)
Wrapper for source info for pointers decayed from arrays and functions.
Definition TypeLoc.h:1505
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3636
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2261
bool isRequiresExprBody() const
Definition DeclBase.h:2213
DeclContextLookupResult lookup_result
Definition DeclBase.h:2609
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isRecord() const
Definition DeclBase.h:2208
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2163
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
bool isExpansionStmt() const
Definition DeclBase.h:2217
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1426
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition Expr.h:1470
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1416
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1519
void setDecl(ValueDecl *NewD)
Definition Expr.cpp:554
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition Expr.h:1474
DeclarationNameInfo getNameInfo() const
Definition Expr.h:1387
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition Expr.h:1442
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:498
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition Expr.h:1404
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1408
ValueDecl * getDecl()
Definition Expr.h:1383
SourceLocation getBeginLoc() const
Definition Expr.h:1394
SourceLocation getLocation() const
Definition Expr.h:1391
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:582
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:602
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition DeclBase.cpp:779
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:594
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition DeclBase.h:1088
bool isInvalidDecl() const
Definition DeclBase.h:597
SourceLocation getLocation() const
Definition DeclBase.h:448
void setReferenced(bool R=true)
Definition DeclBase.h:632
DeclContext * getDeclContext()
Definition DeclBase.h:457
bool hasAttr() const
Definition DeclBase.h:586
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
Kind getKind() const
Definition DeclBase.h:451
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2017
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:811
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1996
DeclaratorContext getContext() const
Definition DeclSpec.h:2171
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2182
bool isInvalidType() const
Definition DeclSpec.h:2822
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2430
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:574
Designation - Represent a full designation, which is a sequence of designators.
Definition Designator.h:221
const Designator & getDesignator(unsigned Idx) const
Definition Designator.h:232
unsigned getNumDesignators() const
Definition Designator.h:231
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
bool isArrayDesignator() const
Definition Designator.h:108
SourceLocation getEndLoc() const
Returns the end location of this designator.
Definition Designator.h:147
bool isArrayRangeDesignator() const
Definition Designator.h:109
bool isFieldDesignator() const
Definition Designator.h:107
const IdentifierInfo * getFieldDecl() const
Definition Designator.h:123
SourceLocation getBeginLoc() const
Returns the start location of this designator.
Definition Designator.h:140
Expr * getArrayIndex() const
Definition Designator.h:162
A little helper class used to produce diagnostics.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:992
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:761
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseLambdaCapture(MaybeConst< LambdaExpr > *LE, const LambdaCapture *C, MaybeConst< Expr > *Init)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Represents a reference to emded data.
Definition Expr.h:5204
RAII object that enters a new expression evaluation context.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4367
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3997
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:4024
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1496
This represents one expression.
Definition Expr.h:114
LValueClassification
Definition Expr.h:291
@ LV_ArrayTemporary
Definition Expr.h:302
@ LV_ClassTemporary
Definition Expr.h:301
@ LV_MemberFunction
Definition Expr.h:299
@ LV_IncompleteVoidType
Definition Expr.h:294
@ LV_Valid
Definition Expr.h:292
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:289
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3156
isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, does not have an incomplet...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:703
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition Expr.cpp:3085
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
void setType(QualType t)
Definition Expr.h:147
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:449
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
bool EvaluateAsMandatedConstantExpr(EvalResult &Result, const ASTContext &Ctx, SemaProxy &SProxy, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required by the language to be a constant expression.
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition Expr.h:243
bool EvaluateAsMandatedConstantRValue(EvalResult &Result, const ASTContext &Ctx, SemaProxy &SProxy) const
Evaluate an expression that is required by the language to be a constant expression,...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3117
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3138
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isPRValue() const
Definition Expr.h:287
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3378
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:876
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:872
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:880
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:456
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3728
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:225
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3109
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:847
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:856
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:859
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition Expr.h:862
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:849
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4110
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:272
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:466
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr's will refer to the same value as a comparison operand.
Definition Expr.cpp:4369
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:469
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:481
isModifiableLvalueResult
Definition Expr.h:307
@ MLV_DuplicateVectorComponents
Definition Expr.h:311
@ MLV_LValueCast
Definition Expr.h:314
@ MLV_InvalidMessageExpression
Definition Expr.h:323
@ MLV_DuplicateMatrixComponents
Definition Expr.h:312
@ MLV_ConstQualifiedField
Definition Expr.h:317
@ MLV_InvalidExpression
Definition Expr.h:313
@ MLV_IncompleteType
Definition Expr.h:315
@ MLV_Valid
Definition Expr.h:308
@ MLV_ConstQualified
Definition Expr.h:316
@ MLV_NoSetterProperty
Definition Expr.h:320
@ MLV_ArrayTemporary
Definition Expr.h:325
@ MLV_SubObjCPropertySetting
Definition Expr.h:322