clang 23.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"
61#include "clang/Sema/SemaObjC.h"
64#include "clang/Sema/Template.h"
65#include "llvm/ADT/STLExtras.h"
66#include "llvm/ADT/StringExtras.h"
67#include "llvm/Support/ConvertUTF.h"
68#include "llvm/Support/SaveAndRestore.h"
69#include "llvm/Support/TimeProfiler.h"
70#include "llvm/Support/TypeSize.h"
71#include <limits>
72#include <optional>
73
74using namespace clang;
75using namespace sema;
76
77bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
78 // See if this is an auto-typed variable whose initializer we are parsing.
79 if (ParsingInitForAutoVars.count(D))
80 return false;
81
82 // See if this is a deleted function.
83 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->isDeleted())
85 return false;
86
87 // If the function has a deduced return type, and we can't deduce it,
88 // then we can't use it either.
89 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
90 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
91 return false;
92
93 // See if this is an aligned allocation/deallocation function that is
94 // unavailable.
95 if (TreatUnavailableAsInvalid &&
97 return false;
98 }
99
100 // See if this function is unavailable.
101 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
102 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
103 return false;
104
106 return false;
107
108 return true;
109}
110
112 // Warn if this is used but marked unused.
113 if (const auto *A = D->getAttr<UnusedAttr>()) {
114 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
115 // should diagnose them.
116 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
117 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
118 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
119 if (DC && !DC->hasAttr<UnusedAttr>())
120 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
121 }
122 }
123}
124
126 assert(Decl && Decl->isDeleted());
127
128 if (Decl->isDefaulted()) {
129 // If the method was explicitly defaulted, point at that declaration.
130 if (!Decl->isImplicit())
131 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
132
133 // Try to diagnose why this special member function was implicitly
134 // deleted. This might fail, if that reason no longer applies.
136 return;
137 }
138
139 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
140 if (Ctor && Ctor->isInheritingConstructor())
142
143 Diag(Decl->getLocation(), diag::note_availability_specified_here)
144 << Decl << 1;
145}
146
147/// Determine whether a FunctionDecl was ever declared with an
148/// explicit storage class.
150 for (auto *I : D->redecls()) {
151 if (I->getStorageClass() != SC_None)
152 return true;
153 }
154 return false;
155}
156
157/// Check whether we're in an extern inline function and referring to a
158/// variable or function with internal linkage (C11 6.7.4p3).
159///
160/// This is only a warning because we used to silently accept this code, but
161/// in many cases it will not behave correctly. This is not enabled in C++ mode
162/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
163/// and so while there may still be user mistakes, most of the time we can't
164/// prove that there are errors.
166 const NamedDecl *D,
167 SourceLocation Loc) {
168 // This is disabled under C++; there are too many ways for this to fire in
169 // contexts where the warning is a false positive, or where it is technically
170 // correct but benign.
171 //
172 // WG14 N3622 which removed the constraint entirely in C2y. It is left
173 // enabled in earlier language modes because this is a constraint in those
174 // language modes. But in C2y mode, we still want to issue the "incompatible
175 // with previous standards" diagnostic, too.
176 if (S.getLangOpts().CPlusPlus)
177 return;
178
179 // Check if this is an inlined function or method.
180 FunctionDecl *Current = S.getCurFunctionDecl();
181 if (!Current)
182 return;
183 if (!Current->isInlined())
184 return;
185 if (!Current->isExternallyVisible())
186 return;
187
188 // Check if the decl has internal linkage.
190 return;
191
192 // Downgrade from ExtWarn to Extension if
193 // (1) the supposedly external inline function is in the main file,
194 // and probably won't be included anywhere else.
195 // (2) the thing we're referencing is a pure function.
196 // (3) the thing we're referencing is another inline function.
197 // This last can give us false negatives, but it's better than warning on
198 // wrappers for simple C library functions.
199 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
200 unsigned DiagID;
201 if (S.getLangOpts().C2y)
202 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
203 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
205 DiagID = diag::ext_internal_in_extern_inline_quiet;
206 else
207 DiagID = diag::ext_internal_in_extern_inline;
208
209 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
211 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
212 << D;
213}
214
216 const FunctionDecl *First = Cur->getFirstDecl();
217
218 // Suggest "static" on the function, if possible.
220 SourceLocation DeclBegin = First->getSourceRange().getBegin();
221 Diag(DeclBegin, diag::note_convert_inline_to_static)
222 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
223 }
224}
225
227 const ObjCInterfaceDecl *UnknownObjCClass,
228 bool ObjCPropertyAccess,
229 bool AvoidPartialAvailabilityChecks,
230 ObjCInterfaceDecl *ClassReceiver,
231 bool SkipTrailingRequiresClause) {
232 SourceLocation Loc = Locs.front();
234 // If there were any diagnostics suppressed by template argument deduction,
235 // emit them now.
236 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
237 if (Pos != SuppressedDiagnostics.end()) {
238 for (const auto &[DiagLoc, PD] : Pos->second) {
239 DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID()));
240 PD.Emit(Builder);
241 }
242 // Clear out the list of suppressed diagnostics, so that we don't emit
243 // them again for this specialization. However, we don't obsolete this
244 // entry from the table, because we want to avoid ever emitting these
245 // diagnostics again.
246 Pos->second.clear();
247 }
248
249 // C++ [basic.start.main]p3:
250 // The function 'main' shall not be used within a program.
251 if (cast<FunctionDecl>(D)->isMain())
252 Diag(Loc, diag::ext_main_used);
253
255 }
256
257 // See if this is an auto-typed variable whose initializer we are parsing.
258 if (ParsingInitForAutoVars.count(D)) {
259 if (isa<BindingDecl>(D)) {
260 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
261 << D->getDeclName();
262 } else {
263 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
264 << diag::ParsingInitFor::Var << D->getDeclName()
265 << cast<VarDecl>(D)->getType();
266 }
267 return true;
268 }
269
270 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
271 // See if this is a deleted function.
272 if (FD->isDeleted()) {
273 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
274 if (Ctor && Ctor->isInheritingConstructor())
275 Diag(Loc, diag::err_deleted_inherited_ctor_use)
276 << Ctor->getParent()
277 << Ctor->getInheritedConstructor().getConstructor()->getParent();
278 else {
279 StringLiteral *Msg = FD->getDeletedMessage();
280 Diag(Loc, diag::err_deleted_function_use)
281 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
282 }
284 return true;
285 }
286
287 // [expr.prim.id]p4
288 // A program that refers explicitly or implicitly to a function with a
289 // trailing requires-clause whose constraint-expression is not satisfied,
290 // other than to declare it, is ill-formed. [...]
291 //
292 // See if this is a function with constraints that need to be satisfied.
293 // Check this before deducing the return type, as it might instantiate the
294 // definition.
295 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
296 ConstraintSatisfaction Satisfaction;
297 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
298 /*ForOverloadResolution*/ true))
299 // A diagnostic will have already been generated (non-constant
300 // constraint expression, for example)
301 return true;
302 if (!Satisfaction.IsSatisfied) {
303 Diag(Loc,
304 diag::err_reference_to_function_with_unsatisfied_constraints)
305 << D;
306 DiagnoseUnsatisfiedConstraint(Satisfaction);
307 return true;
308 }
309 }
310
311 // If the function has a deduced return type, and we can't deduce it,
312 // then we can't use it either.
313 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
314 DeduceReturnType(FD, Loc))
315 return true;
316
317 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
318 return true;
319
320 }
321
322 if (auto *Concept = dyn_cast<ConceptDecl>(D);
324 return true;
325
326 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
327 // Lambdas are only default-constructible or assignable in C++2a onwards.
328 if (MD->getParent()->isLambda() &&
330 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
331 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
332 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
334 }
335 }
336
337 auto getReferencedObjCProp = [](const NamedDecl *D) ->
338 const ObjCPropertyDecl * {
339 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
340 return MD->findPropertyDecl();
341 return nullptr;
342 };
343 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
344 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
345 return true;
346 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
347 return true;
348 }
349
350 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
351 // Only the variables omp_in and omp_out are allowed in the combiner.
352 // Only the variables omp_priv and omp_orig are allowed in the
353 // initializer-clause.
354 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
355 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
356 isa<VarDecl>(D)) {
357 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
359 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
360 return true;
361 }
362
363 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
364 // List-items in map clauses on this construct may only refer to the declared
365 // variable var and entities that could be referenced by a procedure defined
366 // at the same location.
367 // [OpenMP 5.2] Also allow iterator declared variables.
368 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
369 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
370 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
372 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
373 return true;
374 }
375
376 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
377 Diag(Loc, diag::err_use_of_empty_using_if_exists);
378 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
379 return true;
380 }
381
382 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
383 AvoidPartialAvailabilityChecks, ClassReceiver);
384
385 DiagnoseUnusedOfDecl(*this, D, Loc);
386
388
389 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
390 if (getLangOpts().getFPEvalMethod() !=
392 PP.getLastFPEvalPragmaLocation().isValid() &&
393 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
394 Diag(D->getLocation(),
395 diag::err_type_available_only_in_default_eval_method)
396 << D->getName();
397 }
398
399 if (auto *VD = dyn_cast<ValueDecl>(D))
400 checkTypeSupport(VD->getType(), Loc, VD);
401
402 if (LangOpts.SYCLIsDevice ||
403 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
404 if (!Context.getTargetInfo().isTLSSupported())
405 if (const auto *VD = dyn_cast<VarDecl>(D))
406 if (VD->getTLSKind() != VarDecl::TLS_None)
407 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
408 }
409
410 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(D))
411 SYCL().CheckDeviceUseOfDecl(D, Loc);
412
413 return false;
414}
415
417 ArrayRef<Expr *> Args) {
418 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
419 if (!Attr)
420 return;
421
422 // The number of formal parameters of the declaration.
423 unsigned NumFormalParams;
424
425 // The kind of declaration. This is also an index into a %select in
426 // the diagnostic.
427 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
428
429 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
430 NumFormalParams = MD->param_size();
431 CalleeKind = CK_Method;
432 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
433 NumFormalParams = FD->param_size();
434 CalleeKind = CK_Function;
435 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
436 QualType Ty = VD->getType();
437 const FunctionType *Fn = nullptr;
438 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
439 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
440 if (!Fn)
441 return;
442 CalleeKind = CK_Function;
443 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
444 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
445 CalleeKind = CK_Block;
446 } else {
447 return;
448 }
449
450 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
451 NumFormalParams = proto->getNumParams();
452 else
453 NumFormalParams = 0;
454 } else {
455 return;
456 }
457
458 // "NullPos" is the number of formal parameters at the end which
459 // effectively count as part of the variadic arguments. This is
460 // useful if you would prefer to not have *any* formal parameters,
461 // but the language forces you to have at least one.
462 unsigned NullPos = Attr->getNullPos();
463 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
464 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
465
466 // The number of arguments which should follow the sentinel.
467 unsigned NumArgsAfterSentinel = Attr->getSentinel();
468
469 // If there aren't enough arguments for all the formal parameters,
470 // the sentinel, and the args after the sentinel, complain.
471 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
472 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
473 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
474 return;
475 }
476
477 // Otherwise, find the sentinel expression.
478 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
479 if (!SentinelExpr)
480 return;
481 if (SentinelExpr->isValueDependent())
482 return;
483 if (Context.isSentinelNullExpr(SentinelExpr))
484 return;
485
486 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
487 // or 'NULL' if those are actually defined in the context. Only use
488 // 'nil' for ObjC methods, where it's much more likely that the
489 // variadic arguments form a list of object pointers.
490 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
491 std::string NullValue;
492 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
493 NullValue = "nil";
494 else if (getLangOpts().CPlusPlus11)
495 NullValue = "nullptr";
496 else if (PP.isMacroDefined("NULL"))
497 NullValue = "NULL";
498 else
499 NullValue = "(void*) 0";
500
501 if (MissingNilLoc.isInvalid())
502 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
503 else
504 Diag(MissingNilLoc, diag::warn_missing_sentinel)
505 << int(CalleeKind)
506 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
507 Diag(D->getLocation(), diag::note_sentinel_here)
508 << int(CalleeKind) << Attr->getRange();
509}
510
512 return E ? E->getSourceRange() : SourceRange();
513}
514
515//===----------------------------------------------------------------------===//
516// Standard Promotions and Conversions
517//===----------------------------------------------------------------------===//
518
519/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
521 // Handle any placeholder expressions which made it here.
522 if (E->hasPlaceholderType()) {
524 if (result.isInvalid()) return ExprError();
525 E = result.get();
526 }
527
528 QualType Ty = E->getType();
529 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
530
531 if (Ty->isFunctionType()) {
532 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
533 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
535 return ExprError();
536
537 E = ImpCastExprToType(E, Context.getPointerType(Ty),
538 CK_FunctionToPointerDecay).get();
539 } else if (Ty->isArrayType()) {
540 // In C90 mode, arrays only promote to pointers if the array expression is
541 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
542 // type 'array of type' is converted to an expression that has type 'pointer
543 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
544 // that has type 'array of type' ...". The relevant change is "an lvalue"
545 // (C90) to "an expression" (C99).
546 //
547 // C++ 4.2p1:
548 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
549 // T" can be converted to an rvalue of type "pointer to T".
550 //
551 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
552 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
553 CK_ArrayToPointerDecay);
554 if (Res.isInvalid())
555 return ExprError();
556 E = Res.get();
557 }
558 }
559 return E;
560}
561
563 // Check to see if we are dereferencing a null pointer. If so,
564 // and if not volatile-qualified, this is undefined behavior that the
565 // optimizer will delete, so warn about it. People sometimes try to use this
566 // to get a deterministic trap and are surprised by clang's behavior. This
567 // only handles the pattern "*null", which is a very syntactic check.
568 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
569 if (UO && UO->getOpcode() == UO_Deref &&
570 UO->getSubExpr()->getType()->isPointerType()) {
571 const LangAS AS =
572 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
573 if ((!isTargetAddressSpace(AS) ||
574 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
575 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
577 !UO->getType().isVolatileQualified()) {
578 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
579 S.PDiag(diag::warn_indirection_through_null)
580 << UO->getSubExpr()->getSourceRange());
581 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
582 S.PDiag(diag::note_indirection_through_null));
583 }
584 }
585}
586
587static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
588 SourceLocation AssignLoc,
589 const Expr* RHS) {
590 const ObjCIvarDecl *IV = OIRE->getDecl();
591 if (!IV)
592 return;
593
594 DeclarationName MemberName = IV->getDeclName();
596 if (!Member || !Member->isStr("isa"))
597 return;
598
599 const Expr *Base = OIRE->getBase();
600 QualType BaseType = Base->getType();
601 if (OIRE->isArrow())
602 BaseType = BaseType->getPointeeType();
603 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
604 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
605 ObjCInterfaceDecl *ClassDeclared = nullptr;
606 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
607 if (!ClassDeclared->getSuperClass()
608 && (*ClassDeclared->ivar_begin()) == IV) {
609 if (RHS) {
610 NamedDecl *ObjectSetClass =
612 &S.Context.Idents.get("object_setClass"),
614 if (ObjectSetClass) {
615 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
616 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
618 "object_setClass(")
620 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
621 << FixItHint::CreateInsertion(RHSLocEnd, ")");
622 }
623 else
624 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
625 } else {
626 NamedDecl *ObjectGetClass =
628 &S.Context.Idents.get("object_getClass"),
630 if (ObjectGetClass)
631 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
633 "object_getClass(")
635 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
636 else
637 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
638 }
639 S.Diag(IV->getLocation(), diag::note_ivar_decl);
640 }
641 }
642}
643
645 // Handle any placeholder expressions which made it here.
646 if (E->hasPlaceholderType()) {
648 if (result.isInvalid()) return ExprError();
649 E = result.get();
650 }
651
652 // C++ [conv.lval]p1:
653 // A glvalue of a non-function, non-array type T can be
654 // converted to a prvalue.
655 if (!E->isGLValue()) return E;
656
657 QualType T = E->getType();
658 assert(!T.isNull() && "r-value conversion on typeless expression?");
659
660 // lvalue-to-rvalue conversion cannot be applied to types that decay to
661 // pointers (i.e. function or array types).
662 if (T->canDecayToPointerType())
663 return E;
664
665 // We don't want to throw lvalue-to-rvalue casts on top of
666 // expressions of certain types in C++.
667 if (getLangOpts().CPlusPlus) {
668 if (T == Context.OverloadTy || T->isRecordType() ||
669 (T->isDependentType() && !T->isAnyPointerType() &&
670 !T->isMemberPointerType()))
671 return E;
672 }
673
674 // The C standard is actually really unclear on this point, and
675 // DR106 tells us what the result should be but not why. It's
676 // generally best to say that void types just doesn't undergo
677 // lvalue-to-rvalue at all. Note that expressions of unqualified
678 // 'void' type are never l-values, but qualified void can be.
679 if (T->isVoidType())
680 return E;
681
682 // OpenCL usually rejects direct accesses to values of 'half' type.
683 if (getLangOpts().OpenCL &&
684 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
685 T->isHalfType()) {
686 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
687 << 0 << T;
688 return ExprError();
689 }
690
692 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
693 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
694 &Context.Idents.get("object_getClass"),
696 if (ObjectGetClass)
697 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
698 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
700 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
701 else
702 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
703 }
704 else if (const ObjCIvarRefExpr *OIRE =
705 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
706 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
707
708 // C++ [conv.lval]p1:
709 // [...] If T is a non-class type, the type of the prvalue is the
710 // cv-unqualified version of T. Otherwise, the type of the
711 // rvalue is T.
712 //
713 // C99 6.3.2.1p2:
714 // If the lvalue has qualified type, the value has the unqualified
715 // version of the type of the lvalue; otherwise, the value has the
716 // type of the lvalue.
717 if (T.hasQualifiers())
718 T = T.getUnqualifiedType();
719
720 // Under the MS ABI, lock down the inheritance model now.
721 if (T->isMemberPointerType() &&
722 Context.getTargetInfo().getCXXABI().isMicrosoft())
723 (void)isCompleteType(E->getExprLoc(), T);
724
726 if (Res.isInvalid())
727 return Res;
728 E = Res.get();
729
730 // Loading a __weak object implicitly retains the value, so we need a cleanup to
731 // balance that.
733 Cleanup.setExprNeedsCleanups(true);
734
736 Cleanup.setExprNeedsCleanups(true);
737
739 return ExprError();
740
741 // C++ [conv.lval]p3:
742 // If T is cv std::nullptr_t, the result is a null pointer constant.
743 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
744 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
746
747 // C11 6.3.2.1p2:
748 // ... if the lvalue has atomic type, the value has the non-atomic version
749 // of the type of the lvalue ...
750 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
751 T = Atomic->getValueType().getUnqualifiedType();
752 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
753 nullptr, VK_PRValue, FPOptionsOverride());
754 }
755
756 return Res;
757}
758
761 if (Res.isInvalid())
762 return ExprError();
763 Res = DefaultLvalueConversion(Res.get());
764 if (Res.isInvalid())
765 return ExprError();
766 return Res;
767}
768
770 QualType Ty = E->getType();
771 ExprResult Res = E;
772 // Only do implicit cast for a function type, but not for a pointer
773 // to function type.
774 if (Ty->isFunctionType()) {
775 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
776 CK_FunctionToPointerDecay);
777 if (Res.isInvalid())
778 return ExprError();
779 }
780 Res = DefaultLvalueConversion(Res.get());
781 if (Res.isInvalid())
782 return ExprError();
783 return Res.get();
784}
785
786/// UsualUnaryFPConversions - Promotes floating-point types according to the
787/// current language semantics.
789 QualType Ty = E->getType();
790 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
791
792 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
793 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
794 (getLangOpts().getFPEvalMethod() !=
796 PP.getLastFPEvalPragmaLocation().isValid())) {
797 switch (EvalMethod) {
798 default:
799 llvm_unreachable("Unrecognized float evaluation method");
800 break;
802 llvm_unreachable("Float evaluation method should be set by now");
803 break;
805 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
806 // Widen the expression to double.
807 return Ty->isComplexType()
809 Context.getComplexType(Context.DoubleTy),
810 CK_FloatingComplexCast)
811 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
812 break;
814 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
815 // Widen the expression to long double.
816 return Ty->isComplexType()
818 E, Context.getComplexType(Context.LongDoubleTy),
819 CK_FloatingComplexCast)
820 : ImpCastExprToType(E, Context.LongDoubleTy,
821 CK_FloatingCast);
822 break;
823 }
824 }
825
826 // Half FP have to be promoted to float unless it is natively supported
827 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
828 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
829
830 return E;
831}
832
833/// UsualUnaryConversions - Performs various conversions that are common to most
834/// operators (C99 6.3). The conversions of array and function types are
835/// sometimes suppressed. For example, the array->pointer conversion doesn't
836/// apply if the array is an argument to the sizeof or address (&) operators.
837/// In these instances, this routine should *not* be called.
839 // First, convert to an r-value.
841 if (Res.isInvalid())
842 return ExprError();
843
844 // Promote floating-point types.
845 Res = UsualUnaryFPConversions(Res.get());
846 if (Res.isInvalid())
847 return ExprError();
848 E = Res.get();
849
850 QualType Ty = E->getType();
851 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
852
853 // Try to perform integral promotions if the object has a theoretically
854 // promotable type.
856 // C99 6.3.1.1p2:
857 //
858 // The following may be used in an expression wherever an int or
859 // unsigned int may be used:
860 // - an object or expression with an integer type whose integer
861 // conversion rank is less than or equal to the rank of int
862 // and unsigned int.
863 // - A bit-field of type _Bool, int, signed int, or unsigned int.
864 //
865 // If an int can represent all values of the original type, the
866 // value is converted to an int; otherwise, it is converted to an
867 // unsigned int. These are called the integer promotions. All
868 // other types are unchanged by the integer promotions.
869
870 QualType PTy = Context.isPromotableBitField(E);
871 if (!PTy.isNull()) {
872 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
873 return E;
874 }
875 if (Context.isPromotableIntegerType(Ty)) {
876 QualType PT = Context.getPromotedIntegerType(Ty);
877 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
878 return E;
879 }
880 }
881 return E;
882}
883
884/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
885/// do not have a prototype. Arguments that have type float or __fp16
886/// are promoted to double. All other argument types are converted by
887/// UsualUnaryConversions().
889 QualType Ty = E->getType();
890 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
891
893 if (Res.isInvalid())
894 return ExprError();
895 E = Res.get();
896
897 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
898 // promote to double.
899 // Note that default argument promotion applies only to float (and
900 // half/fp16); it does not apply to _Float16.
901 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
902 if (BTy && (BTy->getKind() == BuiltinType::Half ||
903 BTy->getKind() == BuiltinType::Float)) {
904 if (getLangOpts().OpenCL &&
905 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
906 if (BTy->getKind() == BuiltinType::Half) {
907 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
908 }
909 } else {
910 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
911 }
912 }
913 if (BTy &&
914 getLangOpts().getExtendIntArgs() ==
916 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
917 Context.getTypeSizeInChars(BTy) <
918 Context.getTypeSizeInChars(Context.LongLongTy)) {
919 E = (Ty->isUnsignedIntegerType())
920 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
921 .get()
922 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
923 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
924 "Unexpected typesize for LongLongTy");
925 }
926
927 // C++ performs lvalue-to-rvalue conversion as a default argument
928 // promotion, even on class types, but note:
929 // C++11 [conv.lval]p2:
930 // When an lvalue-to-rvalue conversion occurs in an unevaluated
931 // operand or a subexpression thereof the value contained in the
932 // referenced object is not accessed. Otherwise, if the glvalue
933 // has a class type, the conversion copy-initializes a temporary
934 // of type T from the glvalue and the result of the conversion
935 // is a prvalue for the temporary.
936 // FIXME: add some way to gate this entire thing for correctness in
937 // potentially potentially evaluated contexts.
941 E->getExprLoc(), E);
942 if (Temp.isInvalid())
943 return ExprError();
944 E = Temp.get();
945 }
946
947 // C++ [expr.call]p7, per CWG722:
948 // An argument that has (possibly cv-qualified) type std::nullptr_t is
949 // converted to void* ([conv.ptr]).
950 // (This does not apply to C23 nullptr)
952 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
953
954 return E;
955}
956
958 if (Ty->isIncompleteType()) {
959 // C++11 [expr.call]p7:
960 // After these conversions, if the argument does not have arithmetic,
961 // enumeration, pointer, pointer to member, or class type, the program
962 // is ill-formed.
963 //
964 // Since we've already performed null pointer conversion, array-to-pointer
965 // decay and function-to-pointer decay, the only such type in C++ is cv
966 // void. This also handles initializer lists as variadic arguments.
967 if (Ty->isVoidType())
968 return VarArgKind::Invalid;
969
970 if (Ty->isObjCObjectType())
971 return VarArgKind::Invalid;
972 return VarArgKind::Valid;
973 }
974
976 return VarArgKind::Invalid;
977
978 if (Context.getTargetInfo().getTriple().isWasm() &&
980 return VarArgKind::Invalid;
981 }
982
983 if (Ty.isCXX98PODType(Context))
984 return VarArgKind::Valid;
985
986 // C++11 [expr.call]p7:
987 // Passing a potentially-evaluated argument of class type (Clause 9)
988 // having a non-trivial copy constructor, a non-trivial move constructor,
989 // or a non-trivial destructor, with no corresponding parameter,
990 // is conditionally-supported with implementation-defined semantics.
993 if (!Record->hasNonTrivialCopyConstructor() &&
994 !Record->hasNonTrivialMoveConstructor() &&
995 !Record->hasNonTrivialDestructor())
997
998 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
999 return VarArgKind::Valid;
1000
1001 if (Ty->isObjCObjectType())
1002 return VarArgKind::Invalid;
1003
1004 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1005 return VarArgKind::Valid;
1006
1007 if (getLangOpts().MSVCCompat)
1009
1010 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1011 return VarArgKind::Valid;
1012
1013 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1014 // permitted to reject them. We should consider doing so.
1015 return VarArgKind::Undefined;
1016}
1017
1019 // Don't allow one to pass an Objective-C interface to a vararg.
1020 const QualType &Ty = E->getType();
1021 VarArgKind VAK = isValidVarArgType(Ty);
1022
1023 // Complain about passing non-POD types through varargs.
1024 switch (VAK) {
1027 E->getBeginLoc(), nullptr,
1028 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1029 [[fallthrough]];
1030 case VarArgKind::Valid:
1031 if (Ty->isRecordType()) {
1032 // This is unlikely to be what the user intended. If the class has a
1033 // 'c_str' member function, the user probably meant to call that.
1034 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1035 PDiag(diag::warn_pass_class_arg_to_vararg)
1036 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1037 }
1038 break;
1039
1042 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1043 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1044 << getLangOpts().CPlusPlus11 << Ty << CT);
1045 break;
1046
1049 Diag(E->getBeginLoc(),
1050 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1051 << Ty << CT;
1052 else if (Ty->isObjCObjectType())
1053 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1054 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1055 << Ty << CT);
1056 else
1057 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1058 << isa<InitListExpr>(E) << Ty << CT;
1059 break;
1060 }
1061}
1062
1064 FunctionDecl *FDecl) {
1065 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1066 // Strip the unbridged-cast placeholder expression off, if applicable.
1067 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1068 (CT == VariadicCallType::Method ||
1069 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1070 E = ObjC().stripARCUnbridgedCast(E);
1071
1072 // Otherwise, do normal placeholder checking.
1073 } else {
1074 ExprResult ExprRes = CheckPlaceholderExpr(E);
1075 if (ExprRes.isInvalid())
1076 return ExprError();
1077 E = ExprRes.get();
1078 }
1079 }
1080
1082 if (ExprRes.isInvalid())
1083 return ExprError();
1084
1085 // Copy blocks to the heap.
1086 if (ExprRes.get()->getType()->isBlockPointerType())
1087 maybeExtendBlockObject(ExprRes);
1088
1089 E = ExprRes.get();
1090
1091 // Diagnostics regarding non-POD argument types are
1092 // emitted along with format string checking in Sema::CheckFunctionCall().
1094 // Turn this into a trap.
1095 CXXScopeSpec SS;
1096 SourceLocation TemplateKWLoc;
1097 UnqualifiedId Name;
1098 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1099 E->getBeginLoc());
1100 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1101 /*HasTrailingLParen=*/true,
1102 /*IsAddressOfOperand=*/false);
1103 if (TrapFn.isInvalid())
1104 return ExprError();
1105
1106 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1107 E->getEndLoc());
1108 if (Call.isInvalid())
1109 return ExprError();
1110
1111 ExprResult Comma =
1112 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1113 if (Comma.isInvalid())
1114 return ExprError();
1115 return Comma.get();
1116 }
1117
1118 if (!getLangOpts().CPlusPlus &&
1120 diag::err_call_incomplete_argument))
1121 return ExprError();
1122
1123 return E;
1124}
1125
1126/// Convert complex integers to complex floats and real integers to
1127/// real floats as required for complex arithmetic. Helper function of
1128/// UsualArithmeticConversions()
1129///
1130/// \return false if the integer expression is an integer type and is
1131/// successfully converted to the (complex) float type.
1133 ExprResult &ComplexExpr,
1134 QualType IntTy,
1135 QualType ComplexTy,
1136 bool SkipCast) {
1137 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1138 if (SkipCast) return false;
1139 if (IntTy->isIntegerType()) {
1140 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1141 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1142 } else {
1143 assert(IntTy->isComplexIntegerType());
1144 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1145 CK_IntegralComplexToFloatingComplex);
1146 }
1147 return false;
1148}
1149
1150// This handles complex/complex, complex/float, or float/complex.
1151// When both operands are complex, the shorter operand is converted to the
1152// type of the longer, and that is the type of the result. This corresponds
1153// to what is done when combining two real floating-point operands.
1154// The fun begins when size promotion occur across type domains.
1155// From H&S 6.3.4: When one operand is complex and the other is a real
1156// floating-point type, the less precise type is converted, within it's
1157// real or complex domain, to the precision of the other type. For example,
1158// when combining a "long double" with a "double _Complex", the
1159// "double _Complex" is promoted to "long double _Complex".
1161 QualType ShorterType,
1162 QualType LongerType,
1163 bool PromotePrecision) {
1164 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1166 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1167
1168 if (PromotePrecision) {
1169 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1170 Shorter =
1171 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1172 } else {
1173 if (LongerIsComplex)
1174 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1175 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1176 }
1177 }
1178 return Result;
1179}
1180
1181/// Handle arithmetic conversion with complex types. Helper function of
1182/// UsualArithmeticConversions()
1184 ExprResult &RHS, QualType LHSType,
1185 QualType RHSType, bool IsCompAssign) {
1186 // Handle (complex) integer types.
1187 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1188 /*SkipCast=*/false))
1189 return LHSType;
1190 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1191 /*SkipCast=*/IsCompAssign))
1192 return RHSType;
1193
1194 // Compute the rank of the two types, regardless of whether they are complex.
1195 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1196 if (Order < 0)
1197 // Promote the precision of the LHS if not an assignment.
1198 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1199 /*PromotePrecision=*/!IsCompAssign);
1200 // Promote the precision of the RHS unless it is already the same as the LHS.
1201 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1202 /*PromotePrecision=*/Order > 0);
1203}
1204
1205/// Handle arithmetic conversion from integer to float. Helper function
1206/// of UsualArithmeticConversions()
1208 ExprResult &IntExpr,
1209 QualType FloatTy, QualType IntTy,
1210 bool ConvertFloat, bool ConvertInt) {
1211 if (IntTy->isIntegerType()) {
1212 if (ConvertInt)
1213 // Convert intExpr to the lhs floating point type.
1214 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1215 CK_IntegralToFloating);
1216 return FloatTy;
1217 }
1218
1219 // Convert both sides to the appropriate complex float.
1220 assert(IntTy->isComplexIntegerType());
1221 QualType result = S.Context.getComplexType(FloatTy);
1222
1223 // _Complex int -> _Complex float
1224 if (ConvertInt)
1225 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1226 CK_IntegralComplexToFloatingComplex);
1227
1228 // float -> _Complex float
1229 if (ConvertFloat)
1230 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1231 CK_FloatingRealToComplex);
1232
1233 return result;
1234}
1235
1236/// Handle arithmethic conversion with floating point types. Helper
1237/// function of UsualArithmeticConversions()
1239 ExprResult &RHS, QualType LHSType,
1240 QualType RHSType, bool IsCompAssign) {
1241 bool LHSFloat = LHSType->isRealFloatingType();
1242 bool RHSFloat = RHSType->isRealFloatingType();
1243
1244 // N1169 4.1.4: If one of the operands has a floating type and the other
1245 // operand has a fixed-point type, the fixed-point operand
1246 // is converted to the floating type [...]
1247 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1248 if (LHSFloat)
1249 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1250 else if (!IsCompAssign)
1251 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1252 return LHSFloat ? LHSType : RHSType;
1253 }
1254
1255 // If we have two real floating types, convert the smaller operand
1256 // to the bigger result.
1257 if (LHSFloat && RHSFloat) {
1258 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1259 if (order > 0) {
1260 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1261 return LHSType;
1262 }
1263
1264 assert(order < 0 && "illegal float comparison");
1265 if (!IsCompAssign)
1266 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1267 return RHSType;
1268 }
1269
1270 if (LHSFloat) {
1271 // Half FP has to be promoted to float unless it is natively supported
1272 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1273 LHSType = S.Context.FloatTy;
1274
1275 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1276 /*ConvertFloat=*/!IsCompAssign,
1277 /*ConvertInt=*/ true);
1278 }
1279 assert(RHSFloat);
1280 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1281 /*ConvertFloat=*/ true,
1282 /*ConvertInt=*/!IsCompAssign);
1283}
1284
1285/// Diagnose attempts to convert between __float128, __ibm128 and
1286/// long double if there is no support for such conversion.
1287/// Helper function of UsualArithmeticConversions().
1288static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1289 QualType RHSType) {
1290 // No issue if either is not a floating point type.
1291 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1292 return false;
1293
1294 // No issue if both have the same 128-bit float semantics.
1295 auto *LHSComplex = LHSType->getAs<ComplexType>();
1296 auto *RHSComplex = RHSType->getAs<ComplexType>();
1297
1298 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1299 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1300
1301 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1302 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1303
1304 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1305 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1306 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1307 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1308 return false;
1309
1310 return true;
1311}
1312
1313typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1314
1315namespace {
1316/// These helper callbacks are placed in an anonymous namespace to
1317/// permit their use as function template parameters.
1318ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1319 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1320}
1321
1322ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1323 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1324 CK_IntegralComplexCast);
1325}
1326}
1327
1328/// Handle integer arithmetic conversions. Helper function of
1329/// UsualArithmeticConversions()
1330template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1332 ExprResult &RHS, QualType LHSType,
1333 QualType RHSType, bool IsCompAssign) {
1334 // The rules for this case are in C99 6.3.1.8
1335 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1336 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1337 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1338 if (LHSSigned == RHSSigned) {
1339 // Same signedness; use the higher-ranked type
1340 if (order >= 0) {
1341 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1342 return LHSType;
1343 } else if (!IsCompAssign)
1344 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1345 return RHSType;
1346 } else if (order != (LHSSigned ? 1 : -1)) {
1347 // The unsigned type has greater than or equal rank to the
1348 // signed type, so use the unsigned type
1349 if (RHSSigned) {
1350 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1351 return LHSType;
1352 } else if (!IsCompAssign)
1353 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1354 return RHSType;
1355 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1356 // The two types are different widths; if we are here, that
1357 // means the signed type is larger than the unsigned type, so
1358 // use the signed type.
1359 if (LHSSigned) {
1360 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1361 return LHSType;
1362 } else if (!IsCompAssign)
1363 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1364 return RHSType;
1365 } else {
1366 // The signed type is higher-ranked than the unsigned type,
1367 // but isn't actually any bigger (like unsigned int and long
1368 // on most 32-bit systems). Use the unsigned type corresponding
1369 // to the signed type.
1370 QualType result =
1371 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1372 RHS = (*doRHSCast)(S, RHS.get(), result);
1373 if (!IsCompAssign)
1374 LHS = (*doLHSCast)(S, LHS.get(), result);
1375 return result;
1376 }
1377}
1378
1379/// Handle conversions with GCC complex int extension. Helper function
1380/// of UsualArithmeticConversions()
1382 ExprResult &RHS, QualType LHSType,
1383 QualType RHSType,
1384 bool IsCompAssign) {
1385 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1386 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1387
1388 if (LHSComplexInt && RHSComplexInt) {
1389 QualType LHSEltType = LHSComplexInt->getElementType();
1390 QualType RHSEltType = RHSComplexInt->getElementType();
1391 QualType ScalarType =
1393 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1394
1395 return S.Context.getComplexType(ScalarType);
1396 }
1397
1398 if (LHSComplexInt) {
1399 QualType LHSEltType = LHSComplexInt->getElementType();
1400 QualType ScalarType =
1402 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1404 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1405 CK_IntegralRealToComplex);
1406
1407 return ComplexType;
1408 }
1409
1410 assert(RHSComplexInt);
1411
1412 QualType RHSEltType = RHSComplexInt->getElementType();
1413 QualType ScalarType =
1415 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1417
1418 if (!IsCompAssign)
1419 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1420 CK_IntegralRealToComplex);
1421 return ComplexType;
1422}
1423
1425 ExprResult &RHS,
1426 QualType LHSType,
1427 QualType RHSType,
1428 bool IsCompAssign) {
1429
1430 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1431 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1432
1433 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1434 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1435
1436 bool LHSHasTrap =
1437 LhsOBT && LhsOBT->getBehaviorKind() ==
1438 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1439 bool RHSHasTrap =
1440 RhsOBT && RhsOBT->getBehaviorKind() ==
1441 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1442 bool LHSHasWrap =
1443 LhsOBT && LhsOBT->getBehaviorKind() ==
1444 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1445 bool RHSHasWrap =
1446 RhsOBT && RhsOBT->getBehaviorKind() ==
1447 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1448
1449 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1450 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1451
1452 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1453 if (LHSHasTrap || RHSHasTrap)
1454 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1455 else if (LHSHasWrap || RHSHasWrap)
1456 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1457
1458 QualType LHSConvType = LHSUnderlyingType;
1459 QualType RHSConvType = RHSUnderlyingType;
1460 if (DominantBehavior) {
1461 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1462 LHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1463 LHSUnderlyingType);
1464 else
1465 LHSConvType = LHSType;
1466
1467 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1468 RHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1469 RHSUnderlyingType);
1470 else
1471 RHSConvType = RHSType;
1472 }
1473
1475 S, LHS, RHS, LHSConvType, RHSConvType, IsCompAssign);
1476}
1477
1478/// Return the rank of a given fixed point or integer type. The value itself
1479/// doesn't matter, but the values must be increasing with proper increasing
1480/// rank as described in N1169 4.1.1.
1481static unsigned GetFixedPointRank(QualType Ty) {
1482 const auto *BTy = Ty->getAs<BuiltinType>();
1483 assert(BTy && "Expected a builtin type.");
1484
1485 switch (BTy->getKind()) {
1486 case BuiltinType::ShortFract:
1487 case BuiltinType::UShortFract:
1488 case BuiltinType::SatShortFract:
1489 case BuiltinType::SatUShortFract:
1490 return 1;
1491 case BuiltinType::Fract:
1492 case BuiltinType::UFract:
1493 case BuiltinType::SatFract:
1494 case BuiltinType::SatUFract:
1495 return 2;
1496 case BuiltinType::LongFract:
1497 case BuiltinType::ULongFract:
1498 case BuiltinType::SatLongFract:
1499 case BuiltinType::SatULongFract:
1500 return 3;
1501 case BuiltinType::ShortAccum:
1502 case BuiltinType::UShortAccum:
1503 case BuiltinType::SatShortAccum:
1504 case BuiltinType::SatUShortAccum:
1505 return 4;
1506 case BuiltinType::Accum:
1507 case BuiltinType::UAccum:
1508 case BuiltinType::SatAccum:
1509 case BuiltinType::SatUAccum:
1510 return 5;
1511 case BuiltinType::LongAccum:
1512 case BuiltinType::ULongAccum:
1513 case BuiltinType::SatLongAccum:
1514 case BuiltinType::SatULongAccum:
1515 return 6;
1516 default:
1517 if (BTy->isInteger())
1518 return 0;
1519 llvm_unreachable("Unexpected fixed point or integer type");
1520 }
1521}
1522
1523/// handleFixedPointConversion - Fixed point operations between fixed
1524/// point types and integers or other fixed point types do not fall under
1525/// usual arithmetic conversion since these conversions could result in loss
1526/// of precsision (N1169 4.1.4). These operations should be calculated with
1527/// the full precision of their result type (N1169 4.1.6.2.1).
1529 QualType RHSTy) {
1530 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1531 "Expected at least one of the operands to be a fixed point type");
1532 assert((LHSTy->isFixedPointOrIntegerType() ||
1533 RHSTy->isFixedPointOrIntegerType()) &&
1534 "Special fixed point arithmetic operation conversions are only "
1535 "applied to ints or other fixed point types");
1536
1537 // If one operand has signed fixed-point type and the other operand has
1538 // unsigned fixed-point type, then the unsigned fixed-point operand is
1539 // converted to its corresponding signed fixed-point type and the resulting
1540 // type is the type of the converted operand.
1541 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1543 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1545
1546 // The result type is the type with the highest rank, whereby a fixed-point
1547 // conversion rank is always greater than an integer conversion rank; if the
1548 // type of either of the operands is a saturating fixedpoint type, the result
1549 // type shall be the saturating fixed-point type corresponding to the type
1550 // with the highest rank; the resulting value is converted (taking into
1551 // account rounding and overflow) to the precision of the resulting type.
1552 // Same ranks between signed and unsigned types are resolved earlier, so both
1553 // types are either signed or both unsigned at this point.
1554 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1555 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1556
1557 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1558
1560 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1561
1562 return ResultTy;
1563}
1564
1565/// Check that the usual arithmetic conversions can be performed on this pair of
1566/// expressions that might be of enumeration type.
1568 SourceLocation Loc,
1569 ArithConvKind ACK) {
1570 // C++2a [expr.arith.conv]p1:
1571 // If one operand is of enumeration type and the other operand is of a
1572 // different enumeration type or a floating-point type, this behavior is
1573 // deprecated ([depr.arith.conv.enum]).
1574 //
1575 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1576 // Eventually we will presumably reject these cases (in C++23 onwards?).
1578 R = RHS->getEnumCoercedType(Context);
1579 bool LEnum = L->isUnscopedEnumerationType(),
1580 REnum = R->isUnscopedEnumerationType();
1581 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1582 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1583 (REnum && L->isFloatingType())) {
1584 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1586 ? diag::warn_arith_conv_enum_float_cxx20
1587 : diag::warn_arith_conv_enum_float)
1588 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1589 << L << R;
1590 } else if (!IsCompAssign && LEnum && REnum &&
1591 !Context.hasSameUnqualifiedType(L, R)) {
1592 unsigned DiagID;
1593 // In C++ 26, usual arithmetic conversions between 2 different enum types
1594 // are ill-formed.
1596 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1597 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1598 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1599 // If either enumeration type is unnamed, it's less likely that the
1600 // user cares about this, but this situation is still deprecated in
1601 // C++2a. Use a different warning group.
1602 DiagID = getLangOpts().CPlusPlus20
1603 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1604 : diag::warn_arith_conv_mixed_anon_enum_types;
1605 } else if (ACK == ArithConvKind::Conditional) {
1606 // Conditional expressions are separated out because they have
1607 // historically had a different warning flag.
1608 DiagID = getLangOpts().CPlusPlus20
1609 ? diag::warn_conditional_mixed_enum_types_cxx20
1610 : diag::warn_conditional_mixed_enum_types;
1611 } else if (ACK == ArithConvKind::Comparison) {
1612 // Comparison expressions are separated out because they have
1613 // historically had a different warning flag.
1614 DiagID = getLangOpts().CPlusPlus20
1615 ? diag::warn_comparison_mixed_enum_types_cxx20
1616 : diag::warn_comparison_mixed_enum_types;
1617 } else {
1618 DiagID = getLangOpts().CPlusPlus20
1619 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1620 : diag::warn_arith_conv_mixed_enum_types;
1621 }
1622 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1623 << (int)ACK << L << R;
1624 }
1625}
1626
1628 Expr *RHS, SourceLocation Loc,
1629 ArithConvKind ACK) {
1630 QualType LHSType = LHS->getType().getUnqualifiedType();
1631 QualType RHSType = RHS->getType().getUnqualifiedType();
1632
1633 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1634 !RHSType->isUnicodeCharacterType())
1635 return;
1636
1637 if (ACK == ArithConvKind::Comparison) {
1638 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1639 return;
1640
1641 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1642 if (T->isChar8Type())
1643 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1644 if (T->isChar16Type())
1645 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1646 assert(T->isChar32Type());
1647 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1648 };
1649
1650 Expr::EvalResult LHSRes, RHSRes;
1651 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1653 SemaRef.isConstantEvaluatedContext());
1654 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1656 SemaRef.isConstantEvaluatedContext());
1657
1658 // Don't warn if the one known value is a representable
1659 // in the type of both expressions.
1660 if (LHSSuccess != RHSuccess) {
1661 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1662 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1663 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1664 return;
1665 }
1666
1667 if (!LHSSuccess || !RHSuccess) {
1668 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1669 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1670 << RHSType;
1671 return;
1672 }
1673
1674 llvm::APSInt LHSValue(32);
1675 LHSValue = LHSRes.Val.getInt();
1676 llvm::APSInt RHSValue(32);
1677 RHSValue = RHSRes.Val.getInt();
1678
1679 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1680 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1681 if (LHSSafe && RHSSafe)
1682 return;
1683
1684 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1685 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1686 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1687 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1688 return;
1689 }
1690
1691 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1692 return;
1693
1694 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1695 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1696 << RHSType;
1697}
1698
1699/// UsualArithmeticConversions - Performs various conversions that are common to
1700/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1701/// routine returns the first non-arithmetic type found. The client is
1702/// responsible for emitting appropriate error diagnostics.
1704 SourceLocation Loc,
1705 ArithConvKind ACK) {
1706
1707 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1708
1709 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1710
1711 if (ACK != ArithConvKind::CompAssign) {
1712 LHS = UsualUnaryConversions(LHS.get());
1713 if (LHS.isInvalid())
1714 return QualType();
1715 }
1716
1717 RHS = UsualUnaryConversions(RHS.get());
1718 if (RHS.isInvalid())
1719 return QualType();
1720
1721 // For conversion purposes, we ignore any qualifiers.
1722 // For example, "const float" and "float" are equivalent.
1723 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1724 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1725
1726 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1727 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1728 LHSType = AtomicLHS->getValueType();
1729
1730 // If both types are identical, no conversion is needed.
1731 if (Context.hasSameType(LHSType, RHSType))
1732 return Context.getCommonSugaredType(LHSType, RHSType);
1733
1734 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1735 // The caller can deal with this (e.g. pointer + int).
1736 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1737 return QualType();
1738
1739 // Apply unary and bitfield promotions to the LHS's type.
1740 QualType LHSUnpromotedType = LHSType;
1741 if (Context.isPromotableIntegerType(LHSType))
1742 LHSType = Context.getPromotedIntegerType(LHSType);
1743 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1744 if (!LHSBitfieldPromoteTy.isNull())
1745 LHSType = LHSBitfieldPromoteTy;
1746 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1747 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1748
1749 // If both types are identical, no conversion is needed.
1750 if (Context.hasSameType(LHSType, RHSType))
1751 return Context.getCommonSugaredType(LHSType, RHSType);
1752
1753 // At this point, we have two different arithmetic types.
1754
1755 // Diagnose attempts to convert between __ibm128, __float128 and long double
1756 // where such conversions currently can't be handled.
1757 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1758 return QualType();
1759
1760 // Handle complex types first (C99 6.3.1.8p1).
1761 if (LHSType->isComplexType() || RHSType->isComplexType())
1762 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1764
1765 // Now handle "real" floating types (i.e. float, double, long double).
1766 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1767 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1769
1770 // Handle GCC complex int extension.
1771 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1772 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1774
1775 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1776 return handleFixedPointConversion(*this, LHSType, RHSType);
1777
1778 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1780 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1781
1782 // Finally, we have two differing integer types.
1784 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1785}
1786
1787//===----------------------------------------------------------------------===//
1788// Semantic Analysis for various Expression Types
1789//===----------------------------------------------------------------------===//
1790
1791
1793 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1794 bool PredicateIsExpr, void *ControllingExprOrType,
1795 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1796 unsigned NumAssocs = ArgTypes.size();
1797 assert(NumAssocs == ArgExprs.size());
1798
1799 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1800 for (unsigned i = 0; i < NumAssocs; ++i) {
1801 if (ArgTypes[i])
1802 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1803 else
1804 Types[i] = nullptr;
1805 }
1806
1807 // If we have a controlling type, we need to convert it from a parsed type
1808 // into a semantic type and then pass that along.
1809 if (!PredicateIsExpr) {
1810 TypeSourceInfo *ControllingType;
1811 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1812 &ControllingType);
1813 assert(ControllingType && "couldn't get the type out of the parser");
1814 ControllingExprOrType = ControllingType;
1815 }
1816
1818 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1819 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1820 delete [] Types;
1821 return ER;
1822}
1823
1824// Helper function to determine type compatibility for C _Generic expressions.
1825// Multiple compatible types within the same _Generic expression is ambiguous
1826// and not valid.
1828 QualType U) {
1829 // Try to handle special types like OverflowBehaviorTypes
1830 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1831 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1832
1833 if (TOBT || UOBT) {
1834 if (TOBT && UOBT) {
1835 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1836 return Ctx.typesAreCompatible(TOBT->getUnderlyingType(),
1837 UOBT->getUnderlyingType());
1838 return false;
1839 }
1840 return false;
1841 }
1842
1843 // We're dealing with types that don't require special handling.
1844 return Ctx.typesAreCompatible(T, U);
1845}
1846
1848 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1849 bool PredicateIsExpr, void *ControllingExprOrType,
1851 unsigned NumAssocs = Types.size();
1852 assert(NumAssocs == Exprs.size());
1853 assert(ControllingExprOrType &&
1854 "Must have either a controlling expression or a controlling type");
1855
1856 Expr *ControllingExpr = nullptr;
1857 TypeSourceInfo *ControllingType = nullptr;
1858 if (PredicateIsExpr) {
1859 // Decay and strip qualifiers for the controlling expression type, and
1860 // handle placeholder type replacement. See committee discussion from WG14
1861 // DR423.
1865 reinterpret_cast<Expr *>(ControllingExprOrType));
1866 if (R.isInvalid())
1867 return ExprError();
1868 ControllingExpr = R.get();
1869 } else {
1870 // The extension form uses the type directly rather than converting it.
1871 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1872 if (!ControllingType)
1873 return ExprError();
1874 }
1875
1876 bool TypeErrorFound = false,
1877 IsResultDependent = ControllingExpr
1878 ? ControllingExpr->isTypeDependent()
1879 : ControllingType->getType()->isDependentType(),
1880 ContainsUnexpandedParameterPack =
1881 ControllingExpr
1882 ? ControllingExpr->containsUnexpandedParameterPack()
1883 : ControllingType->getType()->containsUnexpandedParameterPack();
1884
1885 // The controlling expression is an unevaluated operand, so side effects are
1886 // likely unintended.
1887 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1888 ControllingExpr->HasSideEffects(Context, false))
1889 Diag(ControllingExpr->getExprLoc(),
1890 diag::warn_side_effects_unevaluated_context);
1891
1892 for (unsigned i = 0; i < NumAssocs; ++i) {
1893 if (Exprs[i]->containsUnexpandedParameterPack())
1894 ContainsUnexpandedParameterPack = true;
1895
1896 if (Types[i]) {
1897 if (Types[i]->getType()->containsUnexpandedParameterPack())
1898 ContainsUnexpandedParameterPack = true;
1899
1900 if (Types[i]->getType()->isDependentType()) {
1901 IsResultDependent = true;
1902 } else {
1903 // We relax the restriction on use of incomplete types and non-object
1904 // types with the type-based extension of _Generic. Allowing incomplete
1905 // objects means those can be used as "tags" for a type-safe way to map
1906 // to a value. Similarly, matching on function types rather than
1907 // function pointer types can be useful. However, the restriction on VM
1908 // types makes sense to retain as there are open questions about how
1909 // the selection can be made at compile time.
1910 //
1911 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1912 // complete object type other than a variably modified type."
1913 // C2y removed the requirement that an expression form must
1914 // use a complete type, though it's still as-if the type has undergone
1915 // lvalue conversion. We support this as an extension in C23 and
1916 // earlier because GCC does so.
1917 unsigned D = 0;
1918 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1919 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1920 : diag::ext_assoc_type_incomplete;
1921 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1922 D = diag::err_assoc_type_nonobject;
1923 else if (Types[i]->getType()->isVariablyModifiedType())
1924 D = diag::err_assoc_type_variably_modified;
1925 else if (ControllingExpr) {
1926 // Because the controlling expression undergoes lvalue conversion,
1927 // array conversion, and function conversion, an association which is
1928 // of array type, function type, or is qualified can never be
1929 // reached. We will warn about this so users are less surprised by
1930 // the unreachable association. However, we don't have to handle
1931 // function types; that's not an object type, so it's handled above.
1932 //
1933 // The logic is somewhat different for C++ because C++ has different
1934 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1935 // If T is a non-class type, the type of the prvalue is the cv-
1936 // unqualified version of T. Otherwise, the type of the prvalue is T.
1937 // The result of these rules is that all qualified types in an
1938 // association in C are unreachable, and in C++, only qualified non-
1939 // class types are unreachable.
1940 //
1941 // NB: this does not apply when the first operand is a type rather
1942 // than an expression, because the type form does not undergo
1943 // conversion.
1944 unsigned Reason = 0;
1945 QualType QT = Types[i]->getType();
1946 if (QT->isArrayType())
1947 Reason = 1;
1948 else if (QT.hasQualifiers() &&
1949 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1950 Reason = 2;
1951
1952 if (Reason)
1953 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1954 diag::warn_unreachable_association)
1955 << QT << (Reason - 1);
1956 }
1957
1958 if (D != 0) {
1959 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1960 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1961 if (getDiagnostics().getDiagnosticLevel(
1962 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1964 TypeErrorFound = true;
1965 }
1966
1967 // C11 6.5.1.1p2 "No two generic associations in the same generic
1968 // selection shall specify compatible types."
1969 for (unsigned j = i+1; j < NumAssocs; ++j)
1970 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1972 Types[j]->getType())) {
1973 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1974 diag::err_assoc_compatible_types)
1975 << Types[j]->getTypeLoc().getSourceRange()
1976 << Types[j]->getType()
1977 << Types[i]->getType();
1978 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1979 diag::note_compat_assoc)
1980 << Types[i]->getTypeLoc().getSourceRange()
1981 << Types[i]->getType();
1982 TypeErrorFound = true;
1983 }
1984 }
1985 }
1986 }
1987 if (TypeErrorFound)
1988 return ExprError();
1989
1990 // If we determined that the generic selection is result-dependent, don't
1991 // try to compute the result expression.
1992 if (IsResultDependent) {
1993 if (ControllingExpr)
1994 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1995 Types, Exprs, DefaultLoc, RParenLoc,
1996 ContainsUnexpandedParameterPack);
1997 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1998 Exprs, DefaultLoc, RParenLoc,
1999 ContainsUnexpandedParameterPack);
2000 }
2001
2002 SmallVector<unsigned, 1> CompatIndices;
2003 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2004 // Look at the canonical type of the controlling expression in case it was a
2005 // deduced type like __auto_type. However, when issuing diagnostics, use the
2006 // type the user wrote in source rather than the canonical one.
2007 for (unsigned i = 0; i < NumAssocs; ++i) {
2008 if (!Types[i])
2009 DefaultIndex = i;
2010 else {
2011 bool Compatible;
2012 QualType ControllingQT =
2013 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2014 : ControllingType->getType().getCanonicalType();
2015 QualType AssocQT = Types[i]->getType();
2016
2017 Compatible =
2018 areTypesCompatibleForGeneric(Context, ControllingQT, AssocQT);
2019
2020 if (Compatible)
2021 CompatIndices.push_back(i);
2022 }
2023 }
2024
2025 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2026 TypeSourceInfo *ControllingType) {
2027 // We strip parens here because the controlling expression is typically
2028 // parenthesized in macro definitions.
2029 if (ControllingExpr)
2030 ControllingExpr = ControllingExpr->IgnoreParens();
2031
2032 SourceRange SR = ControllingExpr
2033 ? ControllingExpr->getSourceRange()
2034 : ControllingType->getTypeLoc().getSourceRange();
2035 QualType QT = ControllingExpr ? ControllingExpr->getType()
2036 : ControllingType->getType();
2037
2038 return std::make_pair(SR, QT);
2039 };
2040
2041 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2042 // type compatible with at most one of the types named in its generic
2043 // association list."
2044 if (CompatIndices.size() > 1) {
2045 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2046 SourceRange SR = P.first;
2047 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
2048 << SR << P.second << (unsigned)CompatIndices.size();
2049 for (unsigned I : CompatIndices) {
2050 Diag(Types[I]->getTypeLoc().getBeginLoc(),
2051 diag::note_compat_assoc)
2052 << Types[I]->getTypeLoc().getSourceRange()
2053 << Types[I]->getType();
2054 }
2055 return ExprError();
2056 }
2057
2058 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2059 // its controlling expression shall have type compatible with exactly one of
2060 // the types named in its generic association list."
2061 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2062 CompatIndices.size() == 0) {
2063 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2064 SourceRange SR = P.first;
2065 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
2066 return ExprError();
2067 }
2068
2069 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2070 // type name that is compatible with the type of the controlling expression,
2071 // then the result expression of the generic selection is the expression
2072 // in that generic association. Otherwise, the result expression of the
2073 // generic selection is the expression in the default generic association."
2074 unsigned ResultIndex =
2075 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2076
2077 if (ControllingExpr) {
2079 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
2080 ContainsUnexpandedParameterPack, ResultIndex);
2081 }
2083 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
2084 ContainsUnexpandedParameterPack, ResultIndex);
2085}
2086
2088 switch (Kind) {
2089 default:
2090 llvm_unreachable("unexpected TokenKind");
2091 case tok::kw___func__:
2092 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2093 case tok::kw___FUNCTION__:
2095 case tok::kw___FUNCDNAME__:
2096 return PredefinedIdentKind::FuncDName; // [MS]
2097 case tok::kw___FUNCSIG__:
2098 return PredefinedIdentKind::FuncSig; // [MS]
2099 case tok::kw_L__FUNCTION__:
2100 return PredefinedIdentKind::LFunction; // [MS]
2101 case tok::kw_L__FUNCSIG__:
2102 return PredefinedIdentKind::LFuncSig; // [MS]
2103 case tok::kw___PRETTY_FUNCTION__:
2105 }
2106}
2107
2108/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2109/// to determine the value of a PredefinedExpr. This can be either a
2110/// block, lambda, captured statement, function, otherwise a nullptr.
2113 DC = DC->getParent();
2114 return cast_or_null<Decl>(DC);
2115}
2116
2117/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2118/// location of the token and the offset of the ud-suffix within it.
2120 unsigned Offset) {
2121 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2122 S.getLangOpts());
2123}
2124
2125/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2126/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2128 IdentifierInfo *UDSuffix,
2129 SourceLocation UDSuffixLoc,
2130 ArrayRef<Expr*> Args,
2131 SourceLocation LitEndLoc) {
2132 assert(Args.size() <= 2 && "too many arguments for literal operator");
2133
2134 QualType ArgTy[2];
2135 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2136 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2137 if (ArgTy[ArgIdx]->isArrayType())
2138 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2139 }
2140
2141 DeclarationName OpName =
2143 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2144 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2145
2146 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2147 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2148 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2149 /*AllowStringTemplatePack*/ false,
2150 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2151 return ExprError();
2152
2153 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2154}
2155
2157 // StringToks needs backing storage as it doesn't hold array elements itself
2158 std::vector<Token> ExpandedToks;
2159 if (getLangOpts().MicrosoftExt)
2160 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2161
2162 StringLiteralParser Literal(StringToks, PP,
2164 if (Literal.hadError)
2165 return ExprError();
2166
2167 SmallVector<SourceLocation, 4> StringTokLocs;
2168 for (const Token &Tok : StringToks)
2169 StringTokLocs.push_back(Tok.getLocation());
2170
2171 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2173 false, {}, StringTokLocs);
2174
2175 if (!Literal.getUDSuffix().empty()) {
2176 SourceLocation UDSuffixLoc =
2177 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2178 Literal.getUDSuffixOffset());
2179 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2180 }
2181
2182 return Lit;
2183}
2184
2185std::vector<Token>
2187 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2188 // local macros that expand to string literals that may be concatenated.
2189 // These macros are expanded here (in Sema), because StringLiteralParser
2190 // (in Lex) doesn't know the enclosing function (because it hasn't been
2191 // parsed yet).
2192 assert(getLangOpts().MicrosoftExt);
2193
2194 // Note: Although function local macros are defined only inside functions,
2195 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2196 // expansion of macros into empty string literals without additional checks.
2197 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2198 if (!CurrentDecl)
2199 CurrentDecl = Context.getTranslationUnitDecl();
2200
2201 std::vector<Token> ExpandedToks;
2202 ExpandedToks.reserve(Toks.size());
2203 for (const Token &Tok : Toks) {
2205 assert(tok::isStringLiteral(Tok.getKind()));
2206 ExpandedToks.emplace_back(Tok);
2207 continue;
2208 }
2209 if (isa<TranslationUnitDecl>(CurrentDecl))
2210 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2211 // Stringify predefined expression
2212 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2213 << Tok.getKind();
2214 SmallString<64> Str;
2215 llvm::raw_svector_ostream OS(Str);
2216 Token &Exp = ExpandedToks.emplace_back();
2217 Exp.startToken();
2218 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2219 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2220 OS << 'L';
2221 Exp.setKind(tok::wide_string_literal);
2222 } else {
2223 Exp.setKind(tok::string_literal);
2224 }
2225 OS << '"'
2227 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2228 << '"';
2229 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2230 }
2231 return ExpandedToks;
2232}
2233
2236 assert(!StringToks.empty() && "Must have at least one string!");
2237
2238 // StringToks needs backing storage as it doesn't hold array elements itself
2239 std::vector<Token> ExpandedToks;
2240 if (getLangOpts().MicrosoftExt)
2241 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2242
2243 StringLiteralParser Literal(StringToks, PP);
2244 if (Literal.hadError)
2245 return ExprError();
2246
2247 SmallVector<SourceLocation, 4> StringTokLocs;
2248 for (const Token &Tok : StringToks)
2249 StringTokLocs.push_back(Tok.getLocation());
2250
2251 QualType CharTy = Context.CharTy;
2253 if (Literal.isWide()) {
2254 CharTy = Context.getWideCharType();
2256 } else if (Literal.isUTF8()) {
2257 if (getLangOpts().Char8)
2258 CharTy = Context.Char8Ty;
2259 else if (getLangOpts().C23)
2260 CharTy = Context.UnsignedCharTy;
2262 } else if (Literal.isUTF16()) {
2263 CharTy = Context.Char16Ty;
2265 } else if (Literal.isUTF32()) {
2266 CharTy = Context.Char32Ty;
2268 } else if (Literal.isPascal()) {
2269 CharTy = Context.UnsignedCharTy;
2270 }
2271
2272 // Warn on u8 string literals before C++20 and C23, whose type
2273 // was an array of char before but becomes an array of char8_t.
2274 // In C++20, it cannot be used where a pointer to char is expected.
2275 // In C23, it might have an unexpected value if char was signed.
2276 if (Kind == StringLiteralKind::UTF8 &&
2278 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2279 : !getLangOpts().C23)) {
2280 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2281 ? diag::warn_cxx20_compat_utf8_string
2282 : diag::warn_c23_compat_utf8_string);
2283
2284 // Create removals for all 'u8' prefixes in the string literal(s). This
2285 // ensures C++20/C23 compatibility (but may change the program behavior when
2286 // built by non-Clang compilers for which the execution character set is
2287 // not always UTF-8).
2288 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2289 SourceLocation RemovalDiagLoc;
2290 for (const Token &Tok : StringToks) {
2291 if (Tok.getKind() == tok::utf8_string_literal) {
2292 if (RemovalDiagLoc.isInvalid())
2293 RemovalDiagLoc = Tok.getLocation();
2295 Tok.getLocation(),
2296 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2298 }
2299 }
2300 Diag(RemovalDiagLoc, RemovalDiag);
2301 }
2302
2303 QualType StrTy =
2304 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2305
2306 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2308 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2309 if (Literal.getUDSuffix().empty())
2310 return Lit;
2311
2312 // We're building a user-defined literal.
2313 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2314 SourceLocation UDSuffixLoc =
2315 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2316 Literal.getUDSuffixOffset());
2317
2318 // Make sure we're allowed user-defined literals here.
2319 if (!UDLScope)
2320 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2321
2322 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2323 // operator "" X (str, len)
2324 QualType SizeType = Context.getSizeType();
2325
2326 DeclarationName OpName =
2327 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2328 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2329 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2330
2331 QualType ArgTy[] = {
2332 Context.getArrayDecayedType(StrTy), SizeType
2333 };
2334
2335 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2336 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2337 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2338 /*AllowStringTemplatePack*/ true,
2339 /*DiagnoseMissing*/ true, Lit)) {
2340
2341 case LOLR_Cooked: {
2342 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2343 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2344 StringTokLocs[0]);
2345 Expr *Args[] = { Lit, LenArg };
2346
2347 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2348 }
2349
2350 case LOLR_Template: {
2351 TemplateArgumentListInfo ExplicitArgs;
2352 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2353 TemplateArgumentLocInfo ArgInfo(Lit);
2354 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2355 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2356 &ExplicitArgs);
2357 }
2358
2360 TemplateArgumentListInfo ExplicitArgs;
2361
2362 unsigned CharBits = Context.getIntWidth(CharTy);
2363 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2364 llvm::APSInt Value(CharBits, CharIsUnsigned);
2365
2366 TemplateArgument TypeArg(CharTy);
2367 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2368 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2369
2370 SourceLocation Loc = StringTokLocs.back();
2371 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2372 Value = Lit->getCodeUnit(I);
2373 TemplateArgument Arg(Context, Value, CharTy);
2375 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2376 }
2377 return BuildLiteralOperatorCall(R, OpNameInfo, {}, Loc, &ExplicitArgs);
2378 }
2379 case LOLR_Raw:
2381 llvm_unreachable("unexpected literal operator lookup result");
2382 case LOLR_Error:
2383 return ExprError();
2384 }
2385 llvm_unreachable("unexpected literal operator lookup result");
2386}
2387
2390 SourceLocation Loc,
2391 const CXXScopeSpec *SS) {
2392 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2393 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2394}
2395
2398 const DeclarationNameInfo &NameInfo,
2399 const CXXScopeSpec *SS, NamedDecl *FoundD,
2400 SourceLocation TemplateKWLoc,
2401 const TemplateArgumentListInfo *TemplateArgs) {
2404 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2405 TemplateArgs);
2406}
2407
2408// CUDA/HIP: Check whether a captured reference variable is referencing a
2409// host variable in a device or host device lambda.
2411 VarDecl *VD) {
2412 if (!S.getLangOpts().CUDA || !VD->hasInit())
2413 return false;
2414 assert(VD->getType()->isReferenceType());
2415
2416 // Check whether the reference variable is referencing a host variable.
2417 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2418 if (!DRE)
2419 return false;
2420 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2421 if (!Referee || !Referee->hasGlobalStorage() ||
2422 Referee->hasAttr<CUDADeviceAttr>())
2423 return false;
2424
2425 // Check whether the current function is a device or host device lambda.
2426 // Check whether the reference variable is a capture by getDeclContext()
2427 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2428 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2429 if (MD && MD->getParent()->isLambda() &&
2430 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2431 VD->getDeclContext() != MD)
2432 return true;
2433
2434 return false;
2435}
2436
2438 // A declaration named in an unevaluated operand never constitutes an odr-use.
2440 return NOUR_Unevaluated;
2441
2442 // C++2a [basic.def.odr]p4:
2443 // A variable x whose name appears as a potentially-evaluated expression e
2444 // is odr-used by e unless [...] x is a reference that is usable in
2445 // constant expressions.
2446 // CUDA/HIP:
2447 // If a reference variable referencing a host variable is captured in a
2448 // device or host device lambda, the value of the referee must be copied
2449 // to the capture and the reference variable must be treated as odr-use
2450 // since the value of the referee is not known at compile time and must
2451 // be loaded from the captured.
2452 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2453 if (VD->getType()->isReferenceType() &&
2454 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2456 VD->isUsableInConstantExpressions(Context))
2457 return NOUR_Constant;
2458 }
2459
2460 // All remaining non-variable cases constitute an odr-use. For variables, we
2461 // need to wait and see how the expression is used.
2462 return NOUR_None;
2463}
2464
2467 const DeclarationNameInfo &NameInfo,
2468 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2469 SourceLocation TemplateKWLoc,
2470 const TemplateArgumentListInfo *TemplateArgs) {
2471 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2472 NeedToCaptureVariable(D, NameInfo.getLoc());
2473
2475 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2476 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2478
2479 // C++ [except.spec]p17:
2480 // An exception-specification is considered to be needed when:
2481 // - in an expression, the function is the unique lookup result or
2482 // the selected member of a set of overloaded functions.
2483 //
2484 // We delay doing this until after we've built the function reference and
2485 // marked it as used so that:
2486 // a) if the function is defaulted, we get errors from defining it before /
2487 // instead of errors from computing its exception specification, and
2488 // b) if the function is a defaulted comparison, we can use the body we
2489 // build when defining it as input to the exception specification
2490 // computation rather than computing a new body.
2491 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2492 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2493 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2494 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2495 }
2496 }
2497
2498 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2500 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2502
2503 const auto *FD = dyn_cast<FieldDecl>(D);
2504 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2505 FD = IFD->getAnonField();
2506 if (FD) {
2507 UnusedPrivateFields.remove(FD);
2508 // Just in case we're building an illegal pointer-to-member.
2509 if (FD->isBitField())
2511 }
2512
2513 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2514 // designates a bit-field.
2515 if (const auto *BD = dyn_cast<BindingDecl>(D))
2516 if (const auto *BE = BD->getBinding())
2517 E->setObjectKind(BE->getObjectKind());
2518
2519 return E;
2520}
2521
2522void
2525 DeclarationNameInfo &NameInfo,
2526 const TemplateArgumentListInfo *&TemplateArgs) {
2528 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2529 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2530
2531 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2532 Id.TemplateId->NumArgs);
2533 translateTemplateArguments(TemplateArgsPtr, Buffer);
2534
2535 TemplateName TName = Id.TemplateId->Template.get();
2537 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2538 TemplateArgs = &Buffer;
2539 } else {
2540 NameInfo = GetNameFromUnqualifiedId(Id);
2541 TemplateArgs = nullptr;
2542 }
2543}
2544
2546 // During a default argument instantiation the CurContext points
2547 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2548 // function parameter list, hence add an explicit check.
2549 bool isDefaultArgument =
2550 !CodeSynthesisContexts.empty() &&
2551 CodeSynthesisContexts.back().Kind ==
2553 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2554 bool isInstance = CurMethod && CurMethod->isInstance() &&
2555 R.getNamingClass() == CurMethod->getParent() &&
2556 !isDefaultArgument;
2557
2558 // There are two ways we can find a class-scope declaration during template
2559 // instantiation that we did not find in the template definition: if it is a
2560 // member of a dependent base class, or if it is declared after the point of
2561 // use in the same class. Distinguish these by comparing the class in which
2562 // the member was found to the naming class of the lookup.
2563 unsigned DiagID = diag::err_found_in_dependent_base;
2564 unsigned NoteID = diag::note_member_declared_at;
2565 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2566 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2567 : diag::err_found_later_in_class;
2568 } else if (getLangOpts().MSVCCompat) {
2569 DiagID = diag::ext_found_in_dependent_base;
2570 NoteID = diag::note_dependent_member_use;
2571 }
2572
2573 if (isInstance) {
2574 // Give a code modification hint to insert 'this->'.
2575 Diag(R.getNameLoc(), DiagID)
2576 << R.getLookupName()
2577 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2578 CheckCXXThisCapture(R.getNameLoc());
2579 } else {
2580 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2581 // they're not shadowed).
2582 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2583 }
2584
2585 for (const NamedDecl *D : R)
2586 Diag(D->getLocation(), NoteID);
2587
2588 // Return true if we are inside a default argument instantiation
2589 // and the found name refers to an instance member function, otherwise
2590 // the caller will try to create an implicit member call and this is wrong
2591 // for default arguments.
2592 //
2593 // FIXME: Is this special case necessary? We could allow the caller to
2594 // diagnose this.
2595 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2596 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2597 return true;
2598 }
2599
2600 // Tell the callee to try to recover.
2601 return false;
2602}
2603
2606 TemplateArgumentListInfo *ExplicitTemplateArgs,
2607 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2608 DeclarationName Name = R.getLookupName();
2609 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2610
2611 unsigned diagnostic = diag::err_undeclared_var_use;
2612 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2616 diagnostic = diag::err_undeclared_use;
2617 diagnostic_suggest = diag::err_undeclared_use_suggest;
2618 }
2619
2620 // If the original lookup was an unqualified lookup, fake an
2621 // unqualified lookup. This is useful when (for example) the
2622 // original lookup would not have found something because it was a
2623 // dependent name.
2624 DeclContext *DC =
2625 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2626 while (DC) {
2627 if (isa<CXXRecordDecl>(DC)) {
2628 if (ExplicitTemplateArgs) {
2630 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2631 /*EnteringContext*/ false, TemplateNameIsRequired,
2632 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2633 return true;
2634 } else {
2635 LookupQualifiedName(R, DC);
2636 }
2637
2638 if (!R.empty()) {
2639 // Don't give errors about ambiguities in this lookup.
2640 R.suppressDiagnostics();
2641
2642 // If there's a best viable function among the results, only mention
2643 // that one in the notes.
2644 OverloadCandidateSet Candidates(R.getNameLoc(),
2646 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2648 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2649 OR_Success) {
2650 R.clear();
2651 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2652 R.resolveKind();
2653 }
2654
2656 }
2657
2658 R.clear();
2659 }
2660
2661 DC = DC->getLookupParent();
2662 }
2663
2664 // We didn't find anything, so try to correct for a typo.
2665 TypoCorrection Corrected;
2666 if (S && (Corrected =
2667 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2668 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2669 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2670 bool DroppedSpecifier =
2671 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2672 R.setLookupName(Corrected.getCorrection());
2673
2674 bool AcceptableWithRecovery = false;
2675 bool AcceptableWithoutRecovery = false;
2676 NamedDecl *ND = Corrected.getFoundDecl();
2677 if (ND) {
2678 if (Corrected.isOverloaded()) {
2679 OverloadCandidateSet OCS(R.getNameLoc(),
2682 for (NamedDecl *CD : Corrected) {
2683 if (FunctionTemplateDecl *FTD =
2684 dyn_cast<FunctionTemplateDecl>(CD))
2686 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2687 Args, OCS);
2688 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2689 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2691 Args, OCS);
2692 }
2693 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2694 case OR_Success:
2695 ND = Best->FoundDecl;
2696 Corrected.setCorrectionDecl(ND);
2697 break;
2698 default:
2699 // FIXME: Arbitrarily pick the first declaration for the note.
2700 Corrected.setCorrectionDecl(ND);
2701 break;
2702 }
2703 }
2704 R.addDecl(ND);
2705 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2708 if (!Record)
2711 R.setNamingClass(Record);
2712 }
2713
2714 auto *UnderlyingND = ND->getUnderlyingDecl();
2715 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2716 isa<FunctionTemplateDecl>(UnderlyingND);
2717 // FIXME: If we ended up with a typo for a type name or
2718 // Objective-C class name, we're in trouble because the parser
2719 // is in the wrong place to recover. Suggest the typo
2720 // correction, but don't make it a fix-it since we're not going
2721 // to recover well anyway.
2722 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2723 getAsTypeTemplateDecl(UnderlyingND) ||
2724 isa<ObjCInterfaceDecl>(UnderlyingND);
2725 } else {
2726 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2727 // because we aren't able to recover.
2728 AcceptableWithoutRecovery = true;
2729 }
2730
2731 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2732 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2733 ? diag::note_implicit_param_decl
2734 : diag::note_previous_decl;
2735 if (SS.isEmpty())
2736 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2737 PDiag(NoteID), AcceptableWithRecovery);
2738 else
2739 diagnoseTypo(Corrected,
2740 PDiag(diag::err_no_member_suggest)
2741 << Name << computeDeclContext(SS, false)
2742 << DroppedSpecifier << NameRange,
2743 PDiag(NoteID), AcceptableWithRecovery);
2744
2745 if (Corrected.WillReplaceSpecifier()) {
2747 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2748 SS.MakeTrivial(Context, NNS,
2749 NNS ? NameRange.getBegin() : SourceRange());
2750 }
2751
2752 // Tell the callee whether to try to recover.
2753 return !AcceptableWithRecovery;
2754 }
2755 }
2756 R.clear();
2757
2758 // Emit a special diagnostic for failed member lookups.
2759 // FIXME: computing the declaration context might fail here (?)
2760 if (!SS.isEmpty()) {
2761 Diag(R.getNameLoc(), diag::err_no_member)
2762 << Name << computeDeclContext(SS, false) << NameRange;
2763 return true;
2764 }
2765
2766 // Give up, we can't recover.
2767 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2768 return true;
2769}
2770
2771/// In Microsoft mode, if we are inside a template class whose parent class has
2772/// dependent base classes, and we can't resolve an unqualified identifier, then
2773/// assume the identifier is a member of a dependent base class. We can only
2774/// recover successfully in static methods, instance methods, and other contexts
2775/// where 'this' is available. This doesn't precisely match MSVC's
2776/// instantiation model, but it's close enough.
2777static Expr *
2779 DeclarationNameInfo &NameInfo,
2780 SourceLocation TemplateKWLoc,
2781 const TemplateArgumentListInfo *TemplateArgs) {
2782 // Only try to recover from lookup into dependent bases in static methods or
2783 // contexts where 'this' is available.
2784 QualType ThisType = S.getCurrentThisType();
2785 const CXXRecordDecl *RD = nullptr;
2786 if (!ThisType.isNull())
2787 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2788 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2789 RD = MD->getParent();
2790 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2791 return nullptr;
2792
2793 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2794 // is available, suggest inserting 'this->' as a fixit.
2795 SourceLocation Loc = NameInfo.getLoc();
2796 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2797 DB << NameInfo.getName() << RD;
2798
2799 if (!ThisType.isNull()) {
2800 DB << FixItHint::CreateInsertion(Loc, "this->");
2802 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2803 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2804 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2805 }
2806
2807 // Synthesize a fake NNS that points to the derived class. This will
2808 // perform name lookup during template instantiation.
2809 CXXScopeSpec SS;
2810 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2811 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2813 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2814 TemplateArgs);
2815}
2816
2818 SourceLocation TemplateKWLoc,
2819 UnqualifiedId &Id, bool HasTrailingLParen,
2820 bool IsAddressOfOperand,
2822 bool IsInlineAsmIdentifier) {
2823 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2824 "cannot be direct & operand and have a trailing lparen");
2825 if (SS.isInvalid())
2826 return ExprError();
2827
2828 TemplateArgumentListInfo TemplateArgsBuffer;
2829
2830 // Decompose the UnqualifiedId into the following data.
2831 DeclarationNameInfo NameInfo;
2832 const TemplateArgumentListInfo *TemplateArgs;
2833 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2834
2835 DeclarationName Name = NameInfo.getName();
2837 SourceLocation NameLoc = NameInfo.getLoc();
2838
2839 if (II && II->isEditorPlaceholder()) {
2840 // FIXME: When typed placeholders are supported we can create a typed
2841 // placeholder expression node.
2842 return ExprError();
2843 }
2844
2845 // This specially handles arguments of attributes appertains to a type of C
2846 // struct field such that the name lookup within a struct finds the member
2847 // name, which is not the case for other contexts in C.
2848 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2849 // See if this is reference to a field of struct.
2850 LookupResult R(*this, NameInfo, LookupMemberName);
2851 // LookupName handles a name lookup from within anonymous struct.
2852 if (LookupName(R, S)) {
2853 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2854 QualType type = VD->getType().getNonReferenceType();
2855 // This will eventually be translated into MemberExpr upon
2856 // the use of instantiated struct fields.
2857 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2858 }
2859 }
2860 }
2861
2862 // Perform the required lookup.
2863 LookupResult R(*this, NameInfo,
2867 if (TemplateKWLoc.isValid() || TemplateArgs) {
2868 // Lookup the template name again to correctly establish the context in
2869 // which it was found. This is really unfortunate as we already did the
2870 // lookup to determine that it was a template name in the first place. If
2871 // this becomes a performance hit, we can work harder to preserve those
2872 // results until we get here but it's likely not worth it.
2873 AssumedTemplateKind AssumedTemplate;
2874 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2875 /*EnteringContext=*/false, TemplateKWLoc,
2876 &AssumedTemplate))
2877 return ExprError();
2878
2879 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2880 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2881 IsAddressOfOperand, TemplateArgs);
2882 } else {
2883 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2884 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2885 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2886
2887 // If the result might be in a dependent base class, this is a dependent
2888 // id-expression.
2889 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2890 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2891 IsAddressOfOperand, TemplateArgs);
2892
2893 // If this reference is in an Objective-C method, then we need to do
2894 // some special Objective-C lookup, too.
2895 if (IvarLookupFollowUp) {
2896 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2897 if (E.isInvalid())
2898 return ExprError();
2899
2900 if (Expr *Ex = E.getAs<Expr>())
2901 return Ex;
2902 }
2903 }
2904
2905 if (R.isAmbiguous())
2906 return ExprError();
2907
2908 // This could be an implicitly declared function reference if the language
2909 // mode allows it as a feature.
2910 if (R.empty() && HasTrailingLParen && II &&
2911 getLangOpts().implicitFunctionsAllowed()) {
2912 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2913 if (D) R.addDecl(D);
2914 }
2915
2916 // Determine whether this name might be a candidate for
2917 // argument-dependent lookup.
2918 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2919
2920 if (R.empty() && !ADL) {
2921 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2922 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2923 TemplateKWLoc, TemplateArgs))
2924 return E;
2925 }
2926
2927 // Don't diagnose an empty lookup for inline assembly.
2928 if (IsInlineAsmIdentifier)
2929 return ExprError();
2930
2931 // If this name wasn't predeclared and if this is not a function
2932 // call, diagnose the problem.
2933 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2934 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2935 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2936 "Typo correction callback misconfigured");
2937 if (CCC) {
2938 // Make sure the callback knows what the typo being diagnosed is.
2939 CCC->setTypoName(II);
2940 if (SS.isValid())
2941 CCC->setTypoNNS(SS.getScopeRep());
2942 }
2943 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2944 // a template name, but we happen to have always already looked up the name
2945 // before we get here if it must be a template name.
2946 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2947 {}, nullptr))
2948 return ExprError();
2949
2950 assert(!R.empty() &&
2951 "DiagnoseEmptyLookup returned false but added no results");
2952
2953 // If we found an Objective-C instance variable, let
2954 // LookupInObjCMethod build the appropriate expression to
2955 // reference the ivar.
2956 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2957 R.clear();
2958 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2959 // In a hopelessly buggy code, Objective-C instance variable
2960 // lookup fails and no expression will be built to reference it.
2961 if (!E.isInvalid() && !E.get())
2962 return ExprError();
2963 return E;
2964 }
2965 }
2966
2967 // This is guaranteed from this point on.
2968 assert(!R.empty() || ADL);
2969
2970 // Check whether this might be a C++ implicit instance member access.
2971 // C++ [class.mfct.non-static]p3:
2972 // When an id-expression that is not part of a class member access
2973 // syntax and not used to form a pointer to member is used in the
2974 // body of a non-static member function of class X, if name lookup
2975 // resolves the name in the id-expression to a non-static non-type
2976 // member of some class C, the id-expression is transformed into a
2977 // class member access expression using (*this) as the
2978 // postfix-expression to the left of the . operator.
2979 //
2980 // But we don't actually need to do this for '&' operands if R
2981 // resolved to a function or overloaded function set, because the
2982 // expression is ill-formed if it actually works out to be a
2983 // non-static member function:
2984 //
2985 // C++ [expr.ref]p4:
2986 // Otherwise, if E1.E2 refers to a non-static member function. . .
2987 // [t]he expression can be used only as the left-hand operand of a
2988 // member function call.
2989 //
2990 // There are other safeguards against such uses, but it's important
2991 // to get this right here so that we don't end up making a
2992 // spuriously dependent expression if we're inside a dependent
2993 // instance method.
2994 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2995 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2996 S);
2997
2998 if (TemplateArgs || TemplateKWLoc.isValid()) {
2999
3000 // In C++1y, if this is a variable template id, then check it
3001 // in BuildTemplateIdExpr().
3002 // The single lookup result must be a variable template declaration.
3006 assert(R.getAsSingle<TemplateDecl>() &&
3007 "There should only be one declaration found.");
3008 }
3009
3010 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
3011 }
3012
3013 return BuildDeclarationNameExpr(SS, R, ADL);
3014}
3015
3017 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3018 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3019 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3020 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
3021
3022 if (R.isAmbiguous())
3023 return ExprError();
3024
3025 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3026 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3027 NameInfo, /*TemplateArgs=*/nullptr);
3028
3029 if (R.empty()) {
3030 // Don't diagnose problems with invalid record decl, the secondary no_member
3031 // diagnostic during template instantiation is likely bogus, e.g. if a class
3032 // is invalid because it's derived from an invalid base class, then missing
3033 // members were likely supposed to be inherited.
3035 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
3036 if (CD->isInvalidDecl() || CD->isBeingDefined())
3037 return ExprError();
3038 Diag(NameInfo.getLoc(), diag::err_no_member)
3039 << NameInfo.getName() << DC << SS.getRange();
3040 return ExprError();
3041 }
3042
3043 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3044 QualType ET;
3045 TypeLocBuilder TLB;
3046 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
3047 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
3048 SS.getScopeRep(), TagD,
3049 /*OwnsTag=*/false);
3050 auto TL = TLB.push<TagTypeLoc>(ET);
3052 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3053 TL.setNameLoc(NameInfo.getLoc());
3054 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
3055 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
3056 SS.getScopeRep(), TypedefD);
3057 TLB.push<TypedefTypeLoc>(ET).set(
3058 /*ElaboratedKeywordLoc=*/SourceLocation(),
3059 SS.getWithLocInContext(Context), NameInfo.getLoc());
3060 } else {
3061 // FIXME: What else can appear here?
3062 ET = SemaRef.Context.getTypeDeclType(TD);
3063 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
3064 assert(SS.isEmpty());
3065 }
3066
3067 // Diagnose a missing typename if this resolved unambiguously to a type in
3068 // a dependent context. If we can recover with a type, downgrade this to
3069 // a warning in Microsoft compatibility mode.
3070 unsigned DiagID = diag::err_typename_missing;
3071 if (RecoveryTSI && getLangOpts().MSVCCompat)
3072 DiagID = diag::ext_typename_missing;
3073 SourceLocation Loc = SS.getBeginLoc();
3074 auto D = Diag(Loc, DiagID);
3075 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3076
3077 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3078 // context.
3079 if (!RecoveryTSI)
3080 return ExprError();
3081
3082 // Only issue the fixit if we're prepared to recover.
3083 D << FixItHint::CreateInsertion(Loc, "typename ");
3084
3085 // Recover by pretending this was an elaborated type.
3086 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3087
3088 return ExprEmpty();
3089 }
3090
3091 // If necessary, build an implicit class member access.
3092 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3094 /*TemplateKWLoc=*/SourceLocation(),
3095 R, /*TemplateArgs=*/nullptr,
3096 /*S=*/nullptr);
3097
3098 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3099}
3100
3102 NestedNameSpecifier Qualifier,
3103 NamedDecl *FoundDecl,
3104 NamedDecl *Member) {
3105 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3106 if (!RD)
3107 return From;
3108
3109 QualType DestRecordType;
3110 QualType DestType;
3111 QualType FromRecordType;
3112 QualType FromType = From->getType();
3113 bool PointerConversions = false;
3114 if (isa<FieldDecl>(Member)) {
3115 DestRecordType = Context.getCanonicalTagType(RD);
3116 auto FromPtrType = FromType->getAs<PointerType>();
3117 DestRecordType = Context.getAddrSpaceQualType(
3118 DestRecordType, FromPtrType
3119 ? FromType->getPointeeType().getAddressSpace()
3120 : FromType.getAddressSpace());
3121
3122 if (FromPtrType) {
3123 DestType = Context.getPointerType(DestRecordType);
3124 FromRecordType = FromPtrType->getPointeeType();
3125 PointerConversions = true;
3126 } else {
3127 DestType = DestRecordType;
3128 FromRecordType = FromType;
3129 }
3130 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3131 if (!Method->isImplicitObjectMemberFunction())
3132 return From;
3133
3134 DestType = Method->getThisType().getNonReferenceType();
3135 DestRecordType = Method->getFunctionObjectParameterType();
3136
3137 if (FromType->getAs<PointerType>()) {
3138 FromRecordType = FromType->getPointeeType();
3139 PointerConversions = true;
3140 } else {
3141 FromRecordType = FromType;
3142 DestType = DestRecordType;
3143 }
3144
3145 LangAS FromAS = FromRecordType.getAddressSpace();
3146 LangAS DestAS = DestRecordType.getAddressSpace();
3147 if (FromAS != DestAS) {
3148 QualType FromRecordTypeWithoutAS =
3149 Context.removeAddrSpaceQualType(FromRecordType);
3150 QualType FromTypeWithDestAS =
3151 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3152 if (PointerConversions)
3153 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3154 From = ImpCastExprToType(From, FromTypeWithDestAS,
3155 CK_AddressSpaceConversion, From->getValueKind())
3156 .get();
3157 }
3158 } else {
3159 // No conversion necessary.
3160 return From;
3161 }
3162
3163 if (DestType->isDependentType() || FromType->isDependentType())
3164 return From;
3165
3166 // If the unqualified types are the same, no conversion is necessary.
3167 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3168 return From;
3169
3170 SourceRange FromRange = From->getSourceRange();
3171 SourceLocation FromLoc = FromRange.getBegin();
3172
3173 ExprValueKind VK = From->getValueKind();
3174
3175 // C++ [class.member.lookup]p8:
3176 // [...] Ambiguities can often be resolved by qualifying a name with its
3177 // class name.
3178 //
3179 // If the member was a qualified name and the qualified referred to a
3180 // specific base subobject type, we'll cast to that intermediate type
3181 // first and then to the object in which the member is declared. That allows
3182 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3183 //
3184 // class Base { public: int x; };
3185 // class Derived1 : public Base { };
3186 // class Derived2 : public Base { };
3187 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3188 //
3189 // void VeryDerived::f() {
3190 // x = 17; // error: ambiguous base subobjects
3191 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3192 // }
3193 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3194 QualType QType = QualType(Qualifier.getAsType(), 0);
3195 assert(QType->isRecordType() && "lookup done with non-record type");
3196
3197 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3198
3199 // In C++98, the qualifier type doesn't actually have to be a base
3200 // type of the object type, in which case we just ignore it.
3201 // Otherwise build the appropriate casts.
3202 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3203 CXXCastPath BasePath;
3204 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3205 FromLoc, FromRange, &BasePath))
3206 return ExprError();
3207
3208 if (PointerConversions)
3209 QType = Context.getPointerType(QType);
3210 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3211 VK, &BasePath).get();
3212
3213 FromType = QType;
3214 FromRecordType = QRecordType;
3215
3216 // If the qualifier type was the same as the destination type,
3217 // we're done.
3218 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3219 return From;
3220 }
3221 }
3222
3223 CXXCastPath BasePath;
3224 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3225 FromLoc, FromRange, &BasePath,
3226 /*IgnoreAccess=*/true))
3227 return ExprError();
3228
3229 // Propagate qualifiers to base subobjects as per:
3230 // C++ [basic.type.qualifier]p1.2:
3231 // A volatile object is [...] a subobject of a volatile object.
3232 Qualifiers FromTypeQuals = FromType.getQualifiers();
3233 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3234 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3235
3236 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3237 &BasePath);
3238}
3239
3241 const LookupResult &R,
3242 bool HasTrailingLParen) {
3243 // Only when used directly as the postfix-expression of a call.
3244 if (!HasTrailingLParen)
3245 return false;
3246
3247 // Never if a scope specifier was provided.
3248 if (SS.isNotEmpty())
3249 return false;
3250
3251 // Only in C++ or ObjC++.
3252 if (!getLangOpts().CPlusPlus)
3253 return false;
3254
3255 // Turn off ADL when we find certain kinds of declarations during
3256 // normal lookup:
3257 for (const NamedDecl *D : R) {
3258 // C++0x [basic.lookup.argdep]p3:
3259 // -- a declaration of a class member
3260 // Since using decls preserve this property, we check this on the
3261 // original decl.
3262 if (D->isCXXClassMember())
3263 return false;
3264
3265 // C++0x [basic.lookup.argdep]p3:
3266 // -- a block-scope function declaration that is not a
3267 // using-declaration
3268 // NOTE: we also trigger this for function templates (in fact, we
3269 // don't check the decl type at all, since all other decl types
3270 // turn off ADL anyway).
3271 if (isa<UsingShadowDecl>(D))
3272 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3273 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3274 return false;
3275
3276 // C++0x [basic.lookup.argdep]p3:
3277 // -- a declaration that is neither a function or a function
3278 // template
3279 // And also for builtin functions.
3280 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3281 // But also builtin functions.
3282 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3283 return false;
3284 } else if (!isa<FunctionTemplateDecl>(D))
3285 return false;
3286 }
3287
3288 return true;
3289}
3290
3291
3292/// Diagnoses obvious problems with the use of the given declaration
3293/// as an expression. This is only actually called for lookups that
3294/// were not overloaded, and it doesn't promise that the declaration
3295/// will in fact be used.
3297 bool AcceptInvalid) {
3298 if (D->isInvalidDecl() && !AcceptInvalid)
3299 return true;
3300
3301 if (isa<TypedefNameDecl>(D)) {
3302 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3303 return true;
3304 }
3305
3306 if (isa<ObjCInterfaceDecl>(D)) {
3307 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3308 return true;
3309 }
3310
3311 if (isa<NamespaceDecl>(D)) {
3312 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3313 return true;
3314 }
3315
3316 return false;
3317}
3318
3319// Certain multiversion types should be treated as overloaded even when there is
3320// only one result.
3322 assert(R.isSingleResult() && "Expected only a single result");
3323 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3324 return FD &&
3325 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3326}
3327
3329 LookupResult &R, bool NeedsADL,
3330 bool AcceptInvalidDecl) {
3331 // If this is a single, fully-resolved result and we don't need ADL,
3332 // just build an ordinary singleton decl ref.
3333 if (!NeedsADL && R.isSingleResult() &&
3334 !R.getAsSingle<FunctionTemplateDecl>() &&
3336 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3337 R.getRepresentativeDecl(), nullptr,
3338 AcceptInvalidDecl);
3339
3340 // We only need to check the declaration if there's exactly one
3341 // result, because in the overloaded case the results can only be
3342 // functions and function templates.
3343 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3344 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3345 AcceptInvalidDecl))
3346 return ExprError();
3347
3348 // Otherwise, just build an unresolved lookup expression. Suppress
3349 // any lookup-related diagnostics; we'll hash these out later, when
3350 // we've picked a target.
3351 R.suppressDiagnostics();
3352
3354 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3355 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3356 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3357
3358 return ULE;
3359}
3360
3362 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3363 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3364 bool AcceptInvalidDecl) {
3365 assert(D && "Cannot refer to a NULL declaration");
3366 assert(!isa<FunctionTemplateDecl>(D) &&
3367 "Cannot refer unambiguously to a function template");
3368
3369 SourceLocation Loc = NameInfo.getLoc();
3370 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3371 // Recovery from invalid cases (e.g. D is an invalid Decl).
3372 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3373 // diagnostics, as invalid decls use int as a fallback type.
3374 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3375 }
3376
3377 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3378 // Specifically diagnose references to class templates that are missing
3379 // a template argument list.
3380 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3381 return ExprError();
3382 }
3383
3384 // Make sure that we're referring to a value.
3386 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3387 Diag(D->getLocation(), diag::note_declared_at);
3388 return ExprError();
3389 }
3390
3391 // Check whether this declaration can be used. Note that we suppress
3392 // this check when we're going to perform argument-dependent lookup
3393 // on this function name, because this might not be the function
3394 // that overload resolution actually selects.
3395 if (DiagnoseUseOfDecl(D, Loc))
3396 return ExprError();
3397
3398 auto *VD = cast<ValueDecl>(D);
3399
3400 // Only create DeclRefExpr's for valid Decl's.
3401 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3402 return ExprError();
3403
3404 // Handle members of anonymous structs and unions. If we got here,
3405 // and the reference is to a class member indirect field, then this
3406 // must be the subject of a pointer-to-member expression.
3407 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3408 IndirectField && !IndirectField->isCXXClassMember())
3410 IndirectField);
3411
3412 QualType type = VD->getType();
3413 if (type.isNull())
3414 return ExprError();
3415 ExprValueKind valueKind = VK_PRValue;
3416
3417 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3418 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3419 // is expanded by some outer '...' in the context of the use.
3420 type = type.getNonPackExpansionType();
3421
3422 switch (D->getKind()) {
3423 // Ignore all the non-ValueDecl kinds.
3424#define ABSTRACT_DECL(kind)
3425#define VALUE(type, base)
3426#define DECL(type, base) case Decl::type:
3427#include "clang/AST/DeclNodes.inc"
3428 llvm_unreachable("invalid value decl kind");
3429
3430 // These shouldn't make it here.
3431 case Decl::ObjCAtDefsField:
3432 llvm_unreachable("forming non-member reference to ivar?");
3433
3434 // Enum constants are always r-values and never references.
3435 // Unresolved using declarations are dependent.
3436 case Decl::EnumConstant:
3437 case Decl::UnresolvedUsingValue:
3438 case Decl::OMPDeclareReduction:
3439 case Decl::OMPDeclareMapper:
3440 valueKind = VK_PRValue;
3441 break;
3442
3443 // Fields and indirect fields that got here must be for
3444 // pointer-to-member expressions; we just call them l-values for
3445 // internal consistency, because this subexpression doesn't really
3446 // exist in the high-level semantics.
3447 case Decl::Field:
3448 case Decl::IndirectField:
3449 case Decl::ObjCIvar:
3450 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3451 "building reference to field in C?");
3452
3453 // These can't have reference type in well-formed programs, but
3454 // for internal consistency we do this anyway.
3455 type = type.getNonReferenceType();
3456 valueKind = VK_LValue;
3457 break;
3458
3459 // Non-type template parameters are either l-values or r-values
3460 // depending on the type.
3461 case Decl::NonTypeTemplateParm: {
3462 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3463 type = reftype->getPointeeType();
3464 valueKind = VK_LValue; // even if the parameter is an r-value reference
3465 break;
3466 }
3467
3468 // [expr.prim.id.unqual]p2:
3469 // If the entity is a template parameter object for a template
3470 // parameter of type T, the type of the expression is const T.
3471 // [...] The expression is an lvalue if the entity is a [...] template
3472 // parameter object.
3473 if (type->isRecordType()) {
3474 type = type.getUnqualifiedType().withConst();
3475 valueKind = VK_LValue;
3476 break;
3477 }
3478
3479 // For non-references, we need to strip qualifiers just in case
3480 // the template parameter was declared as 'const int' or whatever.
3481 valueKind = VK_PRValue;
3482 type = type.getUnqualifiedType();
3483 break;
3484 }
3485
3486 case Decl::Var:
3487 case Decl::VarTemplateSpecialization:
3488 case Decl::VarTemplatePartialSpecialization:
3489 case Decl::Decomposition:
3490 case Decl::Binding:
3491 case Decl::OMPCapturedExpr:
3492 // In C, "extern void blah;" is valid and is an r-value.
3493 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3494 type->isVoidType()) {
3495 valueKind = VK_PRValue;
3496 break;
3497 }
3498 [[fallthrough]];
3499
3500 case Decl::ImplicitParam:
3501 case Decl::ParmVar: {
3502 // These are always l-values.
3503 valueKind = VK_LValue;
3504 type = type.getNonReferenceType();
3505
3506 // FIXME: Does the addition of const really only apply in
3507 // potentially-evaluated contexts? Since the variable isn't actually
3508 // captured in an unevaluated context, it seems that the answer is no.
3509 if (!isUnevaluatedContext()) {
3510 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3511 if (!CapturedType.isNull())
3512 type = CapturedType;
3513 }
3514 break;
3515 }
3516
3517 case Decl::Function: {
3518 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3519 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3520 type = Context.BuiltinFnTy;
3521 valueKind = VK_PRValue;
3522 break;
3523 }
3524 }
3525
3526 const FunctionType *fty = type->castAs<FunctionType>();
3527
3528 // If we're referring to a function with an __unknown_anytype
3529 // result type, make the entire expression __unknown_anytype.
3530 if (fty->getReturnType() == Context.UnknownAnyTy) {
3531 type = Context.UnknownAnyTy;
3532 valueKind = VK_PRValue;
3533 break;
3534 }
3535
3536 // Functions are l-values in C++.
3537 if (getLangOpts().CPlusPlus) {
3538 valueKind = VK_LValue;
3539 break;
3540 }
3541
3542 // C99 DR 316 says that, if a function type comes from a
3543 // function definition (without a prototype), that type is only
3544 // used for checking compatibility. Therefore, when referencing
3545 // the function, we pretend that we don't have the full function
3546 // type.
3547 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3548 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3549 fty->getExtInfo());
3550
3551 // Functions are r-values in C.
3552 valueKind = VK_PRValue;
3553 break;
3554 }
3555
3556 case Decl::CXXDeductionGuide:
3557 llvm_unreachable("building reference to deduction guide");
3558
3559 case Decl::MSProperty:
3560 case Decl::MSGuid:
3561 case Decl::TemplateParamObject:
3562 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3563 // capture in OpenMP, or duplicated between host and device?
3564 valueKind = VK_LValue;
3565 break;
3566
3567 case Decl::UnnamedGlobalConstant:
3568 valueKind = VK_LValue;
3569 break;
3570
3571 case Decl::CXXMethod:
3572 // If we're referring to a method with an __unknown_anytype
3573 // result type, make the entire expression __unknown_anytype.
3574 // This should only be possible with a type written directly.
3575 if (const FunctionProtoType *proto =
3576 dyn_cast<FunctionProtoType>(VD->getType()))
3577 if (proto->getReturnType() == Context.UnknownAnyTy) {
3578 type = Context.UnknownAnyTy;
3579 valueKind = VK_PRValue;
3580 break;
3581 }
3582
3583 // C++ methods are l-values if static, r-values if non-static.
3584 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3585 valueKind = VK_LValue;
3586 break;
3587 }
3588 [[fallthrough]];
3589
3590 case Decl::CXXConversion:
3591 case Decl::CXXDestructor:
3592 case Decl::CXXConstructor:
3593 valueKind = VK_PRValue;
3594 break;
3595 }
3596
3597 auto *E =
3598 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3599 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3600 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3601 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3602 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3603 // diagnostics).
3604 if (VD->isInvalidDecl() && E)
3605 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3606 return E;
3607}
3608
3609static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3611 Target.resize(CharByteWidth * (Source.size() + 1));
3612 char *ResultPtr = &Target[0];
3613 const llvm::UTF8 *ErrorPtr;
3614 bool success =
3615 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3616 (void)success;
3617 assert(success);
3618 Target.resize(ResultPtr - &Target[0]);
3619}
3620
3623 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3624 if (!currentDecl) {
3625 Diag(Loc, diag::ext_predef_outside_function);
3626 currentDecl = Context.getTranslationUnitDecl();
3627 }
3628
3629 QualType ResTy;
3630 StringLiteral *SL = nullptr;
3631 if (cast<DeclContext>(currentDecl)->isDependentContext())
3632 ResTy = Context.DependentTy;
3633 else {
3634 // Pre-defined identifiers are of type char[x], where x is the length of
3635 // the string.
3636 bool ForceElaboratedPrinting =
3637 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3638 auto Str =
3639 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3640 unsigned Length = Str.length();
3641
3642 llvm::APInt LengthI(32, Length + 1);
3645 ResTy =
3646 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3647 SmallString<32> RawChars;
3648 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3649 Str, RawChars);
3650 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3652 /*IndexTypeQuals*/ 0);
3654 /*Pascal*/ false, ResTy, Loc);
3655 } else {
3656 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3657 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3659 /*IndexTypeQuals*/ 0);
3661 /*Pascal*/ false, ResTy, Loc);
3662 }
3663 }
3664
3665 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3666 SL);
3667}
3668
3672
3674 SmallString<16> CharBuffer;
3675 bool Invalid = false;
3676 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3677 if (Invalid)
3678 return ExprError();
3679
3680 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3681 PP, Tok.getKind());
3682 if (Literal.hadError())
3683 return ExprError();
3684
3685 QualType Ty;
3686 if (Literal.isWide())
3687 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3688 else if (Literal.isUTF8() && getLangOpts().C23)
3689 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3690 else if (Literal.isUTF8() && getLangOpts().Char8)
3691 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3692 else if (Literal.isUTF16())
3693 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3694 else if (Literal.isUTF32())
3695 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3696 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3697 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3698 else
3699 Ty = Context.CharTy; // 'x' -> char in C++;
3700 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3701
3703 if (Literal.isWide())
3705 else if (Literal.isUTF16())
3707 else if (Literal.isUTF32())
3709 else if (Literal.isUTF8())
3711
3712 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3713 Tok.getLocation());
3714
3715 if (Literal.getUDSuffix().empty())
3716 return Lit;
3717
3718 // We're building a user-defined literal.
3719 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3720 SourceLocation UDSuffixLoc =
3721 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3722
3723 // Make sure we're allowed user-defined literals here.
3724 if (!UDLScope)
3725 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3726
3727 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3728 // operator "" X (ch)
3729 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3730 Lit, Tok.getLocation());
3731}
3732
3734 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3736 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3737 Context.IntTy, Loc);
3738}
3739
3741 QualType Ty, SourceLocation Loc) {
3742 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3743
3744 using llvm::APFloat;
3745 APFloat Val(Format);
3746
3747 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3748 if (RM == llvm::RoundingMode::Dynamic)
3749 RM = llvm::RoundingMode::NearestTiesToEven;
3750 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3751
3752 // Overflow is always an error, but underflow is only an error if
3753 // we underflowed to zero (APFloat reports denormals as underflow).
3754 if ((result & APFloat::opOverflow) ||
3755 ((result & APFloat::opUnderflow) && Val.isZero())) {
3756 unsigned diagnostic;
3757 SmallString<20> buffer;
3758 if (result & APFloat::opOverflow) {
3759 diagnostic = diag::warn_float_overflow;
3760 APFloat::getLargest(Format).toString(buffer);
3761 } else {
3762 diagnostic = diag::warn_float_underflow;
3763 APFloat::getSmallest(Format).toString(buffer);
3764 }
3765
3766 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3767 }
3768
3769 bool isExact = (result == APFloat::opOK);
3770 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3771}
3772
3773bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3774 assert(E && "Invalid expression");
3775
3776 if (E->isValueDependent())
3777 return false;
3778
3779 QualType QT = E->getType();
3780 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3781 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3782 return true;
3783 }
3784
3785 llvm::APSInt ValueAPS;
3787
3788 if (R.isInvalid())
3789 return true;
3790
3791 // GCC allows the value of unroll count to be 0.
3792 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3793 // "The values of 0 and 1 block any unrolling of the loop."
3794 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3795 // '#pragma unroll' cases.
3796 bool ValueIsPositive =
3797 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3798 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3799 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3800 << toString(ValueAPS, 10) << ValueIsPositive;
3801 return true;
3802 }
3803
3804 return false;
3805}
3806
3808 // Fast path for a single digit (which is quite common). A single digit
3809 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3810 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3811 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3812 return ActOnIntegerConstant(Tok.getLocation(), Val);
3813 }
3814
3815 SmallString<128> SpellingBuffer;
3816 // NumericLiteralParser wants to overread by one character. Add padding to
3817 // the buffer in case the token is copied to the buffer. If getSpelling()
3818 // returns a StringRef to the memory buffer, it should have a null char at
3819 // the EOF, so it is also safe.
3820 SpellingBuffer.resize(Tok.getLength() + 1);
3821
3822 // Get the spelling of the token, which eliminates trigraphs, etc.
3823 bool Invalid = false;
3824 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3825 if (Invalid)
3826 return ExprError();
3827
3828 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3829 PP.getSourceManager(), PP.getLangOpts(),
3830 PP.getTargetInfo(), PP.getDiagnostics());
3831 if (Literal.hadError)
3832 return ExprError();
3833
3834 if (Literal.hasUDSuffix()) {
3835 // We're building a user-defined literal.
3836 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3837 SourceLocation UDSuffixLoc =
3838 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3839
3840 // Make sure we're allowed user-defined literals here.
3841 if (!UDLScope)
3842 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3843
3844 QualType CookedTy;
3845 if (Literal.isFloatingLiteral()) {
3846 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3847 // long double, the literal is treated as a call of the form
3848 // operator "" X (f L)
3849 CookedTy = Context.LongDoubleTy;
3850 } else {
3851 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3852 // unsigned long long, the literal is treated as a call of the form
3853 // operator "" X (n ULL)
3854 CookedTy = Context.UnsignedLongLongTy;
3855 }
3856
3857 DeclarationName OpName =
3858 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3859 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3860 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3861
3862 SourceLocation TokLoc = Tok.getLocation();
3863
3864 // Perform literal operator lookup to determine if we're building a raw
3865 // literal or a cooked one.
3866 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3867 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3868 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3869 /*AllowStringTemplatePack*/ false,
3870 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3872 // Lookup failure for imaginary constants isn't fatal, there's still the
3873 // GNU extension producing _Complex types.
3874 break;
3875 case LOLR_Error:
3876 return ExprError();
3877 case LOLR_Cooked: {
3878 Expr *Lit;
3879 if (Literal.isFloatingLiteral()) {
3880 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3881 } else {
3882 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3883 if (Literal.GetIntegerValue(ResultVal))
3884 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3885 << /* Unsigned */ 1;
3886 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3887 Tok.getLocation());
3888 }
3889 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3890 }
3891
3892 case LOLR_Raw: {
3893 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3894 // literal is treated as a call of the form
3895 // operator "" X ("n")
3896 unsigned Length = Literal.getUDSuffixOffset();
3897 QualType StrTy = Context.getConstantArrayType(
3898 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3899 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3900 Expr *Lit =
3901 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3903 /*Pascal*/ false, StrTy, TokLoc);
3904 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3905 }
3906
3907 case LOLR_Template: {
3908 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3909 // template), L is treated as a call fo the form
3910 // operator "" X <'c1', 'c2', ... 'ck'>()
3911 // where n is the source character sequence c1 c2 ... ck.
3912 TemplateArgumentListInfo ExplicitArgs;
3913 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3914 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3915 llvm::APSInt Value(CharBits, CharIsUnsigned);
3916 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3917 Value = TokSpelling[I];
3918 TemplateArgument Arg(Context, Value, Context.CharTy);
3920 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3921 }
3922 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3923 }
3925 llvm_unreachable("unexpected literal operator lookup result");
3926 }
3927 }
3928
3929 Expr *Res;
3930
3931 if (Literal.isFixedPointLiteral()) {
3932 QualType Ty;
3933
3934 if (Literal.isAccum) {
3935 if (Literal.isHalf) {
3936 Ty = Context.ShortAccumTy;
3937 } else if (Literal.isLong) {
3938 Ty = Context.LongAccumTy;
3939 } else {
3940 Ty = Context.AccumTy;
3941 }
3942 } else if (Literal.isFract) {
3943 if (Literal.isHalf) {
3944 Ty = Context.ShortFractTy;
3945 } else if (Literal.isLong) {
3946 Ty = Context.LongFractTy;
3947 } else {
3948 Ty = Context.FractTy;
3949 }
3950 }
3951
3952 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3953
3954 bool isSigned = !Literal.isUnsigned;
3955 unsigned scale = Context.getFixedPointScale(Ty);
3956 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3957
3958 llvm::APInt Val(bit_width, 0, isSigned);
3959 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3960 bool ValIsZero = Val.isZero() && !Overflowed;
3961
3962 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3963 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3964 // Clause 6.4.4 - The value of a constant shall be in the range of
3965 // representable values for its type, with exception for constants of a
3966 // fract type with a value of exactly 1; such a constant shall denote
3967 // the maximal value for the type.
3968 --Val;
3969 else if (Val.ugt(MaxVal) || Overflowed)
3970 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3971
3973 Tok.getLocation(), scale);
3974 } else if (Literal.isFloatingLiteral()) {
3975 QualType Ty;
3976 if (Literal.isHalf){
3977 if (getLangOpts().HLSL ||
3978 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3979 Ty = Context.HalfTy;
3980 else {
3981 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3982 return ExprError();
3983 }
3984 } else if (Literal.isFloat)
3985 Ty = Context.FloatTy;
3986 else if (Literal.isLong)
3987 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3988 else if (Literal.isFloat16)
3989 Ty = Context.Float16Ty;
3990 else if (Literal.isFloat128)
3991 Ty = Context.Float128Ty;
3992 else if (getLangOpts().HLSL)
3993 Ty = Context.FloatTy;
3994 else
3995 Ty = Context.DoubleTy;
3996
3997 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3998
3999 if (Ty == Context.DoubleTy) {
4000 if (getLangOpts().SinglePrecisionConstants) {
4001 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4002 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4003 }
4004 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4005 "cl_khr_fp64", getLangOpts())) {
4006 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4007 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4009 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4010 }
4011 }
4012 } else if (!Literal.isIntegerLiteral()) {
4013 return ExprError();
4014 } else {
4015 QualType Ty;
4016
4017 // 'z/uz' literals are a C++23 feature.
4018 if (Literal.isSizeT)
4019 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4021 ? diag::warn_cxx20_compat_size_t_suffix
4022 : diag::ext_cxx23_size_t_suffix
4023 : diag::err_cxx23_size_t_suffix);
4024
4025 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4026 // but we do not currently support the suffix in C++ mode because it's not
4027 // entirely clear whether WG21 will prefer this suffix to return a library
4028 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4029 // literals are a C++ extension.
4030 if (Literal.isBitInt)
4031 PP.Diag(Tok.getLocation(),
4032 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4033 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4034 : diag::ext_c23_bitint_suffix);
4035
4036 // Get the value in the widest-possible width. What is "widest" depends on
4037 // whether the literal is a bit-precise integer or not. For a bit-precise
4038 // integer type, try to scan the source to determine how many bits are
4039 // needed to represent the value. This may seem a bit expensive, but trying
4040 // to get the integer value from an overly-wide APInt is *extremely*
4041 // expensive, so the naive approach of assuming
4042 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4043 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4044 if (Literal.isBitInt)
4045 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4046 Literal.getLiteralDigits(), Literal.getRadix());
4047 if (Literal.MicrosoftInteger) {
4048 if (Literal.MicrosoftInteger == 128 &&
4049 !Context.getTargetInfo().hasInt128Type())
4050 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4051 << Literal.isUnsigned;
4052 BitsNeeded = Literal.MicrosoftInteger;
4053 }
4054
4055 llvm::APInt ResultVal(BitsNeeded, 0);
4056
4057 if (Literal.GetIntegerValue(ResultVal)) {
4058 // If this value didn't fit into uintmax_t, error and force to ull.
4059 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4060 << /* Unsigned */ 1;
4061 Ty = Context.UnsignedLongLongTy;
4062 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4063 "long long is not intmax_t?");
4064 } else {
4065 // If this value fits into a ULL, try to figure out what else it fits into
4066 // according to the rules of C99 6.4.4.1p5.
4067
4068 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4069 // be an unsigned int.
4070 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4071
4072 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4073 // suffix for portability of code with C++, but both `l` and `ll` are
4074 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4075 // same.
4076 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4077 Literal.isLong = true;
4078 Literal.isLongLong = false;
4079 }
4080
4081 // Check from smallest to largest, picking the smallest type we can.
4082 unsigned Width = 0;
4083
4084 // Microsoft specific integer suffixes are explicitly sized.
4085 if (Literal.MicrosoftInteger) {
4086 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4087 Width = 8;
4088 Ty = Context.CharTy;
4089 } else {
4090 Width = Literal.MicrosoftInteger;
4091 Ty = Context.getIntTypeForBitwidth(Width,
4092 /*Signed=*/!Literal.isUnsigned);
4093 }
4094 }
4095
4096 // Bit-precise integer literals are automagically-sized based on the
4097 // width required by the literal.
4098 if (Literal.isBitInt) {
4099 // The signed version has one more bit for the sign value. There are no
4100 // zero-width bit-precise integers, even if the literal value is 0.
4101 Width = std::max(ResultVal.getActiveBits(), 1u) +
4102 (Literal.isUnsigned ? 0u : 1u);
4103
4104 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4105 // and reset the type to the largest supported width.
4106 unsigned int MaxBitIntWidth =
4107 Context.getTargetInfo().getMaxBitIntWidth();
4108 if (Width > MaxBitIntWidth) {
4109 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4110 << Literal.isUnsigned;
4111 Width = MaxBitIntWidth;
4112 }
4113
4114 // Reset the result value to the smaller APInt and select the correct
4115 // type to be used. Note, we zext even for signed values because the
4116 // literal itself is always an unsigned value (a preceeding - is a
4117 // unary operator, not part of the literal).
4118 ResultVal = ResultVal.zextOrTrunc(Width);
4119 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4120 }
4121
4122 // Check C++23 size_t literals.
4123 if (Literal.isSizeT) {
4124 assert(!Literal.MicrosoftInteger &&
4125 "size_t literals can't be Microsoft literals");
4126 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4127 Context.getTargetInfo().getSizeType());
4128
4129 // Does it fit in size_t?
4130 if (ResultVal.isIntN(SizeTSize)) {
4131 // Does it fit in ssize_t?
4132 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4133 Ty = Context.getSignedSizeType();
4134 else if (AllowUnsigned)
4135 Ty = Context.getSizeType();
4136 Width = SizeTSize;
4137 }
4138 }
4139
4140 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4141 !Literal.isSizeT) {
4142 // Are int/unsigned possibilities?
4143 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4144
4145 // Does it fit in a unsigned int?
4146 if (ResultVal.isIntN(IntSize)) {
4147 // Does it fit in a signed int?
4148 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4149 Ty = Context.IntTy;
4150 else if (AllowUnsigned)
4151 Ty = Context.UnsignedIntTy;
4152 Width = IntSize;
4153 }
4154 }
4155
4156 // Are long/unsigned long possibilities?
4157 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4158 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4159
4160 // Does it fit in a unsigned long?
4161 if (ResultVal.isIntN(LongSize)) {
4162 // Does it fit in a signed long?
4163 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4164 Ty = Context.LongTy;
4165 else if (AllowUnsigned)
4166 Ty = Context.UnsignedLongTy;
4167 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4168 // is compatible.
4169 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4170 const unsigned LongLongSize =
4171 Context.getTargetInfo().getLongLongWidth();
4172 Diag(Tok.getLocation(),
4174 ? Literal.isLong
4175 ? diag::warn_old_implicitly_unsigned_long_cxx
4176 : /*C++98 UB*/ diag::
4177 ext_old_implicitly_unsigned_long_cxx
4178 : diag::warn_old_implicitly_unsigned_long)
4179 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4180 : /*will be ill-formed*/ 1);
4181 Ty = Context.UnsignedLongTy;
4182 }
4183 Width = LongSize;
4184 }
4185 }
4186
4187 // Check long long if needed.
4188 if (Ty.isNull() && !Literal.isSizeT) {
4189 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4190
4191 // Does it fit in a unsigned long long?
4192 if (ResultVal.isIntN(LongLongSize)) {
4193 // Does it fit in a signed long long?
4194 // To be compatible with MSVC, hex integer literals ending with the
4195 // LL or i64 suffix are always signed in Microsoft mode.
4196 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4197 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4198 Ty = Context.LongLongTy;
4199 else if (AllowUnsigned)
4200 Ty = Context.UnsignedLongLongTy;
4201 Width = LongLongSize;
4202
4203 // 'long long' is a C99 or C++11 feature, whether the literal
4204 // explicitly specified 'long long' or we needed the extra width.
4205 if (getLangOpts().CPlusPlus)
4206 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4207 ? diag::warn_cxx98_compat_longlong
4208 : diag::ext_cxx11_longlong);
4209 else if (!getLangOpts().C99)
4210 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4211 }
4212 }
4213
4214 // If we still couldn't decide a type, we either have 'size_t' literal
4215 // that is out of range, or a decimal literal that does not fit in a
4216 // signed long long and has no U suffix.
4217 if (Ty.isNull()) {
4218 if (Literal.isSizeT)
4219 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4220 << Literal.isUnsigned;
4221 else
4222 Diag(Tok.getLocation(),
4223 diag::ext_integer_literal_too_large_for_signed);
4224 Ty = Context.UnsignedLongLongTy;
4225 Width = Context.getTargetInfo().getLongLongWidth();
4226 }
4227
4228 if (ResultVal.getBitWidth() != Width)
4229 ResultVal = ResultVal.trunc(Width);
4230 }
4231 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4232 }
4233
4234 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4235 if (Literal.isImaginary) {
4236 Res = new (Context) ImaginaryLiteral(Res,
4237 Context.getComplexType(Res->getType()));
4238
4239 // In C++, this is a GNU extension. In C, it's a C2y extension.
4240 unsigned DiagId;
4241 if (getLangOpts().CPlusPlus)
4242 DiagId = diag::ext_gnu_imaginary_constant;
4243 else if (getLangOpts().C2y)
4244 DiagId = diag::warn_c23_compat_imaginary_constant;
4245 else
4246 DiagId = diag::ext_c2y_imaginary_constant;
4247 Diag(Tok.getLocation(), DiagId);
4248 }
4249 return Res;
4250}
4251
4253 assert(E && "ActOnParenExpr() missing expr");
4254 QualType ExprTy = E->getType();
4255 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4256 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4257 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4258 return new (Context) ParenExpr(L, R, E);
4259}
4260
4262 SourceLocation Loc,
4263 SourceRange ArgRange) {
4264 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4265 // scalar or vector data type argument..."
4266 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4267 // type (C99 6.2.5p18) or void.
4268 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4269 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4270 << T << ArgRange;
4271 return true;
4272 }
4273
4274 assert((T->isVoidType() || !T->isIncompleteType()) &&
4275 "Scalar types should always be complete");
4276 return false;
4277}
4278
4280 SourceLocation Loc,
4281 SourceRange ArgRange) {
4282 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4283 if (!T->isVectorType() && !T->isSizelessVectorType())
4284 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4285 << ""
4286 << "__builtin_vectorelements" << T << ArgRange;
4287
4288 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
4289 if (T->isSVESizelessBuiltinType()) {
4290 llvm::StringMap<bool> CallerFeatureMap;
4291 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
4292 return S.ARM().checkSVETypeSupport(T, Loc, FD, CallerFeatureMap);
4293 }
4294 }
4295
4296 return false;
4297}
4298
4300 SourceLocation Loc,
4301 SourceRange ArgRange) {
4302 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4303 return true;
4304
4305 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4306 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4307 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4308 return true;
4309 }
4310
4311 return false;
4312}
4313
4315 SourceLocation Loc,
4316 SourceRange ArgRange,
4317 UnaryExprOrTypeTrait TraitKind) {
4318 // Invalid types must be hard errors for SFINAE in C++.
4319 if (S.LangOpts.CPlusPlus)
4320 return true;
4321
4322 // C99 6.5.3.4p1:
4323 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4324 TraitKind == UETT_PreferredAlignOf) {
4325
4326 // sizeof(function)/alignof(function) is allowed as an extension.
4327 if (T->isFunctionType()) {
4328 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4329 << getTraitSpelling(TraitKind) << ArgRange;
4330 return false;
4331 }
4332
4333 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4334 // this is an error (OpenCL v1.1 s6.3.k)
4335 if (T->isVoidType()) {
4336 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4337 : diag::ext_sizeof_alignof_void_type;
4338 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4339 return false;
4340 }
4341 }
4342 return true;
4343}
4344
4346 SourceLocation Loc,
4347 SourceRange ArgRange,
4348 UnaryExprOrTypeTrait TraitKind) {
4349 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4350 // runtime doesn't allow it.
4351 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4352 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4353 << T << (TraitKind == UETT_SizeOf)
4354 << ArgRange;
4355 return true;
4356 }
4357
4358 return false;
4359}
4360
4361/// Check whether E is a pointer from a decayed array type (the decayed
4362/// pointer type is equal to T) and emit a warning if it is.
4364 const Expr *E) {
4365 // Don't warn if the operation changed the type.
4366 if (T != E->getType())
4367 return;
4368
4369 // Now look for array decays.
4370 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4371 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4372 return;
4373
4374 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4375 << ICE->getType()
4376 << ICE->getSubExpr()->getType();
4377}
4378
4380 UnaryExprOrTypeTrait ExprKind) {
4381 QualType ExprTy = E->getType();
4382 assert(!ExprTy->isReferenceType());
4383
4384 bool IsUnevaluatedOperand =
4385 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4386 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4387 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4388 if (IsUnevaluatedOperand) {
4390 if (Result.isInvalid())
4391 return true;
4392 E = Result.get();
4393 }
4394
4395 // The operand for sizeof and alignof is in an unevaluated expression context,
4396 // so side effects could result in unintended consequences.
4397 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4398 // used to build SFINAE gadgets.
4399 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4400 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4402 !E->getType()->isVariableArrayType() &&
4403 E->HasSideEffects(Context, false))
4404 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4405
4406 if (ExprKind == UETT_VecStep)
4407 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4408 E->getSourceRange());
4409
4410 if (ExprKind == UETT_VectorElements)
4411 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4412 E->getSourceRange());
4413
4414 // Explicitly list some types as extensions.
4415 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4416 E->getSourceRange(), ExprKind))
4417 return false;
4418
4419 // WebAssembly tables are always illegal operands to unary expressions and
4420 // type traits.
4421 if (Context.getTargetInfo().getTriple().isWasm() &&
4423 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4424 << getTraitSpelling(ExprKind);
4425 return true;
4426 }
4427
4428 // 'alignof' applied to an expression only requires the base element type of
4429 // the expression to be complete. 'sizeof' requires the expression's type to
4430 // be complete (and will attempt to complete it if it's an array of unknown
4431 // bound).
4432 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4434 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4435 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4436 getTraitSpelling(ExprKind), E->getSourceRange()))
4437 return true;
4438 } else {
4440 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4441 getTraitSpelling(ExprKind), E->getSourceRange()))
4442 return true;
4443 }
4444
4445 // Completing the expression's type may have changed it.
4446 ExprTy = E->getType();
4447 assert(!ExprTy->isReferenceType());
4448
4449 if (ExprTy->isFunctionType()) {
4450 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4451 << getTraitSpelling(ExprKind) << E->getSourceRange();
4452 return true;
4453 }
4454
4455 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4456 E->getSourceRange(), ExprKind))
4457 return true;
4458
4459 if (ExprKind == UETT_CountOf) {
4460 // The type has to be an array type. We already checked for incomplete
4461 // types above.
4462 QualType ExprType = E->IgnoreParens()->getType();
4463 if (!ExprType->isArrayType()) {
4464 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4465 return true;
4466 }
4467 // FIXME: warn on _Countof on an array parameter. Not warning on it
4468 // currently because there are papers in WG14 about array types which do
4469 // not decay that could impact this behavior, so we want to see if anything
4470 // changes here before coming up with a warning group for _Countof-related
4471 // diagnostics.
4472 }
4473
4474 if (ExprKind == UETT_SizeOf) {
4475 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4476 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4477 QualType OType = PVD->getOriginalType();
4478 QualType Type = PVD->getType();
4479 if (Type->isPointerType() && OType->isArrayType()) {
4480 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4481 << Type << OType;
4482 Diag(PVD->getLocation(), diag::note_declared_at);
4483 }
4484 }
4485 }
4486
4487 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4488 // decays into a pointer and returns an unintended result. This is most
4489 // likely a typo for "sizeof(array) op x".
4490 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4491 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4492 BO->getLHS());
4493 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4494 BO->getRHS());
4495 }
4496 }
4497
4498 return false;
4499}
4500
4501static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4502 // Cannot know anything else if the expression is dependent.
4503 if (E->isTypeDependent())
4504 return false;
4505
4506 if (E->getObjectKind() == OK_BitField) {
4507 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4508 << 1 << E->getSourceRange();
4509 return true;
4510 }
4511
4512 ValueDecl *D = nullptr;
4513 Expr *Inner = E->IgnoreParens();
4514 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4515 D = DRE->getDecl();
4516 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4517 D = ME->getMemberDecl();
4518 }
4519
4520 // If it's a field, require the containing struct to have a
4521 // complete definition so that we can compute the layout.
4522 //
4523 // This can happen in C++11 onwards, either by naming the member
4524 // in a way that is not transformed into a member access expression
4525 // (in an unevaluated operand, for instance), or by naming the member
4526 // in a trailing-return-type.
4527 //
4528 // For the record, since __alignof__ on expressions is a GCC
4529 // extension, GCC seems to permit this but always gives the
4530 // nonsensical answer 0.
4531 //
4532 // We don't really need the layout here --- we could instead just
4533 // directly check for all the appropriate alignment-lowing
4534 // attributes --- but that would require duplicating a lot of
4535 // logic that just isn't worth duplicating for such a marginal
4536 // use-case.
4537 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4538 // Fast path this check, since we at least know the record has a
4539 // definition if we can find a member of it.
4540 if (!FD->getParent()->isCompleteDefinition()) {
4541 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4542 << E->getSourceRange();
4543 return true;
4544 }
4545
4546 // Otherwise, if it's a field, and the field doesn't have
4547 // reference type, then it must have a complete type (or be a
4548 // flexible array member, which we explicitly want to
4549 // white-list anyway), which makes the following checks trivial.
4550 if (!FD->getType()->isReferenceType())
4551 return false;
4552 }
4553
4554 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4555}
4556
4558 E = E->IgnoreParens();
4559
4560 // Cannot know anything else if the expression is dependent.
4561 if (E->isTypeDependent())
4562 return false;
4563
4564 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4565}
4566
4568 CapturingScopeInfo *CSI) {
4569 assert(T->isVariablyModifiedType());
4570 assert(CSI != nullptr);
4571
4572 // We're going to walk down into the type and look for VLA expressions.
4573 do {
4574 const Type *Ty = T.getTypePtr();
4575 switch (Ty->getTypeClass()) {
4576#define TYPE(Class, Base)
4577#define ABSTRACT_TYPE(Class, Base)
4578#define NON_CANONICAL_TYPE(Class, Base)
4579#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4580#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4581#include "clang/AST/TypeNodes.inc"
4582 T = QualType();
4583 break;
4584 // These types are never variably-modified.
4585 case Type::Builtin:
4586 case Type::Complex:
4587 case Type::Vector:
4588 case Type::ExtVector:
4589 case Type::ConstantMatrix:
4590 case Type::Record:
4591 case Type::Enum:
4592 case Type::TemplateSpecialization:
4593 case Type::ObjCObject:
4594 case Type::ObjCInterface:
4595 case Type::ObjCObjectPointer:
4596 case Type::ObjCTypeParam:
4597 case Type::Pipe:
4598 case Type::BitInt:
4599 case Type::HLSLInlineSpirv:
4600 llvm_unreachable("type class is never variably-modified!");
4601 case Type::Adjusted:
4602 T = cast<AdjustedType>(Ty)->getOriginalType();
4603 break;
4604 case Type::Decayed:
4605 T = cast<DecayedType>(Ty)->getPointeeType();
4606 break;
4607 case Type::ArrayParameter:
4608 T = cast<ArrayParameterType>(Ty)->getElementType();
4609 break;
4610 case Type::Pointer:
4611 T = cast<PointerType>(Ty)->getPointeeType();
4612 break;
4613 case Type::BlockPointer:
4614 T = cast<BlockPointerType>(Ty)->getPointeeType();
4615 break;
4616 case Type::LValueReference:
4617 case Type::RValueReference:
4618 T = cast<ReferenceType>(Ty)->getPointeeType();
4619 break;
4620 case Type::MemberPointer:
4621 T = cast<MemberPointerType>(Ty)->getPointeeType();
4622 break;
4623 case Type::ConstantArray:
4624 case Type::IncompleteArray:
4625 // Losing element qualification here is fine.
4626 T = cast<ArrayType>(Ty)->getElementType();
4627 break;
4628 case Type::VariableArray: {
4629 // Losing element qualification here is fine.
4631
4632 // Unknown size indication requires no size computation.
4633 // Otherwise, evaluate and record it.
4634 auto Size = VAT->getSizeExpr();
4635 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4637 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4638
4639 T = VAT->getElementType();
4640 break;
4641 }
4642 case Type::FunctionProto:
4643 case Type::FunctionNoProto:
4644 T = cast<FunctionType>(Ty)->getReturnType();
4645 break;
4646 case Type::Paren:
4647 case Type::TypeOf:
4648 case Type::UnaryTransform:
4649 case Type::Attributed:
4650 case Type::BTFTagAttributed:
4651 case Type::OverflowBehavior:
4652 case Type::HLSLAttributedResource:
4653 case Type::SubstTemplateTypeParm:
4654 case Type::MacroQualified:
4655 case Type::CountAttributed:
4656 // Keep walking after single level desugaring.
4657 T = T.getSingleStepDesugaredType(Context);
4658 break;
4659 case Type::Typedef:
4660 T = cast<TypedefType>(Ty)->desugar();
4661 break;
4662 case Type::Decltype:
4663 T = cast<DecltypeType>(Ty)->desugar();
4664 break;
4665 case Type::PackIndexing:
4666 T = cast<PackIndexingType>(Ty)->desugar();
4667 break;
4668 case Type::Using:
4669 T = cast<UsingType>(Ty)->desugar();
4670 break;
4671 case Type::Auto:
4672 case Type::DeducedTemplateSpecialization:
4673 T = cast<DeducedType>(Ty)->getDeducedType();
4674 break;
4675 case Type::TypeOfExpr:
4676 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4677 break;
4678 case Type::Atomic:
4679 T = cast<AtomicType>(Ty)->getValueType();
4680 break;
4681 case Type::PredefinedSugar:
4682 T = cast<PredefinedSugarType>(Ty)->desugar();
4683 break;
4684 }
4685 } while (!T.isNull() && T->isVariablyModifiedType());
4686}
4687
4689 SourceLocation OpLoc,
4690 SourceRange ExprRange,
4691 UnaryExprOrTypeTrait ExprKind,
4692 StringRef KWName) {
4693 if (ExprType->isDependentType())
4694 return false;
4695
4696 // C++ [expr.sizeof]p2:
4697 // When applied to a reference or a reference type, the result
4698 // is the size of the referenced type.
4699 // C++11 [expr.alignof]p3:
4700 // When alignof is applied to a reference type, the result
4701 // shall be the alignment of the referenced type.
4702 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4703 ExprType = Ref->getPointeeType();
4704
4705 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4706 // When alignof or _Alignof is applied to an array type, the result
4707 // is the alignment of the element type.
4708 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4709 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4710 // If the trait is 'alignof' in C before C2y, the ability to apply the
4711 // trait to an incomplete array is an extension.
4712 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4713 ExprType->isIncompleteArrayType())
4714 Diag(OpLoc, getLangOpts().C2y
4715 ? diag::warn_c2y_compat_alignof_incomplete_array
4716 : diag::ext_c2y_alignof_incomplete_array);
4717 ExprType = Context.getBaseElementType(ExprType);
4718 }
4719
4720 if (ExprKind == UETT_VecStep)
4721 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4722
4723 if (ExprKind == UETT_VectorElements)
4724 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4725 ExprRange);
4726
4727 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4728 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4729 ExprRange);
4730
4731 // Explicitly list some types as extensions.
4732 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4733 ExprKind))
4734 return false;
4735
4737 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4738 KWName, ExprRange))
4739 return true;
4740
4741 if (ExprType->isFunctionType()) {
4742 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4743 return true;
4744 }
4745
4746 if (ExprKind == UETT_CountOf) {
4747 // The type has to be an array type. We already checked for incomplete
4748 // types above.
4749 if (!ExprType->isArrayType()) {
4750 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4751 return true;
4752 }
4753 }
4754
4755 // WebAssembly tables are always illegal operands to unary expressions and
4756 // type traits.
4757 if (Context.getTargetInfo().getTriple().isWasm() &&
4758 ExprType->isWebAssemblyTableType()) {
4759 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4760 << getTraitSpelling(ExprKind);
4761 return true;
4762 }
4763
4764 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4765 ExprKind))
4766 return true;
4767
4768 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4769 if (auto *TT = ExprType->getAs<TypedefType>()) {
4770 for (auto I = FunctionScopes.rbegin(),
4771 E = std::prev(FunctionScopes.rend());
4772 I != E; ++I) {
4773 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4774 if (CSI == nullptr)
4775 break;
4776 DeclContext *DC = nullptr;
4777 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4778 DC = LSI->CallOperator;
4779 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4780 DC = CRSI->TheCapturedDecl;
4781 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4782 DC = BSI->TheDecl;
4783 if (DC) {
4784 if (DC->containsDecl(TT->getDecl()))
4785 break;
4786 captureVariablyModifiedType(Context, ExprType, CSI);
4787 }
4788 }
4789 }
4790 }
4791
4792 return false;
4793}
4794
4796 SourceLocation OpLoc,
4797 UnaryExprOrTypeTrait ExprKind,
4798 SourceRange R) {
4799 if (!TInfo)
4800 return ExprError();
4801
4802 QualType T = TInfo->getType();
4803
4804 if (!T->isDependentType() &&
4805 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4806 getTraitSpelling(ExprKind)))
4807 return ExprError();
4808
4809 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4810 // properly deal with VLAs in nested calls of sizeof and typeof.
4811 if (currentEvaluationContext().isUnevaluated() &&
4812 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4813 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4814 TInfo->getType()->isVariablyModifiedType())
4815 TInfo = TransformToPotentiallyEvaluated(TInfo);
4816
4817 // It's possible that the transformation above failed.
4818 if (!TInfo)
4819 return ExprError();
4820
4821 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4822 return new (Context) UnaryExprOrTypeTraitExpr(
4823 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4824}
4825
4828 UnaryExprOrTypeTrait ExprKind) {
4830 if (PE.isInvalid())
4831 return ExprError();
4832
4833 E = PE.get();
4834
4835 // Verify that the operand is valid.
4836 bool isInvalid = false;
4837 if (E->isTypeDependent()) {
4838 // Delay type-checking for type-dependent expressions.
4839 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4840 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4841 } else if (ExprKind == UETT_VecStep) {
4843 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4844 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4845 isInvalid = true;
4846 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4847 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4848 isInvalid = true;
4849 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4850 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4852 }
4853
4854 if (isInvalid)
4855 return ExprError();
4856
4857 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4858 E->getType()->isVariableArrayType()) {
4860 if (PE.isInvalid()) return ExprError();
4861 E = PE.get();
4862 }
4863
4864 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4865 return new (Context) UnaryExprOrTypeTraitExpr(
4866 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4867}
4868
4871 UnaryExprOrTypeTrait ExprKind, bool IsType,
4872 void *TyOrEx, SourceRange ArgRange) {
4873 // If error parsing type, ignore.
4874 if (!TyOrEx) return ExprError();
4875
4876 if (IsType) {
4877 TypeSourceInfo *TInfo;
4878 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4879 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4880 }
4881
4882 Expr *ArgEx = (Expr *)TyOrEx;
4883 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4884 return Result;
4885}
4886
4888 SourceLocation OpLoc, SourceRange R) {
4889 if (!TInfo)
4890 return true;
4891 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4892 UETT_AlignOf, KWName);
4893}
4894
4896 SourceLocation OpLoc, SourceRange R) {
4897 TypeSourceInfo *TInfo;
4899 &TInfo);
4900 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4901}
4902
4904 bool IsReal) {
4905 if (V.get()->isTypeDependent())
4906 return S.Context.DependentTy;
4907
4908 // _Real and _Imag are only l-values for normal l-values.
4909 if (V.get()->getObjectKind() != OK_Ordinary) {
4910 V = S.DefaultLvalueConversion(V.get());
4911 if (V.isInvalid())
4912 return QualType();
4913 }
4914
4915 // These operators return the element type of a complex type.
4916 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4917 return CT->getElementType();
4918
4919 // Otherwise they pass through real integer and floating point types here.
4920 if (V.get()->getType()->isArithmeticType())
4921 return V.get()->getType();
4922
4923 // Test for placeholders.
4924 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4925 if (PR.isInvalid()) return QualType();
4926 if (PR.get() != V.get()) {
4927 V = PR;
4928 return CheckRealImagOperand(S, V, Loc, IsReal);
4929 }
4930
4931 // Reject anything else.
4932 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4933 << (IsReal ? "__real" : "__imag");
4934 return QualType();
4935}
4936
4937
4938
4941 tok::TokenKind Kind, Expr *Input) {
4943 switch (Kind) {
4944 default: llvm_unreachable("Unknown unary op!");
4945 case tok::plusplus: Opc = UO_PostInc; break;
4946 case tok::minusminus: Opc = UO_PostDec; break;
4947 }
4948
4949 // Since this might is a postfix expression, get rid of ParenListExprs.
4951 if (Result.isInvalid()) return ExprError();
4952 Input = Result.get();
4953
4954 return BuildUnaryOp(S, OpLoc, Opc, Input);
4955}
4956
4957/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4958///
4959/// \return true on error
4961 SourceLocation opLoc,
4962 Expr *op) {
4963 assert(op->getType()->isObjCObjectPointerType());
4965 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4966 return false;
4967
4968 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4970 << op->getSourceRange();
4971 return true;
4972}
4973
4975 auto *BaseNoParens = Base->IgnoreParens();
4976 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4977 return MSProp->getPropertyDecl()->getType()->isArrayType();
4978 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4979}
4980
4981// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4982// Typically this is DependentTy, but can sometimes be more precise.
4983//
4984// There are cases when we could determine a non-dependent type:
4985// - LHS and RHS may have non-dependent types despite being type-dependent
4986// (e.g. unbounded array static members of the current instantiation)
4987// - one may be a dependent-sized array with known element type
4988// - one may be a dependent-typed valid index (enum in current instantiation)
4989//
4990// We *always* return a dependent type, in such cases it is DependentTy.
4991// This avoids creating type-dependent expressions with non-dependent types.
4992// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4994 const ASTContext &Ctx) {
4995 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4996 QualType LTy = LHS->getType(), RTy = RHS->getType();
4998 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4999 if (const PointerType *PT = LTy->getAs<PointerType>())
5000 Result = PT->getPointeeType();
5001 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5002 Result = AT->getElementType();
5003 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5004 if (const PointerType *PT = RTy->getAs<PointerType>())
5005 Result = PT->getPointeeType();
5006 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5007 Result = AT->getElementType();
5008 }
5009 // Ensure we return a dependent type.
5010 return Result->isDependentType() ? Result : Ctx.DependentTy;
5011}
5012
5014 SourceLocation lbLoc,
5015 MultiExprArg ArgExprs,
5016 SourceLocation rbLoc) {
5017
5018 if (base && !base->getType().isNull() &&
5019 base->hasPlaceholderType(BuiltinType::ArraySection)) {
5020 auto *AS = cast<ArraySectionExpr>(base);
5021 if (AS->isOMPArraySection())
5023 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
5024 /*Length*/ nullptr,
5025 /*Stride=*/nullptr, rbLoc);
5026
5027 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
5028 SourceLocation(), /*Length*/ nullptr,
5029 rbLoc);
5030 }
5031
5032 // Since this might be a postfix expression, get rid of ParenListExprs.
5033 if (isa<ParenListExpr>(base)) {
5035 if (result.isInvalid())
5036 return ExprError();
5037 base = result.get();
5038 }
5039
5040 // Check if base and idx form a MatrixSubscriptExpr.
5041 //
5042 // Helper to check for comma expressions, which are not allowed as indices for
5043 // matrix subscript expressions.
5044 //
5045 // In C++23, we get multiple arguments instead of a comma expression.
5046 auto CheckAndReportCommaError = [&](Expr *E) {
5047 if (ArgExprs.size() > 1 ||
5048 (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp())) {
5049 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5050 << SourceRange(base->getBeginLoc(), rbLoc);
5051 return true;
5052 }
5053 return false;
5054 };
5055 // The matrix subscript operator ([][])is considered a single operator.
5056 // Separating the index expressions by parenthesis is not allowed.
5057 if (base && !base->getType().isNull() &&
5058 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5059 !isa<MatrixSubscriptExpr>(base)) {
5060 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5061 << SourceRange(base->getBeginLoc(), rbLoc);
5062 return ExprError();
5063 }
5064 // If the base is a MatrixSubscriptExpr, try to create a new
5065 // MatrixSubscriptExpr.
5066 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5067 if (matSubscriptE) {
5068 if (CheckAndReportCommaError(ArgExprs.front()))
5069 return ExprError();
5070
5071 assert(matSubscriptE->isIncomplete() &&
5072 "base has to be an incomplete matrix subscript");
5073 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5074 matSubscriptE->getRowIdx(),
5075 ArgExprs.front(), rbLoc);
5076 }
5077 if (base->getType()->isWebAssemblyTableType()) {
5078 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5079 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5080 return ExprError();
5081 }
5082
5083 CheckInvalidBuiltinCountedByRef(base,
5085
5086 // Handle any non-overload placeholder types in the base and index
5087 // expressions. We can't handle overloads here because the other
5088 // operand might be an overloadable type, in which case the overload
5089 // resolution for the operator overload should get the first crack
5090 // at the overload.
5091 bool IsMSPropertySubscript = false;
5092 if (base->getType()->isNonOverloadPlaceholderType()) {
5093 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5094 if (!IsMSPropertySubscript) {
5095 ExprResult result = CheckPlaceholderExpr(base);
5096 if (result.isInvalid())
5097 return ExprError();
5098 base = result.get();
5099 }
5100 }
5101
5102 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5103 if (base->getType()->isMatrixType()) {
5104 if (CheckAndReportCommaError(ArgExprs.front()))
5105 return ExprError();
5106
5107 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5108 rbLoc);
5109 }
5110
5111 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5112 Expr *idx = ArgExprs[0];
5113 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5115 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5116 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5117 << SourceRange(base->getBeginLoc(), rbLoc);
5118 }
5119 }
5120
5121 if (ArgExprs.size() == 1 &&
5122 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5123 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5124 if (result.isInvalid())
5125 return ExprError();
5126 ArgExprs[0] = result.get();
5127 } else {
5128 if (CheckArgsForPlaceholders(ArgExprs))
5129 return ExprError();
5130 }
5131
5132 // Build an unanalyzed expression if either operand is type-dependent.
5133 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5134 (base->isTypeDependent() ||
5136 !isa<PackExpansionExpr>(ArgExprs[0])) {
5137 return new (Context) ArraySubscriptExpr(
5138 base, ArgExprs.front(),
5139 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5140 VK_LValue, OK_Ordinary, rbLoc);
5141 }
5142
5143 // MSDN, property (C++)
5144 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5145 // This attribute can also be used in the declaration of an empty array in a
5146 // class or structure definition. For example:
5147 // __declspec(property(get=GetX, put=PutX)) int x[];
5148 // The above statement indicates that x[] can be used with one or more array
5149 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5150 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5151 if (IsMSPropertySubscript) {
5152 if (ArgExprs.size() > 1) {
5153 Diag(base->getExprLoc(),
5154 diag::err_ms_property_subscript_expects_single_arg);
5155 return ExprError();
5156 }
5157
5158 // Build MS property subscript expression if base is MS property reference
5159 // or MS property subscript.
5160 return new (Context)
5161 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5162 VK_LValue, OK_Ordinary, rbLoc);
5163 }
5164
5165 // Use C++ overloaded-operator rules if either operand has record
5166 // type. The spec says to do this if either type is *overloadable*,
5167 // but enum types can't declare subscript operators or conversion
5168 // operators, so there's nothing interesting for overload resolution
5169 // to do if there aren't any record types involved.
5170 //
5171 // ObjC pointers have their own subscripting logic that is not tied
5172 // to overload resolution and so should not take this path.
5173 //
5174 // Issue a better diagnostic if we tried to pass multiple arguments to
5175 // a builtin subscript operator rather than diagnosing this as a generic
5176 // overload resolution failure.
5177 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5178 !base->getType()->isRecordType() &&
5179 !base->getType()->isObjCObjectPointerType()) {
5180 Diag(base->getExprLoc(), diag::err_ovl_builtin_subscript_expects_single_arg)
5181 << base->getType() << base->getSourceRange();
5182 return ExprError();
5183 }
5184
5186 ((base->getType()->isRecordType() ||
5187 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5188 ArgExprs[0]->getType()->isRecordType())))) {
5189 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5190 }
5191
5192 ExprResult Res =
5193 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5194
5195 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5196 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5197
5198 return Res;
5199}
5200
5203 InitializationKind Kind =
5205 InitializationSequence InitSeq(*this, Entity, Kind, E);
5206 return InitSeq.Perform(*this, Entity, Kind, E);
5207}
5208
5210 Expr *RowIdx,
5211 SourceLocation RBLoc) {
5213 if (BaseR.isInvalid())
5214 return BaseR;
5215 Base = BaseR.get();
5216
5217 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5218 if (RowR.isInvalid())
5219 return RowR;
5220 RowIdx = RowR.get();
5221
5222 // Build an unanalyzed expression if any of the operands is type-dependent.
5223 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5224 return new (Context)
5225 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5226
5227 // Check that IndexExpr is an integer expression. If it is a constant
5228 // expression, check that it is less than Dim (= the number of elements in the
5229 // corresponding dimension).
5230 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5231 bool IsColumnIdx) -> Expr * {
5232 if (!IndexExpr->getType()->isIntegerType() &&
5233 !IndexExpr->isTypeDependent()) {
5234 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5235 << IsColumnIdx;
5236 return nullptr;
5237 }
5238
5239 if (std::optional<llvm::APSInt> Idx =
5240 IndexExpr->getIntegerConstantExpr(Context)) {
5241 if ((*Idx < 0 || *Idx >= Dim)) {
5242 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5243 << IsColumnIdx << Dim;
5244 return nullptr;
5245 }
5246 }
5247
5248 ExprResult ConvExpr = IndexExpr;
5249 assert(!ConvExpr.isInvalid() &&
5250 "should be able to convert any integer type to size type");
5251 return ConvExpr.get();
5252 };
5253
5254 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5255 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5256 if (!RowIdx)
5257 return ExprError();
5258
5259 QualType RowVecQT =
5260 Context.getExtVectorType(MTy->getElementType(), MTy->getNumColumns());
5261
5262 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5263}
5264
5266 Expr *ColumnIdx,
5267 SourceLocation RBLoc) {
5269 if (BaseR.isInvalid())
5270 return BaseR;
5271 Base = BaseR.get();
5272
5273 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5274 if (RowR.isInvalid())
5275 return RowR;
5276 RowIdx = RowR.get();
5277
5278 if (!ColumnIdx)
5279 return new (Context) MatrixSubscriptExpr(
5280 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5281
5282 // Build an unanalyzed expression if any of the operands is type-dependent.
5283 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5284 ColumnIdx->isTypeDependent())
5285 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5286 Context.DependentTy, RBLoc);
5287
5288 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5289 if (ColumnR.isInvalid())
5290 return ColumnR;
5291 ColumnIdx = ColumnR.get();
5292
5293 // Check that IndexExpr is an integer expression. If it is a constant
5294 // expression, check that it is less than Dim (= the number of elements in the
5295 // corresponding dimension).
5296 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5297 bool IsColumnIdx) -> Expr * {
5298 if (!IndexExpr->getType()->isIntegerType() &&
5299 !IndexExpr->isTypeDependent()) {
5300 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5301 << IsColumnIdx;
5302 return nullptr;
5303 }
5304
5305 if (std::optional<llvm::APSInt> Idx =
5306 IndexExpr->getIntegerConstantExpr(Context)) {
5307 if ((*Idx < 0 || *Idx >= Dim)) {
5308 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5309 << IsColumnIdx << Dim;
5310 return nullptr;
5311 }
5312 }
5313
5314 ExprResult ConvExpr = IndexExpr;
5315 assert(!ConvExpr.isInvalid() &&
5316 "should be able to convert any integer type to size type");
5317 return ConvExpr.get();
5318 };
5319
5320 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5321 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5322 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5323 if (!RowIdx || !ColumnIdx)
5324 return ExprError();
5325
5326 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5327 MTy->getElementType(), RBLoc);
5328}
5329
5330void Sema::CheckAddressOfNoDeref(const Expr *E) {
5331 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5332 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5333
5334 // For expressions like `&(*s).b`, the base is recorded and what should be
5335 // checked.
5336 const MemberExpr *Member = nullptr;
5337 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5338 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5339
5340 LastRecord.PossibleDerefs.erase(StrippedExpr);
5341}
5342
5343void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5345 return;
5346
5347 QualType ResultTy = E->getType();
5348 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5349
5350 // Bail if the element is an array since it is not memory access.
5351 if (isa<ArrayType>(ResultTy))
5352 return;
5353
5354 if (ResultTy->hasAttr(attr::NoDeref)) {
5355 LastRecord.PossibleDerefs.insert(E);
5356 return;
5357 }
5358
5359 // Check if the base type is a pointer to a member access of a struct
5360 // marked with noderef.
5361 const Expr *Base = E->getBase();
5362 QualType BaseTy = Base->getType();
5363 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5364 // Not a pointer access
5365 return;
5366
5367 const MemberExpr *Member = nullptr;
5368 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5369 Member->isArrow())
5370 Base = Member->getBase();
5371
5372 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5373 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5374 LastRecord.PossibleDerefs.insert(E);
5375 }
5376}
5377
5380 Expr *Idx, SourceLocation RLoc) {
5381 Expr *LHSExp = Base;
5382 Expr *RHSExp = Idx;
5383
5386
5387 // Per C++ core issue 1213, the result is an xvalue if either operand is
5388 // a non-lvalue array, and an lvalue otherwise.
5389 if (getLangOpts().CPlusPlus11) {
5390 for (auto *Op : {LHSExp, RHSExp}) {
5391 Op = Op->IgnoreImplicit();
5392 if (Op->getType()->isArrayType() && !Op->isLValue())
5393 VK = VK_XValue;
5394 }
5395 }
5396
5397 // Perform default conversions.
5398 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5400 if (Result.isInvalid())
5401 return ExprError();
5402 LHSExp = Result.get();
5403 }
5405 if (Result.isInvalid())
5406 return ExprError();
5407 RHSExp = Result.get();
5408
5409 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5410
5411 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5412 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5413 // in the subscript position. As a result, we need to derive the array base
5414 // and index from the expression types.
5415 Expr *BaseExpr, *IndexExpr;
5416 QualType ResultType;
5417 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5418 BaseExpr = LHSExp;
5419 IndexExpr = RHSExp;
5420 ResultType =
5422 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5423 BaseExpr = LHSExp;
5424 IndexExpr = RHSExp;
5425 ResultType = PTy->getPointeeType();
5426 } else if (const ObjCObjectPointerType *PTy =
5427 LHSTy->getAs<ObjCObjectPointerType>()) {
5428 BaseExpr = LHSExp;
5429 IndexExpr = RHSExp;
5430
5431 // Use custom logic if this should be the pseudo-object subscript
5432 // expression.
5433 if (!LangOpts.isSubscriptPointerArithmetic())
5434 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5435 nullptr, nullptr);
5436
5437 ResultType = PTy->getPointeeType();
5438 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5439 // Handle the uncommon case of "123[Ptr]".
5440 BaseExpr = RHSExp;
5441 IndexExpr = LHSExp;
5442 ResultType = PTy->getPointeeType();
5443 } else if (const ObjCObjectPointerType *PTy =
5444 RHSTy->getAs<ObjCObjectPointerType>()) {
5445 // Handle the uncommon case of "123[Ptr]".
5446 BaseExpr = RHSExp;
5447 IndexExpr = LHSExp;
5448 ResultType = PTy->getPointeeType();
5449 if (!LangOpts.isSubscriptPointerArithmetic()) {
5450 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5451 << ResultType << BaseExpr->getSourceRange();
5452 return ExprError();
5453 }
5454 } else if (LHSTy->isSubscriptableVectorType()) {
5455 if (LHSTy->isBuiltinType() &&
5456 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5457 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5458 if (BTy->isSVEBool())
5459 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5460 << LHSExp->getSourceRange()
5461 << RHSExp->getSourceRange());
5462 ResultType = BTy->getSveEltType(Context);
5463 } else {
5464 const VectorType *VTy = LHSTy->getAs<VectorType>();
5465 ResultType = VTy->getElementType();
5466 }
5467 BaseExpr = LHSExp; // vectors: V[123]
5468 IndexExpr = RHSExp;
5469 // We apply C++ DR1213 to vector subscripting too.
5470 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5471 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5472 if (Materialized.isInvalid())
5473 return ExprError();
5474 LHSExp = Materialized.get();
5475 }
5476 VK = LHSExp->getValueKind();
5477 if (VK != VK_PRValue)
5478 OK = OK_VectorComponent;
5479
5480 QualType BaseType = BaseExpr->getType();
5481 Qualifiers BaseQuals = BaseType.getQualifiers();
5482 Qualifiers MemberQuals = ResultType.getQualifiers();
5483 Qualifiers Combined = BaseQuals + MemberQuals;
5484 if (Combined != MemberQuals)
5485 ResultType = Context.getQualifiedType(ResultType, Combined);
5486 } else if (LHSTy->isArrayType()) {
5487 // If we see an array that wasn't promoted by
5488 // DefaultFunctionArrayLvalueConversion, it must be an array that
5489 // wasn't promoted because of the C90 rule that doesn't
5490 // allow promoting non-lvalue arrays. Warn, then
5491 // force the promotion here.
5492 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5493 << LHSExp->getSourceRange();
5494 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5495 CK_ArrayToPointerDecay).get();
5496 LHSTy = LHSExp->getType();
5497
5498 BaseExpr = LHSExp;
5499 IndexExpr = RHSExp;
5500 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5501 } else if (RHSTy->isArrayType()) {
5502 // Same as previous, except for 123[f().a] case
5503 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5504 << RHSExp->getSourceRange();
5505 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5506 CK_ArrayToPointerDecay).get();
5507 RHSTy = RHSExp->getType();
5508
5509 BaseExpr = RHSExp;
5510 IndexExpr = LHSExp;
5511 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5512 } else {
5513 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5514 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5515 }
5516 // C99 6.5.2.1p1
5517 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5518 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5519 << IndexExpr->getSourceRange());
5520
5521 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5522 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5523 !IndexExpr->isTypeDependent()) {
5524 std::optional<llvm::APSInt> IntegerContantExpr =
5526 if (!IntegerContantExpr.has_value() ||
5527 IntegerContantExpr.value().isNegative())
5528 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5529 }
5530
5531 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5532 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5533 // type. Note that Functions are not objects, and that (in C99 parlance)
5534 // incomplete types are not object types.
5535 if (ResultType->isFunctionType()) {
5536 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5537 << ResultType << BaseExpr->getSourceRange();
5538 return ExprError();
5539 }
5540
5541 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5542 // GNU extension: subscripting on pointer to void
5543 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5544 << BaseExpr->getSourceRange();
5545
5546 // C forbids expressions of unqualified void type from being l-values.
5547 // See IsCForbiddenLValueType.
5548 if (!ResultType.hasQualifiers())
5549 VK = VK_PRValue;
5550 } else if (!ResultType->isDependentType() &&
5551 !ResultType.isWebAssemblyReferenceType() &&
5553 LLoc, ResultType,
5554 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5555 return ExprError();
5556
5557 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5558 !ResultType.isCForbiddenLValueType());
5559
5561 FunctionScopes.size() > 1) {
5562 if (auto *TT =
5563 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5564 for (auto I = FunctionScopes.rbegin(),
5565 E = std::prev(FunctionScopes.rend());
5566 I != E; ++I) {
5567 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5568 if (CSI == nullptr)
5569 break;
5570 DeclContext *DC = nullptr;
5571 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5572 DC = LSI->CallOperator;
5573 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5574 DC = CRSI->TheCapturedDecl;
5575 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5576 DC = BSI->TheDecl;
5577 if (DC) {
5578 if (DC->containsDecl(TT->getDecl()))
5579 break;
5581 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5582 }
5583 }
5584 }
5585 }
5586
5587 return new (Context)
5588 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5589}
5590
5592 ParmVarDecl *Param, Expr *RewrittenInit,
5593 bool SkipImmediateInvocations) {
5594 if (Param->hasUnparsedDefaultArg()) {
5595 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5596 // If we've already cleared out the location for the default argument,
5597 // that means we're parsing it right now.
5598 if (!UnparsedDefaultArgLocs.count(Param)) {
5599 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5600 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5601 Param->setInvalidDecl();
5602 return true;
5603 }
5604
5605 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5606 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5608 diag::note_default_argument_declared_here);
5609 return true;
5610 }
5611
5612 if (Param->hasUninstantiatedDefaultArg()) {
5613 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5614 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5615 return true;
5616 }
5617
5618 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5619 assert(Init && "default argument but no initializer?");
5620
5621 // If the default expression creates temporaries, we need to
5622 // push them to the current stack of expression temporaries so they'll
5623 // be properly destroyed.
5624 // FIXME: We should really be rebuilding the default argument with new
5625 // bound temporaries; see the comment in PR5810.
5626 // We don't need to do that with block decls, though, because
5627 // blocks in default argument expression can never capture anything.
5628 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5629 // Set the "needs cleanups" bit regardless of whether there are
5630 // any explicit objects.
5631 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5632 // Append all the objects to the cleanup list. Right now, this
5633 // should always be a no-op, because blocks in default argument
5634 // expressions should never be able to capture anything.
5635 assert(!InitWithCleanup->getNumObjects() &&
5636 "default argument expression has capturing blocks?");
5637 }
5638 // C++ [expr.const]p15.1:
5639 // An expression or conversion is in an immediate function context if it is
5640 // potentially evaluated and [...] its innermost enclosing non-block scope
5641 // is a function parameter scope of an immediate function.
5643 *this,
5647 Param);
5648 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5649 SkipImmediateInvocations;
5650 runWithSufficientStackSpace(CallLoc, [&] {
5651 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5652 });
5653 return false;
5654}
5655
5660 }
5661
5662 bool HasImmediateCalls = false;
5663
5664 bool VisitCallExpr(CallExpr *E) override {
5665 if (const FunctionDecl *FD = E->getDirectCallee())
5666 HasImmediateCalls |= FD->isImmediateFunction();
5668 }
5669
5671 if (const FunctionDecl *FD = E->getConstructor())
5672 HasImmediateCalls |= FD->isImmediateFunction();
5674 }
5675
5676 // SourceLocExpr are not immediate invocations
5677 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5678 // need to be rebuilt so that they refer to the correct SourceLocation and
5679 // DeclContext.
5681 HasImmediateCalls = true;
5683 }
5684
5685 // A nested lambda might have parameters with immediate invocations
5686 // in their default arguments.
5687 // The compound statement is not visited (as it does not constitute a
5688 // subexpression).
5689 // FIXME: We should consider visiting and transforming captures
5690 // with init expressions.
5691 bool VisitLambdaExpr(LambdaExpr *E) override {
5692 return VisitCXXMethodDecl(E->getCallOperator());
5693 }
5694
5696 return TraverseStmt(E->getExpr());
5697 }
5698
5700 return TraverseStmt(E->getExpr());
5701 }
5702};
5703
5705 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5708
5709 bool AlwaysRebuild() { return true; }
5710
5711 // Lambda can only have immediate invocations in the default
5712 // args of their parameters, which is transformed upon calling the closure.
5713 // The body is not a subexpression, so we have nothing to do.
5714 // FIXME: Immediate calls in capture initializers should be transformed.
5717
5718 // Make sure we don't rebuild the this pointer as it would
5719 // cause it to incorrectly point it to the outermost class
5720 // in the case of nested struct initialization.
5722
5723 // Rewrite to source location to refer to the context in which they are used.
5725 DeclContext *DC = E->getParentContext();
5726 if (DC == SemaRef.CurContext)
5727 return E;
5728
5729 // FIXME: During instantiation, because the rebuild of defaults arguments
5730 // is not always done in the context of the template instantiator,
5731 // we run the risk of producing a dependent source location
5732 // that would never be rebuilt.
5733 // This usually happens during overload resolution, or in contexts
5734 // where the value of the source location does not matter.
5735 // However, we should find a better way to deal with source location
5736 // of function templates.
5737 if (!SemaRef.CurrentInstantiationScope ||
5738 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5739 DC = SemaRef.CurContext;
5740
5741 return getDerived().RebuildSourceLocExpr(
5742 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5743 }
5744};
5745
5747 FunctionDecl *FD, ParmVarDecl *Param,
5748 Expr *Init) {
5749 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5750
5751 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5752 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5753 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5754 InitializationContext =
5756 if (!InitializationContext.has_value())
5757 InitializationContext.emplace(CallLoc, Param, CurContext);
5758
5759 if (!Init && !Param->hasUnparsedDefaultArg()) {
5760 // Mark that we are replacing a default argument first.
5761 // If we are instantiating a template we won't have to
5762 // retransform immediate calls.
5763 // C++ [expr.const]p15.1:
5764 // An expression or conversion is in an immediate function context if it
5765 // is potentially evaluated and [...] its innermost enclosing non-block
5766 // scope is a function parameter scope of an immediate function.
5768 *this,
5772 Param);
5773
5774 if (Param->hasUninstantiatedDefaultArg()) {
5775 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5776 return ExprError();
5777 }
5778 // CWG2631
5779 // An immediate invocation that is not evaluated where it appears is
5780 // evaluated and checked for whether it is a constant expression at the
5781 // point where the enclosing initializer is used in a function call.
5783 if (!NestedDefaultChecking)
5784 V.TraverseDecl(Param);
5785
5786 // Rewrite the call argument that was created from the corresponding
5787 // parameter's default argument.
5788 if (V.HasImmediateCalls ||
5789 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5790 if (V.HasImmediateCalls)
5791 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5792 CallLoc, Param, CurContext};
5793 // Pass down lifetime extending flag, and collect temporaries in
5794 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5798 ExprResult Res;
5799 runWithSufficientStackSpace(CallLoc, [&] {
5800 Res = Immediate.TransformInitializer(Param->getInit(),
5801 /*NotCopy=*/false);
5802 });
5803 if (Res.isInvalid())
5804 return ExprError();
5805 Res = ConvertParamDefaultArgument(Param, Res.get(),
5806 Res.get()->getBeginLoc());
5807 if (Res.isInvalid())
5808 return ExprError();
5809 Init = Res.get();
5810 }
5811 }
5812
5814 CallLoc, FD, Param, Init,
5815 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5816 return ExprError();
5817
5818 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5819 Init, InitializationContext->Context);
5820}
5821
5823 FieldDecl *Field) {
5824 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5825 return Pattern;
5826 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5827 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5829 ClassPattern->lookup(Field->getDeclName());
5830 auto Rng = llvm::make_filter_range(
5831 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5832 if (Rng.empty())
5833 return nullptr;
5834 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5835 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5836 // && "Duplicated instantiation pattern for field decl");
5837 return cast<FieldDecl>(*Rng.begin());
5838}
5839
5841 assert(Field->hasInClassInitializer());
5842
5843 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5844
5845 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5846
5847 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5848 InitializationContext =
5850 if (!InitializationContext.has_value())
5851 InitializationContext.emplace(Loc, Field, CurContext);
5852
5853 Expr *Init = nullptr;
5854
5855 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5856 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5859
5860 if (!Field->getInClassInitializer()) {
5861 // Maybe we haven't instantiated the in-class initializer. Go check the
5862 // pattern FieldDecl to see if it has one.
5863 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5864 FieldDecl *Pattern =
5866 assert(Pattern && "We must have set the Pattern!");
5867 if (!Pattern->hasInClassInitializer() ||
5868 InstantiateInClassInitializer(Loc, Field, Pattern,
5870 Field->setInvalidDecl();
5871 return ExprError();
5872 }
5873 }
5874 }
5875
5876 // CWG2631
5877 // An immediate invocation that is not evaluated where it appears is
5878 // evaluated and checked for whether it is a constant expression at the
5879 // point where the enclosing initializer is used in a [...] a constructor
5880 // definition, or an aggregate initialization.
5882 if (!NestedDefaultChecking)
5883 V.TraverseDecl(Field);
5884
5885 // CWG1815
5886 // Support lifetime extension of temporary created by aggregate
5887 // initialization using a default member initializer. We should rebuild
5888 // the initializer in a lifetime extension context if the initializer
5889 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5890 // extension code recurses into the default initializer and does lifetime
5891 // extension when warranted.
5892 bool ContainsAnyTemporaries =
5893 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5894 if (Field->getInClassInitializer() &&
5895 !Field->getInClassInitializer()->containsErrors() &&
5896 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5897 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5898 CurContext};
5899 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5900 NestedDefaultChecking;
5901 // Pass down lifetime extending flag, and collect temporaries in
5902 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5906 ExprResult Res;
5908 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5909 /*CXXDirectInit=*/false);
5910 });
5911 if (!Res.isInvalid())
5912 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5913 if (Res.isInvalid()) {
5914 Field->setInvalidDecl();
5915 return ExprError();
5916 }
5917 Init = Res.get();
5918 }
5919
5920 if (Field->getInClassInitializer()) {
5921 Expr *E = Init ? Init : Field->getInClassInitializer();
5922 if (!NestedDefaultChecking)
5924 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5925 });
5928 // C++11 [class.base.init]p7:
5929 // The initialization of each base and member constitutes a
5930 // full-expression.
5931 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5932 if (Res.isInvalid()) {
5933 Field->setInvalidDecl();
5934 return ExprError();
5935 }
5936 Init = Res.get();
5937
5938 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5939 Field, InitializationContext->Context,
5940 Init);
5941 }
5942
5943 // DR1351:
5944 // If the brace-or-equal-initializer of a non-static data member
5945 // invokes a defaulted default constructor of its class or of an
5946 // enclosing class in a potentially evaluated subexpression, the
5947 // program is ill-formed.
5948 //
5949 // This resolution is unworkable: the exception specification of the
5950 // default constructor can be needed in an unevaluated context, in
5951 // particular, in the operand of a noexcept-expression, and we can be
5952 // unable to compute an exception specification for an enclosed class.
5953 //
5954 // Any attempt to resolve the exception specification of a defaulted default
5955 // constructor before the initializer is lexically complete will ultimately
5956 // come here at which point we can diagnose it.
5957 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5958 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5959 << OutermostClass << Field;
5960 Diag(Field->getEndLoc(),
5961 diag::note_default_member_initializer_not_yet_parsed);
5962 // Recover by marking the field invalid, unless we're in a SFINAE context.
5963 if (!isSFINAEContext())
5964 Field->setInvalidDecl();
5965 return ExprError();
5966}
5967
5969 const FunctionProtoType *Proto,
5970 Expr *Fn) {
5971 if (Proto && Proto->isVariadic()) {
5972 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5974 else if (Fn && Fn->getType()->isBlockPointerType())
5976 else if (FDecl) {
5977 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5978 if (Method->isInstance())
5980 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5983 }
5985}
5986
5987namespace {
5988class FunctionCallCCC final : public FunctionCallFilterCCC {
5989public:
5990 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5991 unsigned NumArgs, MemberExpr *ME)
5992 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5993 FunctionName(FuncName) {}
5994
5995 bool ValidateCandidate(const TypoCorrection &candidate) override {
5996 if (!candidate.getCorrectionSpecifier() ||
5997 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5998 return false;
5999 }
6000
6002 }
6003
6004 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6005 return std::make_unique<FunctionCallCCC>(*this);
6006 }
6007
6008private:
6009 const IdentifierInfo *const FunctionName;
6010};
6011}
6012
6014 FunctionDecl *FDecl,
6015 ArrayRef<Expr *> Args) {
6016 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6017 DeclarationName FuncName = FDecl->getDeclName();
6018 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6019
6020 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6021 if (TypoCorrection Corrected = S.CorrectTypo(
6023 S.getScopeForContext(S.CurContext), nullptr, CCC,
6025 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6026 if (Corrected.isOverloaded()) {
6029 for (NamedDecl *CD : Corrected) {
6030 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6032 OCS);
6033 }
6034 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6035 case OR_Success:
6036 ND = Best->FoundDecl;
6037 Corrected.setCorrectionDecl(ND);
6038 break;
6039 default:
6040 break;
6041 }
6042 }
6043 ND = ND->getUnderlyingDecl();
6045 return Corrected;
6046 }
6047 }
6048 return TypoCorrection();
6049}
6050
6051// [C++26][[expr.unary.op]/p4
6052// A pointer to member is only formed when an explicit &
6053// is used and its operand is a qualified-id not enclosed in parentheses.
6055 if (!isa<ParenExpr>(Fn))
6056 return false;
6057
6058 Fn = Fn->IgnoreParens();
6059
6060 auto *UO = dyn_cast<UnaryOperator>(Fn);
6061 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6062 return false;
6063 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
6064 return DRE->hasQualifier();
6065 }
6066 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
6067 return bool(OVL->getQualifier());
6068 return false;
6069}
6070
6071bool
6073 FunctionDecl *FDecl,
6074 const FunctionProtoType *Proto,
6075 ArrayRef<Expr *> Args,
6076 SourceLocation RParenLoc,
6077 bool IsExecConfig) {
6078 // Bail out early if calling a builtin with custom typechecking.
6079 // For HLSL builtin aliases, argument conversion is still needed because
6080 // overload resolution may have selected a conversion sequence (e.g.,
6081 // vector-to-scalar truncation) that must be applied before the custom
6082 // type checker runs.
6083 if (FDecl)
6084 if (unsigned ID = FDecl->getBuiltinID())
6085 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6086 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6087 return false;
6088
6089 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6090 // assignment, to the types of the corresponding parameter, ...
6091
6092 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6093 bool HasExplicitObjectParameter =
6094 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6095 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6096 unsigned NumParams = Proto->getNumParams();
6097 bool Invalid = false;
6098 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6099 unsigned FnKind = Fn->getType()->isBlockPointerType()
6100 ? 1 /* block */
6101 : (IsExecConfig ? 3 /* kernel function (exec config) */
6102 : 0 /* function */);
6103
6104 // If too few arguments are available (and we don't have default
6105 // arguments for the remaining parameters), don't make the call.
6106 if (Args.size() < NumParams) {
6107 if (Args.size() < MinArgs) {
6108 TypoCorrection TC;
6109 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6110 unsigned diag_id =
6111 MinArgs == NumParams && !Proto->isVariadic()
6112 ? diag::err_typecheck_call_too_few_args_suggest
6113 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6115 TC, PDiag(diag_id)
6116 << FnKind << MinArgs - ExplicitObjectParameterOffset
6117 << static_cast<unsigned>(Args.size()) -
6118 ExplicitObjectParameterOffset
6119 << HasExplicitObjectParameter << TC.getCorrectionRange());
6120 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6121 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6122 ->getDeclName())
6123 Diag(RParenLoc,
6124 MinArgs == NumParams && !Proto->isVariadic()
6125 ? diag::err_typecheck_call_too_few_args_one
6126 : diag::err_typecheck_call_too_few_args_at_least_one)
6127 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6128 << HasExplicitObjectParameter << Fn->getSourceRange();
6129 else
6130 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6131 ? diag::err_typecheck_call_too_few_args
6132 : diag::err_typecheck_call_too_few_args_at_least)
6133 << FnKind << MinArgs - ExplicitObjectParameterOffset
6134 << static_cast<unsigned>(Args.size()) -
6135 ExplicitObjectParameterOffset
6136 << HasExplicitObjectParameter << Fn->getSourceRange();
6137
6138 // Emit the location of the prototype.
6139 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6140 Diag(FDecl->getLocation(), diag::note_callee_decl)
6141 << FDecl << FDecl->getParametersSourceRange();
6142
6143 return true;
6144 }
6145 // We reserve space for the default arguments when we create
6146 // the call expression, before calling ConvertArgumentsForCall.
6147 assert((Call->getNumArgs() == NumParams) &&
6148 "We should have reserved space for the default arguments before!");
6149 }
6150
6151 // If too many are passed and not variadic, error on the extras and drop
6152 // them.
6153 if (Args.size() > NumParams) {
6154 if (!Proto->isVariadic()) {
6155 TypoCorrection TC;
6156 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6157 unsigned diag_id =
6158 MinArgs == NumParams && !Proto->isVariadic()
6159 ? diag::err_typecheck_call_too_many_args_suggest
6160 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6162 TC, PDiag(diag_id)
6163 << FnKind << NumParams - ExplicitObjectParameterOffset
6164 << static_cast<unsigned>(Args.size()) -
6165 ExplicitObjectParameterOffset
6166 << HasExplicitObjectParameter << TC.getCorrectionRange());
6167 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6168 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6169 ->getDeclName())
6170 Diag(Args[NumParams]->getBeginLoc(),
6171 MinArgs == NumParams
6172 ? diag::err_typecheck_call_too_many_args_one
6173 : diag::err_typecheck_call_too_many_args_at_most_one)
6174 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6175 << static_cast<unsigned>(Args.size()) -
6176 ExplicitObjectParameterOffset
6177 << HasExplicitObjectParameter << Fn->getSourceRange()
6178 << SourceRange(Args[NumParams]->getBeginLoc(),
6179 Args.back()->getEndLoc());
6180 else
6181 Diag(Args[NumParams]->getBeginLoc(),
6182 MinArgs == NumParams
6183 ? diag::err_typecheck_call_too_many_args
6184 : diag::err_typecheck_call_too_many_args_at_most)
6185 << FnKind << NumParams - ExplicitObjectParameterOffset
6186 << static_cast<unsigned>(Args.size()) -
6187 ExplicitObjectParameterOffset
6188 << HasExplicitObjectParameter << Fn->getSourceRange()
6189 << SourceRange(Args[NumParams]->getBeginLoc(),
6190 Args.back()->getEndLoc());
6191
6192 // Emit the location of the prototype.
6193 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6194 Diag(FDecl->getLocation(), diag::note_callee_decl)
6195 << FDecl << FDecl->getParametersSourceRange();
6196
6197 // This deletes the extra arguments.
6198 Call->shrinkNumArgs(NumParams);
6199 return true;
6200 }
6201 }
6202 SmallVector<Expr *, 8> AllArgs;
6203 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6204
6205 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6206 AllArgs, CallType);
6207 if (Invalid)
6208 return true;
6209 unsigned TotalNumArgs = AllArgs.size();
6210 for (unsigned i = 0; i < TotalNumArgs; ++i)
6211 Call->setArg(i, AllArgs[i]);
6212
6213 Call->computeDependence();
6214 return false;
6215}
6216
6218 const FunctionProtoType *Proto,
6219 unsigned FirstParam, ArrayRef<Expr *> Args,
6220 SmallVectorImpl<Expr *> &AllArgs,
6221 VariadicCallType CallType, bool AllowExplicit,
6222 bool IsListInitialization) {
6223 unsigned NumParams = Proto->getNumParams();
6224 bool Invalid = false;
6225 size_t ArgIx = 0;
6226 // Continue to check argument types (even if we have too few/many args).
6227 for (unsigned i = FirstParam; i < NumParams; i++) {
6228 QualType ProtoArgType = Proto->getParamType(i);
6229
6230 Expr *Arg;
6231 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6232 if (ArgIx < Args.size()) {
6233 Arg = Args[ArgIx++];
6234
6235 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6236 diag::err_call_incomplete_argument, Arg))
6237 return true;
6238
6239 // Strip the unbridged-cast placeholder expression off, if applicable.
6240 bool CFAudited = false;
6241 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6242 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6243 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6244 Arg = ObjC().stripARCUnbridgedCast(Arg);
6245 else if (getLangOpts().ObjCAutoRefCount &&
6246 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6247 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6248 CFAudited = true;
6249
6250 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6251 ProtoArgType->isBlockPointerType())
6252 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6253 BE->getBlockDecl()->setDoesNotEscape();
6254 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6256 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6257 if (ArgExpr.isInvalid())
6258 return true;
6259 Arg = ArgExpr.getAs<Expr>();
6260 }
6261
6262 InitializedEntity Entity =
6264 ProtoArgType)
6266 Context, ProtoArgType, Proto->isParamConsumed(i));
6267
6268 // Remember that parameter belongs to a CF audited API.
6269 if (CFAudited)
6270 Entity.setParameterCFAudited();
6271
6272 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6273 // function boundaries is a common oversight.
6274 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6275 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6276 bool isPedantic =
6277 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6278 Diag(Arg->getExprLoc(),
6279 isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6280 : diag::warn_obt_discarded_at_function_boundary)
6281 << Arg->getType() << ProtoArgType;
6282 }
6283
6285 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6286 if (ArgE.isInvalid())
6287 return true;
6288
6289 Arg = ArgE.getAs<Expr>();
6290 } else {
6291 assert(Param && "can't use default arguments without a known callee");
6292
6293 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6294 if (ArgExpr.isInvalid())
6295 return true;
6296
6297 Arg = ArgExpr.getAs<Expr>();
6298 }
6299
6300 // Check for array bounds violations for each argument to the call. This
6301 // check only triggers warnings when the argument isn't a more complex Expr
6302 // with its own checking, such as a BinaryOperator.
6303 CheckArrayAccess(Arg);
6304
6305 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6306 CheckStaticArrayArgument(CallLoc, Param, Arg);
6307
6308 AllArgs.push_back(Arg);
6309 }
6310
6311 // If this is a variadic call, handle args passed through "...".
6312 if (CallType != VariadicCallType::DoesNotApply) {
6313 // Assume that extern "C" functions with variadic arguments that
6314 // return __unknown_anytype aren't *really* variadic.
6315 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6316 FDecl->isExternC()) {
6317 for (Expr *A : Args.slice(ArgIx)) {
6318 QualType paramType; // ignored
6319 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6320 Invalid |= arg.isInvalid();
6321 AllArgs.push_back(arg.get());
6322 }
6323
6324 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6325 } else {
6326 for (Expr *A : Args.slice(ArgIx)) {
6327 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6328 Invalid |= Arg.isInvalid();
6329 AllArgs.push_back(Arg.get());
6330 }
6331 }
6332
6333 // Check for array bounds violations.
6334 for (Expr *A : Args.slice(ArgIx))
6335 CheckArrayAccess(A);
6336 }
6337 return Invalid;
6338}
6339
6341 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6342 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6343 TL = DTL.getOriginalLoc();
6344 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6345 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6346 << ATL.getLocalSourceRange();
6347}
6348
6349void
6351 ParmVarDecl *Param,
6352 const Expr *ArgExpr) {
6353 // Static array parameters are not supported in C++.
6354 if (!Param || getLangOpts().CPlusPlus)
6355 return;
6356
6357 QualType OrigTy = Param->getOriginalType();
6358
6359 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6360 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6361 return;
6362
6363 if (ArgExpr->isNullPointerConstant(Context,
6365 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6366 DiagnoseCalleeStaticArrayParam(*this, Param);
6367 return;
6368 }
6369
6370 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6371 if (!CAT)
6372 return;
6373
6374 const ConstantArrayType *ArgCAT =
6375 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6376 if (!ArgCAT)
6377 return;
6378
6379 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6380 ArgCAT->getElementType())) {
6381 if (ArgCAT->getSize().ult(CAT->getSize())) {
6382 Diag(CallLoc, diag::warn_static_array_too_small)
6383 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6384 << (unsigned)CAT->getZExtSize() << 0;
6385 DiagnoseCalleeStaticArrayParam(*this, Param);
6386 }
6387 return;
6388 }
6389
6390 std::optional<CharUnits> ArgSize =
6392 std::optional<CharUnits> ParmSize =
6394 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6395 Diag(CallLoc, diag::warn_static_array_too_small)
6396 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6397 << (unsigned)ParmSize->getQuantity() << 1;
6398 DiagnoseCalleeStaticArrayParam(*this, Param);
6399 }
6400}
6401
6402/// Given a function expression of unknown-any type, try to rebuild it
6403/// to have a function type.
6405
6406/// Is the given type a placeholder that we need to lower out
6407/// immediately during argument processing?
6409 // Placeholders are never sugared.
6410 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6411 if (!placeholder) return false;
6412
6413 switch (placeholder->getKind()) {
6414 // Ignore all the non-placeholder types.
6415#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6416 case BuiltinType::Id:
6417#include "clang/Basic/OpenCLImageTypes.def"
6418#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6419 case BuiltinType::Id:
6420#include "clang/Basic/OpenCLExtensionTypes.def"
6421 // In practice we'll never use this, since all SVE types are sugared
6422 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6423#define SVE_TYPE(Name, Id, SingletonId) \
6424 case BuiltinType::Id:
6425#include "clang/Basic/AArch64ACLETypes.def"
6426#define PPC_VECTOR_TYPE(Name, Id, Size) \
6427 case BuiltinType::Id:
6428#include "clang/Basic/PPCTypes.def"
6429#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6430#include "clang/Basic/RISCVVTypes.def"
6431#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6432#include "clang/Basic/WebAssemblyReferenceTypes.def"
6433#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6434#include "clang/Basic/AMDGPUTypes.def"
6435#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6436#include "clang/Basic/HLSLIntangibleTypes.def"
6437#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6438#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6439#include "clang/AST/BuiltinTypes.def"
6440 return false;
6441
6442 case BuiltinType::UnresolvedTemplate:
6443 // We cannot lower out overload sets; they might validly be resolved
6444 // by the call machinery.
6445 case BuiltinType::Overload:
6446 return false;
6447
6448 // Unbridged casts in ARC can be handled in some call positions and
6449 // should be left in place.
6450 case BuiltinType::ARCUnbridgedCast:
6451 return false;
6452
6453 // Pseudo-objects should be converted as soon as possible.
6454 case BuiltinType::PseudoObject:
6455 return true;
6456
6457 // The debugger mode could theoretically but currently does not try
6458 // to resolve unknown-typed arguments based on known parameter types.
6459 case BuiltinType::UnknownAny:
6460 return true;
6461
6462 // These are always invalid as call arguments and should be reported.
6463 case BuiltinType::BoundMember:
6464 case BuiltinType::BuiltinFn:
6465 case BuiltinType::IncompleteMatrixIdx:
6466 case BuiltinType::ArraySection:
6467 case BuiltinType::OMPArrayShaping:
6468 case BuiltinType::OMPIterator:
6469 return true;
6470
6471 }
6472 llvm_unreachable("bad builtin type kind");
6473}
6474
6476 // Apply this processing to all the arguments at once instead of
6477 // dying at the first failure.
6478 bool hasInvalid = false;
6479 for (size_t i = 0, e = args.size(); i != e; i++) {
6480 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6481 ExprResult result = CheckPlaceholderExpr(args[i]);
6482 if (result.isInvalid()) hasInvalid = true;
6483 else args[i] = result.get();
6484 }
6485 }
6486 return hasInvalid;
6487}
6488
6489/// If a builtin function has a pointer argument with no explicit address
6490/// space, then it should be able to accept a pointer to any address
6491/// space as input. In order to do this, we need to replace the
6492/// standard builtin declaration with one that uses the same address space
6493/// as the call.
6494///
6495/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6496/// it does not contain any pointer arguments without
6497/// an address space qualifer. Otherwise the rewritten
6498/// FunctionDecl is returned.
6499/// TODO: Handle pointer return types.
6501 FunctionDecl *FDecl,
6502 MultiExprArg ArgExprs) {
6503
6504 QualType DeclType = FDecl->getType();
6505 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6506
6507 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6508 ArgExprs.size() < FT->getNumParams())
6509 return nullptr;
6510
6511 bool NeedsNewDecl = false;
6512 unsigned i = 0;
6513 SmallVector<QualType, 8> OverloadParams;
6514
6515 {
6516 // The lvalue conversions in this loop are only for type resolution and
6517 // don't actually occur.
6520 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6521
6522 for (QualType ParamType : FT->param_types()) {
6523
6524 // Convert array arguments to pointer to simplify type lookup.
6525 ExprResult ArgRes =
6527 if (ArgRes.isInvalid())
6528 return nullptr;
6529 Expr *Arg = ArgRes.get();
6530 QualType ArgType = Arg->getType();
6531 if (!ParamType->isPointerType() ||
6532 ParamType->getPointeeType().hasAddressSpace() ||
6533 !ArgType->isPointerType() ||
6534 !ArgType->getPointeeType().hasAddressSpace() ||
6535 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6536 OverloadParams.push_back(ParamType);
6537 continue;
6538 }
6539
6540 QualType PointeeType = ParamType->getPointeeType();
6541 NeedsNewDecl = true;
6542 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6543
6544 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6545 OverloadParams.push_back(Context.getPointerType(PointeeType));
6546 }
6547 }
6548
6549 if (!NeedsNewDecl)
6550 return nullptr;
6551
6553 EPI.Variadic = FT->isVariadic();
6554 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6555 OverloadParams, EPI);
6556 DeclContext *Parent = FDecl->getParent();
6557 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6558 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6559 FDecl->getIdentifier(), OverloadTy,
6560 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6561 false,
6562 /*hasPrototype=*/true);
6564 FT = cast<FunctionProtoType>(OverloadTy);
6565 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6566 QualType ParamType = FT->getParamType(i);
6567 ParmVarDecl *Parm =
6568 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6569 SourceLocation(), nullptr, ParamType,
6570 /*TInfo=*/nullptr, SC_None, nullptr);
6571 Parm->setScopeInfo(0, i);
6572 Params.push_back(Parm);
6573 }
6574 OverloadDecl->setParams(Params);
6575 // We cannot merge host/device attributes of redeclarations. They have to
6576 // be consistent when created.
6577 if (Sema->LangOpts.CUDA) {
6578 if (FDecl->hasAttr<CUDAHostAttr>())
6579 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6580 if (FDecl->hasAttr<CUDADeviceAttr>())
6581 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6582 }
6583 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6584 return OverloadDecl;
6585}
6586
6587static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6588 FunctionDecl *Callee,
6589 MultiExprArg ArgExprs) {
6590 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6591 // similar attributes) really don't like it when functions are called with an
6592 // invalid number of args.
6593 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6594 /*PartialOverloading=*/false) &&
6595 !Callee->isVariadic())
6596 return;
6597 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6598 return;
6599
6600 if (const EnableIfAttr *Attr =
6601 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6602 S.Diag(Fn->getBeginLoc(),
6603 isa<CXXMethodDecl>(Callee)
6604 ? diag::err_ovl_no_viable_member_function_in_call
6605 : diag::err_ovl_no_viable_function_in_call)
6606 << Callee << Callee->getSourceRange();
6607 S.Diag(Callee->getLocation(),
6608 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6609 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6610 return;
6611 }
6612}
6613
6615 const UnresolvedMemberExpr *const UME, Sema &S) {
6616
6617 const auto GetFunctionLevelDCIfCXXClass =
6618 [](Sema &S) -> const CXXRecordDecl * {
6619 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6620 if (!DC || !DC->getParent())
6621 return nullptr;
6622
6623 // If the call to some member function was made from within a member
6624 // function body 'M' return return 'M's parent.
6625 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6626 return MD->getParent()->getCanonicalDecl();
6627 // else the call was made from within a default member initializer of a
6628 // class, so return the class.
6629 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6630 return RD->getCanonicalDecl();
6631 return nullptr;
6632 };
6633 // If our DeclContext is neither a member function nor a class (in the
6634 // case of a lambda in a default member initializer), we can't have an
6635 // enclosing 'this'.
6636
6637 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6638 if (!CurParentClass)
6639 return false;
6640
6641 // The naming class for implicit member functions call is the class in which
6642 // name lookup starts.
6643 const CXXRecordDecl *const NamingClass =
6645 assert(NamingClass && "Must have naming class even for implicit access");
6646
6647 // If the unresolved member functions were found in a 'naming class' that is
6648 // related (either the same or derived from) to the class that contains the
6649 // member function that itself contained the implicit member access.
6650
6651 return CurParentClass == NamingClass ||
6652 CurParentClass->isDerivedFrom(NamingClass);
6653}
6654
6655static void
6657 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6658
6659 if (!UME)
6660 return;
6661
6662 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6663 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6664 // already been captured, or if this is an implicit member function call (if
6665 // it isn't, an attempt to capture 'this' should already have been made).
6666 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6667 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6668 return;
6669
6670 // Check if the naming class in which the unresolved members were found is
6671 // related (same as or is a base of) to the enclosing class.
6672
6674 return;
6675
6676
6677 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6678 // If the enclosing function is not dependent, then this lambda is
6679 // capture ready, so if we can capture this, do so.
6680 if (!EnclosingFunctionCtx->isDependentContext()) {
6681 // If the current lambda and all enclosing lambdas can capture 'this' -
6682 // then go ahead and capture 'this' (since our unresolved overload set
6683 // contains at least one non-static member function).
6684 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6685 S.CheckCXXThisCapture(CallLoc);
6686 } else if (S.CurContext->isDependentContext()) {
6687 // ... since this is an implicit member reference, that might potentially
6688 // involve a 'this' capture, mark 'this' for potential capture in
6689 // enclosing lambdas.
6690 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6691 CurLSI->addPotentialThisCapture(CallLoc);
6692 }
6693}
6694
6695// Once a call is fully resolved, warn for unqualified calls to specific
6696// C++ standard functions, like move and forward.
6698 const CallExpr *Call) {
6699 // We are only checking unary move and forward so exit early here.
6700 if (Call->getNumArgs() != 1)
6701 return;
6702
6703 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6704 if (!E || isa<UnresolvedLookupExpr>(E))
6705 return;
6706 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6707 if (!DRE || !DRE->getLocation().isValid())
6708 return;
6709
6710 if (DRE->getQualifier())
6711 return;
6712
6713 const FunctionDecl *FD = Call->getDirectCallee();
6714 if (!FD)
6715 return;
6716
6717 // Only warn for some functions deemed more frequent or problematic.
6718 unsigned BuiltinID = FD->getBuiltinID();
6719 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6720 return;
6721
6722 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6724 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6725}
6726
6728 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6729 Expr *ExecConfig) {
6731 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6732 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6733 if (Call.isInvalid())
6734 return Call;
6735
6736 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6737 // language modes.
6738 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6739 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6740 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6741 << ULE->getName();
6742 }
6743
6744 if (LangOpts.OpenMP)
6745 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6746 ExecConfig);
6747 if (LangOpts.CPlusPlus) {
6748 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6750
6751 // If we previously found that the id-expression of this call refers to a
6752 // consteval function but the call is dependent, we should not treat is an
6753 // an invalid immediate call.
6754 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6755 DRE && Call.get()->isValueDependent()) {
6757 }
6758 }
6759 return Call;
6760}
6761
6762// Any type that could be used to form a callable expression
6763static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6764 QualType T = E->getType();
6765 if (T->isDependentType())
6766 return true;
6767
6768 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6769 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6770 T->isFunctionType() || T->isFunctionReferenceType() ||
6771 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6772 T->isBlockPointerType() || T->isRecordType())
6773 return true;
6774
6777}
6778
6780 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6781 Expr *ExecConfig, bool IsExecConfig,
6782 bool AllowRecovery) {
6783 // Since this might be a postfix expression, get rid of ParenListExprs.
6785 if (Result.isInvalid()) return ExprError();
6786 Fn = Result.get();
6787
6788 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6789 // later, when we check boolean conditions, for now we merely forward it
6790 // without any additional checking.
6791 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6792 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6793 const auto *FD = cast<FunctionDecl>(Fn->getReferencedDeclOfCallee());
6794
6795 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6796 QualType FnPtrTy = Context.getPointerType(FD->getType());
6797 Expr *R = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6798 return CallExpr::Create(
6799 Context, R, ArgExprs, Context.AMDGPUFeaturePredicateTy,
6801 }
6802 }
6803
6804 if (CheckArgsForPlaceholders(ArgExprs))
6805 return ExprError();
6806
6807 // The result of __builtin_counted_by_ref cannot be used as a function
6808 // argument. It allows leaking and modification of bounds safety information.
6809 for (const Expr *Arg : ArgExprs)
6810 if (CheckInvalidBuiltinCountedByRef(Arg,
6812 return ExprError();
6813
6814 if (getLangOpts().CPlusPlus) {
6815 // If this is a pseudo-destructor expression, build the call immediately.
6817 if (!ArgExprs.empty()) {
6818 // Pseudo-destructor calls should not have any arguments.
6819 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6821 SourceRange(ArgExprs.front()->getBeginLoc(),
6822 ArgExprs.back()->getEndLoc()));
6823 }
6824
6825 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6826 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6827 }
6828 if (Fn->getType() == Context.PseudoObjectTy) {
6829 ExprResult result = CheckPlaceholderExpr(Fn);
6830 if (result.isInvalid()) return ExprError();
6831 Fn = result.get();
6832 }
6833
6834 // Determine whether this is a dependent call inside a C++ template,
6835 // in which case we won't do any semantic analysis now.
6836 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6837 if (ExecConfig) {
6839 cast<CallExpr>(ExecConfig), ArgExprs,
6840 Context.DependentTy, VK_PRValue,
6841 RParenLoc, CurFPFeatureOverrides());
6842 } else {
6843
6845 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6846 Fn->getBeginLoc());
6847
6848 // If the type of the function itself is not dependent
6849 // check that it is a reasonable as a function, as type deduction
6850 // later assume the CallExpr has a sensible TYPE.
6851 if (!MayBeFunctionType(Context, Fn))
6852 return ExprError(
6853 Diag(LParenLoc, diag::err_typecheck_call_not_function)
6854 << Fn->getType() << Fn->getSourceRange());
6855
6856 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6857 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6858 }
6859 }
6860
6861 // Determine whether this is a call to an object (C++ [over.call.object]).
6862 if (Fn->getType()->isRecordType())
6863 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6864 RParenLoc);
6865
6866 if (Fn->getType() == Context.UnknownAnyTy) {
6867 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6868 if (result.isInvalid()) return ExprError();
6869 Fn = result.get();
6870 }
6871
6872 if (Fn->getType() == Context.BoundMemberTy) {
6873 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6874 RParenLoc, ExecConfig, IsExecConfig,
6875 AllowRecovery);
6876 }
6877 }
6878
6879 // Check for overloaded calls. This can happen even in C due to extensions.
6880 if (Fn->getType() == Context.OverloadTy) {
6882
6883 // We aren't supposed to apply this logic if there's an '&' involved.
6886 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6887 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6888 OverloadExpr *ovl = find.Expression;
6889 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6891 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6892 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6893 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6894 RParenLoc, ExecConfig, IsExecConfig,
6895 AllowRecovery);
6896 }
6897 }
6898
6899 // If we're directly calling a function, get the appropriate declaration.
6900 if (Fn->getType() == Context.UnknownAnyTy) {
6901 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6902 if (result.isInvalid()) return ExprError();
6903 Fn = result.get();
6904 }
6905
6906 Expr *NakedFn = Fn->IgnoreParens();
6907
6908 bool CallingNDeclIndirectly = false;
6909 NamedDecl *NDecl = nullptr;
6910 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6911 if (UnOp->getOpcode() == UO_AddrOf) {
6912 CallingNDeclIndirectly = true;
6913 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6914 }
6915 }
6916
6917 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6918 NDecl = DRE->getDecl();
6919
6920 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6921 if (FDecl && FDecl->getBuiltinID()) {
6922 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
6923 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
6924 if (Context.BuiltinInfo.isTSBuiltin(FDecl->getBuiltinID()) &&
6925 !Context.BuiltinInfo.isAuxBuiltinID(FDecl->getBuiltinID())) {
6927 getFunctionLevelDeclContext(/*AllowLambda=*/true)));
6928 }
6929 }
6930
6931 // Rewrite the function decl for this builtin by replacing parameters
6932 // with no explicit address space with the address space of the arguments
6933 // in ArgExprs.
6934 if ((FDecl =
6935 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6936 NDecl = FDecl;
6938 Context, DRE->getQualifierLoc(), SourceLocation(), FDecl, false,
6939 SourceLocation(), Fn->getType() /* BuiltinFnTy */,
6940 Fn->getValueKind(), FDecl, nullptr, DRE->isNonOdrUse());
6941 }
6942 }
6943 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6944 NDecl = ME->getMemberDecl();
6945
6946 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6947 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6948 FD, /*Complain=*/true, Fn->getBeginLoc()))
6949 return ExprError();
6950
6951 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6952
6953 // If this expression is a call to a builtin function in HIP compilation,
6954 // allow a pointer-type argument to default address space to be passed as a
6955 // pointer-type parameter to a non-default address space. If Arg is declared
6956 // in the default address space and Param is declared in a non-default
6957 // address space, perform an implicit address space cast to the parameter
6958 // type.
6959 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
6960 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6961 ++Idx) {
6962 ParmVarDecl *Param = FD->getParamDecl(Idx);
6963 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6964 !ArgExprs[Idx]->getType()->isPointerType())
6965 continue;
6966
6967 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6968 auto ArgTy = ArgExprs[Idx]->getType();
6969 auto ArgPtTy = ArgTy->getPointeeType();
6970 auto ArgAS = ArgPtTy.getAddressSpace();
6971
6972 // Add address space cast if target address spaces are different
6973 bool NeedImplicitASC =
6974 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6975 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6976 // or from specific AS which has target AS matching that of Param.
6978 if (!NeedImplicitASC)
6979 continue;
6980
6981 // First, ensure that the Arg is an RValue.
6982 if (ArgExprs[Idx]->isGLValue()) {
6983 ExprResult Res = DefaultLvalueConversion(ArgExprs[Idx]);
6984 if (Res.isInvalid())
6985 return ExprError();
6986 ArgExprs[Idx] = Res.get();
6987 }
6988
6989 // Construct a new arg type with address space of Param
6990 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6991 ArgPtQuals.setAddressSpace(ParamAS);
6992 auto NewArgPtTy =
6993 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6994 auto NewArgTy =
6995 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6996 ArgTy.getQualifiers());
6997
6998 // Finally perform an implicit address space cast
6999 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7000 CK_AddressSpaceConversion)
7001 .get();
7002 }
7003 }
7004 }
7005
7006 if (Context.isDependenceAllowed() &&
7007 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7008 assert(!getLangOpts().CPlusPlus);
7009 assert((Fn->containsErrors() ||
7010 llvm::any_of(ArgExprs,
7011 [](clang::Expr *E) { return E->containsErrors(); })) &&
7012 "should only occur in error-recovery path.");
7013 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7014 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7015 }
7016 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7017 ExecConfig, IsExecConfig);
7018}
7019
7021 MultiExprArg CallArgs) {
7022 std::string Name = Context.BuiltinInfo.getName(Id);
7023 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7025 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7026
7027 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7028 assert(BuiltInDecl && "failed to find builtin declaration");
7029
7030 ExprResult DeclRef =
7031 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7032 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7033
7035 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7036
7037 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7038 return Call.get();
7039}
7040
7042 SourceLocation BuiltinLoc,
7043 SourceLocation RParenLoc) {
7044 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7045 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7046}
7047
7049 SourceLocation BuiltinLoc,
7050 SourceLocation RParenLoc) {
7053 QualType SrcTy = E->getType();
7054 if (!SrcTy->isDependentType() &&
7055 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7056 return ExprError(
7057 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7058 << DestTy << SrcTy << E->getSourceRange());
7059 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7060}
7061
7063 SourceLocation BuiltinLoc,
7064 SourceLocation RParenLoc) {
7065 TypeSourceInfo *TInfo;
7066 GetTypeFromParser(ParsedDestTy, &TInfo);
7067 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7068}
7069
7071 SourceLocation LParenLoc,
7072 ArrayRef<Expr *> Args,
7073 SourceLocation RParenLoc, Expr *Config,
7074 bool IsExecConfig, ADLCallKind UsesADL) {
7075 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7076 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7077
7078 auto IsSJLJ = [&] {
7079 switch (BuiltinID) {
7080 case Builtin::BI__builtin_longjmp:
7081 case Builtin::BI__builtin_setjmp:
7082 case Builtin::BI__sigsetjmp:
7083 case Builtin::BI_longjmp:
7084 case Builtin::BI_setjmp:
7085 case Builtin::BIlongjmp:
7086 case Builtin::BIsetjmp:
7087 case Builtin::BIsiglongjmp:
7088 case Builtin::BIsigsetjmp:
7089 return true;
7090 default:
7091 return false;
7092 }
7093 };
7094
7095 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7096 if (!CurrentDefer.empty() && IsSJLJ()) {
7097 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7098 // for more than just blocks (e.g. lambdas, nested classes...).
7099 Scope *DeferParent = CurrentDefer.back().first;
7100 Scope *Block = CurScope->getBlockParent();
7101 if (DeferParent->Contains(*CurScope) &&
7102 (!Block || !DeferParent->Contains(*Block)))
7103 Diag(Fn->getExprLoc(), diag::err_defer_invalid_sjlj) << FDecl;
7104 }
7105
7106 // Functions with 'interrupt' attribute cannot be called directly.
7107 if (FDecl) {
7108 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7109 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7110 return ExprError();
7111 }
7112 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7113 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
7114 return ExprError();
7115 }
7116 }
7117
7118 // X86 interrupt handlers may only call routines with attribute
7119 // no_caller_saved_registers since there is no efficient way to
7120 // save and restore the non-GPR state.
7121 if (auto *Caller = getCurFunctionDecl()) {
7122 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7123 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7124 const TargetInfo &TI = Context.getTargetInfo();
7125 bool HasNonGPRRegisters =
7126 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
7127 if (HasNonGPRRegisters &&
7128 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7129 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
7130 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7131 if (FDecl)
7132 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7133 }
7134 }
7135 }
7136
7137 // Extract the return type from the builtin function pointer type.
7138 QualType ResultTy;
7139 if (BuiltinID)
7140 ResultTy = FDecl->getCallResultType();
7141 else
7142 ResultTy = Context.BoolTy;
7143
7144 // Promote the function operand.
7145 // We special-case function promotion here because we only allow promoting
7146 // builtin functions to function pointers in the callee of a call.
7148 if (BuiltinID &&
7149 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7150 // FIXME Several builtins still have setType in
7151 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7152 // Builtins.td to ensure they are correct before removing setType calls.
7153 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7154 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7155 } else
7157 if (Result.isInvalid())
7158 return ExprError();
7159 Fn = Result.get();
7160
7161 // Check for a valid function type, but only if it is not a builtin which
7162 // requires custom type checking. These will be handled by
7163 // CheckBuiltinFunctionCall below just after creation of the call expression.
7164 const FunctionType *FuncT = nullptr;
7165 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7166 retry:
7167 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7168 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7169 // have type pointer to function".
7170 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7171 if (!FuncT)
7172 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7173 << Fn->getType() << Fn->getSourceRange());
7174 } else if (const BlockPointerType *BPT =
7175 Fn->getType()->getAs<BlockPointerType>()) {
7176 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7177 } else {
7178 // Handle calls to expressions of unknown-any type.
7179 if (Fn->getType() == Context.UnknownAnyTy) {
7180 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7181 if (rewrite.isInvalid())
7182 return ExprError();
7183 Fn = rewrite.get();
7184 goto retry;
7185 }
7186
7187 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7188 << Fn->getType() << Fn->getSourceRange());
7189 }
7190 }
7191
7192 // Get the number of parameters in the function prototype, if any.
7193 // We will allocate space for max(Args.size(), NumParams) arguments
7194 // in the call expression.
7195 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7196 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7197
7198 CallExpr *TheCall;
7199 if (Config) {
7200 assert(UsesADL == ADLCallKind::NotADL &&
7201 "CUDAKernelCallExpr should not use ADL");
7202 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7203 Args, ResultTy, VK_PRValue, RParenLoc,
7204 CurFPFeatureOverrides(), NumParams);
7205 } else {
7206 TheCall =
7207 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7208 CurFPFeatureOverrides(), NumParams, UsesADL);
7209 }
7210
7211 // Bail out early if calling a builtin with custom type checking.
7212 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7213 // For HLSL builtin aliases, the call was resolved via overload resolution
7214 // which may have selected a conversion sequence (e.g., vector-to-scalar
7215 // truncation). Convert arguments to match the declared prototype before
7216 // the custom type checker runs, otherwise the builtin will operate on
7217 // the unconverted argument types.
7218 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7219 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7220 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, P, Args, RParenLoc,
7221 IsExecConfig))
7222 return ExprError();
7223 }
7224 }
7225 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7226 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
7227 E = CheckForImmediateInvocation(E, FDecl);
7228 return E;
7229 }
7230
7231 if (getLangOpts().CUDA) {
7232 if (Config) {
7233 // CUDA: Kernel calls must be to global functions
7234 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7235 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7236 << FDecl << Fn->getSourceRange());
7237
7238 // CUDA: Kernel function must have 'void' return type
7239 if (!FuncT->getReturnType()->isVoidType() &&
7240 !FuncT->getReturnType()->getAs<AutoType>() &&
7242 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7243 << Fn->getType() << Fn->getSourceRange());
7244 } else {
7245 // CUDA: Calls to global functions must be configured
7246 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7247 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7248 << FDecl << Fn->getSourceRange());
7249 }
7250 }
7251
7252 // Check for a valid return type
7253 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7254 FDecl))
7255 return ExprError();
7256
7257 // We know the result type of the call, set it.
7258 TheCall->setType(FuncT->getCallResultType(Context));
7260
7261 // WebAssembly tables can't be used as arguments.
7262 if (Context.getTargetInfo().getTriple().isWasm()) {
7263 for (const Expr *Arg : Args) {
7264 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7265 return ExprError(Diag(Arg->getExprLoc(),
7266 diag::err_wasm_table_as_function_parameter));
7267 }
7268 }
7269 }
7270
7271 if (Proto) {
7272 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7273 IsExecConfig))
7274 return ExprError();
7275 } else {
7276 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7277
7278 if (FDecl) {
7279 // Check if we have too few/too many template arguments, based
7280 // on our knowledge of the function definition.
7281 const FunctionDecl *Def = nullptr;
7282 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7283 Proto = Def->getType()->getAs<FunctionProtoType>();
7284 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7285 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7286 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7287 }
7288
7289 // If the function we're calling isn't a function prototype, but we have
7290 // a function prototype from a prior declaratiom, use that prototype.
7291 if (!FDecl->hasPrototype())
7292 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7293 }
7294
7295 // If we still haven't found a prototype to use but there are arguments to
7296 // the call, diagnose this as calling a function without a prototype.
7297 // However, if we found a function declaration, check to see if
7298 // -Wdeprecated-non-prototype was disabled where the function was declared.
7299 // If so, we will silence the diagnostic here on the assumption that this
7300 // interface is intentional and the user knows what they're doing. We will
7301 // also silence the diagnostic if there is a function declaration but it
7302 // was implicitly defined (the user already gets diagnostics about the
7303 // creation of the implicit function declaration, so the additional warning
7304 // is not helpful).
7305 if (!Proto && !Args.empty() &&
7306 (!FDecl || (!FDecl->isImplicit() &&
7307 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7308 FDecl->getLocation()))))
7309 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7310 << (FDecl != nullptr) << FDecl;
7311
7312 // Promote the arguments (C99 6.5.2.2p6).
7313 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7314 Expr *Arg = Args[i];
7315
7316 if (Proto && i < Proto->getNumParams()) {
7318 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7319 ExprResult ArgE =
7321 if (ArgE.isInvalid())
7322 return true;
7323
7324 Arg = ArgE.getAs<Expr>();
7325
7326 } else {
7328
7329 if (ArgE.isInvalid())
7330 return true;
7331
7332 Arg = ArgE.getAs<Expr>();
7333 }
7334
7335 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7336 diag::err_call_incomplete_argument, Arg))
7337 return ExprError();
7338
7339 TheCall->setArg(i, Arg);
7340 }
7341 TheCall->computeDependence();
7342 }
7343
7344 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7345 if (Method->isImplicitObjectMemberFunction())
7346 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7347 << Fn->getSourceRange() << 0);
7348
7349 // Check for sentinels
7350 if (NDecl)
7351 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7352
7353 // Warn for unions passing across security boundary (CMSE).
7354 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7355 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7356 if (const auto *RT =
7357 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7358 if (RT->getDecl()->isOrContainsUnion())
7359 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7360 << 0 << i;
7361 }
7362 }
7363 }
7364
7365 // Do special checking on direct calls to functions.
7366 if (FDecl) {
7367 if (CheckFunctionCall(FDecl, TheCall, Proto))
7368 return ExprError();
7369
7370 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7371
7372 if (BuiltinID)
7373 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7374 } else if (NDecl) {
7375 if (CheckPointerCall(NDecl, TheCall, Proto))
7376 return ExprError();
7377 } else {
7378 if (CheckOtherCall(TheCall, Proto))
7379 return ExprError();
7380 }
7381
7382 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7383}
7384
7387 SourceLocation RParenLoc, Expr *InitExpr) {
7388 assert(Ty && "ActOnCompoundLiteral(): missing type");
7389 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7390
7391 TypeSourceInfo *TInfo;
7392 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7393 if (!TInfo)
7394 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7395
7396 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7397}
7398
7401 SourceLocation RParenLoc, Expr *LiteralExpr) {
7402 QualType literalType = TInfo->getType();
7403
7404 if (literalType->isArrayType()) {
7406 LParenLoc, Context.getBaseElementType(literalType),
7407 diag::err_array_incomplete_or_sizeless_type,
7408 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7409 return ExprError();
7410 if (literalType->isVariableArrayType()) {
7411 // C23 6.7.10p4: An entity of variable length array type shall not be
7412 // initialized except by an empty initializer.
7413 //
7414 // The C extension warnings are issued from ParseBraceInitializer() and
7415 // do not need to be issued here. However, we continue to issue an error
7416 // in the case there are initializers or we are compiling C++. We allow
7417 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7418 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7419 // FIXME: should we allow this construct in C++ when it makes sense to do
7420 // so?
7421 //
7422 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7423 // shall specify an object type or an array of unknown size, but not a
7424 // variable length array type. This seems odd, as it allows 'int a[size] =
7425 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7426 // says, this is what's implemented here for C (except for the extension
7427 // that permits constant foldable size arrays)
7428
7429 auto diagID = LangOpts.CPlusPlus
7430 ? diag::err_variable_object_no_init
7431 : diag::err_compound_literal_with_vla_type;
7432 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7433 diagID))
7434 return ExprError();
7435 }
7436 } else if (!literalType->isDependentType() &&
7437 RequireCompleteType(LParenLoc, literalType,
7438 diag::err_typecheck_decl_incomplete_type,
7439 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7440 return ExprError();
7441
7442 InitializedEntity Entity
7446 SourceRange(LParenLoc, RParenLoc),
7447 /*InitList=*/true);
7448 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7449 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7450 &literalType);
7451 if (Result.isInvalid())
7452 return ExprError();
7453 LiteralExpr = Result.get();
7454
7455 // We treat the compound literal as being at file scope if it's not in a
7456 // function or method body, or within the function's prototype scope. This
7457 // means the following compound literal is not at file scope:
7458 // void func(char *para[(int [1]){ 0 }[0]);
7459 const Scope *S = getCurScope();
7460 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7461 !S->isInCFunctionScope() &&
7462 (!S || !S->isFunctionPrototypeScope());
7463
7464 // In C, compound literals are l-values for some reason.
7465 // For GCC compatibility, in C++, file-scope array compound literals with
7466 // constant initializers are also l-values, and compound literals are
7467 // otherwise prvalues.
7468 //
7469 // (GCC also treats C++ list-initialized file-scope array prvalues with
7470 // constant initializers as l-values, but that's non-conforming, so we don't
7471 // follow it there.)
7472 //
7473 // FIXME: It would be better to handle the lvalue cases as materializing and
7474 // lifetime-extending a temporary object, but our materialized temporaries
7475 // representation only supports lifetime extension from a variable, not "out
7476 // of thin air".
7477 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7478 // is bound to the result of applying array-to-pointer decay to the compound
7479 // literal.
7480 // FIXME: GCC supports compound literals of reference type, which should
7481 // obviously have a value kind derived from the kind of reference involved.
7483 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7484 ? VK_PRValue
7485 : VK_LValue;
7486
7487 // C99 6.5.2.5
7488 // "If the compound literal occurs outside the body of a function, the
7489 // initializer list shall consist of constant expressions."
7490 if (IsFileScope)
7491 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7492 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7493 Expr *Init = ILE->getInit(i);
7494 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7495 !Init->isConstantInitializer(Context)) {
7496 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7497 << Init->getSourceBitField();
7498 return ExprError();
7499 }
7500
7501 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7502 }
7503
7504 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7505 LiteralExpr, IsFileScope);
7506 if (IsFileScope) {
7507 if (!LiteralExpr->isTypeDependent() &&
7508 !LiteralExpr->isValueDependent() &&
7509 !literalType->isDependentType()) // C99 6.5.2.5p3
7510 if (CheckForConstantInitializer(LiteralExpr))
7511 return ExprError();
7512 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7513 literalType.getAddressSpace() != LangAS::Default) {
7514 // Embedded-C extensions to C99 6.5.2.5:
7515 // "If the compound literal occurs inside the body of a function, the
7516 // type name shall not be qualified by an address-space qualifier."
7517 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7518 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7519 return ExprError();
7520 }
7521
7522 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7523 // Compound literals that have automatic storage duration are destroyed at
7524 // the end of the scope in C; in C++, they're just temporaries.
7525
7526 // Emit diagnostics if it is or contains a C union type that is non-trivial
7527 // to destruct.
7532
7533 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7534 if (literalType.isDestructedType()) {
7535 Cleanup.setExprNeedsCleanups(true);
7536 ExprCleanupObjects.push_back(E);
7538 }
7539 }
7540
7543 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7544 E->getInitializer()->getExprLoc());
7545
7546 return MaybeBindToTemporary(E);
7547}
7548
7551 SourceLocation RBraceLoc) {
7552 // Only produce each kind of designated initialization diagnostic once.
7553 SourceLocation FirstDesignator;
7554 bool DiagnosedArrayDesignator = false;
7555 bool DiagnosedNestedDesignator = false;
7556 bool DiagnosedMixedDesignator = false;
7557
7558 // Check that any designated initializers are syntactically valid in the
7559 // current language mode.
7560 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7561 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7562 if (FirstDesignator.isInvalid())
7563 FirstDesignator = DIE->getBeginLoc();
7564
7565 if (!getLangOpts().CPlusPlus)
7566 break;
7567
7568 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7569 DiagnosedNestedDesignator = true;
7570 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7571 << DIE->getDesignatorsSourceRange();
7572 }
7573
7574 for (auto &Desig : DIE->designators()) {
7575 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7576 DiagnosedArrayDesignator = true;
7577 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7578 << Desig.getSourceRange();
7579 }
7580 }
7581
7582 if (!DiagnosedMixedDesignator &&
7583 !isa<DesignatedInitExpr>(InitArgList[0])) {
7584 DiagnosedMixedDesignator = true;
7585 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7586 << DIE->getSourceRange();
7587 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7588 << InitArgList[0]->getSourceRange();
7589 }
7590 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7591 isa<DesignatedInitExpr>(InitArgList[0])) {
7592 DiagnosedMixedDesignator = true;
7593 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7594 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7595 << DIE->getSourceRange();
7596 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7597 << InitArgList[I]->getSourceRange();
7598 }
7599 }
7600
7601 if (FirstDesignator.isValid()) {
7602 // Only diagnose designated initiaization as a C++20 extension if we didn't
7603 // already diagnose use of (non-C++20) C99 designator syntax.
7604 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7605 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7606 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7607 ? diag::warn_cxx17_compat_designated_init
7608 : diag::ext_cxx_designated_init);
7609 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7610 Diag(FirstDesignator, diag::ext_designated_init);
7611 }
7612 }
7613
7614 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7615}
7616
7618 MultiExprArg InitArgList,
7619 SourceLocation RBraceLoc, bool IsExplicit) {
7620 // Semantic analysis for initializers is done by ActOnDeclarator() and
7621 // CheckInitializer() - it requires knowledge of the object being initialized.
7622
7623 // Immediately handle non-overload placeholders. Overloads can be
7624 // resolved contextually, but everything else here can't.
7625 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7626 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7627 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7628
7629 // Ignore failures; dropping the entire initializer list because
7630 // of one failure would be terrible for indexing/etc.
7631 if (result.isInvalid()) continue;
7632
7633 InitArgList[I] = result.get();
7634 }
7635 }
7636
7637 InitListExpr *E = new (Context)
7638 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7639 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7640 return E;
7641}
7642
7644 assert(E.get()->getType()->isBlockPointerType());
7645 assert(E.get()->isPRValue());
7646
7647 // Only do this in an r-value context.
7648 if (!getLangOpts().ObjCAutoRefCount) return;
7649
7651 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7652 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7653 Cleanup.setExprNeedsCleanups(true);
7654}
7655
7657 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7658 // Also, callers should have filtered out the invalid cases with
7659 // pointers. Everything else should be possible.
7660
7661 QualType SrcTy = Src.get()->getType();
7662 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7663 return CK_NoOp;
7664
7665 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7667 llvm_unreachable("member pointer type in C");
7668
7669 case Type::STK_CPointer:
7672 switch (DestTy->getScalarTypeKind()) {
7673 case Type::STK_CPointer: {
7674 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7675 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7676 if (SrcAS != DestAS)
7677 return CK_AddressSpaceConversion;
7678 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7679 return CK_NoOp;
7680 return CK_BitCast;
7681 }
7683 return (SrcKind == Type::STK_BlockPointer
7684 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7686 if (SrcKind == Type::STK_ObjCObjectPointer)
7687 return CK_BitCast;
7688 if (SrcKind == Type::STK_CPointer)
7689 return CK_CPointerToObjCPointerCast;
7691 return CK_BlockPointerToObjCPointerCast;
7692 case Type::STK_Bool:
7693 return CK_PointerToBoolean;
7694 case Type::STK_Integral:
7695 return CK_PointerToIntegral;
7696 case Type::STK_Floating:
7701 llvm_unreachable("illegal cast from pointer");
7702 }
7703 llvm_unreachable("Should have returned before this");
7704
7706 switch (DestTy->getScalarTypeKind()) {
7708 return CK_FixedPointCast;
7709 case Type::STK_Bool:
7710 return CK_FixedPointToBoolean;
7711 case Type::STK_Integral:
7712 return CK_FixedPointToIntegral;
7713 case Type::STK_Floating:
7714 return CK_FixedPointToFloating;
7717 Diag(Src.get()->getExprLoc(),
7718 diag::err_unimplemented_conversion_with_fixed_point_type)
7719 << DestTy;
7720 return CK_IntegralCast;
7721 case Type::STK_CPointer:
7725 llvm_unreachable("illegal cast to pointer type");
7726 }
7727 llvm_unreachable("Should have returned before this");
7728
7729 case Type::STK_Bool: // casting from bool is like casting from an integer
7730 case Type::STK_Integral:
7731 switch (DestTy->getScalarTypeKind()) {
7732 case Type::STK_CPointer:
7737 return CK_NullToPointer;
7738 return CK_IntegralToPointer;
7739 case Type::STK_Bool:
7740 return CK_IntegralToBoolean;
7741 case Type::STK_Integral:
7742 return CK_IntegralCast;
7743 case Type::STK_Floating:
7744 return CK_IntegralToFloating;
7746 Src = ImpCastExprToType(Src.get(),
7747 DestTy->castAs<ComplexType>()->getElementType(),
7748 CK_IntegralCast);
7749 return CK_IntegralRealToComplex;
7751 Src = ImpCastExprToType(Src.get(),
7752 DestTy->castAs<ComplexType>()->getElementType(),
7753 CK_IntegralToFloating);
7754 return CK_FloatingRealToComplex;
7756 llvm_unreachable("member pointer type in C");
7758 return CK_IntegralToFixedPoint;
7759 }
7760 llvm_unreachable("Should have returned before this");
7761
7762 case Type::STK_Floating:
7763 switch (DestTy->getScalarTypeKind()) {
7764 case Type::STK_Floating:
7765 return CK_FloatingCast;
7766 case Type::STK_Bool:
7767 return CK_FloatingToBoolean;
7768 case Type::STK_Integral:
7769 return CK_FloatingToIntegral;
7771 Src = ImpCastExprToType(Src.get(),
7772 DestTy->castAs<ComplexType>()->getElementType(),
7773 CK_FloatingCast);
7774 return CK_FloatingRealToComplex;
7776 Src = ImpCastExprToType(Src.get(),
7777 DestTy->castAs<ComplexType>()->getElementType(),
7778 CK_FloatingToIntegral);
7779 return CK_IntegralRealToComplex;
7780 case Type::STK_CPointer:
7783 llvm_unreachable("valid float->pointer cast?");
7785 llvm_unreachable("member pointer type in C");
7787 return CK_FloatingToFixedPoint;
7788 }
7789 llvm_unreachable("Should have returned before this");
7790
7792 switch (DestTy->getScalarTypeKind()) {
7794 return CK_FloatingComplexCast;
7796 return CK_FloatingComplexToIntegralComplex;
7797 case Type::STK_Floating: {
7798 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7799 if (Context.hasSameType(ET, DestTy))
7800 return CK_FloatingComplexToReal;
7801 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7802 return CK_FloatingCast;
7803 }
7804 case Type::STK_Bool:
7805 return CK_FloatingComplexToBoolean;
7806 case Type::STK_Integral:
7807 Src = ImpCastExprToType(Src.get(),
7808 SrcTy->castAs<ComplexType>()->getElementType(),
7809 CK_FloatingComplexToReal);
7810 return CK_FloatingToIntegral;
7811 case Type::STK_CPointer:
7814 llvm_unreachable("valid complex float->pointer cast?");
7816 llvm_unreachable("member pointer type in C");
7818 Diag(Src.get()->getExprLoc(),
7819 diag::err_unimplemented_conversion_with_fixed_point_type)
7820 << SrcTy;
7821 return CK_IntegralCast;
7822 }
7823 llvm_unreachable("Should have returned before this");
7824
7826 switch (DestTy->getScalarTypeKind()) {
7828 return CK_IntegralComplexToFloatingComplex;
7830 return CK_IntegralComplexCast;
7831 case Type::STK_Integral: {
7832 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7833 if (Context.hasSameType(ET, DestTy))
7834 return CK_IntegralComplexToReal;
7835 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7836 return CK_IntegralCast;
7837 }
7838 case Type::STK_Bool:
7839 return CK_IntegralComplexToBoolean;
7840 case Type::STK_Floating:
7841 Src = ImpCastExprToType(Src.get(),
7842 SrcTy->castAs<ComplexType>()->getElementType(),
7843 CK_IntegralComplexToReal);
7844 return CK_IntegralToFloating;
7845 case Type::STK_CPointer:
7848 llvm_unreachable("valid complex int->pointer cast?");
7850 llvm_unreachable("member pointer type in C");
7852 Diag(Src.get()->getExprLoc(),
7853 diag::err_unimplemented_conversion_with_fixed_point_type)
7854 << SrcTy;
7855 return CK_IntegralCast;
7856 }
7857 llvm_unreachable("Should have returned before this");
7858 }
7859
7860 llvm_unreachable("Unhandled scalar cast");
7861}
7862
7863static bool breakDownVectorType(QualType type, uint64_t &len,
7864 QualType &eltType) {
7865 // Vectors are simple.
7866 if (const VectorType *vecType = type->getAs<VectorType>()) {
7867 len = vecType->getNumElements();
7868 eltType = vecType->getElementType();
7869 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7870 return true;
7871 }
7872
7873 // We allow lax conversion to and from non-vector types, but only if
7874 // they're real types (i.e. non-complex, non-pointer scalar types).
7875 if (!type->isRealType()) return false;
7876
7877 len = 1;
7878 eltType = type;
7879 return true;
7880}
7881
7883 assert(srcTy->isVectorType() || destTy->isVectorType());
7884
7885 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7886 if (!FirstType->isSVESizelessBuiltinType())
7887 return false;
7888
7889 const auto *VecTy = SecondType->getAs<VectorType>();
7890 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7891 };
7892
7893 return ValidScalableConversion(srcTy, destTy) ||
7894 ValidScalableConversion(destTy, srcTy);
7895}
7896
7898 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7899 return false;
7900
7901 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7902 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7903
7904 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7905 matSrcType->getNumColumns() == matDestType->getNumColumns();
7906}
7907
7909 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7910
7911 uint64_t SrcLen, DestLen;
7912 QualType SrcEltTy, DestEltTy;
7913 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7914 return false;
7915 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7916 return false;
7917
7918 // ASTContext::getTypeSize will return the size rounded up to a
7919 // power of 2, so instead of using that, we need to use the raw
7920 // element size multiplied by the element count.
7921 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7922 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7923
7924 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7925}
7926
7928 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7929 "expected at least one type to be a vector here");
7930
7931 bool IsSrcTyAltivec =
7932 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7934 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7936 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7938
7939 bool IsDestTyAltivec = DestTy->isVectorType() &&
7940 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7942 (DestTy->castAs<VectorType>()->getVectorKind() ==
7944 (DestTy->castAs<VectorType>()->getVectorKind() ==
7946
7947 return (IsSrcTyAltivec || IsDestTyAltivec);
7948}
7949
7951 assert(destTy->isVectorType() || srcTy->isVectorType());
7952
7953 // Disallow lax conversions between scalars and ExtVectors (these
7954 // conversions are allowed for other vector types because common headers
7955 // depend on them). Most scalar OP ExtVector cases are handled by the
7956 // splat path anyway, which does what we want (convert, not bitcast).
7957 // What this rules out for ExtVectors is crazy things like char4*float.
7958 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7959 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7960
7961 return areVectorTypesSameSize(srcTy, destTy);
7962}
7963
7965 assert(destTy->isVectorType() || srcTy->isVectorType());
7966
7967 switch (Context.getLangOpts().getLaxVectorConversions()) {
7969 return false;
7970
7972 if (!srcTy->isIntegralOrEnumerationType()) {
7973 auto *Vec = srcTy->getAs<VectorType>();
7974 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7975 return false;
7976 }
7977 if (!destTy->isIntegralOrEnumerationType()) {
7978 auto *Vec = destTy->getAs<VectorType>();
7979 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7980 return false;
7981 }
7982 // OK, integer (vector) -> integer (vector) bitcast.
7983 break;
7984
7986 break;
7987 }
7988
7989 return areLaxCompatibleVectorTypes(srcTy, destTy);
7990}
7991
7993 CastKind &Kind) {
7994 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7995 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7996 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7997 << DestTy << SrcTy << R;
7998 }
7999 } else if (SrcTy->isMatrixType()) {
8000 return Diag(R.getBegin(),
8001 diag::err_invalid_conversion_between_matrix_and_type)
8002 << SrcTy << DestTy << R;
8003 } else if (DestTy->isMatrixType()) {
8004 return Diag(R.getBegin(),
8005 diag::err_invalid_conversion_between_matrix_and_type)
8006 << DestTy << SrcTy << R;
8007 }
8008
8009 Kind = CK_MatrixCast;
8010 return false;
8011}
8012
8014 CastKind &Kind) {
8015 assert(VectorTy->isVectorType() && "Not a vector type!");
8016
8017 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8018 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8019 return Diag(R.getBegin(),
8020 Ty->isVectorType() ?
8021 diag::err_invalid_conversion_between_vectors :
8022 diag::err_invalid_conversion_between_vector_and_integer)
8023 << VectorTy << Ty << R;
8024 } else
8025 return Diag(R.getBegin(),
8026 diag::err_invalid_conversion_between_vector_and_scalar)
8027 << VectorTy << Ty << R;
8028
8029 Kind = CK_BitCast;
8030 return false;
8031}
8032
8034 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8035
8036 if (DestElemTy == SplattedExpr->getType())
8037 return SplattedExpr;
8038
8039 assert(DestElemTy->isFloatingType() ||
8040 DestElemTy->isIntegralOrEnumerationType());
8041
8042 CastKind CK;
8043 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8044 // OpenCL requires that we convert `true` boolean expressions to -1, but
8045 // only when splatting vectors.
8046 if (DestElemTy->isFloatingType()) {
8047 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8048 // in two steps: boolean to signed integral, then to floating.
8049 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8050 CK_BooleanToSignedIntegral);
8051 SplattedExpr = CastExprRes.get();
8052 CK = CK_IntegralToFloating;
8053 } else {
8054 CK = CK_BooleanToSignedIntegral;
8055 }
8056 } else {
8057 ExprResult CastExprRes = SplattedExpr;
8058 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8059 if (CastExprRes.isInvalid())
8060 return ExprError();
8061 SplattedExpr = CastExprRes.get();
8062 }
8063 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8064}
8065
8067 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8068
8069 if (DestElemTy == SplattedExpr->getType())
8070 return SplattedExpr;
8071
8072 assert(DestElemTy->isFloatingType() ||
8073 DestElemTy->isIntegralOrEnumerationType());
8074
8075 ExprResult CastExprRes = SplattedExpr;
8076 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
8077 if (CastExprRes.isInvalid())
8078 return ExprError();
8079 SplattedExpr = CastExprRes.get();
8080
8081 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8082}
8083
8085 Expr *CastExpr, CastKind &Kind) {
8086 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8087
8088 QualType SrcTy = CastExpr->getType();
8089
8090 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8091 // an ExtVectorType.
8092 // In OpenCL, casts between vectors of different types are not allowed.
8093 // (See OpenCL 6.2).
8094 if (SrcTy->isVectorType()) {
8095 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8096 (getLangOpts().OpenCL &&
8097 !Context.hasSameUnqualifiedType(DestTy, SrcTy) &&
8098 !Context.areCompatibleVectorTypes(DestTy, SrcTy))) {
8099 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8100 << DestTy << SrcTy << R;
8101 return ExprError();
8102 }
8103 Kind = CK_BitCast;
8104 return CastExpr;
8105 }
8106
8107 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8108 // conversion will take place first from scalar to elt type, and then
8109 // splat from elt type to vector.
8110 if (SrcTy->isPointerType())
8111 return Diag(R.getBegin(),
8112 diag::err_invalid_conversion_between_vector_and_scalar)
8113 << DestTy << SrcTy << R;
8114
8115 Kind = CK_VectorSplat;
8116 return prepareVectorSplat(DestTy, CastExpr);
8117}
8118
8119/// Check that a call to alloc_size function specifies sufficient space for the
8120/// destination type.
8121static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8122 const Expr *E) {
8123 QualType SourceType = E->getType();
8124 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8125 DestType == SourceType)
8126 return;
8127
8128 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
8129 if (!CE)
8130 return;
8131
8132 // Find the total size allocated by the function call.
8133 if (!CE->getCalleeAllocSizeAttr())
8134 return;
8135 std::optional<llvm::APInt> AllocSize =
8136 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
8137 // Allocations of size zero are permitted as a special case. They are usually
8138 // done intentionally.
8139 if (!AllocSize || AllocSize->isZero())
8140 return;
8141 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
8142
8143 QualType TargetType = DestType->getPointeeType();
8144 // Find the destination size. As a special case function types have size of
8145 // one byte to match the sizeof operator behavior.
8146 auto LhsSize = TargetType->isFunctionType()
8147 ? CharUnits::One()
8148 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
8149 if (LhsSize && Size < LhsSize)
8150 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
8151 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8152}
8153
8156 Declarator &D, ParsedType &Ty,
8157 SourceLocation RParenLoc, Expr *CastExpr) {
8158 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8159 "ActOnCastExpr(): missing type or expr");
8160
8162 if (D.isInvalidType())
8163 return ExprError();
8164
8165 if (getLangOpts().CPlusPlus) {
8166 // Check that there are no default arguments (C++ only).
8168 }
8169
8171
8172 QualType castType = castTInfo->getType();
8173 Ty = CreateParsedType(castType, castTInfo);
8174
8175 bool isVectorLiteral = false;
8176
8177 // Check for an altivec or OpenCL literal,
8178 // i.e. all the elements are integer constants.
8179 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8180 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8181 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8182 && castType->isVectorType() && (PE || PLE)) {
8183 if (PLE && PLE->getNumExprs() == 0) {
8184 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8185 return ExprError();
8186 }
8187 if (PE || PLE->getNumExprs() == 1) {
8188 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8189 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8190 isVectorLiteral = true;
8191 }
8192 else
8193 isVectorLiteral = true;
8194 }
8195
8196 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8197 // then handle it as such.
8198 if (isVectorLiteral)
8199 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8200
8201 // If the Expr being casted is a ParenListExpr, handle it specially.
8202 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8203 // sequence of BinOp comma operators.
8206 if (Result.isInvalid()) return ExprError();
8207 CastExpr = Result.get();
8208 }
8209
8210 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8211 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8212
8214
8216
8218
8219 CheckSufficientAllocSize(*this, castType, CastExpr);
8220
8221 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8222}
8223
8225 SourceLocation RParenLoc, Expr *E,
8226 TypeSourceInfo *TInfo) {
8227 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8228 "Expected paren or paren list expression");
8229
8230 Expr **exprs;
8231 unsigned numExprs;
8232 Expr *subExpr;
8233 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8234 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8235 LiteralLParenLoc = PE->getLParenLoc();
8236 LiteralRParenLoc = PE->getRParenLoc();
8237 exprs = PE->getExprs();
8238 numExprs = PE->getNumExprs();
8239 } else { // isa<ParenExpr> by assertion at function entrance
8240 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8241 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8242 subExpr = cast<ParenExpr>(E)->getSubExpr();
8243 exprs = &subExpr;
8244 numExprs = 1;
8245 }
8246
8247 QualType Ty = TInfo->getType();
8248 assert(Ty->isVectorType() && "Expected vector type");
8249
8250 SmallVector<Expr *, 8> initExprs;
8251 const VectorType *VTy = Ty->castAs<VectorType>();
8252 unsigned numElems = VTy->getNumElements();
8253
8254 // '(...)' form of vector initialization in AltiVec: the number of
8255 // initializers must be one or must match the size of the vector.
8256 // If a single value is specified in the initializer then it will be
8257 // replicated to all the components of the vector
8259 VTy->getElementType()))
8260 return ExprError();
8262 // The number of initializers must be one or must match the size of the
8263 // vector. If a single value is specified in the initializer then it will
8264 // be replicated to all the components of the vector
8265 if (numExprs == 1) {
8266 QualType ElemTy = VTy->getElementType();
8267 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8268 if (Literal.isInvalid())
8269 return ExprError();
8270 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8271 PrepareScalarCast(Literal, ElemTy));
8272 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8273 }
8274 else if (numExprs < numElems) {
8275 Diag(E->getExprLoc(),
8276 diag::err_incorrect_number_of_vector_initializers);
8277 return ExprError();
8278 }
8279 else
8280 initExprs.append(exprs, exprs + numExprs);
8281 }
8282 else {
8283 // For OpenCL, when the number of initializers is a single value,
8284 // it will be replicated to all components of the vector.
8286 numExprs == 1) {
8287 QualType SrcTy = exprs[0]->getType();
8288 if (!SrcTy->isArithmeticType()) {
8289 Diag(exprs[0]->getBeginLoc(), diag::err_typecheck_convert_incompatible)
8290 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8291 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8292 return ExprError();
8293 }
8294 QualType ElemTy = VTy->getElementType();
8295 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8296 if (Literal.isInvalid())
8297 return ExprError();
8298 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8299 PrepareScalarCast(Literal, ElemTy));
8300 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8301 }
8302
8303 initExprs.append(exprs, exprs + numExprs);
8304 }
8305 // FIXME: This means that pretty-printing the final AST will produce curly
8306 // braces instead of the original commas.
8307 InitListExpr *initE =
8308 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8309 LiteralRParenLoc, /*isExplicit=*/false);
8310 initE->setType(Ty);
8311 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8312}
8313
8316 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8317 if (!E)
8318 return OrigExpr;
8319
8320 ExprResult Result(E->getExpr(0));
8321
8322 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8323 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8324 E->getExpr(i));
8325
8326 if (Result.isInvalid()) return ExprError();
8327
8328 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8329}
8330
8336
8338 unsigned NumUserSpecifiedExprs,
8339 SourceLocation InitLoc,
8340 SourceLocation LParenLoc,
8341 SourceLocation RParenLoc) {
8342 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8343 InitLoc, LParenLoc, RParenLoc);
8344}
8345
8346bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8347 SourceLocation QuestionLoc) {
8348 const Expr *NullExpr = LHSExpr;
8349 const Expr *NonPointerExpr = RHSExpr;
8353
8354 if (NullKind == Expr::NPCK_NotNull) {
8355 NullExpr = RHSExpr;
8356 NonPointerExpr = LHSExpr;
8357 NullKind =
8360 }
8361
8362 if (NullKind == Expr::NPCK_NotNull)
8363 return false;
8364
8365 if (NullKind == Expr::NPCK_ZeroExpression)
8366 return false;
8367
8368 if (NullKind == Expr::NPCK_ZeroLiteral) {
8369 // In this case, check to make sure that we got here from a "NULL"
8370 // string in the source code.
8371 NullExpr = NullExpr->IgnoreParenImpCasts();
8372 SourceLocation loc = NullExpr->getExprLoc();
8373 if (!findMacroSpelling(loc, "NULL"))
8374 return false;
8375 }
8376
8377 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8378 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8379 << NonPointerExpr->getType() << DiagType
8380 << NonPointerExpr->getSourceRange();
8381 return true;
8382}
8383
8384/// Return false if the condition expression is valid, true otherwise.
8385static bool checkCondition(Sema &S, const Expr *Cond,
8386 SourceLocation QuestionLoc) {
8387 QualType CondTy = Cond->getType();
8388
8389 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8390 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8391 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8392 << CondTy << Cond->getSourceRange();
8393 return true;
8394 }
8395
8396 // C99 6.5.15p2
8397 if (CondTy->isScalarType()) return false;
8398
8399 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8400 << CondTy << Cond->getSourceRange();
8401 return true;
8402}
8403
8404/// Return false if the NullExpr can be promoted to PointerTy,
8405/// true otherwise.
8407 QualType PointerTy) {
8408 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8409 !NullExpr.get()->isNullPointerConstant(S.Context,
8411 return true;
8412
8413 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8414 return false;
8415}
8416
8417/// Checks compatibility between two pointers and return the resulting
8418/// type.
8420 ExprResult &RHS,
8421 SourceLocation Loc) {
8422 QualType LHSTy = LHS.get()->getType();
8423 QualType RHSTy = RHS.get()->getType();
8424
8425 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8426 // Two identical pointers types are always compatible.
8427 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8428 }
8429
8430 QualType lhptee, rhptee;
8431
8432 // Get the pointee types.
8433 bool IsBlockPointer = false;
8434 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8435 lhptee = LHSBTy->getPointeeType();
8436 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8437 IsBlockPointer = true;
8438 } else {
8439 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8440 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8441 }
8442
8443 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8444 // differently qualified versions of compatible types, the result type is
8445 // a pointer to an appropriately qualified version of the composite
8446 // type.
8447
8448 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8449 // clause doesn't make sense for our extensions. E.g. address space 2 should
8450 // be incompatible with address space 3: they may live on different devices or
8451 // anything.
8452 Qualifiers lhQual = lhptee.getQualifiers();
8453 Qualifiers rhQual = rhptee.getQualifiers();
8454
8455 LangAS ResultAddrSpace = LangAS::Default;
8456 LangAS LAddrSpace = lhQual.getAddressSpace();
8457 LangAS RAddrSpace = rhQual.getAddressSpace();
8458
8459 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8460 // spaces is disallowed.
8461 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8462 ResultAddrSpace = LAddrSpace;
8463 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8464 ResultAddrSpace = RAddrSpace;
8465 else {
8466 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8467 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8468 << RHS.get()->getSourceRange();
8469 return QualType();
8470 }
8471
8472 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8473 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8474 lhQual.removeCVRQualifiers();
8475 rhQual.removeCVRQualifiers();
8476
8477 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8478 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8479 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8480 << RHS.get()->getSourceRange();
8481 return QualType();
8482 }
8483
8484 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8485 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8486 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8487 // qual types are compatible iff
8488 // * corresponded types are compatible
8489 // * CVR qualifiers are equal
8490 // * address spaces are equal
8491 // Thus for conditional operator we merge CVR and address space unqualified
8492 // pointees and if there is a composite type we return a pointer to it with
8493 // merged qualifiers.
8494 LHSCastKind =
8495 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8496 RHSCastKind =
8497 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8498 lhQual.removeAddressSpace();
8499 rhQual.removeAddressSpace();
8500
8501 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8502 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8503
8504 QualType CompositeTy = S.Context.mergeTypes(
8505 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8506 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8507
8508 if (CompositeTy.isNull()) {
8509 // In this situation, we assume void* type. No especially good
8510 // reason, but this is what gcc does, and we do have to pick
8511 // to get a consistent AST.
8512 QualType incompatTy;
8513 incompatTy = S.Context.getPointerType(
8514 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8515 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8516 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8517
8518 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8519 // for casts between types with incompatible address space qualifiers.
8520 // For the following code the compiler produces casts between global and
8521 // local address spaces of the corresponded innermost pointees:
8522 // local int *global *a;
8523 // global int *global *b;
8524 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8525 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8526 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8527 << RHS.get()->getSourceRange();
8528
8529 return incompatTy;
8530 }
8531
8532 // The pointer types are compatible.
8533 // In case of OpenCL ResultTy should have the address space qualifier
8534 // which is a superset of address spaces of both the 2nd and the 3rd
8535 // operands of the conditional operator.
8536 QualType ResultTy = [&, ResultAddrSpace]() {
8537 if (S.getLangOpts().OpenCL) {
8538 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8539 CompositeQuals.setAddressSpace(ResultAddrSpace);
8540 return S.Context
8541 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8542 .withCVRQualifiers(MergedCVRQual);
8543 }
8544 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8545 }();
8546 if (IsBlockPointer)
8547 ResultTy = S.Context.getBlockPointerType(ResultTy);
8548 else
8549 ResultTy = S.Context.getPointerType(ResultTy);
8550
8551 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8552 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8553 return ResultTy;
8554}
8555
8556/// Return the resulting type when the operands are both block pointers.
8558 ExprResult &LHS,
8559 ExprResult &RHS,
8560 SourceLocation Loc) {
8561 QualType LHSTy = LHS.get()->getType();
8562 QualType RHSTy = RHS.get()->getType();
8563
8564 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8565 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8567 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8568 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8569 return destType;
8570 }
8571 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8572 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8573 << RHS.get()->getSourceRange();
8574 return QualType();
8575 }
8576
8577 // We have 2 block pointer types.
8578 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8579}
8580
8581/// Return the resulting type when the operands are both pointers.
8582static QualType
8584 ExprResult &RHS,
8585 SourceLocation Loc) {
8586 // get the pointer types
8587 QualType LHSTy = LHS.get()->getType();
8588 QualType RHSTy = RHS.get()->getType();
8589
8590 // get the "pointed to" types
8591 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8592 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8593
8594 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8595 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8596 // Figure out necessary qualifiers (C99 6.5.15p6)
8597 QualType destPointee
8598 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8599 QualType destType = S.Context.getPointerType(destPointee);
8600 // Add qualifiers if necessary.
8601 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8602 // Promote to void*.
8603 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8604 return destType;
8605 }
8606 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8607 QualType destPointee
8608 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8609 QualType destType = S.Context.getPointerType(destPointee);
8610 // Add qualifiers if necessary.
8611 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8612 // Promote to void*.
8613 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8614 return destType;
8615 }
8616
8617 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8618}
8619
8620/// Return false if the first expression is not an integer and the second
8621/// expression is not a pointer, true otherwise.
8623 Expr* PointerExpr, SourceLocation Loc,
8624 bool IsIntFirstExpr) {
8625 if (!PointerExpr->getType()->isPointerType() ||
8626 !Int.get()->getType()->isIntegerType())
8627 return false;
8628
8629 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8630 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8631
8632 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8633 << Expr1->getType() << Expr2->getType()
8634 << Expr1->getSourceRange() << Expr2->getSourceRange();
8635 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8636 CK_IntegralToPointer);
8637 return true;
8638}
8639
8640/// Simple conversion between integer and floating point types.
8641///
8642/// Used when handling the OpenCL conditional operator where the
8643/// condition is a vector while the other operands are scalar.
8644///
8645/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8646/// types are either integer or floating type. Between the two
8647/// operands, the type with the higher rank is defined as the "result
8648/// type". The other operand needs to be promoted to the same type. No
8649/// other type promotion is allowed. We cannot use
8650/// UsualArithmeticConversions() for this purpose, since it always
8651/// promotes promotable types.
8653 ExprResult &RHS,
8654 SourceLocation QuestionLoc) {
8656 if (LHS.isInvalid())
8657 return QualType();
8659 if (RHS.isInvalid())
8660 return QualType();
8661
8662 // For conversion purposes, we ignore any qualifiers.
8663 // For example, "const float" and "float" are equivalent.
8664 QualType LHSType =
8666 QualType RHSType =
8668
8669 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8670 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8671 << LHSType << LHS.get()->getSourceRange();
8672 return QualType();
8673 }
8674
8675 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8676 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8677 << RHSType << RHS.get()->getSourceRange();
8678 return QualType();
8679 }
8680
8681 // If both types are identical, no conversion is needed.
8682 if (LHSType == RHSType)
8683 return LHSType;
8684
8685 // Now handle "real" floating types (i.e. float, double, long double).
8686 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8687 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8688 /*IsCompAssign = */ false);
8689
8690 // Finally, we have two differing integer types.
8692 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8693}
8694
8695/// Convert scalar operands to a vector that matches the
8696/// condition in length.
8697///
8698/// Used when handling the OpenCL conditional operator where the
8699/// condition is a vector while the other operands are scalar.
8700///
8701/// We first compute the "result type" for the scalar operands
8702/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8703/// into a vector of that type where the length matches the condition
8704/// vector type. s6.11.6 requires that the element types of the result
8705/// and the condition must have the same number of bits.
8706static QualType
8708 QualType CondTy, SourceLocation QuestionLoc) {
8709 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8710 if (ResTy.isNull()) return QualType();
8711
8712 const VectorType *CV = CondTy->getAs<VectorType>();
8713 assert(CV);
8714
8715 // Determine the vector result type
8716 unsigned NumElements = CV->getNumElements();
8717 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8718
8719 // Ensure that all types have the same number of bits
8721 != S.Context.getTypeSize(ResTy)) {
8722 // Since VectorTy is created internally, it does not pretty print
8723 // with an OpenCL name. Instead, we just print a description.
8724 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8725 SmallString<64> Str;
8726 llvm::raw_svector_ostream OS(Str);
8727 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8728 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8729 << CondTy << OS.str();
8730 return QualType();
8731 }
8732
8733 // Convert operands to the vector result type
8734 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8735 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8736
8737 return VectorTy;
8738}
8739
8740/// Return false if this is a valid OpenCL condition vector
8742 SourceLocation QuestionLoc) {
8743 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8744 // integral type.
8745 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8746 assert(CondTy);
8747 QualType EleTy = CondTy->getElementType();
8748 if (EleTy->isIntegerType()) return false;
8749
8750 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8751 << Cond->getType() << Cond->getSourceRange();
8752 return true;
8753}
8754
8755/// Return false if the vector condition type and the vector
8756/// result type are compatible.
8757///
8758/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8759/// number of elements, and their element types have the same number
8760/// of bits.
8761static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8762 SourceLocation QuestionLoc) {
8763 const VectorType *CV = CondTy->getAs<VectorType>();
8764 const VectorType *RV = VecResTy->getAs<VectorType>();
8765 assert(CV && RV);
8766
8767 if (CV->getNumElements() != RV->getNumElements()) {
8768 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8769 << CondTy << VecResTy;
8770 return true;
8771 }
8772
8773 QualType CVE = CV->getElementType();
8774 QualType RVE = RV->getElementType();
8775
8776 // Boolean vectors are permitted outside of OpenCL mode.
8777 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8778 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8779 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8780 << CondTy << VecResTy;
8781 return true;
8782 }
8783
8784 return false;
8785}
8786
8787/// Return the resulting type for the conditional operator in
8788/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8789/// s6.3.i) when the condition is a vector type.
8790static QualType
8792 ExprResult &LHS, ExprResult &RHS,
8793 SourceLocation QuestionLoc) {
8795 if (Cond.isInvalid())
8796 return QualType();
8797 QualType CondTy = Cond.get()->getType();
8798
8799 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8800 return QualType();
8801
8802 // If either operand is a vector then find the vector type of the
8803 // result as specified in OpenCL v1.1 s6.3.i.
8804 if (LHS.get()->getType()->isVectorType() ||
8805 RHS.get()->getType()->isVectorType()) {
8806 bool IsBoolVecLang =
8807 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8808 QualType VecResTy =
8809 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8810 /*isCompAssign*/ false,
8811 /*AllowBothBool*/ true,
8812 /*AllowBoolConversions*/ false,
8813 /*AllowBooleanOperation*/ IsBoolVecLang,
8814 /*ReportInvalid*/ true);
8815 if (VecResTy.isNull())
8816 return QualType();
8817 // The result type must match the condition type as specified in
8818 // OpenCL v1.1 s6.11.6.
8819 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8820 return QualType();
8821 return VecResTy;
8822 }
8823
8824 // Both operands are scalar.
8825 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8826}
8827
8828/// Return true if the Expr is block type
8829static bool checkBlockType(Sema &S, const Expr *E) {
8830 if (E->getType()->isBlockPointerType()) {
8831 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8832 return true;
8833 }
8834
8835 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8836 QualType Ty = CE->getCallee()->getType();
8837 if (Ty->isBlockPointerType()) {
8838 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8839 return true;
8840 }
8841 }
8842 return false;
8843}
8844
8845/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8846/// In that case, LHS = cond.
8847/// C99 6.5.15
8850 ExprObjectKind &OK,
8851 SourceLocation QuestionLoc) {
8852
8853 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8854 if (!LHSResult.isUsable()) return QualType();
8855 LHS = LHSResult;
8856
8857 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8858 if (!RHSResult.isUsable()) return QualType();
8859 RHS = RHSResult;
8860
8861 // C++ is sufficiently different to merit its own checker.
8862 if (getLangOpts().CPlusPlus)
8863 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8864
8865 VK = VK_PRValue;
8866 OK = OK_Ordinary;
8867
8868 if (Context.isDependenceAllowed() &&
8869 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8870 RHS.get()->isTypeDependent())) {
8871 assert(!getLangOpts().CPlusPlus);
8872 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8873 RHS.get()->containsErrors()) &&
8874 "should only occur in error-recovery path.");
8875 return Context.DependentTy;
8876 }
8877
8878 // The OpenCL operator with a vector condition is sufficiently
8879 // different to merit its own checker.
8880 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8881 Cond.get()->getType()->isExtVectorType())
8882 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8883
8884 // First, check the condition.
8886 if (Cond.isInvalid())
8887 return QualType();
8888 if (checkCondition(*this, Cond.get(), QuestionLoc))
8889 return QualType();
8890
8891 // Handle vectors.
8892 if (LHS.get()->getType()->isVectorType() ||
8893 RHS.get()->getType()->isVectorType())
8894 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8895 /*AllowBothBool*/ true,
8896 /*AllowBoolConversions*/ false,
8897 /*AllowBooleanOperation*/ false,
8898 /*ReportInvalid*/ true);
8899
8900 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
8902 if (LHS.isInvalid() || RHS.isInvalid())
8903 return QualType();
8904
8905 // WebAssembly tables are not allowed as conditional LHS or RHS.
8906 QualType LHSTy = LHS.get()->getType();
8907 QualType RHSTy = RHS.get()->getType();
8908 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8909 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8910 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8911 return QualType();
8912 }
8913
8914 // Diagnose attempts to convert between __ibm128, __float128 and long double
8915 // where such conversions currently can't be handled.
8916 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8917 Diag(QuestionLoc,
8918 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8919 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8920 return QualType();
8921 }
8922
8923 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8924 // selection operator (?:).
8925 if (getLangOpts().OpenCL &&
8926 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8927 return QualType();
8928 }
8929
8930 // If both operands have arithmetic type, do the usual arithmetic conversions
8931 // to find a common type: C99 6.5.15p3,5.
8932 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8933 // Disallow invalid arithmetic conversions, such as those between bit-
8934 // precise integers types of different sizes, or between a bit-precise
8935 // integer and another type.
8936 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8937 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8938 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8939 << RHS.get()->getSourceRange();
8940 return QualType();
8941 }
8942
8943 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8944 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8945
8946 return ResTy;
8947 }
8948
8949 // If both operands are the same structure or union type, the result is that
8950 // type.
8951 // FIXME: Type of conditional expression must be complete in C mode.
8952 if (LHSTy->isRecordType() &&
8953 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
8954 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
8955 RHSTy.getUnqualifiedType());
8956
8957 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8958 // The following || allows only one side to be void (a GCC-ism).
8959 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8960 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8961 // UsualArithmeticConversions already handled the case where both sides
8962 // are the same type.
8963 } else if (RHSTy->isVoidType()) {
8964 ResTy = RHSTy;
8965 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8966 << RHS.get()->getSourceRange();
8967 } else {
8968 ResTy = LHSTy;
8969 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8970 << LHS.get()->getSourceRange();
8971 }
8972 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8973 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8974 return ResTy;
8975 }
8976
8977 // C23 6.5.15p7:
8978 // ... if both the second and third operands have nullptr_t type, the
8979 // result also has that type.
8980 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8981 return ResTy;
8982
8983 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8984 // the type of the other operand."
8985 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8986 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8987
8988 // All objective-c pointer type analysis is done here.
8989 QualType compositeType =
8990 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8991 if (LHS.isInvalid() || RHS.isInvalid())
8992 return QualType();
8993 if (!compositeType.isNull())
8994 return compositeType;
8995
8996
8997 // Handle block pointer types.
8998 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8999 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9000 QuestionLoc);
9001
9002 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9003 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9004 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9005 QuestionLoc);
9006
9007 // GCC compatibility: soften pointer/integer mismatch. Note that
9008 // null pointers have been filtered out by this point.
9009 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9010 /*IsIntFirstExpr=*/true))
9011 return RHSTy;
9012 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9013 /*IsIntFirstExpr=*/false))
9014 return LHSTy;
9015
9016 // Emit a better diagnostic if one of the expressions is a null pointer
9017 // constant and the other is not a pointer type. In this case, the user most
9018 // likely forgot to take the address of the other expression.
9019 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9020 return QualType();
9021
9022 // Finally, if the LHS and RHS types are canonically the same type, we can
9023 // use the common sugared type.
9024 if (Context.hasSameType(LHSTy, RHSTy))
9025 return Context.getCommonSugaredType(LHSTy, RHSTy);
9026
9027 // Otherwise, the operands are not compatible.
9028 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9029 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9030 << RHS.get()->getSourceRange();
9031 return QualType();
9032}
9033
9034/// SuggestParentheses - Emit a note with a fixit hint that wraps
9035/// ParenRange in parentheses.
9037 const PartialDiagnostic &Note,
9038 SourceRange ParenRange) {
9039 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9040 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9041 EndLoc.isValid()) {
9042 Self.Diag(Loc, Note)
9043 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9044 << FixItHint::CreateInsertion(EndLoc, ")");
9045 } else {
9046 // We can't display the parentheses, so just show the bare note.
9047 Self.Diag(Loc, Note) << ParenRange;
9048 }
9049}
9050
9052 return BinaryOperator::isAdditiveOp(Opc) ||
9054 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9055 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9056 // not any of the logical operators. Bitwise-xor is commonly used as a
9057 // logical-xor because there is no logical-xor operator. The logical
9058 // operators, including uses of xor, have a high false positive rate for
9059 // precedence warnings.
9060}
9061
9062/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9063/// expression, either using a built-in or overloaded operator,
9064/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9065/// expression.
9066static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9067 const Expr **RHSExprs) {
9068 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9069 E = E->IgnoreImpCasts();
9071 E = E->IgnoreImpCasts();
9072 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9073 E = MTE->getSubExpr();
9074 E = E->IgnoreImpCasts();
9075 }
9076
9077 // Built-in binary operator.
9078 if (const auto *OP = dyn_cast<BinaryOperator>(E);
9079 OP && IsArithmeticOp(OP->getOpcode())) {
9080 *Opcode = OP->getOpcode();
9081 *RHSExprs = OP->getRHS();
9082 return true;
9083 }
9084
9085 // Overloaded operator.
9086 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9087 if (Call->getNumArgs() != 2)
9088 return false;
9089
9090 // Make sure this is really a binary operator that is safe to pass into
9091 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9092 OverloadedOperatorKind OO = Call->getOperator();
9093 if (OO < OO_Plus || OO > OO_Arrow ||
9094 OO == OO_PlusPlus || OO == OO_MinusMinus)
9095 return false;
9096
9098 if (IsArithmeticOp(OpKind)) {
9099 *Opcode = OpKind;
9100 *RHSExprs = Call->getArg(1);
9101 return true;
9102 }
9103 }
9104
9105 return false;
9106}
9107
9108/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9109/// or is a logical expression such as (x==y) which has int type, but is
9110/// commonly interpreted as boolean.
9111static bool ExprLooksBoolean(const Expr *E) {
9112 E = E->IgnoreParenImpCasts();
9113
9114 if (E->getType()->isBooleanType())
9115 return true;
9116 if (const auto *OP = dyn_cast<BinaryOperator>(E))
9117 return OP->isComparisonOp() || OP->isLogicalOp();
9118 if (const auto *OP = dyn_cast<UnaryOperator>(E))
9119 return OP->getOpcode() == UO_LNot;
9120 if (E->getType()->isPointerType())
9121 return true;
9122 // FIXME: What about overloaded operator calls returning "unspecified boolean
9123 // type"s (commonly pointer-to-members)?
9124
9125 return false;
9126}
9127
9128/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9129/// and binary operator are mixed in a way that suggests the programmer assumed
9130/// the conditional operator has higher precedence, for example:
9131/// "int x = a + someBinaryCondition ? 1 : 2".
9133 Expr *Condition, const Expr *LHSExpr,
9134 const Expr *RHSExpr) {
9135 BinaryOperatorKind CondOpcode;
9136 const Expr *CondRHS;
9137
9138 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9139 return;
9140 if (!ExprLooksBoolean(CondRHS))
9141 return;
9142
9143 // The condition is an arithmetic binary expression, with a right-
9144 // hand side that looks boolean, so warn.
9145
9146 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9147 ? diag::warn_precedence_bitwise_conditional
9148 : diag::warn_precedence_conditional;
9149
9150 Self.Diag(OpLoc, DiagID)
9151 << Condition->getSourceRange()
9152 << BinaryOperator::getOpcodeStr(CondOpcode);
9153
9155 Self, OpLoc,
9156 Self.PDiag(diag::note_precedence_silence)
9157 << BinaryOperator::getOpcodeStr(CondOpcode),
9158 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9159
9160 SuggestParentheses(Self, OpLoc,
9161 Self.PDiag(diag::note_precedence_conditional_first),
9162 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9163}
9164
9165/// Compute the nullability of a conditional expression.
9167 QualType LHSTy, QualType RHSTy,
9168 ASTContext &Ctx) {
9169 if (!ResTy->isAnyPointerType())
9170 return ResTy;
9171
9172 auto GetNullability = [](QualType Ty) {
9173 NullabilityKindOrNone Kind = Ty->getNullability();
9174 if (Kind) {
9175 // For our purposes, treat _Nullable_result as _Nullable.
9178 return *Kind;
9179 }
9181 };
9182
9183 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9184 NullabilityKind MergedKind;
9185
9186 // Compute nullability of a binary conditional expression.
9187 if (IsBin) {
9188 if (LHSKind == NullabilityKind::NonNull)
9189 MergedKind = NullabilityKind::NonNull;
9190 else
9191 MergedKind = RHSKind;
9192 // Compute nullability of a normal conditional expression.
9193 } else {
9194 if (LHSKind == NullabilityKind::Nullable ||
9195 RHSKind == NullabilityKind::Nullable)
9196 MergedKind = NullabilityKind::Nullable;
9197 else if (LHSKind == NullabilityKind::NonNull)
9198 MergedKind = RHSKind;
9199 else if (RHSKind == NullabilityKind::NonNull)
9200 MergedKind = LHSKind;
9201 else
9202 MergedKind = NullabilityKind::Unspecified;
9203 }
9204
9205 // Return if ResTy already has the correct nullability.
9206 if (GetNullability(ResTy) == MergedKind)
9207 return ResTy;
9208
9209 // Strip all nullability from ResTy.
9210 while (ResTy->getNullability())
9211 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9212
9213 // Create a new AttributedType with the new nullability kind.
9214 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
9215}
9216
9218 SourceLocation ColonLoc,
9219 Expr *CondExpr, Expr *LHSExpr,
9220 Expr *RHSExpr) {
9221 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9222 // was the condition.
9223 OpaqueValueExpr *opaqueValue = nullptr;
9224 Expr *commonExpr = nullptr;
9225 if (!LHSExpr) {
9226 commonExpr = CondExpr;
9227 // Lower out placeholder types first. This is important so that we don't
9228 // try to capture a placeholder. This happens in few cases in C++; such
9229 // as Objective-C++'s dictionary subscripting syntax.
9230 if (commonExpr->hasPlaceholderType()) {
9231 ExprResult result = CheckPlaceholderExpr(commonExpr);
9232 if (!result.isUsable()) return ExprError();
9233 commonExpr = result.get();
9234 }
9235 // We usually want to apply unary conversions *before* saving, except
9236 // in the special case of a C++ l-value conditional.
9237 if (!(getLangOpts().CPlusPlus
9238 && !commonExpr->isTypeDependent()
9239 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9240 && commonExpr->isGLValue()
9241 && commonExpr->isOrdinaryOrBitFieldObject()
9242 && RHSExpr->isOrdinaryOrBitFieldObject()
9243 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9244 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9245 if (commonRes.isInvalid())
9246 return ExprError();
9247 commonExpr = commonRes.get();
9248 }
9249
9250 // If the common expression is a class or array prvalue, materialize it
9251 // so that we can safely refer to it multiple times.
9252 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9253 commonExpr->getType()->isArrayType())) {
9254 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9255 if (MatExpr.isInvalid())
9256 return ExprError();
9257 commonExpr = MatExpr.get();
9258 }
9259
9260 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9261 commonExpr->getType(),
9262 commonExpr->getValueKind(),
9263 commonExpr->getObjectKind(),
9264 commonExpr);
9265 LHSExpr = CondExpr = opaqueValue;
9266 }
9267
9268 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9271 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9272 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9273 VK, OK, QuestionLoc);
9274 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9275 RHS.isInvalid())
9276 return ExprError();
9277
9278 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9279 RHS.get());
9280
9281 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9282
9283 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9284 Context);
9285
9286 if (!commonExpr)
9287 return new (Context)
9288 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9289 RHS.get(), result, VK, OK);
9290
9292 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9293 ColonLoc, result, VK, OK);
9294}
9295
9297 unsigned FromAttributes = 0, ToAttributes = 0;
9298 if (const auto *FromFn =
9299 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9300 FromAttributes =
9301 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9302 if (const auto *ToFn =
9303 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9304 ToAttributes =
9305 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9306
9307 return FromAttributes != ToAttributes;
9308}
9309
9310// checkPointerTypesForAssignment - This is a very tricky routine (despite
9311// being closely modeled after the C99 spec:-). The odd characteristic of this
9312// routine is it effectively iqnores the qualifiers on the top level pointee.
9313// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9314// FIXME: add a couple examples in this comment.
9316 QualType LHSType,
9317 QualType RHSType,
9318 SourceLocation Loc) {
9319 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9320 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9321
9322 // get the "pointed to" type (ignoring qualifiers at the top level)
9323 const Type *lhptee, *rhptee;
9324 Qualifiers lhq, rhq;
9325 std::tie(lhptee, lhq) =
9326 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9327 std::tie(rhptee, rhq) =
9328 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9329
9331
9332 // C99 6.5.16.1p1: This following citation is common to constraints
9333 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9334 // qualifiers of the type *pointed to* by the right;
9335
9336 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9337 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9339 // Ignore lifetime for further calculation.
9340 lhq.removeObjCLifetime();
9341 rhq.removeObjCLifetime();
9342 }
9343
9344 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9345 // Treat address-space mismatches as fatal.
9346 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9348
9349 // It's okay to add or remove GC or lifetime qualifiers when converting to
9350 // and from void*.
9353 S.getASTContext()) &&
9354 (lhptee->isVoidType() || rhptee->isVoidType()))
9355 ; // keep old
9356
9357 // Treat lifetime mismatches as fatal.
9358 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9360
9361 // Treat pointer-auth mismatches as fatal.
9362 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9364
9365 // For GCC/MS compatibility, other qualifier mismatches are treated
9366 // as still compatible in C.
9367 else
9369 }
9370
9371 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9372 // incomplete type and the other is a pointer to a qualified or unqualified
9373 // version of void...
9374 if (lhptee->isVoidType()) {
9375 if (rhptee->isIncompleteOrObjectType())
9376 return ConvTy;
9377
9378 // As an extension, we allow cast to/from void* to function pointer.
9379 assert(rhptee->isFunctionType());
9381 }
9382
9383 if (rhptee->isVoidType()) {
9384 // In C, void * to another pointer type is compatible, but we want to note
9385 // that there will be an implicit conversion happening here.
9386 if (lhptee->isIncompleteOrObjectType())
9387 return ConvTy == AssignConvertType::Compatible &&
9388 !S.getLangOpts().CPlusPlus
9390 : ConvTy;
9391
9392 // As an extension, we allow cast to/from void* to function pointer.
9393 assert(lhptee->isFunctionType());
9395 }
9396
9397 if (!S.Diags.isIgnored(
9398 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9399 Loc) &&
9400 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9401 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9403
9404 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9405 // unqualified versions of compatible types, ...
9406 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9407
9408 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9409 if (!S.Context.hasSameType(ltrans, rtrans)) {
9410 QualType LUnderlying =
9411 ltrans->isOverflowBehaviorType()
9412 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9413 : ltrans;
9414 QualType RUnderlying =
9415 rtrans->isOverflowBehaviorType()
9416 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9417 : rtrans;
9418
9419 if (S.Context.hasSameType(LUnderlying, RUnderlying))
9421
9422 ltrans = LUnderlying;
9423 rtrans = RUnderlying;
9424 }
9425 }
9426
9427 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9428 // Check if the pointee types are compatible ignoring the sign.
9429 // We explicitly check for char so that we catch "char" vs
9430 // "unsigned char" on systems where "char" is unsigned.
9431 if (lhptee->isCharType())
9432 ltrans = S.Context.UnsignedCharTy;
9433 else if (lhptee->hasSignedIntegerRepresentation())
9434 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9435
9436 if (rhptee->isCharType())
9437 rtrans = S.Context.UnsignedCharTy;
9438 else if (rhptee->hasSignedIntegerRepresentation())
9439 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9440
9441 if (ltrans == rtrans) {
9442 // Types are compatible ignoring the sign. Qualifier incompatibility
9443 // takes priority over sign incompatibility because the sign
9444 // warning can be disabled.
9445 if (!S.IsAssignConvertCompatible(ConvTy))
9446 return ConvTy;
9447
9449 }
9450
9451 // If we are a multi-level pointer, it's possible that our issue is simply
9452 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9453 // the eventual target type is the same and the pointers have the same
9454 // level of indirection, this must be the issue.
9455 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9456 do {
9457 std::tie(lhptee, lhq) =
9458 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9459 std::tie(rhptee, rhq) =
9460 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9461
9462 // Inconsistent address spaces at this point is invalid, even if the
9463 // address spaces would be compatible.
9464 // FIXME: This doesn't catch address space mismatches for pointers of
9465 // different nesting levels, like:
9466 // __local int *** a;
9467 // int ** b = a;
9468 // It's not clear how to actually determine when such pointers are
9469 // invalidly incompatible.
9470 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9471 return AssignConvertType::
9472 IncompatibleNestedPointerAddressSpaceMismatch;
9473
9474 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9475
9476 if (lhptee == rhptee)
9478 }
9479
9480 // General pointer incompatibility takes priority over qualifiers.
9481 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9484 }
9485 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9486 // hasSameType, so we can skip further checks.
9487 const auto *LFT = ltrans->getAs<FunctionType>();
9488 const auto *RFT = rtrans->getAs<FunctionType>();
9489 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9490 // The invocation of IsFunctionConversion below will try to transform rtrans
9491 // to obtain an exact match for ltrans. This should not fail because of
9492 // mismatches in result type and parameter types, they were already checked
9493 // by typesAreCompatible above. So we will recreate rtrans (or where
9494 // appropriate ltrans) using the result type and parameter types from ltrans
9495 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9496 const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);
9497 const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);
9498 if (LFPT && RFPT) {
9499 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9500 LFPT->getParamTypes(),
9501 RFPT->getExtProtoInfo());
9502 } else if (LFPT) {
9504 EPI.ExtInfo = RFT->getExtInfo();
9505 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9506 LFPT->getParamTypes(), EPI);
9507 } else if (RFPT) {
9508 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9509 // all of its ExtProtoInfo. Transform ltrans instead.
9511 EPI.ExtInfo = LFT->getExtInfo();
9512 ltrans = S.Context.getFunctionType(RFPT->getReturnType(),
9513 RFPT->getParamTypes(), EPI);
9514 } else {
9515 rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),
9516 RFT->getExtInfo());
9517 }
9518 if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&
9519 !S.IsFunctionConversion(rtrans, ltrans))
9521 }
9522 return ConvTy;
9523}
9524
9525/// checkBlockPointerTypesForAssignment - This routine determines whether two
9526/// block pointer types are compatible or whether a block and normal pointer
9527/// are compatible. It is more restrict than comparing two function pointer
9528// types.
9530 QualType LHSType,
9531 QualType RHSType) {
9532 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9533 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9534
9535 QualType lhptee, rhptee;
9536
9537 // get the "pointed to" type (ignoring qualifiers at the top level)
9538 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9539 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9540
9541 // In C++, the types have to match exactly.
9542 if (S.getLangOpts().CPlusPlus)
9544
9546
9547 // For blocks we enforce that qualifiers are identical.
9548 Qualifiers LQuals = lhptee.getLocalQualifiers();
9549 Qualifiers RQuals = rhptee.getLocalQualifiers();
9550 if (S.getLangOpts().OpenCL) {
9551 LQuals.removeAddressSpace();
9552 RQuals.removeAddressSpace();
9553 }
9554 if (LQuals != RQuals)
9556
9557 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9558 // assignment.
9559 // The current behavior is similar to C++ lambdas. A block might be
9560 // assigned to a variable iff its return type and parameters are compatible
9561 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9562 // an assignment. Presumably it should behave in way that a function pointer
9563 // assignment does in C, so for each parameter and return type:
9564 // * CVR and address space of LHS should be a superset of CVR and address
9565 // space of RHS.
9566 // * unqualified types should be compatible.
9567 if (S.getLangOpts().OpenCL) {
9569 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9570 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9572 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9574
9575 return ConvTy;
9576}
9577
9578/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9579/// for assignment compatibility.
9581 QualType LHSType,
9582 QualType RHSType) {
9583 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9584 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9585
9586 if (LHSType->isObjCBuiltinType()) {
9587 // Class is not compatible with ObjC object pointers.
9588 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9589 !RHSType->isObjCQualifiedClassType())
9592 }
9593 if (RHSType->isObjCBuiltinType()) {
9594 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9595 !LHSType->isObjCQualifiedClassType())
9598 }
9599 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9600 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9601
9602 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9603 // make an exception for id<P>
9604 !LHSType->isObjCQualifiedIdType())
9606
9607 if (S.Context.typesAreCompatible(LHSType, RHSType))
9609 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9612}
9613
9615 QualType LHSType,
9616 QualType RHSType) {
9617 // Fake up an opaque expression. We don't actually care about what
9618 // cast operations are required, so if CheckAssignmentConstraints
9619 // adds casts to this they'll be wasted, but fortunately that doesn't
9620 // usually happen on valid code.
9621 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9622 ExprResult RHSPtr = &RHSExpr;
9623 CastKind K;
9624
9625 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9626}
9627
9628/// This helper function returns true if QT is a vector type that has element
9629/// type ElementType.
9630static bool isVector(QualType QT, QualType ElementType) {
9631 if (const VectorType *VT = QT->getAs<VectorType>())
9632 return VT->getElementType().getCanonicalType() == ElementType;
9633 return false;
9634}
9635
9636/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9637/// has code to accommodate several GCC extensions when type checking
9638/// pointers. Here are some objectionable examples that GCC considers warnings:
9639///
9640/// int a, *pint;
9641/// short *pshort;
9642/// struct foo *pfoo;
9643///
9644/// pint = pshort; // warning: assignment from incompatible pointer type
9645/// a = pint; // warning: assignment makes integer from pointer without a cast
9646/// pint = a; // warning: assignment makes pointer from integer without a cast
9647/// pint = pfoo; // warning: assignment from incompatible pointer type
9648///
9649/// As a result, the code for dealing with pointers is more complex than the
9650/// C99 spec dictates.
9651///
9652/// Sets 'Kind' for any result kind except Incompatible.
9654 ExprResult &RHS,
9655 CastKind &Kind,
9656 bool ConvertRHS) {
9657 QualType RHSType = RHS.get()->getType();
9658 QualType OrigLHSType = LHSType;
9659
9660 // Get canonical types. We're not formatting these types, just comparing
9661 // them.
9662 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9663 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9664
9665 // Common case: no conversion required.
9666 if (LHSType == RHSType) {
9667 Kind = CK_NoOp;
9669 }
9670
9671 // If the LHS has an __auto_type, there are no additional type constraints
9672 // to be worried about.
9673 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9674 if (AT->isGNUAutoType()) {
9675 Kind = CK_NoOp;
9677 }
9678 }
9679
9680 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHSType, RHSType);
9681 switch (OBTResult) {
9683 Kind = CK_NoOp;
9686 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9690 break;
9691 }
9692
9693 // Check for incompatible OBT types in pointer pointee types
9694 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9695 QualType LHSPointee = LHSType->getPointeeType();
9696 QualType RHSPointee = RHSType->getPointeeType();
9697 if ((LHSPointee->isOverflowBehaviorType() ||
9698 RHSPointee->isOverflowBehaviorType()) &&
9699 !Context.areCompatibleOverflowBehaviorTypes(LHSPointee, RHSPointee)) {
9700 Kind = CK_NoOp;
9702 }
9703 }
9704
9705 // If we have an atomic type, try a non-atomic assignment, then just add an
9706 // atomic qualification step.
9707 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9709 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9711 return Result;
9712 if (Kind != CK_NoOp && ConvertRHS)
9713 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9714 Kind = CK_NonAtomicToAtomic;
9715 return Result;
9716 }
9717
9718 // If the left-hand side is a reference type, then we are in a
9719 // (rare!) case where we've allowed the use of references in C,
9720 // e.g., as a parameter type in a built-in function. In this case,
9721 // just make sure that the type referenced is compatible with the
9722 // right-hand side type. The caller is responsible for adjusting
9723 // LHSType so that the resulting expression does not have reference
9724 // type.
9725 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9726 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9727 Kind = CK_LValueBitCast;
9729 }
9731 }
9732
9733 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9734 // of an ExtVector type to the same ExtVector type.
9735 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9736 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9737 // Implicit conversions require the same number of elements.
9738 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9740
9741 if (LHSType->isExtVectorBoolType() &&
9742 RHSExtType->getElementType()->isIntegerType()) {
9743 Kind = CK_IntegralToBoolean;
9745 }
9746 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9747 if (Context.getLangOpts().OpenCL &&
9748 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9749 Kind = CK_BitCast;
9751 }
9753 }
9754 if (RHSType->isArithmeticType()) {
9755 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9756 if (ConvertRHS)
9757 RHS = prepareVectorSplat(LHSType, RHS.get());
9758 Kind = CK_VectorSplat;
9760 }
9761 }
9762
9763 // Conversions to or from vector type.
9764 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9765 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9766 // Allow assignments of an AltiVec vector type to an equivalent GCC
9767 // vector type and vice versa
9768 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9769 Kind = CK_BitCast;
9771 }
9772
9773 // If we are allowing lax vector conversions, and LHS and RHS are both
9774 // vectors, the total size only needs to be the same. This is a bitcast;
9775 // no bits are changed but the result type is different.
9776 if (isLaxVectorConversion(RHSType, LHSType)) {
9777 // The default for lax vector conversions with Altivec vectors will
9778 // change, so if we are converting between vector types where
9779 // at least one is an Altivec vector, emit a warning.
9780 if (Context.getTargetInfo().getTriple().isPPC() &&
9781 anyAltivecTypes(RHSType, LHSType) &&
9782 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9783 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9784 << RHSType << LHSType;
9785 Kind = CK_BitCast;
9787 }
9788 }
9789
9790 // When the RHS comes from another lax conversion (e.g. binops between
9791 // scalars and vectors) the result is canonicalized as a vector. When the
9792 // LHS is also a vector, the lax is allowed by the condition above. Handle
9793 // the case where LHS is a scalar.
9794 if (LHSType->isScalarType()) {
9795 const VectorType *VecType = RHSType->getAs<VectorType>();
9796 if (VecType && VecType->getNumElements() == 1 &&
9797 isLaxVectorConversion(RHSType, LHSType)) {
9798 if (Context.getTargetInfo().getTriple().isPPC() &&
9800 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9802 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9803 << RHSType << LHSType;
9804 ExprResult *VecExpr = &RHS;
9805 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9806 Kind = CK_BitCast;
9808 }
9809 }
9810
9811 // Allow assignments between fixed-length and sizeless SVE vectors.
9812 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9813 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9814 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9815 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9816 Kind = CK_BitCast;
9818 }
9819
9820 // Allow assignments between fixed-length and sizeless RVV vectors.
9821 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9822 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9823 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9824 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9825 Kind = CK_BitCast;
9827 }
9828 }
9829
9831 }
9832
9833 // Diagnose attempts to convert between __ibm128, __float128 and long double
9834 // where such conversions currently can't be handled.
9835 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9837
9838 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9839 // discards the imaginary part.
9840 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9841 !LHSType->getAs<ComplexType>())
9843
9844 // Arithmetic conversions.
9845 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9846 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9847 if (ConvertRHS)
9848 Kind = PrepareScalarCast(RHS, LHSType);
9850 }
9851
9852 // Conversions to normal pointers.
9853 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9854 // U* -> T*
9855 if (isa<PointerType>(RHSType)) {
9856 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9857 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9858 if (AddrSpaceL != AddrSpaceR)
9859 Kind = CK_AddressSpaceConversion;
9860 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9861 Kind = CK_NoOp;
9862 else
9863 Kind = CK_BitCast;
9864 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9865 RHS.get()->getBeginLoc());
9866 }
9867
9868 // int -> T*
9869 if (RHSType->isIntegerType()) {
9870 Kind = CK_IntegralToPointer; // FIXME: null?
9872 }
9873
9874 // C pointers are not compatible with ObjC object pointers,
9875 // with two exceptions:
9876 if (isa<ObjCObjectPointerType>(RHSType)) {
9877 // - conversions to void*
9878 if (LHSPointer->getPointeeType()->isVoidType()) {
9879 Kind = CK_BitCast;
9881 }
9882
9883 // - conversions from 'Class' to the redefinition type
9884 if (RHSType->isObjCClassType() &&
9885 Context.hasSameType(LHSType,
9886 Context.getObjCClassRedefinitionType())) {
9887 Kind = CK_BitCast;
9889 }
9890
9891 Kind = CK_BitCast;
9893 }
9894
9895 // U^ -> void*
9896 if (RHSType->getAs<BlockPointerType>()) {
9897 if (LHSPointer->getPointeeType()->isVoidType()) {
9898 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9899 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9900 ->getPointeeType()
9901 .getAddressSpace();
9902 Kind =
9903 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9905 }
9906 }
9907
9909 }
9910
9911 // Conversions to block pointers.
9912 if (isa<BlockPointerType>(LHSType)) {
9913 // U^ -> T^
9914 if (RHSType->isBlockPointerType()) {
9915 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9916 ->getPointeeType()
9917 .getAddressSpace();
9918 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9919 ->getPointeeType()
9920 .getAddressSpace();
9921 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9922 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9923 }
9924
9925 // int or null -> T^
9926 if (RHSType->isIntegerType()) {
9927 Kind = CK_IntegralToPointer; // FIXME: null
9929 }
9930
9931 // id -> T^
9932 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9933 Kind = CK_AnyPointerToBlockPointerCast;
9935 }
9936
9937 // void* -> T^
9938 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9939 if (RHSPT->getPointeeType()->isVoidType()) {
9940 Kind = CK_AnyPointerToBlockPointerCast;
9942 }
9943
9945 }
9946
9947 // Conversions to Objective-C pointers.
9948 if (isa<ObjCObjectPointerType>(LHSType)) {
9949 // A* -> B*
9950 if (RHSType->isObjCObjectPointerType()) {
9951 Kind = CK_BitCast;
9952 AssignConvertType result =
9953 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9954 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9956 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9958 return result;
9959 }
9960
9961 // int or null -> A*
9962 if (RHSType->isIntegerType()) {
9963 Kind = CK_IntegralToPointer; // FIXME: null
9965 }
9966
9967 // In general, C pointers are not compatible with ObjC object pointers,
9968 // with two exceptions:
9969 if (isa<PointerType>(RHSType)) {
9970 Kind = CK_CPointerToObjCPointerCast;
9971
9972 // - conversions from 'void*'
9973 if (RHSType->isVoidPointerType()) {
9975 }
9976
9977 // - conversions to 'Class' from its redefinition type
9978 if (LHSType->isObjCClassType() &&
9979 Context.hasSameType(RHSType,
9980 Context.getObjCClassRedefinitionType())) {
9982 }
9983
9985 }
9986
9987 // Only under strict condition T^ is compatible with an Objective-C pointer.
9988 if (RHSType->isBlockPointerType() &&
9990 if (ConvertRHS)
9992 Kind = CK_BlockPointerToObjCPointerCast;
9994 }
9995
9997 }
9998
9999 // Conversion to nullptr_t (C23 only)
10000 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10003 // null -> nullptr_t
10004 Kind = CK_NullToPointer;
10006 }
10007
10008 // Conversions from pointers that are not covered by the above.
10009 if (isa<PointerType>(RHSType)) {
10010 // T* -> _Bool
10011 if (LHSType == Context.BoolTy) {
10012 Kind = CK_PointerToBoolean;
10014 }
10015
10016 // T* -> int
10017 if (LHSType->isIntegerType()) {
10018 Kind = CK_PointerToIntegral;
10020 }
10021
10023 }
10024
10025 // Conversions from Objective-C pointers that are not covered by the above.
10026 if (isa<ObjCObjectPointerType>(RHSType)) {
10027 // T* -> _Bool
10028 if (LHSType == Context.BoolTy) {
10029 Kind = CK_PointerToBoolean;
10031 }
10032
10033 // T* -> int
10034 if (LHSType->isIntegerType()) {
10035 Kind = CK_PointerToIntegral;
10037 }
10038
10040 }
10041
10042 // struct A -> struct B
10043 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10044 if (Context.typesAreCompatible(LHSType, RHSType)) {
10045 Kind = CK_NoOp;
10047 }
10048 }
10049
10050 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10051 Kind = CK_IntToOCLSampler;
10053 }
10054
10056}
10057
10058/// Constructs a transparent union from an expression that is
10059/// used to initialize the transparent union.
10061 ExprResult &EResult, QualType UnionType,
10062 FieldDecl *Field) {
10063 // Build an initializer list that designates the appropriate member
10064 // of the transparent union.
10065 Expr *E = EResult.get();
10067 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10068 Initializer->setType(UnionType);
10069 Initializer->setInitializedFieldInUnion(Field);
10070
10071 // Build a compound literal constructing a value of the transparent
10072 // union type from this initializer list.
10073 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10074 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10075 VK_PRValue, Initializer, false);
10076}
10077
10080 ExprResult &RHS) {
10081 QualType RHSType = RHS.get()->getType();
10082
10083 // If the ArgType is a Union type, we want to handle a potential
10084 // transparent_union GCC extension.
10085 const RecordType *UT = ArgType->getAsUnionType();
10086 if (!UT)
10088
10089 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10090 if (!UD->hasAttr<TransparentUnionAttr>())
10092
10093 // The field to initialize within the transparent union.
10094 FieldDecl *InitField = nullptr;
10095 // It's compatible if the expression matches any of the fields.
10096 for (auto *it : UD->fields()) {
10097 if (it->getType()->isPointerType()) {
10098 // If the transparent union contains a pointer type, we allow:
10099 // 1) void pointer
10100 // 2) null pointer constant
10101 if (RHSType->isPointerType())
10102 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10103 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10104 InitField = it;
10105 break;
10106 }
10107
10110 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10111 CK_NullToPointer);
10112 InitField = it;
10113 break;
10114 }
10115 }
10116
10117 CastKind Kind;
10118 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
10120 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10121 InitField = it;
10122 break;
10123 }
10124 }
10125
10126 if (!InitField)
10128
10129 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10131}
10132
10134 ExprResult &CallerRHS,
10135 bool Diagnose,
10136 bool DiagnoseCFAudited,
10137 bool ConvertRHS) {
10138 // We need to be able to tell the caller whether we diagnosed a problem, if
10139 // they ask us to issue diagnostics.
10140 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10141
10142 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10143 // we can't avoid *all* modifications at the moment, so we need some somewhere
10144 // to put the updated value.
10145 ExprResult LocalRHS = CallerRHS;
10146 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10147
10148 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10149 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10150 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10151 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10152 Diag(RHS.get()->getExprLoc(),
10153 diag::warn_noderef_to_dereferenceable_pointer)
10154 << RHS.get()->getSourceRange();
10155 }
10156 }
10157 }
10158
10159 if (getLangOpts().CPlusPlus) {
10160 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10161 // C++ 5.17p3: If the left operand is not of class type, the
10162 // expression is implicitly converted (C++ 4) to the
10163 // cv-unqualified type of the left operand.
10164 QualType RHSType = RHS.get()->getType();
10165 if (Diagnose) {
10166 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10168 } else {
10171 /*SuppressUserConversions=*/false,
10172 AllowedExplicit::None,
10173 /*InOverloadResolution=*/false,
10174 /*CStyle=*/false,
10175 /*AllowObjCWritebackConversion=*/false);
10176 if (ICS.isFailure())
10178 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10180 }
10181 if (RHS.isInvalid())
10184 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10185 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10187
10188 // Check if OBT is being discarded during assignment
10189 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10190 if (RHSType->isOverflowBehaviorType() &&
10191 !LHSType->isOverflowBehaviorType()) {
10193 }
10194
10195 return result;
10196 }
10197
10198 // FIXME: Currently, we fall through and treat C++ classes like C
10199 // structures.
10200 // FIXME: We also fall through for atomics; not sure what should
10201 // happen there, though.
10202 } else if (RHS.get()->getType() == Context.OverloadTy) {
10203 // As a set of extensions to C, we support overloading on functions. These
10204 // functions need to be resolved here.
10205 DeclAccessPair DAP;
10207 RHS.get(), LHSType, /*Complain=*/false, DAP))
10208 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10209 else
10211 }
10212
10213 // This check seems unnatural, however it is necessary to ensure the proper
10214 // conversion of functions/arrays. If the conversion were done for all
10215 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10216 // expressions that suppress this implicit conversion (&, sizeof). This needs
10217 // to happen before we check for null pointer conversions because C does not
10218 // undergo the same implicit conversions as C++ does above (by the calls to
10219 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10220 // lvalue to rvalue cast before checking for null pointer constraints. This
10221 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10222 //
10223 // Suppress this for references: C++ 8.5.3p5.
10224 if (!LHSType->isReferenceType()) {
10225 // FIXME: We potentially allocate here even if ConvertRHS is false.
10227 if (RHS.isInvalid())
10229 }
10230
10231 // The constraints are expressed in terms of the atomic, qualified, or
10232 // unqualified type of the LHS.
10233 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10234
10235 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10236 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10237 if ((LHSTypeAfterConversion->isPointerType() ||
10238 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10239 LHSTypeAfterConversion->isBlockPointerType()) &&
10240 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10244 if (Diagnose || ConvertRHS) {
10245 CastKind Kind;
10246 CXXCastPath Path;
10247 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10248 /*IgnoreBaseAccess=*/false, Diagnose);
10249
10250 // If there is a conversion of some kind, check to see what kind of
10251 // pointer conversion happened so we can diagnose a C++ compatibility
10252 // diagnostic if the conversion is invalid. This only matters if the RHS
10253 // is some kind of void pointer. We have a carve-out when the RHS is from
10254 // a macro expansion because the use of a macro may indicate different
10255 // code between C and C++. Consider: char *s = NULL; where NULL is
10256 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10257 // C++, which is valid in C++.
10258 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10259 !RHS.get()->getBeginLoc().isMacroID()) {
10260 QualType CanRHS =
10262 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10263 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10264 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
10265 RHS.get()->getExprLoc());
10266 // Anything that's not considered perfectly compatible would be
10267 // incompatible in C++.
10270 }
10271 }
10272
10273 if (ConvertRHS)
10274 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10275 }
10276 return Ret;
10277 }
10278 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10279 // unqualified bool, and the right operand is a pointer or its type is
10280 // nullptr_t.
10281 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10282 RHS.get()->getType()->isNullPtrType()) {
10283 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10284 // only handles nullptr -> _Bool due to needing an extra conversion
10285 // step.
10286 // We model this by converting from nullptr -> void * and then let the
10287 // conversion from void * -> _Bool happen naturally.
10288 if (Diagnose || ConvertRHS) {
10289 CastKind Kind;
10290 CXXCastPath Path;
10291 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10292 /*IgnoreBaseAccess=*/false, Diagnose);
10293 if (ConvertRHS)
10294 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10295 &Path);
10296 }
10297 }
10298
10299 // OpenCL queue_t type assignment.
10300 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10302 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10304 }
10305
10306 CastKind Kind;
10307 AssignConvertType result =
10308 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10309
10310 // If assigning a void * created by an allocation function call to some other
10311 // type, check that the allocated size is sufficient for that type.
10312 if (result != AssignConvertType::Incompatible &&
10313 RHS.get()->getType()->isVoidPointerType())
10314 CheckSufficientAllocSize(*this, LHSType, RHS.get());
10315
10316 // C99 6.5.16.1p2: The value of the right operand is converted to the
10317 // type of the assignment expression.
10318 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10319 // so that we can use references in built-in functions even in C.
10320 // The getNonReferenceType() call makes sure that the resulting expression
10321 // does not have reference type.
10322 if (result != AssignConvertType::Incompatible &&
10323 RHS.get()->getType() != LHSType) {
10325 Expr *E = RHS.get();
10326
10327 // Check for various Objective-C errors. If we are not reporting
10328 // diagnostics and just checking for errors, e.g., during overload
10329 // resolution, return Incompatible to indicate the failure.
10330 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10331 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
10333 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10334 if (!Diagnose)
10336 }
10337 if (getLangOpts().ObjC &&
10338 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10339 E->getType(), E, Diagnose) ||
10340 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10341 if (!Diagnose)
10343 // Replace the expression with a corrected version and continue so we
10344 // can find further errors.
10345 RHS = E;
10347 }
10348
10349 if (ConvertRHS)
10350 RHS = ImpCastExprToType(E, Ty, Kind);
10351 }
10352
10353 return result;
10354}
10355
10356namespace {
10357/// The original operand to an operator, prior to the application of the usual
10358/// arithmetic conversions and converting the arguments of a builtin operator
10359/// candidate.
10360struct OriginalOperand {
10361 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10362 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10363 Op = MTE->getSubExpr();
10364 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10365 Op = BTE->getSubExpr();
10366 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10367 Orig = ICE->getSubExprAsWritten();
10368 Conversion = ICE->getConversionFunction();
10369 }
10370 }
10371
10372 QualType getType() const { return Orig->getType(); }
10373
10374 Expr *Orig;
10375 NamedDecl *Conversion;
10376};
10377}
10378
10380 ExprResult &RHS) {
10381 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10382
10383 Diag(Loc, diag::err_typecheck_invalid_operands)
10384 << OrigLHS.getType() << OrigRHS.getType()
10385 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10386
10387 // If a user-defined conversion was applied to either of the operands prior
10388 // to applying the built-in operator rules, tell the user about it.
10389 if (OrigLHS.Conversion) {
10390 Diag(OrigLHS.Conversion->getLocation(),
10391 diag::note_typecheck_invalid_operands_converted)
10392 << 0 << LHS.get()->getType();
10393 }
10394 if (OrigRHS.Conversion) {
10395 Diag(OrigRHS.Conversion->getLocation(),
10396 diag::note_typecheck_invalid_operands_converted)
10397 << 1 << RHS.get()->getType();
10398 }
10399
10400 return QualType();
10401}
10402
10404 ExprResult &RHS) {
10405 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10406 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10407
10408 bool LHSNatVec = LHSType->isVectorType();
10409 bool RHSNatVec = RHSType->isVectorType();
10410
10411 if (!(LHSNatVec && RHSNatVec)) {
10412 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10413 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10414 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10415 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10416 << Vector->getSourceRange();
10417 return QualType();
10418 }
10419
10420 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10421 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10422 << RHS.get()->getSourceRange();
10423
10424 return QualType();
10425}
10426
10427/// Try to convert a value of non-vector type to a vector type by converting
10428/// the type to the element type of the vector and then performing a splat.
10429/// If the language is OpenCL, we only use conversions that promote scalar
10430/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10431/// for float->int.
10432///
10433/// OpenCL V2.0 6.2.6.p2:
10434/// An error shall occur if any scalar operand type has greater rank
10435/// than the type of the vector element.
10436///
10437/// \param scalar - if non-null, actually perform the conversions
10438/// \return true if the operation fails (but without diagnosing the failure)
10440 QualType scalarTy,
10441 QualType vectorEltTy,
10442 QualType vectorTy,
10443 unsigned &DiagID) {
10444 // The conversion to apply to the scalar before splatting it,
10445 // if necessary.
10446 CastKind scalarCast = CK_NoOp;
10447
10448 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10449 scalarCast = CK_IntegralToBoolean;
10450 } else if (vectorEltTy->isIntegralType(S.Context)) {
10451 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10452 (scalarTy->isIntegerType() &&
10453 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10454 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10455 return true;
10456 }
10457 if (!scalarTy->isIntegralType(S.Context))
10458 return true;
10459 scalarCast = CK_IntegralCast;
10460 } else if (vectorEltTy->isRealFloatingType()) {
10461 if (scalarTy->isRealFloatingType()) {
10462 if (S.getLangOpts().OpenCL &&
10463 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10464 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10465 return true;
10466 }
10467 scalarCast = CK_FloatingCast;
10468 }
10469 else if (scalarTy->isIntegralType(S.Context))
10470 scalarCast = CK_IntegralToFloating;
10471 else
10472 return true;
10473 } else {
10474 return true;
10475 }
10476
10477 // Adjust scalar if desired.
10478 if (scalar) {
10479 if (scalarCast != CK_NoOp)
10480 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10481 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10482 }
10483 return false;
10484}
10485
10486/// Convert vector E to a vector with the same number of elements but different
10487/// element type.
10488static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10489 const auto *VecTy = E->getType()->getAs<VectorType>();
10490 assert(VecTy && "Expression E must be a vector");
10491 QualType NewVecTy =
10492 VecTy->isExtVectorType()
10493 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10494 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10495 VecTy->getVectorKind());
10496
10497 // Look through the implicit cast. Return the subexpression if its type is
10498 // NewVecTy.
10499 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10500 if (ICE->getSubExpr()->getType() == NewVecTy)
10501 return ICE->getSubExpr();
10502
10503 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10504 return S.ImpCastExprToType(E, NewVecTy, Cast);
10505}
10506
10507/// Test if a (constant) integer Int can be casted to another integer type
10508/// IntTy without losing precision.
10510 QualType OtherIntTy) {
10511 Expr *E = Int->get();
10513 return false;
10514
10515 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10516
10517 // Reject cases where the value of the Int is unknown as that would
10518 // possibly cause truncation, but accept cases where the scalar can be
10519 // demoted without loss of precision.
10520 Expr::EvalResult EVResult;
10521 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10522 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10523 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10524 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10525
10526 if (CstInt) {
10527 // If the scalar is constant and is of a higher order and has more active
10528 // bits that the vector element type, reject it.
10529 llvm::APSInt Result = EVResult.Val.getInt();
10530 unsigned NumBits = IntSigned
10531 ? (Result.isNegative() ? Result.getSignificantBits()
10532 : Result.getActiveBits())
10533 : Result.getActiveBits();
10534 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10535 return true;
10536
10537 // If the signedness of the scalar type and the vector element type
10538 // differs and the number of bits is greater than that of the vector
10539 // element reject it.
10540 return (IntSigned != OtherIntSigned &&
10541 NumBits > S.Context.getIntWidth(OtherIntTy));
10542 }
10543
10544 // Reject cases where the value of the scalar is not constant and it's
10545 // order is greater than that of the vector element type.
10546 return (Order < 0);
10547}
10548
10549/// Test if a (constant) integer Int can be casted to floating point type
10550/// FloatTy without losing precision.
10552 QualType FloatTy) {
10553 if (Int->get()->containsErrors())
10554 return false;
10555
10556 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10557
10558 // Determine if the integer constant can be expressed as a floating point
10559 // number of the appropriate type.
10560 Expr::EvalResult EVResult;
10561 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10562
10563 uint64_t Bits = 0;
10564 if (CstInt) {
10565 // Reject constants that would be truncated if they were converted to
10566 // the floating point type. Test by simple to/from conversion.
10567 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10568 // could be avoided if there was a convertFromAPInt method
10569 // which could signal back if implicit truncation occurred.
10570 llvm::APSInt Result = EVResult.Val.getInt();
10571 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10572 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10573 llvm::APFloat::rmTowardZero);
10574 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10576 bool Ignored = false;
10577 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10578 &Ignored);
10579 if (Result != ConvertBack)
10580 return true;
10581 } else {
10582 // Reject types that cannot be fully encoded into the mantissa of
10583 // the float.
10584 Bits = S.Context.getTypeSize(IntTy);
10585 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10586 S.Context.getFloatTypeSemantics(FloatTy));
10587 if (Bits > FloatPrec)
10588 return true;
10589 }
10590
10591 return false;
10592}
10593
10594/// Attempt to convert and splat Scalar into a vector whose types matches
10595/// Vector following GCC conversion rules. The rule is that implicit
10596/// conversion can occur when Scalar can be casted to match Vector's element
10597/// type without causing truncation of Scalar.
10599 ExprResult *Vector) {
10600 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10601 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10602 QualType VectorEltTy;
10603
10604 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10605 assert(!isa<ExtVectorType>(VT) &&
10606 "ExtVectorTypes should not be handled here!");
10607 VectorEltTy = VT->getElementType();
10608 } else if (VectorTy->isSveVLSBuiltinType()) {
10609 VectorEltTy =
10610 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10611 } else {
10612 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10613 }
10614
10615 // Reject cases where the vector element type or the scalar element type are
10616 // not integral or floating point types.
10617 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10618 return true;
10619
10620 // The conversion to apply to the scalar before splatting it,
10621 // if necessary.
10622 CastKind ScalarCast = CK_NoOp;
10623
10624 // Accept cases where the vector elements are integers and the scalar is
10625 // an integer.
10626 // FIXME: Notionally if the scalar was a floating point value with a precise
10627 // integral representation, we could cast it to an appropriate integer
10628 // type and then perform the rest of the checks here. GCC will perform
10629 // this conversion in some cases as determined by the input language.
10630 // We should accept it on a language independent basis.
10631 if (VectorEltTy->isIntegralType(S.Context) &&
10632 ScalarTy->isIntegralType(S.Context) &&
10633 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10634
10635 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10636 return true;
10637
10638 ScalarCast = CK_IntegralCast;
10639 } else if (VectorEltTy->isIntegralType(S.Context) &&
10640 ScalarTy->isRealFloatingType()) {
10641 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10642 ScalarCast = CK_FloatingToIntegral;
10643 else
10644 return true;
10645 } else if (VectorEltTy->isRealFloatingType()) {
10646 if (ScalarTy->isRealFloatingType()) {
10647
10648 // Reject cases where the scalar type is not a constant and has a higher
10649 // Order than the vector element type.
10650 llvm::APFloat Result(0.0);
10651
10652 // Determine whether this is a constant scalar. In the event that the
10653 // value is dependent (and thus cannot be evaluated by the constant
10654 // evaluator), skip the evaluation. This will then diagnose once the
10655 // expression is instantiated.
10656 bool CstScalar = Scalar->get()->isValueDependent() ||
10657 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10658 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10659 if (!CstScalar && Order < 0)
10660 return true;
10661
10662 // If the scalar cannot be safely casted to the vector element type,
10663 // reject it.
10664 if (CstScalar) {
10665 bool Truncated = false;
10666 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10667 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10668 if (Truncated)
10669 return true;
10670 }
10671
10672 ScalarCast = CK_FloatingCast;
10673 } else if (ScalarTy->isIntegralType(S.Context)) {
10674 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10675 return true;
10676
10677 ScalarCast = CK_IntegralToFloating;
10678 } else
10679 return true;
10680 } else if (ScalarTy->isEnumeralType())
10681 return true;
10682
10683 // Adjust scalar if desired.
10684 if (ScalarCast != CK_NoOp)
10685 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10686 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10687 return false;
10688}
10689
10691 SourceLocation Loc, bool IsCompAssign,
10692 bool AllowBothBool,
10693 bool AllowBoolConversions,
10694 bool AllowBoolOperation,
10695 bool ReportInvalid) {
10696 if (!IsCompAssign) {
10698 if (LHS.isInvalid())
10699 return QualType();
10700 }
10702 if (RHS.isInvalid())
10703 return QualType();
10704
10705 // For conversion purposes, we ignore any qualifiers.
10706 // For example, "const float" and "float" are equivalent.
10707 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10708 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10709
10710 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10711 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10712 assert(LHSVecType || RHSVecType);
10713
10714 if (getLangOpts().HLSL)
10715 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10716 IsCompAssign);
10717
10718 // Any operation with MFloat8 type is only possible with C intrinsics
10719 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10720 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10721 return InvalidOperands(Loc, LHS, RHS);
10722
10723 // AltiVec-style "vector bool op vector bool" combinations are allowed
10724 // for some operators but not others.
10725 if (!AllowBothBool && LHSVecType &&
10726 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10727 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10728 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10729
10730 // This operation may not be performed on boolean vectors.
10731 if (!AllowBoolOperation &&
10732 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10733 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10734
10735 // If the vector types are identical, return.
10736 if (Context.hasSameType(LHSType, RHSType))
10737 return Context.getCommonSugaredType(LHSType, RHSType);
10738
10739 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10740 if (LHSVecType && RHSVecType &&
10741 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10742 if (isa<ExtVectorType>(LHSVecType)) {
10743 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10744 return LHSType;
10745 }
10746
10747 if (!IsCompAssign)
10748 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10749 return RHSType;
10750 }
10751
10752 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10753 // can be mixed, with the result being the non-bool type. The non-bool
10754 // operand must have integer element type.
10755 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10756 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10757 (Context.getTypeSize(LHSVecType->getElementType()) ==
10758 Context.getTypeSize(RHSVecType->getElementType()))) {
10759 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10760 LHSVecType->getElementType()->isIntegerType() &&
10761 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10762 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10763 return LHSType;
10764 }
10765 if (!IsCompAssign &&
10766 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10767 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10768 RHSVecType->getElementType()->isIntegerType()) {
10769 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10770 return RHSType;
10771 }
10772 }
10773
10774 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10775 // invalid since the ambiguity can affect the ABI.
10776 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10777 unsigned &SVEorRVV) {
10778 const VectorType *VecType = SecondType->getAs<VectorType>();
10779 SVEorRVV = 0;
10780 if (FirstType->isSizelessBuiltinType() && VecType) {
10783 return true;
10789 SVEorRVV = 1;
10790 return true;
10791 }
10792 }
10793
10794 return false;
10795 };
10796
10797 unsigned SVEorRVV;
10798 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10799 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10800 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10801 << SVEorRVV << LHSType << RHSType;
10802 return QualType();
10803 }
10804
10805 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10806 // invalid since the ambiguity can affect the ABI.
10807 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10808 unsigned &SVEorRVV) {
10809 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10810 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10811
10812 SVEorRVV = 0;
10813 if (FirstVecType && SecondVecType) {
10814 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10815 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10816 SecondVecType->getVectorKind() ==
10818 return true;
10819 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10820 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10821 SecondVecType->getVectorKind() ==
10823 SecondVecType->getVectorKind() ==
10825 SecondVecType->getVectorKind() ==
10827 SVEorRVV = 1;
10828 return true;
10829 }
10830 }
10831 return false;
10832 }
10833
10834 if (SecondVecType &&
10835 SecondVecType->getVectorKind() == VectorKind::Generic) {
10836 if (FirstType->isSVESizelessBuiltinType())
10837 return true;
10838 if (FirstType->isRVVSizelessBuiltinType()) {
10839 SVEorRVV = 1;
10840 return true;
10841 }
10842 }
10843
10844 return false;
10845 };
10846
10847 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10848 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10849 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10850 << SVEorRVV << LHSType << RHSType;
10851 return QualType();
10852 }
10853
10854 // If there's a vector type and a scalar, try to convert the scalar to
10855 // the vector element type and splat.
10856 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10857 if (!RHSVecType) {
10858 if (isa<ExtVectorType>(LHSVecType)) {
10859 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10860 LHSVecType->getElementType(), LHSType,
10861 DiagID))
10862 return LHSType;
10863 } else {
10864 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10865 return LHSType;
10866 }
10867 }
10868 if (!LHSVecType) {
10869 if (isa<ExtVectorType>(RHSVecType)) {
10870 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10871 LHSType, RHSVecType->getElementType(),
10872 RHSType, DiagID))
10873 return RHSType;
10874 } else {
10875 if (LHS.get()->isLValue() ||
10876 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10877 return RHSType;
10878 }
10879 }
10880
10881 // FIXME: The code below also handles conversion between vectors and
10882 // non-scalars, we should break this down into fine grained specific checks
10883 // and emit proper diagnostics.
10884 QualType VecType = LHSVecType ? LHSType : RHSType;
10885 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10886 QualType OtherType = LHSVecType ? RHSType : LHSType;
10887 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10888 if (isLaxVectorConversion(OtherType, VecType)) {
10889 if (Context.getTargetInfo().getTriple().isPPC() &&
10890 anyAltivecTypes(RHSType, LHSType) &&
10891 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10892 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10893 // If we're allowing lax vector conversions, only the total (data) size
10894 // needs to be the same. For non compound assignment, if one of the types is
10895 // scalar, the result is always the vector type.
10896 if (!IsCompAssign) {
10897 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10898 return VecType;
10899 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10900 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10901 // type. Note that this is already done by non-compound assignments in
10902 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10903 // <1 x T> -> T. The result is also a vector type.
10904 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10905 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10906 ExprResult *RHSExpr = &RHS;
10907 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10908 return VecType;
10909 }
10910 }
10911
10912 // Okay, the expression is invalid.
10913
10914 // If there's a non-vector, non-real operand, diagnose that.
10915 if ((!RHSVecType && !RHSType->isRealType()) ||
10916 (!LHSVecType && !LHSType->isRealType())) {
10917 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10918 << LHSType << RHSType
10919 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10920 return QualType();
10921 }
10922
10923 // OpenCL V1.1 6.2.6.p1:
10924 // If the operands are of more than one vector type, then an error shall
10925 // occur. Implicit conversions between vector types are not permitted, per
10926 // section 6.2.1.
10927 if (getLangOpts().OpenCL &&
10928 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10929 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10930 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10931 << RHSType;
10932 return QualType();
10933 }
10934
10935
10936 // If there is a vector type that is not a ExtVector and a scalar, we reach
10937 // this point if scalar could not be converted to the vector's element type
10938 // without truncation.
10939 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10940 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10941 QualType Scalar = LHSVecType ? RHSType : LHSType;
10942 QualType Vector = LHSVecType ? LHSType : RHSType;
10943 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10944 Diag(Loc,
10945 diag::err_typecheck_vector_not_convertable_implict_truncation)
10946 << ScalarOrVector << Scalar << Vector;
10947
10948 return QualType();
10949 }
10950
10951 // Otherwise, use the generic diagnostic.
10952 Diag(Loc, DiagID)
10953 << LHSType << RHSType
10954 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10955 return QualType();
10956}
10957
10959 SourceLocation Loc,
10960 bool IsCompAssign,
10961 ArithConvKind OperationKind) {
10962 if (!IsCompAssign) {
10964 if (LHS.isInvalid())
10965 return QualType();
10966 }
10968 if (RHS.isInvalid())
10969 return QualType();
10970
10971 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10972 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10973
10974 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10975 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10976
10977 unsigned DiagID = diag::err_typecheck_invalid_operands;
10978 if ((OperationKind == ArithConvKind::Arithmetic) &&
10979 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10980 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10981 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10982 << RHS.get()->getSourceRange();
10983 return QualType();
10984 }
10985
10986 if (Context.hasSameType(LHSType, RHSType))
10987 return LHSType;
10988
10989 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10990 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10991 return LHSType;
10992 }
10993 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10994 if (LHS.get()->isLValue() ||
10995 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10996 return RHSType;
10997 }
10998
10999 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11000 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11001 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11002 << LHSType << RHSType << LHS.get()->getSourceRange()
11003 << RHS.get()->getSourceRange();
11004 return QualType();
11005 }
11006
11007 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11008 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11009 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11010 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11011 << LHSType << RHSType << LHS.get()->getSourceRange()
11012 << RHS.get()->getSourceRange();
11013 return QualType();
11014 }
11015
11016 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11017 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11018 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11019 bool ScalarOrVector =
11020 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11021
11022 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11023 << ScalarOrVector << Scalar << Vector;
11024
11025 return QualType();
11026 }
11027
11028 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11029 << RHS.get()->getSourceRange();
11030 return QualType();
11031}
11032
11033// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11034// expression. These are mainly cases where the null pointer is used as an
11035// integer instead of a pointer.
11037 SourceLocation Loc, bool IsCompare) {
11038 // The canonical way to check for a GNU null is with isNullPointerConstant,
11039 // but we use a bit of a hack here for speed; this is a relatively
11040 // hot path, and isNullPointerConstant is slow.
11041 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11042 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11043
11044 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11045
11046 // Avoid analyzing cases where the result will either be invalid (and
11047 // diagnosed as such) or entirely valid and not something to warn about.
11048 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11049 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11050 return;
11051
11052 // Comparison operations would not make sense with a null pointer no matter
11053 // what the other expression is.
11054 if (!IsCompare) {
11055 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11056 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11057 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11058 return;
11059 }
11060
11061 // The rest of the operations only make sense with a null pointer
11062 // if the other expression is a pointer.
11063 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11064 NonNullType->canDecayToPointerType())
11065 return;
11066
11067 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11068 << LHSNull /* LHS is NULL */ << NonNullType
11069 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11070}
11071
11073 SourceLocation OpLoc) {
11074 // If the divisor is real, then this is real/real or complex/real division.
11075 // Either way there can be no precision loss.
11076 auto *CT = DivisorTy->getAs<ComplexType>();
11077 if (!CT)
11078 return;
11079
11080 QualType ElementType = CT->getElementType().getCanonicalType();
11081 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11083 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11084 return;
11085
11086 ASTContext &Ctx = S.getASTContext();
11087 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11088 const llvm::fltSemantics &ElementTypeSemantics =
11089 Ctx.getFloatTypeSemantics(ElementType);
11090 const llvm::fltSemantics &HigherElementTypeSemantics =
11091 Ctx.getFloatTypeSemantics(HigherElementType);
11092
11093 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11094 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11095 (HigherElementType == Ctx.LongDoubleTy &&
11096 !Ctx.getTargetInfo().hasLongDoubleType())) {
11097 // Retain the location of the first use of higher precision type.
11100 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11101 if (Type == HigherElementType) {
11102 Num++;
11103 return;
11104 }
11105 }
11106 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
11107 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
11108 }
11109}
11110
11112 SourceLocation Loc) {
11113 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11114 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11115 if (!LUE || !RUE)
11116 return;
11117 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11118 RUE->getKind() != UETT_SizeOf)
11119 return;
11120
11121 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11122 QualType LHSTy = LHSArg->getType();
11123 QualType RHSTy;
11124
11125 if (RUE->isArgumentType())
11126 RHSTy = RUE->getArgumentType().getNonReferenceType();
11127 else
11128 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11129
11130 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11131 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11132 return;
11133
11134 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11135 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11136 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11137 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11138 << LHSArgDecl;
11139 }
11140 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11141 QualType ArrayElemTy = ArrayTy->getElementType();
11142 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11143 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11144 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11145 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11146 return;
11147 S.Diag(Loc, diag::warn_division_sizeof_array)
11148 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11149 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11150 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11151 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11152 << LHSArgDecl;
11153 }
11154
11155 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11156 }
11157}
11158
11160 ExprResult &RHS,
11161 SourceLocation Loc, bool IsDiv) {
11162 // Check for division/remainder by zero.
11163 Expr::EvalResult RHSValue;
11164 if (!RHS.get()->isValueDependent() &&
11165 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11166 RHSValue.Val.getInt() == 0)
11167 S.DiagRuntimeBehavior(Loc, RHS.get(),
11168 S.PDiag(diag::warn_remainder_division_by_zero)
11169 << IsDiv << RHS.get()->getSourceRange());
11170}
11171
11172static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11173 const ExprResult &LHS, const ExprResult &RHS,
11174 BinaryOperatorKind Opc) {
11175 if (!LHS.isUsable() || !RHS.isUsable())
11176 return;
11177 const Expr *LHSExpr = LHS.get();
11178 const Expr *RHSExpr = RHS.get();
11179 const QualType LHSType = LHSExpr->getType();
11180 const QualType RHSType = RHSExpr->getType();
11181 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11182 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11183 if (!LHSIsScoped && !RHSIsScoped)
11184 return;
11185 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11186 return;
11187 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11188 return;
11189 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11190 return;
11191 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11192 SourceLocation BeginLoc = expr->getBeginLoc();
11193 QualType IntType = type->castAs<EnumType>()
11194 ->getDecl()
11195 ->getDefinitionOrSelf()
11196 ->getIntegerType();
11197 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11198 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
11199 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
11200 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
11201 };
11202 if (LHSIsScoped) {
11203 DiagnosticHelper(LHSExpr, LHSType);
11204 }
11205 if (RHSIsScoped) {
11206 DiagnosticHelper(RHSExpr, RHSType);
11207 }
11208}
11209
11211 SourceLocation Loc,
11212 BinaryOperatorKind Opc) {
11213 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11214 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11215
11216 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11217
11218 QualType LHSTy = LHS.get()->getType();
11219 QualType RHSTy = RHS.get()->getType();
11220 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11221 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11222 /*AllowBothBool*/ getLangOpts().AltiVec,
11223 /*AllowBoolConversions*/ false,
11224 /*AllowBooleanOperation*/ false,
11225 /*ReportInvalid*/ true);
11226 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11227 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11229 if (!IsDiv &&
11230 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11231 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11232 // For division, only matrix-by-scalar is supported. Other combinations with
11233 // matrix types are invalid.
11234 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11235 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11236
11238 LHS, RHS, Loc,
11240 if (LHS.isInvalid() || RHS.isInvalid())
11241 return QualType();
11242
11243 if (compType.isNull() || !compType->isArithmeticType()) {
11244 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11245 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11246 return ResultTy;
11247 }
11248 if (IsDiv) {
11249 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
11250 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11251 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11252 }
11253 return compType;
11254}
11255
11257 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11258 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11259
11260 // Note: This check is here to simplify the double exclusions of
11261 // scalar and vector HLSL checks. No getLangOpts().HLSL
11262 // is needed since all languages exlcude doubles.
11263 if (LHS.get()->getType()->isDoubleType() ||
11264 RHS.get()->getType()->isDoubleType() ||
11265 (LHS.get()->getType()->isVectorType() && LHS.get()
11266 ->getType()
11267 ->getAs<VectorType>()
11268 ->getElementType()
11269 ->isDoubleType()) ||
11270 (RHS.get()->getType()->isVectorType() && RHS.get()
11271 ->getType()
11272 ->getAs<VectorType>()
11273 ->getElementType()
11274 ->isDoubleType()))
11275 return InvalidOperands(Loc, LHS, RHS);
11276
11277 if (LHS.get()->getType()->isVectorType() ||
11278 RHS.get()->getType()->isVectorType()) {
11279 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11280 RHS.get()->getType()->hasIntegerRepresentation()) ||
11281 (getLangOpts().HLSL &&
11282 (LHS.get()->getType()->hasFloatingRepresentation() ||
11284 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11285 /*AllowBothBool*/ getLangOpts().AltiVec,
11286 /*AllowBoolConversions*/ false,
11287 /*AllowBooleanOperation*/ false,
11288 /*ReportInvalid*/ true);
11289 return InvalidOperands(Loc, LHS, RHS);
11290 }
11291
11292 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11293 RHS.get()->getType()->isSveVLSBuiltinType()) {
11294 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11296 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11298
11299 return InvalidOperands(Loc, LHS, RHS);
11300 }
11301
11303 LHS, RHS, Loc,
11305 if (LHS.isInvalid() || RHS.isInvalid())
11306 return QualType();
11307
11308 if (compType.isNull() ||
11309 (!compType->isIntegerType() &&
11310 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11311 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11312 diagnoseScopedEnums(*this, Loc, LHS, RHS,
11313 IsCompAssign ? BO_RemAssign : BO_Rem);
11314 return ResultTy;
11315 }
11316 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11317 return compType;
11318}
11319
11320/// Diagnose invalid arithmetic on two void pointers.
11322 Expr *LHSExpr, Expr *RHSExpr) {
11323 S.Diag(Loc, S.getLangOpts().CPlusPlus
11324 ? diag::err_typecheck_pointer_arith_void_type
11325 : diag::ext_gnu_void_ptr)
11326 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11327 << RHSExpr->getSourceRange();
11328}
11329
11330/// Diagnose invalid arithmetic on a void pointer.
11332 Expr *Pointer) {
11333 S.Diag(Loc, S.getLangOpts().CPlusPlus
11334 ? diag::err_typecheck_pointer_arith_void_type
11335 : diag::ext_gnu_void_ptr)
11336 << 0 /* one pointer */ << Pointer->getSourceRange();
11337}
11338
11339/// Diagnose invalid arithmetic on a null pointer.
11340///
11341/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11342/// idiom, which we recognize as a GNU extension.
11343///
11345 Expr *Pointer, bool IsGNUIdiom) {
11346 if (IsGNUIdiom)
11347 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11348 << Pointer->getSourceRange();
11349 else
11350 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11351 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11352}
11353
11354/// Diagnose invalid subraction on a null pointer.
11355///
11357 Expr *Pointer, bool BothNull) {
11358 // Null - null is valid in C++ [expr.add]p7
11359 if (BothNull && S.getLangOpts().CPlusPlus)
11360 return;
11361
11362 // Is this s a macro from a system header?
11364 return;
11365
11367 S.PDiag(diag::warn_pointer_sub_null_ptr)
11368 << S.getLangOpts().CPlusPlus
11369 << Pointer->getSourceRange());
11370}
11371
11372/// Diagnose invalid arithmetic on two function pointers.
11374 Expr *LHS, Expr *RHS) {
11375 assert(LHS->getType()->isAnyPointerType());
11376 assert(RHS->getType()->isAnyPointerType());
11377 S.Diag(Loc, S.getLangOpts().CPlusPlus
11378 ? diag::err_typecheck_pointer_arith_function_type
11379 : diag::ext_gnu_ptr_func_arith)
11380 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11381 // We only show the second type if it differs from the first.
11383 RHS->getType())
11384 << RHS->getType()->getPointeeType()
11385 << LHS->getSourceRange() << RHS->getSourceRange();
11386}
11387
11388/// Diagnose invalid arithmetic on a function pointer.
11390 Expr *Pointer) {
11391 assert(Pointer->getType()->isAnyPointerType());
11392 S.Diag(Loc, S.getLangOpts().CPlusPlus
11393 ? diag::err_typecheck_pointer_arith_function_type
11394 : diag::ext_gnu_ptr_func_arith)
11395 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11396 << 0 /* one pointer, so only one type */
11397 << Pointer->getSourceRange();
11398}
11399
11400/// Emit error if Operand is incomplete pointer type
11401///
11402/// \returns True if pointer has incomplete type
11404 Expr *Operand) {
11405 QualType ResType = Operand->getType();
11406 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11407 ResType = ResAtomicType->getValueType();
11408
11409 assert(ResType->isAnyPointerType());
11410 QualType PointeeTy = ResType->getPointeeType();
11411 return S.RequireCompleteSizedType(
11412 Loc, PointeeTy,
11413 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11414 Operand->getSourceRange());
11415}
11416
11417/// Check the validity of an arithmetic pointer operand.
11418///
11419/// If the operand has pointer type, this code will check for pointer types
11420/// which are invalid in arithmetic operations. These will be diagnosed
11421/// appropriately, including whether or not the use is supported as an
11422/// extension.
11423///
11424/// \returns True when the operand is valid to use (even if as an extension).
11426 Expr *Operand) {
11427 QualType ResType = Operand->getType();
11428 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11429 ResType = ResAtomicType->getValueType();
11430
11431 if (!ResType->isAnyPointerType()) return true;
11432
11433 QualType PointeeTy = ResType->getPointeeType();
11434 if (PointeeTy->isVoidType()) {
11435 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11436 return !S.getLangOpts().CPlusPlus;
11437 }
11438 if (PointeeTy->isFunctionType()) {
11439 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11440 return !S.getLangOpts().CPlusPlus;
11441 }
11442
11443 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11444
11445 return true;
11446}
11447
11448/// Check the validity of a binary arithmetic operation w.r.t. pointer
11449/// operands.
11450///
11451/// This routine will diagnose any invalid arithmetic on pointer operands much
11452/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11453/// for emitting a single diagnostic even for operations where both LHS and RHS
11454/// are (potentially problematic) pointers.
11455///
11456/// \returns True when the operand is valid to use (even if as an extension).
11458 Expr *LHSExpr, Expr *RHSExpr) {
11459 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11460 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11461 if (!isLHSPointer && !isRHSPointer) return true;
11462
11463 QualType LHSPointeeTy, RHSPointeeTy;
11464 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11465 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11466
11467 // if both are pointers check if operation is valid wrt address spaces
11468 if (isLHSPointer && isRHSPointer) {
11469 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11470 S.getASTContext())) {
11471 S.Diag(Loc,
11472 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11473 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11474 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11475 return false;
11476 }
11477 }
11478
11479 // Check for arithmetic on pointers to incomplete types.
11480 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11481 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11482 if (isLHSVoidPtr || isRHSVoidPtr) {
11483 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11484 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11485 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11486
11487 return !S.getLangOpts().CPlusPlus;
11488 }
11489
11490 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11491 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11492 if (isLHSFuncPtr || isRHSFuncPtr) {
11493 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11494 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11495 RHSExpr);
11496 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11497
11498 return !S.getLangOpts().CPlusPlus;
11499 }
11500
11501 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11502 return false;
11503 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11504 return false;
11505
11506 return true;
11507}
11508
11509/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11510/// literal.
11512 Expr *LHSExpr, Expr *RHSExpr) {
11513 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11514 Expr* IndexExpr = RHSExpr;
11515 if (!StrExpr) {
11516 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11517 IndexExpr = LHSExpr;
11518 }
11519
11520 bool IsStringPlusInt = StrExpr &&
11522 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11523 return;
11524
11525 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11526 Self.Diag(OpLoc, diag::warn_string_plus_int)
11527 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11528
11529 // Only print a fixit for "str" + int, not for int + "str".
11530 if (IndexExpr == RHSExpr) {
11531 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11532 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11533 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11535 << FixItHint::CreateInsertion(EndLoc, "]");
11536 } else
11537 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11538}
11539
11540/// Emit a warning when adding a char literal to a string.
11542 Expr *LHSExpr, Expr *RHSExpr) {
11543 const Expr *StringRefExpr = LHSExpr;
11544 const CharacterLiteral *CharExpr =
11545 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11546
11547 if (!CharExpr) {
11548 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11549 StringRefExpr = RHSExpr;
11550 }
11551
11552 if (!CharExpr || !StringRefExpr)
11553 return;
11554
11555 const QualType StringType = StringRefExpr->getType();
11556
11557 // Return if not a PointerType.
11558 if (!StringType->isAnyPointerType())
11559 return;
11560
11561 // Return if not a CharacterType.
11562 if (!StringType->getPointeeType()->isAnyCharacterType())
11563 return;
11564
11565 ASTContext &Ctx = Self.getASTContext();
11566 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11567
11568 const QualType CharType = CharExpr->getType();
11569 if (!CharType->isAnyCharacterType() &&
11570 CharType->isIntegerType() &&
11571 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11572 Self.Diag(OpLoc, diag::warn_string_plus_char)
11573 << DiagRange << Ctx.CharTy;
11574 } else {
11575 Self.Diag(OpLoc, diag::warn_string_plus_char)
11576 << DiagRange << CharExpr->getType();
11577 }
11578
11579 // Only print a fixit for str + char, not for char + str.
11580 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11581 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11582 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11583 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11585 << FixItHint::CreateInsertion(EndLoc, "]");
11586 } else {
11587 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11588 }
11589}
11590
11591/// Emit error when two pointers are incompatible.
11593 Expr *LHSExpr, Expr *RHSExpr) {
11594 assert(LHSExpr->getType()->isAnyPointerType());
11595 assert(RHSExpr->getType()->isAnyPointerType());
11596 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11597 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11598 << RHSExpr->getSourceRange();
11599}
11600
11601// C99 6.5.6
11604 QualType* CompLHSTy) {
11605 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11606
11607 if (LHS.get()->getType()->isVectorType() ||
11608 RHS.get()->getType()->isVectorType()) {
11609 QualType compType =
11610 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11611 /*AllowBothBool*/ getLangOpts().AltiVec,
11612 /*AllowBoolConversions*/ getLangOpts().ZVector,
11613 /*AllowBooleanOperation*/ false,
11614 /*ReportInvalid*/ true);
11615 if (CompLHSTy) *CompLHSTy = compType;
11616 return compType;
11617 }
11618
11619 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11620 RHS.get()->getType()->isSveVLSBuiltinType()) {
11621 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11623 if (CompLHSTy)
11624 *CompLHSTy = compType;
11625 return compType;
11626 }
11627
11628 if (LHS.get()->getType()->isConstantMatrixType() ||
11629 RHS.get()->getType()->isConstantMatrixType()) {
11630 QualType compType =
11631 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11632 if (CompLHSTy)
11633 *CompLHSTy = compType;
11634 return compType;
11635 }
11636
11638 LHS, RHS, Loc,
11640 if (LHS.isInvalid() || RHS.isInvalid())
11641 return QualType();
11642
11643 // Diagnose "string literal" '+' int and string '+' "char literal".
11644 if (Opc == BO_Add) {
11645 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11646 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11647 }
11648
11649 // handle the common case first (both operands are arithmetic).
11650 if (!compType.isNull() && compType->isArithmeticType()) {
11651 if (CompLHSTy) *CompLHSTy = compType;
11652 return compType;
11653 }
11654
11655 // Type-checking. Ultimately the pointer's going to be in PExp;
11656 // note that we bias towards the LHS being the pointer.
11657 Expr *PExp = LHS.get(), *IExp = RHS.get();
11658
11659 bool isObjCPointer;
11660 if (PExp->getType()->isPointerType()) {
11661 isObjCPointer = false;
11662 } else if (PExp->getType()->isObjCObjectPointerType()) {
11663 isObjCPointer = true;
11664 } else {
11665 std::swap(PExp, IExp);
11666 if (PExp->getType()->isPointerType()) {
11667 isObjCPointer = false;
11668 } else if (PExp->getType()->isObjCObjectPointerType()) {
11669 isObjCPointer = true;
11670 } else {
11671 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11672 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11673 return ResultTy;
11674 }
11675 }
11676 assert(PExp->getType()->isAnyPointerType());
11677
11678 if (!IExp->getType()->isIntegerType())
11679 return InvalidOperands(Loc, LHS, RHS);
11680
11681 // Adding to a null pointer results in undefined behavior.
11684 // In C++ adding zero to a null pointer is defined.
11685 Expr::EvalResult KnownVal;
11686 if (!getLangOpts().CPlusPlus ||
11687 (!IExp->isValueDependent() &&
11688 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11689 KnownVal.Val.getInt() != 0))) {
11690 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11692 Context, BO_Add, PExp, IExp);
11693 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11694 }
11695 }
11696
11697 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11698 return QualType();
11699
11700 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11701 return QualType();
11702
11703 // Arithmetic on label addresses is normally allowed, except when we add
11704 // a ptrauth signature to the addresses.
11705 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11706 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11707 << /*addition*/ 1;
11708 return QualType();
11709 }
11710
11711 // Check array bounds for pointer arithemtic
11712 CheckArrayAccess(PExp, IExp);
11713
11714 if (CompLHSTy) {
11715 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11716 if (LHSTy.isNull()) {
11717 LHSTy = LHS.get()->getType();
11718 if (Context.isPromotableIntegerType(LHSTy))
11719 LHSTy = Context.getPromotedIntegerType(LHSTy);
11720 }
11721 *CompLHSTy = LHSTy;
11722 }
11723
11724 return PExp->getType();
11725}
11726
11727// C99 6.5.6
11729 SourceLocation Loc,
11731 QualType *CompLHSTy) {
11732 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11733
11734 if (LHS.get()->getType()->isVectorType() ||
11735 RHS.get()->getType()->isVectorType()) {
11736 QualType compType =
11737 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11738 /*AllowBothBool*/ getLangOpts().AltiVec,
11739 /*AllowBoolConversions*/ getLangOpts().ZVector,
11740 /*AllowBooleanOperation*/ false,
11741 /*ReportInvalid*/ true);
11742 if (CompLHSTy) *CompLHSTy = compType;
11743 return compType;
11744 }
11745
11746 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11747 RHS.get()->getType()->isSveVLSBuiltinType()) {
11748 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11750 if (CompLHSTy)
11751 *CompLHSTy = compType;
11752 return compType;
11753 }
11754
11755 if (LHS.get()->getType()->isConstantMatrixType() ||
11756 RHS.get()->getType()->isConstantMatrixType()) {
11757 QualType compType =
11758 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11759 if (CompLHSTy)
11760 *CompLHSTy = compType;
11761 return compType;
11762 }
11763
11765 LHS, RHS, Loc,
11767 if (LHS.isInvalid() || RHS.isInvalid())
11768 return QualType();
11769
11770 // Enforce type constraints: C99 6.5.6p3.
11771
11772 // Handle the common case first (both operands are arithmetic).
11773 if (!compType.isNull() && compType->isArithmeticType()) {
11774 if (CompLHSTy) *CompLHSTy = compType;
11775 return compType;
11776 }
11777
11778 // Either ptr - int or ptr - ptr.
11779 if (LHS.get()->getType()->isAnyPointerType()) {
11780 QualType lpointee = LHS.get()->getType()->getPointeeType();
11781
11782 // Diagnose bad cases where we step over interface counts.
11783 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11784 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11785 return QualType();
11786
11787 // Arithmetic on label addresses is normally allowed, except when we add
11788 // a ptrauth signature to the addresses.
11789 if (isa<AddrLabelExpr>(LHS.get()) &&
11790 getLangOpts().PointerAuthIndirectGotos) {
11791 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11792 << /*subtraction*/ 0;
11793 return QualType();
11794 }
11795
11796 // The result type of a pointer-int computation is the pointer type.
11797 if (RHS.get()->getType()->isIntegerType()) {
11798 // Subtracting from a null pointer should produce a warning.
11799 // The last argument to the diagnose call says this doesn't match the
11800 // GNU int-to-pointer idiom.
11803 // In C++ adding zero to a null pointer is defined.
11804 Expr::EvalResult KnownVal;
11805 if (!getLangOpts().CPlusPlus ||
11806 (!RHS.get()->isValueDependent() &&
11807 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11808 KnownVal.Val.getInt() != 0))) {
11809 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11810 }
11811 }
11812
11813 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11814 return QualType();
11815
11816 // Check array bounds for pointer arithemtic
11817 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11818 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11819
11820 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11821 return LHS.get()->getType();
11822 }
11823
11824 // Handle pointer-pointer subtractions.
11825 if (const PointerType *RHSPTy
11826 = RHS.get()->getType()->getAs<PointerType>()) {
11827 QualType rpointee = RHSPTy->getPointeeType();
11828
11829 if (getLangOpts().CPlusPlus) {
11830 // Pointee types must be the same: C++ [expr.add]
11831 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11832 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11833 }
11834 } else {
11835 // Pointee types must be compatible C99 6.5.6p3
11836 if (!Context.typesAreCompatible(
11837 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11838 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11839 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11840 return QualType();
11841 }
11842 }
11843
11845 LHS.get(), RHS.get()))
11846 return QualType();
11847
11848 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11850 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11852
11853 // Subtracting nullptr or from nullptr is suspect
11854 if (LHSIsNullPtr)
11855 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11856 if (RHSIsNullPtr)
11857 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11858
11859 // The pointee type may have zero size. As an extension, a structure or
11860 // union may have zero size or an array may have zero length. In this
11861 // case subtraction does not make sense.
11862 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11863 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11864 if (ElementSize.isZero()) {
11865 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11866 << rpointee.getUnqualifiedType()
11867 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11868 }
11869 }
11870
11871 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11872 return Context.getPointerDiffType();
11873 }
11874 }
11875
11876 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11877 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11878 return ResultTy;
11879}
11880
11882 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11883 return ET->getDecl()->isScoped();
11884 return false;
11885}
11886
11889 QualType LHSType) {
11890 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11891 // so skip remaining warnings as we don't want to modify values within Sema.
11892 if (S.getLangOpts().OpenCL)
11893 return;
11894
11895 if (Opc == BO_Shr &&
11897 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
11898
11899 // Check right/shifter operand
11900 Expr::EvalResult RHSResult;
11901 if (RHS.get()->isValueDependent() ||
11902 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11903 return;
11904 llvm::APSInt Right = RHSResult.Val.getInt();
11905
11906 if (Right.isNegative()) {
11907 S.DiagRuntimeBehavior(Loc, RHS.get(),
11908 S.PDiag(diag::warn_shift_negative)
11909 << RHS.get()->getSourceRange());
11910 return;
11911 }
11912
11913 QualType LHSExprType = LHS.get()->getType();
11914 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11915 if (LHSExprType->isBitIntType())
11916 LeftSize = S.Context.getIntWidth(LHSExprType);
11917 else if (LHSExprType->isFixedPointType()) {
11918 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11919 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11920 }
11921 if (Right.uge(LeftSize)) {
11922 S.DiagRuntimeBehavior(Loc, RHS.get(),
11923 S.PDiag(diag::warn_shift_gt_typewidth)
11924 << RHS.get()->getSourceRange());
11925 return;
11926 }
11927
11928 // FIXME: We probably need to handle fixed point types specially here.
11929 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11930 return;
11931
11932 // When left shifting an ICE which is signed, we can check for overflow which
11933 // according to C++ standards prior to C++2a has undefined behavior
11934 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11935 // more than the maximum value representable in the result type, so never
11936 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11937 // expression is still probably a bug.)
11938 Expr::EvalResult LHSResult;
11939 if (LHS.get()->isValueDependent() ||
11941 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11942 return;
11943 llvm::APSInt Left = LHSResult.Val.getInt();
11944
11945 // Don't warn if signed overflow is defined, then all the rest of the
11946 // diagnostics will not be triggered because the behavior is defined.
11947 // Also don't warn in C++20 mode (and newer), as signed left shifts
11948 // always wrap and never overflow.
11949 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11950 return;
11951
11952 // If LHS does not have a non-negative value then, the
11953 // behavior is undefined before C++2a. Warn about it.
11954 if (Left.isNegative()) {
11955 S.DiagRuntimeBehavior(Loc, LHS.get(),
11956 S.PDiag(diag::warn_shift_lhs_negative)
11957 << LHS.get()->getSourceRange());
11958 return;
11959 }
11960
11961 llvm::APInt ResultBits =
11962 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11963 if (ResultBits.ule(LeftSize))
11964 return;
11965 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11966 Result = Result.shl(Right);
11967
11968 // Print the bit representation of the signed integer as an unsigned
11969 // hexadecimal number.
11970 SmallString<40> HexResult;
11971 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11972
11973 // If we are only missing a sign bit, this is less likely to result in actual
11974 // bugs -- if the result is cast back to an unsigned type, it will have the
11975 // expected value. Thus we place this behind a different warning that can be
11976 // turned off separately if needed.
11977 if (ResultBits - 1 == LeftSize) {
11978 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11979 << HexResult << LHSType
11980 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11981 return;
11982 }
11983
11984 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11985 << HexResult.str() << Result.getSignificantBits() << LHSType
11986 << Left.getBitWidth() << LHS.get()->getSourceRange()
11987 << RHS.get()->getSourceRange();
11988}
11989
11990/// Return the resulting type when a vector is shifted
11991/// by a scalar or vector shift amount.
11993 SourceLocation Loc, bool IsCompAssign) {
11994 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11995 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11996 !LHS.get()->getType()->isVectorType()) {
11997 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11998 << RHS.get()->getType() << LHS.get()->getType()
11999 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12000 return QualType();
12001 }
12002
12003 if (!IsCompAssign) {
12004 LHS = S.UsualUnaryConversions(LHS.get());
12005 if (LHS.isInvalid()) return QualType();
12006 }
12007
12008 RHS = S.UsualUnaryConversions(RHS.get());
12009 if (RHS.isInvalid()) return QualType();
12010
12011 QualType LHSType = LHS.get()->getType();
12012 // Note that LHS might be a scalar because the routine calls not only in
12013 // OpenCL case.
12014 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12015 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12016
12017 // Note that RHS might not be a vector.
12018 QualType RHSType = RHS.get()->getType();
12019 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12020 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12021
12022 // Do not allow shifts for boolean vectors.
12023 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12024 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12025 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12026 << LHS.get()->getType() << RHS.get()->getType()
12027 << LHS.get()->getSourceRange();
12028 return QualType();
12029 }
12030
12031 // The operands need to be integers.
12032 if (!LHSEleType->isIntegerType()) {
12033 S.Diag(Loc, diag::err_typecheck_expect_int)
12034 << LHS.get()->getType() << LHS.get()->getSourceRange();
12035 return QualType();
12036 }
12037
12038 if (!RHSEleType->isIntegerType()) {
12039 S.Diag(Loc, diag::err_typecheck_expect_int)
12040 << RHS.get()->getType() << RHS.get()->getSourceRange();
12041 return QualType();
12042 }
12043
12044 if (!LHSVecTy) {
12045 assert(RHSVecTy);
12046 if (IsCompAssign)
12047 return RHSType;
12048 if (LHSEleType != RHSEleType) {
12049 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
12050 LHSEleType = RHSEleType;
12051 }
12052 QualType VecTy =
12053 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
12054 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
12055 LHSType = VecTy;
12056 } else if (RHSVecTy) {
12057 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12058 // are applied component-wise. So if RHS is a vector, then ensure
12059 // that the number of elements is the same as LHS...
12060 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12061 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12062 << LHS.get()->getType() << RHS.get()->getType()
12063 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12064 return QualType();
12065 }
12066 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12067 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12068 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12069 if (LHSBT != RHSBT &&
12070 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12071 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12072 << LHS.get()->getType() << RHS.get()->getType()
12073 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12074 }
12075 }
12076 } else {
12077 // ...else expand RHS to match the number of elements in LHS.
12078 QualType VecTy =
12079 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12080 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12081 }
12082
12083 return LHSType;
12084}
12085
12087 ExprResult &RHS, SourceLocation Loc,
12088 bool IsCompAssign) {
12089 if (!IsCompAssign) {
12090 LHS = S.UsualUnaryConversions(LHS.get());
12091 if (LHS.isInvalid())
12092 return QualType();
12093 }
12094
12095 RHS = S.UsualUnaryConversions(RHS.get());
12096 if (RHS.isInvalid())
12097 return QualType();
12098
12099 QualType LHSType = LHS.get()->getType();
12100 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12101 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12102 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12103 : LHSType;
12104
12105 // Note that RHS might not be a vector
12106 QualType RHSType = RHS.get()->getType();
12107 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12108 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12109 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12110 : RHSType;
12111
12112 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12113 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12114 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12115 << LHSType << RHSType << LHS.get()->getSourceRange();
12116 return QualType();
12117 }
12118
12119 if (!LHSEleType->isIntegerType()) {
12120 S.Diag(Loc, diag::err_typecheck_expect_int)
12121 << LHS.get()->getType() << LHS.get()->getSourceRange();
12122 return QualType();
12123 }
12124
12125 if (!RHSEleType->isIntegerType()) {
12126 S.Diag(Loc, diag::err_typecheck_expect_int)
12127 << RHS.get()->getType() << RHS.get()->getSourceRange();
12128 return QualType();
12129 }
12130
12131 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12132 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12133 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12134 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12135 << LHSType << RHSType << LHS.get()->getSourceRange()
12136 << RHS.get()->getSourceRange();
12137 return QualType();
12138 }
12139
12140 if (!LHSType->isSveVLSBuiltinType()) {
12141 assert(RHSType->isSveVLSBuiltinType());
12142 if (IsCompAssign)
12143 return RHSType;
12144 if (LHSEleType != RHSEleType) {
12145 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12146 LHSEleType = RHSEleType;
12147 }
12148 const llvm::ElementCount VecSize =
12149 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12150 QualType VecTy =
12151 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12152 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12153 LHSType = VecTy;
12154 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12155 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12156 S.Context.getTypeSize(LHSBuiltinTy)) {
12157 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12158 << LHSType << RHSType << LHS.get()->getSourceRange()
12159 << RHS.get()->getSourceRange();
12160 return QualType();
12161 }
12162 } else {
12163 const llvm::ElementCount VecSize =
12164 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12165 if (LHSEleType != RHSEleType) {
12166 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12167 RHSEleType = LHSEleType;
12168 }
12169 QualType VecTy =
12170 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12171 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12172 }
12173
12174 return LHSType;
12175}
12176
12177// C99 6.5.7
12180 bool IsCompAssign) {
12181 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12182
12183 // Vector shifts promote their scalar inputs to vector type.
12184 if (LHS.get()->getType()->isVectorType() ||
12185 RHS.get()->getType()->isVectorType()) {
12186 if (LangOpts.ZVector) {
12187 // The shift operators for the z vector extensions work basically
12188 // like general shifts, except that neither the LHS nor the RHS is
12189 // allowed to be a "vector bool".
12190 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12191 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12192 return InvalidOperands(Loc, LHS, RHS);
12193 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12194 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12195 return InvalidOperands(Loc, LHS, RHS);
12196 }
12197 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12198 }
12199
12200 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12201 RHS.get()->getType()->isSveVLSBuiltinType())
12202 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12203
12204 // Shifts don't perform usual arithmetic conversions, they just do integer
12205 // promotions on each operand. C99 6.5.7p3
12206
12207 // For the LHS, do usual unary conversions, but then reset them away
12208 // if this is a compound assignment.
12209 ExprResult OldLHS = LHS;
12210 LHS = UsualUnaryConversions(LHS.get());
12211 if (LHS.isInvalid())
12212 return QualType();
12213 QualType LHSType = LHS.get()->getType();
12214 if (IsCompAssign) LHS = OldLHS;
12215
12216 // The RHS is simpler.
12217 RHS = UsualUnaryConversions(RHS.get());
12218 if (RHS.isInvalid())
12219 return QualType();
12220 QualType RHSType = RHS.get()->getType();
12221
12222 // C99 6.5.7p2: Each of the operands shall have integer type.
12223 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12224 if ((!LHSType->isFixedPointOrIntegerType() &&
12225 !LHSType->hasIntegerRepresentation()) ||
12226 !RHSType->hasIntegerRepresentation()) {
12227 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12228 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12229 return ResultTy;
12230 }
12231
12232 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12233
12234 // "The type of the result is that of the promoted left operand."
12235 return LHSType;
12236}
12237
12238/// Diagnose bad pointer comparisons.
12240 ExprResult &LHS, ExprResult &RHS,
12241 bool IsError) {
12242 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12243 : diag::ext_typecheck_comparison_of_distinct_pointers)
12244 << LHS.get()->getType() << RHS.get()->getType()
12245 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12246}
12247
12248/// Returns false if the pointers are converted to a composite type,
12249/// true otherwise.
12251 ExprResult &LHS, ExprResult &RHS) {
12252 // C++ [expr.rel]p2:
12253 // [...] Pointer conversions (4.10) and qualification
12254 // conversions (4.4) are performed on pointer operands (or on
12255 // a pointer operand and a null pointer constant) to bring
12256 // them to their composite pointer type. [...]
12257 //
12258 // C++ [expr.eq]p1 uses the same notion for (in)equality
12259 // comparisons of pointers.
12260
12261 QualType LHSType = LHS.get()->getType();
12262 QualType RHSType = RHS.get()->getType();
12263 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12264 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12265
12266 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12267 if (T.isNull()) {
12268 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12269 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12270 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12271 else
12272 S.InvalidOperands(Loc, LHS, RHS);
12273 return true;
12274 }
12275
12276 return false;
12277}
12278
12280 ExprResult &LHS,
12281 ExprResult &RHS,
12282 bool IsError) {
12283 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12284 : diag::ext_typecheck_comparison_of_fptr_to_void)
12285 << LHS.get()->getType() << RHS.get()->getType()
12286 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12287}
12288
12290 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12291 case Stmt::ObjCArrayLiteralClass:
12292 case Stmt::ObjCDictionaryLiteralClass:
12293 case Stmt::ObjCStringLiteralClass:
12294 case Stmt::ObjCBoxedExprClass:
12295 return true;
12296 default:
12297 // Note that ObjCBoolLiteral is NOT an object literal!
12298 return false;
12299 }
12300}
12301
12302static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12305
12306 // If this is not actually an Objective-C object, bail out.
12307 if (!Type)
12308 return false;
12309
12310 // Get the LHS object's interface type.
12311 QualType InterfaceType = Type->getPointeeType();
12312
12313 // If the RHS isn't an Objective-C object, bail out.
12314 if (!RHS->getType()->isObjCObjectPointerType())
12315 return false;
12316
12317 // Try to find the -isEqual: method.
12318 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12319 ObjCMethodDecl *Method =
12320 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
12321 /*IsInstance=*/true);
12322 if (!Method) {
12323 if (Type->isObjCIdType()) {
12324 // For 'id', just check the global pool.
12325 Method =
12327 /*receiverId=*/true);
12328 } else {
12329 // Check protocols.
12330 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
12331 /*IsInstance=*/true);
12332 }
12333 }
12334
12335 if (!Method)
12336 return false;
12337
12338 QualType T = Method->parameters()[0]->getType();
12339 if (!T->isObjCObjectPointerType())
12340 return false;
12341
12342 QualType R = Method->getReturnType();
12343 if (!R->isScalarType())
12344 return false;
12345
12346 return true;
12347}
12348
12350 ExprResult &LHS, ExprResult &RHS,
12352 Expr *Literal;
12353 Expr *Other;
12354 if (isObjCObjectLiteral(LHS)) {
12355 Literal = LHS.get();
12356 Other = RHS.get();
12357 } else {
12358 Literal = RHS.get();
12359 Other = LHS.get();
12360 }
12361
12362 // Don't warn on comparisons against nil.
12363 Other = Other->IgnoreParenCasts();
12364 if (Other->isNullPointerConstant(S.getASTContext(),
12366 return;
12367
12368 // This should be kept in sync with warn_objc_literal_comparison.
12369 // LK_String should always be after the other literals, since it has its own
12370 // warning flag.
12371 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12372 assert(LiteralKind != SemaObjC::LK_Block);
12373 if (LiteralKind == SemaObjC::LK_None) {
12374 llvm_unreachable("Unknown Objective-C object literal kind");
12375 }
12376
12377 if (LiteralKind == SemaObjC::LK_String)
12378 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12379 << Literal->getSourceRange();
12380 else
12381 S.Diag(Loc, diag::warn_objc_literal_comparison)
12382 << LiteralKind << Literal->getSourceRange();
12383
12385 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12386 SourceLocation Start = LHS.get()->getBeginLoc();
12388 CharSourceRange OpRange =
12390
12391 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12392 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12393 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12394 << FixItHint::CreateInsertion(End, "]");
12395 }
12396}
12397
12398/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12400 ExprResult &RHS, SourceLocation Loc,
12401 BinaryOperatorKind Opc) {
12402 // Check that left hand side is !something.
12403 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12404 if (!UO || UO->getOpcode() != UO_LNot) return;
12405
12406 // Only check if the right hand side is non-bool arithmetic type.
12407 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12408
12409 // Make sure that the something in !something is not bool.
12410 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12411 if (SubExpr->isKnownToHaveBooleanValue()) return;
12412
12413 // Emit warning.
12414 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12415 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12416 << Loc << IsBitwiseOp;
12417
12418 // First note suggest !(x < y)
12419 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12420 SourceLocation FirstClose = RHS.get()->getEndLoc();
12421 FirstClose = S.getLocForEndOfToken(FirstClose);
12422 if (FirstClose.isInvalid())
12423 FirstOpen = SourceLocation();
12424 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12425 << IsBitwiseOp
12426 << FixItHint::CreateInsertion(FirstOpen, "(")
12427 << FixItHint::CreateInsertion(FirstClose, ")");
12428
12429 // Second note suggests (!x) < y
12430 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12431 SourceLocation SecondClose = LHS.get()->getEndLoc();
12432 SecondClose = S.getLocForEndOfToken(SecondClose);
12433 if (SecondClose.isInvalid())
12434 SecondOpen = SourceLocation();
12435 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12436 << FixItHint::CreateInsertion(SecondOpen, "(")
12437 << FixItHint::CreateInsertion(SecondClose, ")");
12438}
12439
12440// Returns true if E refers to a non-weak array.
12441static bool checkForArray(const Expr *E) {
12442 const ValueDecl *D = nullptr;
12443 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12444 D = DR->getDecl();
12445 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12446 if (Mem->isImplicitAccess())
12447 D = Mem->getMemberDecl();
12448 }
12449 if (!D)
12450 return false;
12451 return D->getType()->isArrayType() && !D->isWeak();
12452}
12453
12454/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12455/// pointer and size is an unsigned integer. Return whether the result is
12456/// always true/false.
12457static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12458 const Expr *RHS,
12459 BinaryOperatorKind Opc) {
12460 if (!LHS->getType()->isPointerType() ||
12461 S.getLangOpts().PointerOverflowDefined)
12462 return std::nullopt;
12463
12464 // Canonicalize to >= or < predicate.
12465 switch (Opc) {
12466 case BO_GE:
12467 case BO_LT:
12468 break;
12469 case BO_GT:
12470 std::swap(LHS, RHS);
12471 Opc = BO_LT;
12472 break;
12473 case BO_LE:
12474 std::swap(LHS, RHS);
12475 Opc = BO_GE;
12476 break;
12477 default:
12478 return std::nullopt;
12479 }
12480
12481 auto *BO = dyn_cast<BinaryOperator>(LHS);
12482 if (!BO || BO->getOpcode() != BO_Add)
12483 return std::nullopt;
12484
12485 Expr *Other;
12486 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12487 Other = BO->getRHS();
12488 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12489 Other = BO->getLHS();
12490 else
12491 return std::nullopt;
12492
12493 if (!Other->getType()->isUnsignedIntegerType())
12494 return std::nullopt;
12495
12496 return Opc == BO_GE;
12497}
12498
12499/// Diagnose some forms of syntactically-obvious tautological comparison.
12501 Expr *LHS, Expr *RHS,
12502 BinaryOperatorKind Opc) {
12503 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12504 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12505
12506 QualType LHSType = LHS->getType();
12507 QualType RHSType = RHS->getType();
12508 if (LHSType->hasFloatingRepresentation() ||
12509 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12511 return;
12512
12513 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12514 // Tautological diagnostics.
12515 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12516 return;
12517
12518 // Comparisons between two array types are ill-formed for operator<=>, so
12519 // we shouldn't emit any additional warnings about it.
12520 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12521 return;
12522
12523 // For non-floating point types, check for self-comparisons of the form
12524 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12525 // often indicate logic errors in the program.
12526 //
12527 // NOTE: Don't warn about comparison expressions resulting from macro
12528 // expansion. Also don't warn about comparisons which are only self
12529 // comparisons within a template instantiation. The warnings should catch
12530 // obvious cases in the definition of the template anyways. The idea is to
12531 // warn when the typed comparison operator will always evaluate to the same
12532 // result.
12533
12534 // Used for indexing into %select in warn_comparison_always
12535 enum {
12536 AlwaysConstant,
12537 AlwaysTrue,
12538 AlwaysFalse,
12539 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12540 };
12541
12542 // C++1a [array.comp]:
12543 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12544 // operands of array type.
12545 // C++2a [depr.array.comp]:
12546 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12547 // operands of array type are deprecated.
12548 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12549 RHSStripped->getType()->isArrayType()) {
12550 auto IsDeprArrayComparionIgnored =
12551 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12552 auto DiagID = S.getLangOpts().CPlusPlus26
12553 ? diag::warn_array_comparison_cxx26
12554 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12555 ? diag::warn_array_comparison
12556 : diag::warn_depr_array_comparison;
12557 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12558 << LHSStripped->getType() << RHSStripped->getType();
12559 // Carry on to produce the tautological comparison warning, if this
12560 // expression is potentially-evaluated, we can resolve the array to a
12561 // non-weak declaration, and so on.
12562 }
12563
12564 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12565 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12566 unsigned Result;
12567 switch (Opc) {
12568 case BO_EQ:
12569 case BO_LE:
12570 case BO_GE:
12571 Result = AlwaysTrue;
12572 break;
12573 case BO_NE:
12574 case BO_LT:
12575 case BO_GT:
12576 Result = AlwaysFalse;
12577 break;
12578 case BO_Cmp:
12579 Result = AlwaysEqual;
12580 break;
12581 default:
12582 Result = AlwaysConstant;
12583 break;
12584 }
12585 S.DiagRuntimeBehavior(Loc, nullptr,
12586 S.PDiag(diag::warn_comparison_always)
12587 << 0 /*self-comparison*/
12588 << Result);
12589 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12590 // What is it always going to evaluate to?
12591 unsigned Result;
12592 switch (Opc) {
12593 case BO_EQ: // e.g. array1 == array2
12594 Result = AlwaysFalse;
12595 break;
12596 case BO_NE: // e.g. array1 != array2
12597 Result = AlwaysTrue;
12598 break;
12599 default: // e.g. array1 <= array2
12600 // The best we can say is 'a constant'
12601 Result = AlwaysConstant;
12602 break;
12603 }
12604 S.DiagRuntimeBehavior(Loc, nullptr,
12605 S.PDiag(diag::warn_comparison_always)
12606 << 1 /*array comparison*/
12607 << Result);
12608 } else if (std::optional<bool> Res =
12609 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12610 S.DiagRuntimeBehavior(Loc, nullptr,
12611 S.PDiag(diag::warn_comparison_always)
12612 << 2 /*pointer comparison*/
12613 << (*Res ? AlwaysTrue : AlwaysFalse));
12614 }
12615 }
12616
12617 if (isa<CastExpr>(LHSStripped))
12618 LHSStripped = LHSStripped->IgnoreParenCasts();
12619 if (isa<CastExpr>(RHSStripped))
12620 RHSStripped = RHSStripped->IgnoreParenCasts();
12621
12622 // Warn about comparisons against a string constant (unless the other
12623 // operand is null); the user probably wants string comparison function.
12624 Expr *LiteralString = nullptr;
12625 Expr *LiteralStringStripped = nullptr;
12626 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12627 !RHSStripped->isNullPointerConstant(S.Context,
12629 LiteralString = LHS;
12630 LiteralStringStripped = LHSStripped;
12631 } else if ((isa<StringLiteral>(RHSStripped) ||
12632 isa<ObjCEncodeExpr>(RHSStripped)) &&
12633 !LHSStripped->isNullPointerConstant(S.Context,
12635 LiteralString = RHS;
12636 LiteralStringStripped = RHSStripped;
12637 }
12638
12639 if (LiteralString) {
12640 S.DiagRuntimeBehavior(Loc, nullptr,
12641 S.PDiag(diag::warn_stringcompare)
12642 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12643 << LiteralString->getSourceRange());
12644 }
12645}
12646
12648 switch (CK) {
12649 default: {
12650#ifndef NDEBUG
12651 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12652 << "\n";
12653#endif
12654 llvm_unreachable("unhandled cast kind");
12655 }
12656 case CK_UserDefinedConversion:
12657 return ICK_Identity;
12658 case CK_LValueToRValue:
12659 return ICK_Lvalue_To_Rvalue;
12660 case CK_ArrayToPointerDecay:
12661 return ICK_Array_To_Pointer;
12662 case CK_FunctionToPointerDecay:
12664 case CK_IntegralCast:
12666 case CK_FloatingCast:
12668 case CK_IntegralToFloating:
12669 case CK_FloatingToIntegral:
12670 return ICK_Floating_Integral;
12671 case CK_IntegralComplexCast:
12672 case CK_FloatingComplexCast:
12673 case CK_FloatingComplexToIntegralComplex:
12674 case CK_IntegralComplexToFloatingComplex:
12676 case CK_FloatingComplexToReal:
12677 case CK_FloatingRealToComplex:
12678 case CK_IntegralComplexToReal:
12679 case CK_IntegralRealToComplex:
12680 return ICK_Complex_Real;
12681 case CK_HLSLArrayRValue:
12682 return ICK_HLSL_Array_RValue;
12683 }
12684}
12685
12687 QualType FromType,
12688 SourceLocation Loc) {
12689 // Check for a narrowing implicit conversion.
12692 SCS.setToType(0, FromType);
12693 SCS.setToType(1, ToType);
12694 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12695 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12696
12697 APValue PreNarrowingValue;
12698 QualType PreNarrowingType;
12699 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12700 PreNarrowingType,
12701 /*IgnoreFloatToIntegralConversion*/ true)) {
12703 // Implicit conversion to a narrower type, but the expression is
12704 // value-dependent so we can't tell whether it's actually narrowing.
12705 case NK_Not_Narrowing:
12706 return false;
12707
12709 // Implicit conversion to a narrower type, and the value is not a constant
12710 // expression.
12711 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12712 << /*Constant*/ 1
12713 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12714 return true;
12715
12717 // Implicit conversion to a narrower type, and the value is not a constant
12718 // expression.
12719 case NK_Type_Narrowing:
12720 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12721 << /*Constant*/ 0 << FromType << ToType;
12722 // TODO: It's not a constant expression, but what if the user intended it
12723 // to be? Can we produce notes to help them figure out why it isn't?
12724 return true;
12725 }
12726 llvm_unreachable("unhandled case in switch");
12727}
12728
12730 ExprResult &LHS,
12731 ExprResult &RHS,
12732 SourceLocation Loc) {
12733 QualType LHSType = LHS.get()->getType();
12734 QualType RHSType = RHS.get()->getType();
12735 // Dig out the original argument type and expression before implicit casts
12736 // were applied. These are the types/expressions we need to check the
12737 // [expr.spaceship] requirements against.
12738 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12739 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12740 QualType LHSStrippedType = LHSStripped.get()->getType();
12741 QualType RHSStrippedType = RHSStripped.get()->getType();
12742
12743 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12744 // other is not, the program is ill-formed.
12745 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12746 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12747 return QualType();
12748 }
12749
12750 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12751 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12752 RHSStrippedType->isEnumeralType();
12753 if (NumEnumArgs == 1) {
12754 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12755 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12756 if (OtherTy->hasFloatingRepresentation()) {
12757 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12758 return QualType();
12759 }
12760 }
12761 if (NumEnumArgs == 2) {
12762 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12763 // type E, the operator yields the result of converting the operands
12764 // to the underlying type of E and applying <=> to the converted operands.
12765 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12766 S.InvalidOperands(Loc, LHS, RHS);
12767 return QualType();
12768 }
12769 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12770 assert(IntType->isArithmeticType());
12771
12772 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12773 // promote the boolean type, and all other promotable integer types, to
12774 // avoid this.
12775 if (S.Context.isPromotableIntegerType(IntType))
12776 IntType = S.Context.getPromotedIntegerType(IntType);
12777
12778 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12779 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12780 LHSType = RHSType = IntType;
12781 }
12782
12783 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12784 // usual arithmetic conversions are applied to the operands.
12785 QualType Type =
12787 if (LHS.isInvalid() || RHS.isInvalid())
12788 return QualType();
12789 if (Type.isNull()) {
12790 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12791 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
12792 return ResultTy;
12793 }
12794
12795 std::optional<ComparisonCategoryType> CCT =
12797 if (!CCT)
12798 return S.InvalidOperands(Loc, LHS, RHS);
12799
12800 bool HasNarrowing = checkThreeWayNarrowingConversion(
12801 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12802 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12803 RHS.get()->getBeginLoc());
12804 if (HasNarrowing)
12805 return QualType();
12806
12807 assert(!Type.isNull() && "composite type for <=> has not been set");
12808
12811}
12812
12814 ExprResult &RHS,
12815 SourceLocation Loc,
12816 BinaryOperatorKind Opc) {
12817 if (Opc == BO_Cmp)
12818 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12819
12820 // C99 6.5.8p3 / C99 6.5.9p4
12821 QualType Type =
12823 if (LHS.isInvalid() || RHS.isInvalid())
12824 return QualType();
12825 if (Type.isNull()) {
12826 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12827 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12828 return ResultTy;
12829 }
12830 assert(Type->isArithmeticType() || Type->isEnumeralType());
12831
12833 return S.InvalidOperands(Loc, LHS, RHS);
12834
12835 // Check for comparisons of floating point operands using != and ==.
12837 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12838
12839 // The result of comparisons is 'bool' in C++, 'int' in C.
12841}
12842
12844 if (!NullE.get()->getType()->isAnyPointerType())
12845 return;
12846 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12847 if (!E.get()->getType()->isAnyPointerType() &&
12851 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12852 if (CL->getValue() == 0)
12853 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12854 << NullValue
12856 NullValue ? "NULL" : "(void *)0");
12857 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12858 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12859 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12860 if (T == Context.CharTy)
12861 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12862 << NullValue
12864 NullValue ? "NULL" : "(void *)0");
12865 }
12866 }
12867}
12868
12869// C99 6.5.8, C++ [expr.rel]
12871 SourceLocation Loc,
12872 BinaryOperatorKind Opc) {
12873 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12874 bool IsThreeWay = Opc == BO_Cmp;
12875 bool IsOrdered = IsRelational || IsThreeWay;
12876 auto IsAnyPointerType = [](ExprResult E) {
12877 QualType Ty = E.get()->getType();
12878 return Ty->isPointerType() || Ty->isMemberPointerType();
12879 };
12880
12881 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12882 // type, array-to-pointer, ..., conversions are performed on both operands to
12883 // bring them to their composite type.
12884 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12885 // any type-related checks.
12886 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12888 if (LHS.isInvalid())
12889 return QualType();
12891 if (RHS.isInvalid())
12892 return QualType();
12893 } else {
12894 LHS = DefaultLvalueConversion(LHS.get());
12895 if (LHS.isInvalid())
12896 return QualType();
12897 RHS = DefaultLvalueConversion(RHS.get());
12898 if (RHS.isInvalid())
12899 return QualType();
12900 }
12901
12902 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12906 }
12907
12908 // Handle vector comparisons separately.
12909 if (LHS.get()->getType()->isVectorType() ||
12910 RHS.get()->getType()->isVectorType())
12911 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12912
12913 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12914 RHS.get()->getType()->isSveVLSBuiltinType())
12915 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12916
12917 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12918 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12919
12920 QualType LHSType = LHS.get()->getType();
12921 QualType RHSType = RHS.get()->getType();
12922 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12923 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12924 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12925
12926 if ((LHSType->isPointerType() &&
12928 (RHSType->isPointerType() &&
12930 return InvalidOperands(Loc, LHS, RHS);
12931
12932 const Expr::NullPointerConstantKind LHSNullKind =
12934 const Expr::NullPointerConstantKind RHSNullKind =
12936 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12937 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12938
12939 auto computeResultTy = [&]() {
12940 if (Opc != BO_Cmp)
12941 return QualType(Context.getLogicalOperationType());
12942 assert(getLangOpts().CPlusPlus);
12943 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12944
12945 QualType CompositeTy = LHS.get()->getType();
12946 assert(!CompositeTy->isReferenceType());
12947
12948 std::optional<ComparisonCategoryType> CCT =
12950 if (!CCT)
12951 return InvalidOperands(Loc, LHS, RHS);
12952
12953 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12954 // P0946R0: Comparisons between a null pointer constant and an object
12955 // pointer result in std::strong_equality, which is ill-formed under
12956 // P1959R0.
12957 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12958 << (LHSIsNull ? LHS.get()->getSourceRange()
12959 : RHS.get()->getSourceRange());
12960 return QualType();
12961 }
12962
12965 };
12966
12967 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12968 bool IsEquality = Opc == BO_EQ;
12969 if (RHSIsNull)
12970 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12971 RHS.get()->getSourceRange());
12972 else
12973 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12974 LHS.get()->getSourceRange());
12975 }
12976
12977 if (IsOrdered && LHSType->isFunctionPointerType() &&
12978 RHSType->isFunctionPointerType()) {
12979 // Valid unless a relational comparison of function pointers
12980 bool IsError = Opc == BO_Cmp;
12981 auto DiagID =
12982 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12983 : getLangOpts().CPlusPlus
12984 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12985 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12986 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12987 << RHS.get()->getSourceRange();
12988 if (IsError)
12989 return QualType();
12990 }
12991
12992 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12993 (RHSType->isIntegerType() && !RHSIsNull)) {
12994 // Skip normal pointer conversion checks in this case; we have better
12995 // diagnostics for this below.
12996 } else if (getLangOpts().CPlusPlus) {
12997 // Equality comparison of a function pointer to a void pointer is invalid,
12998 // but we allow it as an extension.
12999 // FIXME: If we really want to allow this, should it be part of composite
13000 // pointer type computation so it works in conditionals too?
13001 if (!IsOrdered &&
13002 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13003 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13004 // This is a gcc extension compatibility comparison.
13005 // In a SFINAE context, we treat this as a hard error to maintain
13006 // conformance with the C++ standard.
13007 bool IsError = isSFINAEContext();
13008 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError);
13009
13010 if (IsError)
13011 return QualType();
13012
13013 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13014 return computeResultTy();
13015 }
13016
13017 // C++ [expr.eq]p2:
13018 // If at least one operand is a pointer [...] bring them to their
13019 // composite pointer type.
13020 // C++ [expr.spaceship]p6
13021 // If at least one of the operands is of pointer type, [...] bring them
13022 // to their composite pointer type.
13023 // C++ [expr.rel]p2:
13024 // If both operands are pointers, [...] bring them to their composite
13025 // pointer type.
13026 // For <=>, the only valid non-pointer types are arrays and functions, and
13027 // we already decayed those, so this is really the same as the relational
13028 // comparison rule.
13029 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13030 (IsOrdered ? 2 : 1) &&
13031 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13032 RHSType->isObjCObjectPointerType()))) {
13033 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13034 return QualType();
13035 return computeResultTy();
13036 }
13037 } else if (LHSType->isPointerType() &&
13038 RHSType->isPointerType()) { // C99 6.5.8p2
13039 // All of the following pointer-related warnings are GCC extensions, except
13040 // when handling null pointer constants.
13041 QualType LCanPointeeTy =
13043 QualType RCanPointeeTy =
13045
13046 // C99 6.5.9p2 and C99 6.5.8p2
13047 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
13048 RCanPointeeTy.getUnqualifiedType())) {
13049 if (IsRelational) {
13050 // Pointers both need to point to complete or incomplete types
13051 if ((LCanPointeeTy->isIncompleteType() !=
13052 RCanPointeeTy->isIncompleteType()) &&
13053 !getLangOpts().C11) {
13054 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13055 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13056 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13057 << RCanPointeeTy->isIncompleteType();
13058 }
13059 }
13060 } else if (!IsRelational &&
13061 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13062 // Valid unless comparison between non-null pointer and function pointer
13063 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13064 && !LHSIsNull && !RHSIsNull)
13065 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13066 /*isError*/false);
13067 } else {
13068 // Invalid
13069 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13070 }
13071 if (LCanPointeeTy != RCanPointeeTy) {
13072 // Treat NULL constant as a special case in OpenCL.
13073 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13074 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
13075 getASTContext())) {
13076 Diag(Loc,
13077 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13078 << LHSType << RHSType << 0 /* comparison */
13079 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13080 }
13081 }
13082 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13083 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13084 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13085 : CK_BitCast;
13086
13087 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13088 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13089 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13090 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13091 bool ChangingCFIUncheckedCallee =
13092 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13093
13094 if (LHSIsNull && !RHSIsNull)
13095 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13096 else if (!ChangingCFIUncheckedCallee)
13097 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13098 }
13099 return computeResultTy();
13100 }
13101
13102
13103 // C++ [expr.eq]p4:
13104 // Two operands of type std::nullptr_t or one operand of type
13105 // std::nullptr_t and the other a null pointer constant compare
13106 // equal.
13107 // C23 6.5.9p5:
13108 // If both operands have type nullptr_t or one operand has type nullptr_t
13109 // and the other is a null pointer constant, they compare equal if the
13110 // former is a null pointer.
13111 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13112 if (LHSType->isNullPtrType()) {
13113 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13114 return computeResultTy();
13115 }
13116 if (RHSType->isNullPtrType()) {
13117 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13118 return computeResultTy();
13119 }
13120 }
13121
13122 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13123 // C23 6.5.9p6:
13124 // Otherwise, at least one operand is a pointer. If one is a pointer and
13125 // the other is a null pointer constant or has type nullptr_t, they
13126 // compare equal
13127 if (LHSIsNull && RHSType->isPointerType()) {
13128 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13129 return computeResultTy();
13130 }
13131 if (RHSIsNull && LHSType->isPointerType()) {
13132 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13133 return computeResultTy();
13134 }
13135 }
13136
13137 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13138 // These aren't covered by the composite pointer type rules.
13139 if (!IsOrdered && RHSType->isNullPtrType() &&
13140 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13141 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13142 return computeResultTy();
13143 }
13144 if (!IsOrdered && LHSType->isNullPtrType() &&
13145 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13146 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13147 return computeResultTy();
13148 }
13149
13150 if (getLangOpts().CPlusPlus) {
13151 if (IsRelational &&
13152 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13153 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13154 // HACK: Relational comparison of nullptr_t against a pointer type is
13155 // invalid per DR583, but we allow it within std::less<> and friends,
13156 // since otherwise common uses of it break.
13157 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13158 // friends to have std::nullptr_t overload candidates.
13159 DeclContext *DC = CurContext;
13160 if (isa<FunctionDecl>(DC))
13161 DC = DC->getParent();
13162 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13163 if (CTSD->isInStdNamespace() &&
13164 llvm::StringSwitch<bool>(CTSD->getName())
13165 .Cases({"less", "less_equal", "greater", "greater_equal"}, true)
13166 .Default(false)) {
13167 if (RHSType->isNullPtrType())
13168 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13169 else
13170 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13171 return computeResultTy();
13172 }
13173 }
13174 }
13175
13176 // C++ [expr.eq]p2:
13177 // If at least one operand is a pointer to member, [...] bring them to
13178 // their composite pointer type.
13179 if (!IsOrdered &&
13180 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13181 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13182 return QualType();
13183 else
13184 return computeResultTy();
13185 }
13186 }
13187
13188 // Handle block pointer types.
13189 if (!IsOrdered && LHSType->isBlockPointerType() &&
13190 RHSType->isBlockPointerType()) {
13191 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13192 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13193
13194 if (!LHSIsNull && !RHSIsNull &&
13195 !Context.typesAreCompatible(lpointee, rpointee)) {
13196 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13197 << LHSType << RHSType << LHS.get()->getSourceRange()
13198 << RHS.get()->getSourceRange();
13199 }
13200 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13201 return computeResultTy();
13202 }
13203
13204 // Allow block pointers to be compared with null pointer constants.
13205 if (!IsOrdered
13206 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13207 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13208 if (!LHSIsNull && !RHSIsNull) {
13209 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13211 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13212 ->getPointeeType()->isVoidType())))
13213 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13214 << LHSType << RHSType << LHS.get()->getSourceRange()
13215 << RHS.get()->getSourceRange();
13216 }
13217 if (LHSIsNull && !RHSIsNull)
13218 LHS = ImpCastExprToType(LHS.get(), RHSType,
13219 RHSType->isPointerType() ? CK_BitCast
13220 : CK_AnyPointerToBlockPointerCast);
13221 else
13222 RHS = ImpCastExprToType(RHS.get(), LHSType,
13223 LHSType->isPointerType() ? CK_BitCast
13224 : CK_AnyPointerToBlockPointerCast);
13225 return computeResultTy();
13226 }
13227
13228 if (LHSType->isObjCObjectPointerType() ||
13229 RHSType->isObjCObjectPointerType()) {
13230 const PointerType *LPT = LHSType->getAs<PointerType>();
13231 const PointerType *RPT = RHSType->getAs<PointerType>();
13232 if (LPT || RPT) {
13233 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13234 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13235
13236 if (!LPtrToVoid && !RPtrToVoid &&
13237 !Context.typesAreCompatible(LHSType, RHSType)) {
13238 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13239 /*isError*/false);
13240 }
13241 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13242 // the RHS, but we have test coverage for this behavior.
13243 // FIXME: Consider using convertPointersToCompositeType in C++.
13244 if (LHSIsNull && !RHSIsNull) {
13245 Expr *E = LHS.get();
13246 if (getLangOpts().ObjCAutoRefCount)
13247 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
13249 LHS = ImpCastExprToType(E, RHSType,
13250 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13251 }
13252 else {
13253 Expr *E = RHS.get();
13254 if (getLangOpts().ObjCAutoRefCount)
13255 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
13257 /*Diagnose=*/true,
13258 /*DiagnoseCFAudited=*/false, Opc);
13259 RHS = ImpCastExprToType(E, LHSType,
13260 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13261 }
13262 return computeResultTy();
13263 }
13264 if (LHSType->isObjCObjectPointerType() &&
13265 RHSType->isObjCObjectPointerType()) {
13266 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13267 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13268 /*isError*/false);
13270 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13271
13272 if (LHSIsNull && !RHSIsNull)
13273 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13274 else
13275 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13276 return computeResultTy();
13277 }
13278
13279 if (!IsOrdered && LHSType->isBlockPointerType() &&
13281 LHS = ImpCastExprToType(LHS.get(), RHSType,
13282 CK_BlockPointerToObjCPointerCast);
13283 return computeResultTy();
13284 } else if (!IsOrdered &&
13286 RHSType->isBlockPointerType()) {
13287 RHS = ImpCastExprToType(RHS.get(), LHSType,
13288 CK_BlockPointerToObjCPointerCast);
13289 return computeResultTy();
13290 }
13291 }
13292 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13293 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13294 unsigned DiagID = 0;
13295 bool isError = false;
13296 if (LangOpts.DebuggerSupport) {
13297 // Under a debugger, allow the comparison of pointers to integers,
13298 // since users tend to want to compare addresses.
13299 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13300 (RHSIsNull && RHSType->isIntegerType())) {
13301 if (IsOrdered) {
13302 isError = getLangOpts().CPlusPlus;
13303 DiagID =
13304 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13305 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13306 }
13307 } else if (getLangOpts().CPlusPlus) {
13308 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13309 isError = true;
13310 } else if (IsOrdered)
13311 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13312 else
13313 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13314
13315 if (DiagID) {
13316 Diag(Loc, DiagID)
13317 << LHSType << RHSType << LHS.get()->getSourceRange()
13318 << RHS.get()->getSourceRange();
13319 if (isError)
13320 return QualType();
13321 }
13322
13323 if (LHSType->isIntegerType())
13324 LHS = ImpCastExprToType(LHS.get(), RHSType,
13325 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13326 else
13327 RHS = ImpCastExprToType(RHS.get(), LHSType,
13328 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13329 return computeResultTy();
13330 }
13331
13332 // Handle block pointers.
13333 if (!IsOrdered && RHSIsNull
13334 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13335 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13336 return computeResultTy();
13337 }
13338 if (!IsOrdered && LHSIsNull
13339 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13340 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13341 return computeResultTy();
13342 }
13343
13344 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13345 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13346 return computeResultTy();
13347 }
13348
13349 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13350 return computeResultTy();
13351 }
13352
13353 if (LHSIsNull && RHSType->isQueueT()) {
13354 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13355 return computeResultTy();
13356 }
13357
13358 if (LHSType->isQueueT() && RHSIsNull) {
13359 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13360 return computeResultTy();
13361 }
13362 }
13363
13364 return InvalidOperands(Loc, LHS, RHS);
13365}
13366
13368 const VectorType *VTy = V->castAs<VectorType>();
13369 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13370
13371 if (isa<ExtVectorType>(VTy)) {
13372 if (VTy->isExtVectorBoolType())
13373 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13374 if (TypeSize == Context.getTypeSize(Context.CharTy))
13375 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13376 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13377 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13378 if (TypeSize == Context.getTypeSize(Context.IntTy))
13379 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13380 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13381 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13382 if (TypeSize == Context.getTypeSize(Context.LongTy))
13383 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13384 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13385 "Unhandled vector element size in vector compare");
13386 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13387 }
13388
13389 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13390 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13392 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13393 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13395 if (TypeSize == Context.getTypeSize(Context.LongTy))
13396 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13398 if (TypeSize == Context.getTypeSize(Context.IntTy))
13399 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13401 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13402 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13404 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13405 "Unhandled vector element size in vector compare");
13406 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13408}
13409
13411 const BuiltinType *VTy = V->castAs<BuiltinType>();
13412 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13413
13414 const QualType ETy = V->getSveEltType(Context);
13415 const auto TypeSize = Context.getTypeSize(ETy);
13416
13417 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13418 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13419 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13420}
13421
13423 SourceLocation Loc,
13424 BinaryOperatorKind Opc) {
13425 if (Opc == BO_Cmp) {
13426 Diag(Loc, diag::err_three_way_vector_comparison);
13427 return QualType();
13428 }
13429
13430 // Check to make sure we're operating on vectors of the same type and width,
13431 // Allowing one side to be a scalar of element type.
13432 QualType vType =
13433 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13434 /*AllowBothBool*/ true,
13435 /*AllowBoolConversions*/ getLangOpts().ZVector,
13436 /*AllowBooleanOperation*/ true,
13437 /*ReportInvalid*/ true);
13438 if (vType.isNull())
13439 return vType;
13440
13441 QualType LHSType = LHS.get()->getType();
13442
13443 // Determine the return type of a vector compare. By default clang will return
13444 // a scalar for all vector compares except vector bool and vector pixel.
13445 // With the gcc compiler we will always return a vector type and with the xl
13446 // compiler we will always return a scalar type. This switch allows choosing
13447 // which behavior is prefered.
13448 if (getLangOpts().AltiVec) {
13449 switch (getLangOpts().getAltivecSrcCompat()) {
13451 // If AltiVec, the comparison results in a numeric type, i.e.
13452 // bool for C++, int for C
13453 if (vType->castAs<VectorType>()->getVectorKind() ==
13455 return Context.getLogicalOperationType();
13456 else
13457 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13458 break;
13460 // For GCC we always return the vector type.
13461 break;
13463 return Context.getLogicalOperationType();
13464 break;
13465 }
13466 }
13467
13468 // For non-floating point types, check for self-comparisons of the form
13469 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13470 // often indicate logic errors in the program.
13471 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13472
13473 // Check for comparisons of floating point operands using != and ==.
13474 if (LHSType->hasFloatingRepresentation()) {
13475 assert(RHS.get()->getType()->hasFloatingRepresentation());
13476 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13477 }
13478
13479 // Return a signed type for the vector.
13480 return GetSignedVectorType(vType);
13481}
13482
13484 ExprResult &RHS,
13485 SourceLocation Loc,
13486 BinaryOperatorKind Opc) {
13487 if (Opc == BO_Cmp) {
13488 Diag(Loc, diag::err_three_way_vector_comparison);
13489 return QualType();
13490 }
13491
13492 // Check to make sure we're operating on vectors of the same type and width,
13493 // Allowing one side to be a scalar of element type.
13495 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13496
13497 if (vType.isNull())
13498 return vType;
13499
13500 QualType LHSType = LHS.get()->getType();
13501
13502 // For non-floating point types, check for self-comparisons of the form
13503 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13504 // often indicate logic errors in the program.
13505 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13506
13507 // Check for comparisons of floating point operands using != and ==.
13508 if (LHSType->hasFloatingRepresentation()) {
13509 assert(RHS.get()->getType()->hasFloatingRepresentation());
13510 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13511 }
13512
13513 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13514 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13515
13516 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13517 RHSBuiltinTy->isSVEBool())
13518 return LHSType;
13519
13520 // Return a signed type for the vector.
13521 return GetSignedSizelessVectorType(vType);
13522}
13523
13524static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13525 const ExprResult &XorRHS,
13526 const SourceLocation Loc) {
13527 // Do not diagnose macros.
13528 if (Loc.isMacroID())
13529 return;
13530
13531 // Do not diagnose if both LHS and RHS are macros.
13532 if (XorLHS.get()->getExprLoc().isMacroID() &&
13533 XorRHS.get()->getExprLoc().isMacroID())
13534 return;
13535
13536 bool Negative = false;
13537 bool ExplicitPlus = false;
13538 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13539 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13540
13541 if (!LHSInt)
13542 return;
13543 if (!RHSInt) {
13544 // Check negative literals.
13545 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13546 UnaryOperatorKind Opc = UO->getOpcode();
13547 if (Opc != UO_Minus && Opc != UO_Plus)
13548 return;
13549 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13550 if (!RHSInt)
13551 return;
13552 Negative = (Opc == UO_Minus);
13553 ExplicitPlus = !Negative;
13554 } else {
13555 return;
13556 }
13557 }
13558
13559 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13560 llvm::APInt RightSideValue = RHSInt->getValue();
13561 if (LeftSideValue != 2 && LeftSideValue != 10)
13562 return;
13563
13564 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13565 return;
13566
13568 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13569 llvm::StringRef ExprStr =
13571
13572 CharSourceRange XorRange =
13574 llvm::StringRef XorStr =
13576 // Do not diagnose if xor keyword/macro is used.
13577 if (XorStr == "xor")
13578 return;
13579
13580 std::string LHSStr = std::string(Lexer::getSourceText(
13581 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13582 S.getSourceManager(), S.getLangOpts()));
13583 std::string RHSStr = std::string(Lexer::getSourceText(
13584 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13585 S.getSourceManager(), S.getLangOpts()));
13586
13587 if (Negative) {
13588 RightSideValue = -RightSideValue;
13589 RHSStr = "-" + RHSStr;
13590 } else if (ExplicitPlus) {
13591 RHSStr = "+" + RHSStr;
13592 }
13593
13594 StringRef LHSStrRef = LHSStr;
13595 StringRef RHSStrRef = RHSStr;
13596 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13597 // literals.
13598 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13599 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13600 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13601 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13602 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13603 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13604 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13605 return;
13606
13607 bool SuggestXor =
13608 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13609 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13610 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13611 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13612 std::string SuggestedExpr = "1 << " + RHSStr;
13613 bool Overflow = false;
13614 llvm::APInt One = (LeftSideValue - 1);
13615 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13616 if (Overflow) {
13617 if (RightSideIntValue < 64)
13618 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13619 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13620 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13621 else if (RightSideIntValue == 64)
13622 S.Diag(Loc, diag::warn_xor_used_as_pow)
13623 << ExprStr << toString(XorValue, 10, true);
13624 else
13625 return;
13626 } else {
13627 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13628 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13629 << toString(PowValue, 10, true)
13631 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13632 }
13633
13634 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13635 << ("0x2 ^ " + RHSStr) << SuggestXor;
13636 } else if (LeftSideValue == 10) {
13637 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13638 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13639 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13640 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13641 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13642 << ("0xA ^ " + RHSStr) << SuggestXor;
13643 }
13644}
13645
13647 SourceLocation Loc,
13648 BinaryOperatorKind Opc) {
13649 // Ensure that either both operands are of the same vector type, or
13650 // one operand is of a vector type and the other is of its element type.
13651 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13652 /*AllowBothBool*/ true,
13653 /*AllowBoolConversions*/ false,
13654 /*AllowBooleanOperation*/ false,
13655 /*ReportInvalid*/ false);
13656 if (vType.isNull())
13657 return InvalidOperands(Loc, LHS, RHS);
13658 if (getLangOpts().OpenCL &&
13659 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13661 return InvalidOperands(Loc, LHS, RHS);
13662 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13663 // usage of the logical operators && and || with vectors in C. This
13664 // check could be notionally dropped.
13665 if (!getLangOpts().CPlusPlus &&
13666 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13667 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13668 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13669 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13670 // `select` functions.
13671 if (getLangOpts().HLSL &&
13672 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13673 (void)InvalidOperands(Loc, LHS, RHS);
13674 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13675 return QualType();
13676 }
13677
13678 return GetSignedVectorType(LHS.get()->getType());
13679}
13680
13682 SourceLocation Loc,
13683 BinaryOperatorKind Opc) {
13684
13685 if (!getLangOpts().HLSL) {
13686 assert(false && "Logical operands are not supported in C\\C++");
13687 return QualType();
13688 }
13689
13690 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13691 (void)InvalidOperands(Loc, LHS, RHS);
13692 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13693 return QualType();
13694 }
13695 SemaRef.Diag(LHS.get()->getBeginLoc(), diag::err_hlsl_langstd_unimplemented)
13696 << getLangOpts().getHLSLVersion();
13697 return QualType();
13698}
13699
13701 SourceLocation Loc,
13702 bool IsCompAssign) {
13703 if (!IsCompAssign) {
13705 if (LHS.isInvalid())
13706 return QualType();
13707 }
13709 if (RHS.isInvalid())
13710 return QualType();
13711
13712 // For conversion purposes, we ignore any qualifiers.
13713 // For example, "const float" and "float" are equivalent.
13714 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13715 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13716
13717 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13718 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13719 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13720
13721 if (Context.hasSameType(LHSType, RHSType))
13722 return Context.getCommonSugaredType(LHSType, RHSType);
13723
13724 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13725 // case we have to return InvalidOperands.
13726 ExprResult OriginalLHS = LHS;
13727 ExprResult OriginalRHS = RHS;
13728 if (LHSMatType && !RHSMatType) {
13729 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13730 if (!RHS.isInvalid())
13731 return LHSType;
13732
13733 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13734 }
13735
13736 if (!LHSMatType && RHSMatType) {
13737 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13738 if (!LHS.isInvalid())
13739 return RHSType;
13740 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13741 }
13742
13743 return InvalidOperands(Loc, LHS, RHS);
13744}
13745
13747 SourceLocation Loc,
13748 bool IsCompAssign) {
13749 if (!IsCompAssign) {
13751 if (LHS.isInvalid())
13752 return QualType();
13753 }
13755 if (RHS.isInvalid())
13756 return QualType();
13757
13758 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13759 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13760 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13761
13762 if (LHSMatType && RHSMatType) {
13763 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13764 return InvalidOperands(Loc, LHS, RHS);
13765
13766 if (Context.hasSameType(LHSMatType, RHSMatType))
13767 return Context.getCommonSugaredType(
13768 LHS.get()->getType().getUnqualifiedType(),
13769 RHS.get()->getType().getUnqualifiedType());
13770
13771 QualType LHSELTy = LHSMatType->getElementType(),
13772 RHSELTy = RHSMatType->getElementType();
13773 if (!Context.hasSameType(LHSELTy, RHSELTy))
13774 return InvalidOperands(Loc, LHS, RHS);
13775
13776 return Context.getConstantMatrixType(
13777 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13778 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13779 }
13780 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13781}
13782
13784 switch (Opc) {
13785 default:
13786 return false;
13787 case BO_And:
13788 case BO_AndAssign:
13789 case BO_Or:
13790 case BO_OrAssign:
13791 case BO_Xor:
13792 case BO_XorAssign:
13793 return true;
13794 }
13795}
13796
13798 SourceLocation Loc,
13799 BinaryOperatorKind Opc) {
13800 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13801
13802 bool IsCompAssign =
13803 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13804
13805 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13806
13807 if (LHS.get()->getType()->isVectorType() ||
13808 RHS.get()->getType()->isVectorType()) {
13809 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13811 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13812 /*AllowBothBool*/ true,
13813 /*AllowBoolConversions*/ getLangOpts().ZVector,
13814 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13815 /*ReportInvalid*/ true);
13816 return InvalidOperands(Loc, LHS, RHS);
13817 }
13818
13819 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13820 RHS.get()->getType()->isSveVLSBuiltinType()) {
13821 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13823 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13825 return InvalidOperands(Loc, LHS, RHS);
13826 }
13827
13828 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13829 RHS.get()->getType()->isSveVLSBuiltinType()) {
13830 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13832 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13834 return InvalidOperands(Loc, LHS, RHS);
13835 }
13836
13837 if (Opc == BO_And)
13838 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13839
13840 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13842 return InvalidOperands(Loc, LHS, RHS);
13843
13844 ExprResult LHSResult = LHS, RHSResult = RHS;
13846 LHSResult, RHSResult, Loc,
13848 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13849 return QualType();
13850 LHS = LHSResult.get();
13851 RHS = RHSResult.get();
13852
13853 if (Opc == BO_Xor)
13854 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13855
13856 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13857 return compType;
13858 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13859 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13860 return ResultTy;
13861}
13862
13863// C99 6.5.[13,14]
13865 SourceLocation Loc,
13866 BinaryOperatorKind Opc) {
13867 // Check vector operands differently.
13868 if (LHS.get()->getType()->isVectorType() ||
13869 RHS.get()->getType()->isVectorType())
13870 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13871
13872 if (LHS.get()->getType()->isConstantMatrixType() ||
13873 RHS.get()->getType()->isConstantMatrixType())
13874 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13875
13876 bool EnumConstantInBoolContext = false;
13877 for (const ExprResult &HS : {LHS, RHS}) {
13878 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13879 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13880 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13881 EnumConstantInBoolContext = true;
13882 }
13883 }
13884
13885 if (EnumConstantInBoolContext)
13886 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13887
13888 // WebAssembly tables can't be used with logical operators.
13889 QualType LHSTy = LHS.get()->getType();
13890 QualType RHSTy = RHS.get()->getType();
13891 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13892 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13893 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13894 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13895 return InvalidOperands(Loc, LHS, RHS);
13896 }
13897
13898 // Diagnose cases where the user write a logical and/or but probably meant a
13899 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13900 // is a constant.
13901 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13902 !LHS.get()->getType()->isBooleanType() &&
13903 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13904 // Don't warn in macros or template instantiations.
13905 !Loc.isMacroID() && !inTemplateInstantiation()) {
13906 // If the RHS can be constant folded, and if it constant folds to something
13907 // that isn't 0 or 1 (which indicate a potential logical operation that
13908 // happened to fold to true/false) then warn.
13909 // Parens on the RHS are ignored.
13910 Expr::EvalResult EVResult;
13911 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13912 llvm::APSInt Result = EVResult.Val.getInt();
13913 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13914 !RHS.get()->getExprLoc().isMacroID()) ||
13915 (Result != 0 && Result != 1)) {
13916 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13917 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13918 // Suggest replacing the logical operator with the bitwise version
13919 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13920 << (Opc == BO_LAnd ? "&" : "|")
13923 Opc == BO_LAnd ? "&" : "|");
13924 if (Opc == BO_LAnd)
13925 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13926 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13929 RHS.get()->getEndLoc()));
13930 }
13931 }
13932 }
13933
13934 if (!Context.getLangOpts().CPlusPlus) {
13935 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13936 // not operate on the built-in scalar and vector float types.
13937 if (Context.getLangOpts().OpenCL &&
13938 Context.getLangOpts().OpenCLVersion < 120) {
13939 if (LHS.get()->getType()->isFloatingType() ||
13940 RHS.get()->getType()->isFloatingType())
13941 return InvalidOperands(Loc, LHS, RHS);
13942 }
13943
13944 LHS = UsualUnaryConversions(LHS.get());
13945 if (LHS.isInvalid())
13946 return QualType();
13947
13948 RHS = UsualUnaryConversions(RHS.get());
13949 if (RHS.isInvalid())
13950 return QualType();
13951
13952 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
13954 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
13956
13957 if (!LHS.get()->getType()->isScalarType() ||
13958 !RHS.get()->getType()->isScalarType())
13959 return InvalidOperands(Loc, LHS, RHS);
13960
13961 return Context.IntTy;
13962 }
13963
13964 // The following is safe because we only use this method for
13965 // non-overloadable operands.
13966
13967 // C++ [expr.log.and]p1
13968 // C++ [expr.log.or]p1
13969 // The operands are both contextually converted to type bool.
13971 if (LHSRes.isInvalid()) {
13972 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13973 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13974 return ResultTy;
13975 }
13976 LHS = LHSRes;
13977
13979 if (RHSRes.isInvalid()) {
13980 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13981 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13982 return ResultTy;
13983 }
13984 RHS = RHSRes;
13985
13986 // C++ [expr.log.and]p2
13987 // C++ [expr.log.or]p2
13988 // The result is a bool.
13989 return Context.BoolTy;
13990}
13991
13992static bool IsReadonlyMessage(Expr *E, Sema &S) {
13993 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13994 if (!ME) return false;
13995 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13996 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13998 if (!Base) return false;
13999 return Base->getMethodDecl() != nullptr;
14000}
14001
14002/// Is the given expression (which must be 'const') a reference to a
14003/// variable which was originally non-const, but which has become
14004/// 'const' due to being captured within a block?
14007 assert(E->isLValue() && E->getType().isConstQualified());
14008 E = E->IgnoreParens();
14009
14010 // Must be a reference to a declaration from an enclosing scope.
14011 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14012 if (!DRE) return NCCK_None;
14014
14015 ValueDecl *Value = DRE->getDecl();
14016
14017 // The declaration must be a value which is not declared 'const'.
14019 return NCCK_None;
14020
14021 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
14022 if (Binding) {
14023 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14024 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14025 return NCCK_Lambda;
14026 }
14027
14028 VarDecl *Var = dyn_cast<VarDecl>(Value);
14029 if (!Var)
14030 return NCCK_None;
14031 if (Var->getType()->isReferenceType())
14032 return NCCK_None;
14033
14034 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14035
14036 // Decide whether the first capture was for a block or a lambda.
14037 DeclContext *DC = S.CurContext, *Prev = nullptr;
14038 // Decide whether the first capture was for a block or a lambda.
14039 while (DC) {
14040 // For init-capture, it is possible that the variable belongs to the
14041 // template pattern of the current context.
14042 if (auto *FD = dyn_cast<FunctionDecl>(DC))
14043 if (Var->isInitCapture() &&
14044 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14045 break;
14046 if (DC == Var->getDeclContext())
14047 break;
14048 Prev = DC;
14049 DC = DC->getParent();
14050 }
14051 // Unless we have an init-capture, we've gone one step too far.
14052 if (!Var->isInitCapture())
14053 DC = Prev;
14054 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
14055}
14056
14057static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14058 Ty = Ty.getNonReferenceType();
14059 if (IsDereference && Ty->isPointerType())
14060 Ty = Ty->getPointeeType();
14061 return !Ty.isConstQualified();
14062}
14063
14064// Update err_typecheck_assign_const and note_typecheck_assign_const
14065// when this enum is changed.
14066enum {
14071 ConstUnknown, // Keep as last element
14072};
14073
14074/// Emit the "read-only variable not assignable" error and print notes to give
14075/// more information about why the variable is not assignable, such as pointing
14076/// to the declaration of a const variable, showing that a method is const, or
14077/// that the function is returning a const reference.
14078static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14079 SourceLocation Loc) {
14080 SourceRange ExprRange = E->getSourceRange();
14081
14082 // Only emit one error on the first const found. All other consts will emit
14083 // a note to the error.
14084 bool DiagnosticEmitted = false;
14085
14086 // Track if the current expression is the result of a dereference, and if the
14087 // next checked expression is the result of a dereference.
14088 bool IsDereference = false;
14089 bool NextIsDereference = false;
14090
14091 // Loop to process MemberExpr chains.
14092 while (true) {
14093 IsDereference = NextIsDereference;
14094
14096 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14097 NextIsDereference = ME->isArrow();
14098 const ValueDecl *VD = ME->getMemberDecl();
14099 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14100 // Mutable fields can be modified even if the class is const.
14101 if (Field->isMutable()) {
14102 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14103 break;
14104 }
14105
14106 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14107 if (!DiagnosticEmitted) {
14108 S.Diag(Loc, diag::err_typecheck_assign_const)
14109 << ExprRange << ConstMember << false /*static*/ << Field
14110 << Field->getType();
14111 DiagnosticEmitted = true;
14112 }
14113 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14114 << ConstMember << false /*static*/ << Field << Field->getType()
14115 << Field->getSourceRange();
14116 }
14117 E = ME->getBase();
14118 continue;
14119 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14120 if (VDecl->getType().isConstQualified()) {
14121 if (!DiagnosticEmitted) {
14122 S.Diag(Loc, diag::err_typecheck_assign_const)
14123 << ExprRange << ConstMember << true /*static*/ << VDecl
14124 << VDecl->getType();
14125 DiagnosticEmitted = true;
14126 }
14127 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14128 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14129 << VDecl->getSourceRange();
14130 }
14131 // Static fields do not inherit constness from parents.
14132 break;
14133 }
14134 break; // End MemberExpr
14135 } else if (const ArraySubscriptExpr *ASE =
14136 dyn_cast<ArraySubscriptExpr>(E)) {
14137 E = ASE->getBase()->IgnoreParenImpCasts();
14138 continue;
14139 } else if (const ExtVectorElementExpr *EVE =
14140 dyn_cast<ExtVectorElementExpr>(E)) {
14141 E = EVE->getBase()->IgnoreParenImpCasts();
14142 continue;
14143 }
14144 break;
14145 }
14146
14147 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14148 // Function calls
14149 const FunctionDecl *FD = CE->getDirectCallee();
14150 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14151 if (!DiagnosticEmitted) {
14152 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14153 << ConstFunction << FD;
14154 DiagnosticEmitted = true;
14155 }
14157 diag::note_typecheck_assign_const)
14158 << ConstFunction << FD << FD->getReturnType()
14159 << FD->getReturnTypeSourceRange();
14160 }
14161 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14162 // Point to variable declaration.
14163 if (const ValueDecl *VD = DRE->getDecl()) {
14164 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14165 if (!DiagnosticEmitted) {
14166 S.Diag(Loc, diag::err_typecheck_assign_const)
14167 << ExprRange << ConstVariable << VD << VD->getType();
14168 DiagnosticEmitted = true;
14169 }
14170 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14171 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14172 }
14173 }
14174 } else if (isa<CXXThisExpr>(E)) {
14175 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14176 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14177 if (MD->isConst()) {
14178 if (!DiagnosticEmitted) {
14179 S.Diag(Loc, diag::err_typecheck_assign_const_method)
14180 << ExprRange << MD;
14181 DiagnosticEmitted = true;
14182 }
14183 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const_method)
14184 << MD << MD->getSourceRange();
14185 }
14186 }
14187 }
14188 }
14189
14190 if (DiagnosticEmitted)
14191 return;
14192
14193 // Can't determine a more specific message, so display the generic error.
14194 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14195}
14196
14202
14204 const RecordType *Ty,
14205 SourceLocation Loc, SourceRange Range,
14206 OriginalExprKind OEK,
14207 bool &DiagnosticEmitted) {
14208 std::vector<const RecordType *> RecordTypeList;
14209 RecordTypeList.push_back(Ty);
14210 unsigned NextToCheckIndex = 0;
14211 // We walk the record hierarchy breadth-first to ensure that we print
14212 // diagnostics in field nesting order.
14213 while (RecordTypeList.size() > NextToCheckIndex) {
14214 bool IsNested = NextToCheckIndex > 0;
14215 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14216 ->getDecl()
14218 ->fields()) {
14219 // First, check every field for constness.
14220 QualType FieldTy = Field->getType();
14221 if (FieldTy.isConstQualified()) {
14222 if (!DiagnosticEmitted) {
14223 S.Diag(Loc, diag::err_typecheck_assign_const)
14224 << Range << NestedConstMember << OEK << VD
14225 << IsNested << Field;
14226 DiagnosticEmitted = true;
14227 }
14228 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14229 << NestedConstMember << IsNested << Field
14230 << FieldTy << Field->getSourceRange();
14231 }
14232
14233 // Then we append it to the list to check next in order.
14234 FieldTy = FieldTy.getCanonicalType();
14235 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14236 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14237 RecordTypeList.push_back(FieldRecTy);
14238 }
14239 }
14240 ++NextToCheckIndex;
14241 }
14242}
14243
14244/// Emit an error for the case where a record we are trying to assign to has a
14245/// const-qualified field somewhere in its hierarchy.
14246static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14247 SourceLocation Loc) {
14248 QualType Ty = E->getType();
14249 assert(Ty->isRecordType() && "lvalue was not record?");
14250 SourceRange Range = E->getSourceRange();
14251 const auto *RTy = Ty->getAsCanonical<RecordType>();
14252 bool DiagEmitted = false;
14253
14254 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14255 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14256 Range, OEK_Member, DiagEmitted);
14257 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14258 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14259 Range, OEK_Variable, DiagEmitted);
14260 else
14261 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14262 Range, OEK_LValue, DiagEmitted);
14263 if (!DiagEmitted)
14264 DiagnoseConstAssignment(S, E, Loc);
14265}
14266
14267/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14268/// emit an error and return true. If so, return false.
14270 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14271
14273
14274 SourceLocation OrigLoc = Loc;
14276 &Loc);
14277 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14279 if (IsLV == Expr::MLV_Valid)
14280 return false;
14281
14282 unsigned DiagID = 0;
14283 bool NeedType = false;
14284 switch (IsLV) { // C99 6.5.16p2
14286 // Use a specialized diagnostic when we're assigning to an object
14287 // from an enclosing function or block.
14289 if (NCCK == NCCK_Block)
14290 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14291 else
14292 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14293 break;
14294 }
14295
14296 // In ARC, use some specialized diagnostics for occasions where we
14297 // infer 'const'. These are always pseudo-strong variables.
14298 if (S.getLangOpts().ObjCAutoRefCount) {
14299 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14300 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14301 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14302
14303 // Use the normal diagnostic if it's pseudo-__strong but the
14304 // user actually wrote 'const'.
14305 if (var->isARCPseudoStrong() &&
14306 (!var->getTypeSourceInfo() ||
14307 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14308 // There are three pseudo-strong cases:
14309 // - self
14310 ObjCMethodDecl *method = S.getCurMethodDecl();
14311 if (method && var == method->getSelfDecl()) {
14312 DiagID = method->isClassMethod()
14313 ? diag::err_typecheck_arc_assign_self_class_method
14314 : diag::err_typecheck_arc_assign_self;
14315
14316 // - Objective-C externally_retained attribute.
14317 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14318 isa<ParmVarDecl>(var)) {
14319 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14320
14321 // - fast enumeration variables
14322 } else {
14323 DiagID = diag::err_typecheck_arr_assign_enumeration;
14324 }
14325
14326 SourceRange Assign;
14327 if (Loc != OrigLoc)
14328 Assign = SourceRange(OrigLoc, OrigLoc);
14329 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14330 // We need to preserve the AST regardless, so migration tool
14331 // can do its job.
14332 return false;
14333 }
14334 }
14335 }
14336
14337 // If none of the special cases above are triggered, then this is a
14338 // simple const assignment.
14339 if (DiagID == 0) {
14340 DiagnoseConstAssignment(S, E, Loc);
14341 return true;
14342 }
14343
14344 break;
14346 DiagnoseConstAssignment(S, E, Loc);
14347 return true;
14350 return true;
14353 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14354 NeedType = true;
14355 break;
14357 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14358 NeedType = true;
14359 break;
14361 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14362 break;
14363 case Expr::MLV_Valid:
14364 llvm_unreachable("did not take early return for MLV_Valid");
14368 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14369 break;
14372 return S.RequireCompleteType(Loc, E->getType(),
14373 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14375 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14376 break;
14378 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14379 break;
14381 llvm_unreachable("readonly properties should be processed differently");
14383 DiagID = diag::err_readonly_message_assignment;
14384 break;
14386 DiagID = diag::err_no_subobject_property_setting;
14387 break;
14388 }
14389
14390 SourceRange Assign;
14391 if (Loc != OrigLoc)
14392 Assign = SourceRange(OrigLoc, OrigLoc);
14393 if (NeedType)
14394 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14395 else
14396 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14397 return true;
14398}
14399
14400static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14401 SourceLocation Loc,
14402 Sema &Sema) {
14404 return;
14406 return;
14407 if (Loc.isInvalid() || Loc.isMacroID())
14408 return;
14409 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14410 return;
14411
14412 // C / C++ fields
14413 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14414 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14415 if (ML && MR) {
14416 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14417 return;
14418 const ValueDecl *LHSDecl =
14420 const ValueDecl *RHSDecl =
14422 if (LHSDecl != RHSDecl)
14423 return;
14424 if (LHSDecl->getType().isVolatileQualified())
14425 return;
14426 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14427 if (RefTy->getPointeeType().isVolatileQualified())
14428 return;
14429
14430 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14431 }
14432
14433 // Objective-C instance variables
14434 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14435 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14436 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14437 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14438 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14439 if (RL && RR && RL->getDecl() == RR->getDecl())
14440 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14441 }
14442}
14443
14444// C99 6.5.16.1
14446 SourceLocation Loc,
14447 QualType CompoundType,
14448 BinaryOperatorKind Opc) {
14449 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14450
14451 // Verify that LHS is a modifiable lvalue, and emit error if not.
14452 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14453 return QualType();
14454
14455 QualType LHSType = LHSExpr->getType();
14456 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14457 CompoundType;
14458
14459 if (RHS.isUsable()) {
14460 // Even if this check fails don't return early to allow the best
14461 // possible error recovery and to allow any subsequent diagnostics to
14462 // work.
14463 const ValueDecl *Assignee = nullptr;
14464 bool ShowFullyQualifiedAssigneeName = false;
14465 // In simple cases describe what is being assigned to
14466 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14467 Assignee = DR->getDecl();
14468 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14469 Assignee = ME->getMemberDecl();
14470 ShowFullyQualifiedAssigneeName = true;
14471 }
14472
14474 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14475 ShowFullyQualifiedAssigneeName);
14476 }
14477
14478 // OpenCL v1.2 s6.1.1.1 p2:
14479 // The half data type can only be used to declare a pointer to a buffer that
14480 // contains half values
14481 if (getLangOpts().OpenCL &&
14482 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14483 LHSType->isHalfType()) {
14484 Diag(Loc, diag::err_opencl_half_load_store) << 1
14485 << LHSType.getUnqualifiedType();
14486 return QualType();
14487 }
14488
14489 // WebAssembly tables can't be used on RHS of an assignment expression.
14490 if (RHSType->isWebAssemblyTableType()) {
14491 Diag(Loc, diag::err_wasm_table_art) << 0;
14492 return QualType();
14493 }
14494
14495 AssignConvertType ConvTy;
14496 if (CompoundType.isNull()) {
14497 Expr *RHSCheck = RHS.get();
14498
14499 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14500
14501 QualType LHSTy(LHSType);
14502 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14503 if (RHS.isInvalid())
14504 return QualType();
14505 // Special case of NSObject attributes on c-style pointer types.
14507 ((Context.isObjCNSObjectType(LHSType) &&
14508 RHSType->isObjCObjectPointerType()) ||
14509 (Context.isObjCNSObjectType(RHSType) &&
14510 LHSType->isObjCObjectPointerType())))
14512
14513 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14514 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14515
14516 // If the RHS is a unary plus or minus, check to see if they = and + are
14517 // right next to each other. If so, the user may have typo'd "x =+ 4"
14518 // instead of "x += 4".
14519 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14520 RHSCheck = ICE->getSubExpr();
14521 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14522 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14523 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14524 // Only if the two operators are exactly adjacent.
14525 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14526 // And there is a space or other character before the subexpr of the
14527 // unary +/-. We don't want to warn on "x=-1".
14528 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14529 UO->getSubExpr()->getBeginLoc().isFileID()) {
14530 Diag(Loc, diag::warn_not_compound_assign)
14531 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14532 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14533 }
14534 }
14535
14536 if (IsAssignConvertCompatible(ConvTy)) {
14537 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14538 // Warn about retain cycles where a block captures the LHS, but
14539 // not if the LHS is a simple variable into which the block is
14540 // being stored...unless that variable can be captured by reference!
14541 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14542 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14543 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14544 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14545 }
14546
14547 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14549 // It is safe to assign a weak reference into a strong variable.
14550 // Although this code can still have problems:
14551 // id x = self.weakProp;
14552 // id y = self.weakProp;
14553 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14554 // paths through the function. This should be revisited if
14555 // -Wrepeated-use-of-weak is made flow-sensitive.
14556 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14557 // variable, which will be valid for the current autorelease scope.
14558 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14559 RHS.get()->getBeginLoc()))
14561
14562 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14563 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14564 }
14565 }
14566 } else {
14567 // Compound assignment "x += y"
14568 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14569 }
14570
14571 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14573 return QualType();
14574
14575 CheckForNullPointerDereference(*this, LHSExpr);
14576
14577 AssignedEntity AE{LHSExpr};
14578 checkAssignmentLifetime(*this, AE, RHS.get());
14579
14580 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14581 if (CompoundType.isNull()) {
14582 // C++2a [expr.ass]p5:
14583 // A simple-assignment whose left operand is of a volatile-qualified
14584 // type is deprecated unless the assignment is either a discarded-value
14585 // expression or an unevaluated operand
14586 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14587 }
14588 }
14589
14590 // C11 6.5.16p3: The type of an assignment expression is the type of the
14591 // left operand would have after lvalue conversion.
14592 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14593 // qualified type, the value has the unqualified version of the type of the
14594 // lvalue; additionally, if the lvalue has atomic type, the value has the
14595 // non-atomic version of the type of the lvalue.
14596 // C++ 5.17p1: the type of the assignment expression is that of its left
14597 // operand.
14598 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14599}
14600
14601// Scenarios to ignore if expression E is:
14602// 1. an explicit cast expression into void
14603// 2. a function call expression that returns void
14604static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14605 E = E->IgnoreParens();
14606
14607 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14608 if (CE->getCastKind() == CK_ToVoid) {
14609 return true;
14610 }
14611
14612 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14613 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14614 CE->getSubExpr()->getType()->isDependentType()) {
14615 return true;
14616 }
14617 }
14618
14619 if (const auto *CE = dyn_cast<CallExpr>(E))
14620 return CE->getCallReturnType(Context)->isVoidType();
14621 return false;
14622}
14623
14625 // No warnings in macros
14626 if (Loc.isMacroID())
14627 return;
14628
14629 // Don't warn in template instantiations.
14631 return;
14632
14633 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14634 // instead, skip more than needed, then call back into here with the
14635 // CommaVisitor in SemaStmt.cpp.
14636 // The listed locations are the initialization and increment portions
14637 // of a for loop. The additional checks are on the condition of
14638 // if statements, do/while loops, and for loops.
14639 // Differences in scope flags for C89 mode requires the extra logic.
14640 const unsigned ForIncrementFlags =
14641 getLangOpts().C99 || getLangOpts().CPlusPlus
14644 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14645 const unsigned ScopeFlags = getCurScope()->getFlags();
14646 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14647 (ScopeFlags & ForInitFlags) == ForInitFlags)
14648 return;
14649
14650 // If there are multiple comma operators used together, get the RHS of the
14651 // of the comma operator as the LHS.
14652 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14653 if (BO->getOpcode() != BO_Comma)
14654 break;
14655 LHS = BO->getRHS();
14656 }
14657
14658 // Only allow some expressions on LHS to not warn.
14659 if (IgnoreCommaOperand(LHS, Context))
14660 return;
14661
14662 Diag(Loc, diag::warn_comma_operator);
14663 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14664 << LHS->getSourceRange()
14666 LangOpts.CPlusPlus ? "static_cast<void>("
14667 : "(void)(")
14668 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14669 ")");
14670}
14671
14672// C99 6.5.17
14674 SourceLocation Loc) {
14675 LHS = S.CheckPlaceholderExpr(LHS.get());
14676 RHS = S.CheckPlaceholderExpr(RHS.get());
14677 if (LHS.isInvalid() || RHS.isInvalid())
14678 return QualType();
14679
14680 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14681 // operands, but not unary promotions.
14682 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14683
14684 // So we treat the LHS as a ignored value, and in C++ we allow the
14685 // containing site to determine what should be done with the RHS.
14686 LHS = S.IgnoredValueConversions(LHS.get());
14687 if (LHS.isInvalid())
14688 return QualType();
14689
14690 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14691
14692 if (!S.getLangOpts().CPlusPlus) {
14694 if (RHS.isInvalid())
14695 return QualType();
14696 if (!RHS.get()->getType()->isVoidType())
14697 S.RequireCompleteType(Loc, RHS.get()->getType(),
14698 diag::err_incomplete_type);
14699 }
14700
14701 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14702 S.DiagnoseCommaOperator(LHS.get(), Loc);
14703
14704 return RHS.get()->getType();
14705}
14706
14707/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14708/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14711 ExprObjectKind &OK,
14712 SourceLocation OpLoc, bool IsInc,
14713 bool IsPrefix) {
14714 QualType ResType = Op->getType();
14715 // Atomic types can be used for increment / decrement where the non-atomic
14716 // versions can, so ignore the _Atomic() specifier for the purpose of
14717 // checking.
14718 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14719 ResType = ResAtomicType->getValueType();
14720
14721 assert(!ResType.isNull() && "no type for increment/decrement expression");
14722
14723 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14724 // Decrement of bool is not allowed.
14725 if (!IsInc) {
14726 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14727 return QualType();
14728 }
14729 // Increment of bool sets it to true, but is deprecated.
14730 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14731 : diag::warn_increment_bool)
14732 << Op->getSourceRange();
14733 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14734 // Error on enum increments and decrements in C++ mode
14735 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14736 return QualType();
14737 } else if (ResType->isRealType()) {
14738 // OK!
14739 } else if (ResType->isPointerType()) {
14740 // C99 6.5.2.4p2, 6.5.6p2
14741 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14742 return QualType();
14743 } else if (ResType->isOverflowBehaviorType()) {
14744 // OK!
14745 } else if (ResType->isObjCObjectPointerType()) {
14746 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14747 // Otherwise, we just need a complete type.
14748 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14749 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14750 return QualType();
14751 } else if (ResType->isAnyComplexType()) {
14752 // C99 does not support ++/-- on complex types, we allow as an extension.
14753 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14754 : diag::ext_c2y_increment_complex)
14755 << IsInc << Op->getSourceRange();
14756 } else if (ResType->isPlaceholderType()) {
14758 if (PR.isInvalid()) return QualType();
14759 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14760 IsInc, IsPrefix);
14761 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14762 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14763 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14764 (ResType->castAs<VectorType>()->getVectorKind() !=
14766 // The z vector extensions allow ++ and -- for non-bool vectors.
14767 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14768 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14769 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14770 } else {
14771 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14772 << ResType << int(IsInc) << Op->getSourceRange();
14773 return QualType();
14774 }
14775 // At this point, we know we have a real, complex or pointer type.
14776 // Now make sure the operand is a modifiable lvalue.
14777 if (CheckForModifiableLvalue(Op, OpLoc, S))
14778 return QualType();
14779 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14780 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14781 // An operand with volatile-qualified type is deprecated
14782 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14783 << IsInc << ResType;
14784 }
14785 // In C++, a prefix increment is the same type as the operand. Otherwise
14786 // (in C or with postfix), the increment is the unqualified type of the
14787 // operand.
14788 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14789 VK = VK_LValue;
14790 OK = Op->getObjectKind();
14791 return ResType;
14792 } else {
14793 VK = VK_PRValue;
14794 return ResType.getUnqualifiedType();
14795 }
14796}
14797
14798/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14799/// This routine allows us to typecheck complex/recursive expressions
14800/// where the declaration is needed for type checking. We only need to
14801/// handle cases when the expression references a function designator
14802/// or is an lvalue. Here are some examples:
14803/// - &(x) => x
14804/// - &*****f => f for f a function designator.
14805/// - &s.xx => s
14806/// - &s.zz[1].yy -> s, if zz is an array
14807/// - *(x + 1) -> x, if x is an array
14808/// - &"123"[2] -> 0
14809/// - & __real__ x -> x
14810///
14811/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14812/// members.
14814 switch (E->getStmtClass()) {
14815 case Stmt::DeclRefExprClass:
14816 return cast<DeclRefExpr>(E)->getDecl();
14817 case Stmt::MemberExprClass:
14818 // If this is an arrow operator, the address is an offset from
14819 // the base's value, so the object the base refers to is
14820 // irrelevant.
14821 if (cast<MemberExpr>(E)->isArrow())
14822 return nullptr;
14823 // Otherwise, the expression refers to a part of the base
14824 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14825 case Stmt::ArraySubscriptExprClass: {
14826 // FIXME: This code shouldn't be necessary! We should catch the implicit
14827 // promotion of register arrays earlier.
14828 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14829 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14830 if (ICE->getSubExpr()->getType()->isArrayType())
14831 return getPrimaryDecl(ICE->getSubExpr());
14832 }
14833 return nullptr;
14834 }
14835 case Stmt::UnaryOperatorClass: {
14837
14838 switch(UO->getOpcode()) {
14839 case UO_Real:
14840 case UO_Imag:
14841 case UO_Extension:
14842 return getPrimaryDecl(UO->getSubExpr());
14843 default:
14844 return nullptr;
14845 }
14846 }
14847 case Stmt::ParenExprClass:
14848 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14849 case Stmt::ImplicitCastExprClass:
14850 // If the result of an implicit cast is an l-value, we care about
14851 // the sub-expression; otherwise, the result here doesn't matter.
14852 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14853 case Stmt::CXXUuidofExprClass:
14854 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14855 default:
14856 return nullptr;
14857 }
14858}
14859
14860namespace {
14861enum {
14862 AO_Bit_Field = 0,
14863 AO_Vector_Element = 1,
14864 AO_Property_Expansion = 2,
14865 AO_Register_Variable = 3,
14866 AO_Matrix_Element = 4,
14867 AO_No_Error = 5
14868};
14869}
14870/// Diagnose invalid operand for address of operations.
14871///
14872/// \param Type The type of operand which cannot have its address taken.
14874 Expr *E, unsigned Type) {
14875 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14876}
14877
14879 const Expr *Op,
14880 const CXXMethodDecl *MD) {
14881 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14882
14883 if (Op != DRE)
14884 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14885 << Op->getSourceRange();
14886
14887 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14888 if (isa<CXXDestructorDecl>(MD))
14889 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14890 << DRE->getSourceRange();
14891
14892 if (DRE->getQualifier())
14893 return false;
14894
14895 if (MD->getParent()->getName().empty())
14896 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14897 << DRE->getSourceRange();
14898
14899 SmallString<32> Str;
14900 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14901 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14902 << DRE->getSourceRange()
14903 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14904}
14905
14907 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14908 if (PTy->getKind() == BuiltinType::Overload) {
14909 Expr *E = OrigOp.get()->IgnoreParens();
14910 if (!isa<OverloadExpr>(E)) {
14911 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14912 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14913 << OrigOp.get()->getSourceRange();
14914 return QualType();
14915 }
14916
14920 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14921 << OrigOp.get()->getSourceRange();
14922 return QualType();
14923 }
14924
14925 return Context.OverloadTy;
14926 }
14927
14928 if (PTy->getKind() == BuiltinType::UnknownAny)
14929 return Context.UnknownAnyTy;
14930
14931 if (PTy->getKind() == BuiltinType::BoundMember) {
14932 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14933 << OrigOp.get()->getSourceRange();
14934 return QualType();
14935 }
14936
14937 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14938 if (OrigOp.isInvalid()) return QualType();
14939 }
14940
14941 if (OrigOp.get()->isTypeDependent())
14942 return Context.DependentTy;
14943
14944 assert(!OrigOp.get()->hasPlaceholderType());
14945
14946 // Make sure to ignore parentheses in subsequent checks
14947 Expr *op = OrigOp.get()->IgnoreParens();
14948
14949 // In OpenCL captures for blocks called as lambda functions
14950 // are located in the private address space. Blocks used in
14951 // enqueue_kernel can be located in a different address space
14952 // depending on a vendor implementation. Thus preventing
14953 // taking an address of the capture to avoid invalid AS casts.
14954 if (LangOpts.OpenCL) {
14955 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14956 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14957 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14958 return QualType();
14959 }
14960 }
14961
14962 if (getLangOpts().C99) {
14963 // Implement C99-only parts of addressof rules.
14964 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14965 if (uOp->getOpcode() == UO_Deref)
14966 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14967 // (assuming the deref expression is valid).
14968 return uOp->getSubExpr()->getType();
14969 }
14970 // Technically, there should be a check for array subscript
14971 // expressions here, but the result of one is always an lvalue anyway.
14972 }
14973 ValueDecl *dcl = getPrimaryDecl(op);
14974
14975 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14976 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14977 op->getBeginLoc()))
14978 return QualType();
14979
14981 unsigned AddressOfError = AO_No_Error;
14982
14983 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14984 bool IsError = isSFINAEContext();
14985 Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary
14986 : diag::ext_typecheck_addrof_temporary)
14987 << op->getType() << op->getSourceRange();
14988 if (IsError)
14989 return QualType();
14990 // Materialize the temporary as an lvalue so that we can take its address.
14991 OrigOp = op =
14992 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14993 } else if (isa<ObjCSelectorExpr>(op)) {
14994 return Context.getPointerType(op->getType());
14995 } else if (lval == Expr::LV_MemberFunction) {
14996 // If it's an instance method, make a member pointer.
14997 // The expression must have exactly the form &A::foo.
14998
14999 // If the underlying expression isn't a decl ref, give up.
15000 if (!isa<DeclRefExpr>(op)) {
15001 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15002 << OrigOp.get()->getSourceRange();
15003 return QualType();
15004 }
15005 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
15007
15008 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15009 QualType MPTy = Context.getMemberPointerType(
15010 op->getType(), DRE->getQualifier(), MD->getParent());
15011
15012 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15013 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15014 // When pointer authentication is enabled, argument and return types of
15015 // vitual member functions must be complete. This is because vitrual
15016 // member function pointers are implemented using virtual dispatch
15017 // thunks and the thunks cannot be emitted if the argument or return
15018 // types are incomplete.
15019 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15020 SourceLocation DeclRefLoc,
15021 SourceLocation RetArgTypeLoc) {
15022 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
15023 Diag(DeclRefLoc,
15024 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15025 Diag(RetArgTypeLoc,
15026 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15027 << T;
15028 return true;
15029 }
15030 return false;
15031 };
15032 QualType RetTy = MD->getReturnType();
15033 bool IsIncomplete =
15034 !RetTy->isVoidType() &&
15035 ReturnOrParamTypeIsIncomplete(
15036 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15037 for (auto *PVD : MD->parameters())
15038 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15039 PVD->getBeginLoc());
15040 if (IsIncomplete)
15041 return QualType();
15042 }
15043
15044 // Under the MS ABI, lock down the inheritance model now.
15045 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15046 (void)isCompleteType(OpLoc, MPTy);
15047 return MPTy;
15048 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15049 // C99 6.5.3.2p1
15050 // The operand must be either an l-value or a function designator
15051 if (!op->getType()->isFunctionType()) {
15052 // Use a special diagnostic for loads from property references.
15053 if (isa<PseudoObjectExpr>(op)) {
15054 AddressOfError = AO_Property_Expansion;
15055 } else {
15056 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15057 << op->getType() << op->getSourceRange();
15058 return QualType();
15059 }
15060 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
15061 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
15062 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15063 }
15064
15065 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15066 // The operand cannot be a bit-field
15067 AddressOfError = AO_Bit_Field;
15068 } else if (op->getObjectKind() == OK_VectorComponent) {
15069 // The operand cannot be an element of a vector
15070 AddressOfError = AO_Vector_Element;
15071 } else if (op->getObjectKind() == OK_MatrixComponent) {
15072 // The operand cannot be an element of a matrix.
15073 AddressOfError = AO_Matrix_Element;
15074 } else if (dcl) { // C99 6.5.3.2p1
15075 // We have an lvalue with a decl. Make sure the decl is not declared
15076 // with the register storage-class specifier.
15077 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15078 // in C++ it is not error to take address of a register
15079 // variable (c++03 7.1.1P3)
15080 if (vd->getStorageClass() == SC_Register &&
15082 AddressOfError = AO_Register_Variable;
15083 }
15084 } else if (isa<MSPropertyDecl>(dcl)) {
15085 AddressOfError = AO_Property_Expansion;
15086 } else if (isa<FunctionTemplateDecl>(dcl)) {
15087 return Context.OverloadTy;
15088 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15089 // Okay: we can take the address of a field.
15090 // Could be a pointer to member, though, if there is an explicit
15091 // scope qualifier for the class.
15092
15093 // [C++26] [expr.prim.id.general]
15094 // If an id-expression E denotes a non-static non-type member
15095 // of some class C [...] and if E is a qualified-id, E is
15096 // not the un-parenthesized operand of the unary & operator [...]
15097 // the id-expression is transformed into a class member access expression.
15098 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
15099 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
15100 DeclContext *Ctx = dcl->getDeclContext();
15101 if (Ctx && Ctx->isRecord()) {
15102 if (dcl->getType()->isReferenceType()) {
15103 Diag(OpLoc,
15104 diag::err_cannot_form_pointer_to_member_of_reference_type)
15105 << dcl->getDeclName() << dcl->getType();
15106 return QualType();
15107 }
15108
15109 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15110 Ctx = Ctx->getParent();
15111
15112 QualType MPTy = Context.getMemberPointerType(
15113 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
15114 // Under the MS ABI, lock down the inheritance model now.
15115 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15116 (void)isCompleteType(OpLoc, MPTy);
15117 return MPTy;
15118 }
15119 }
15123 llvm_unreachable("Unknown/unexpected decl type");
15124 }
15125
15126 if (AddressOfError != AO_No_Error) {
15127 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15128 return QualType();
15129 }
15130
15131 if (lval == Expr::LV_IncompleteVoidType) {
15132 // Taking the address of a void variable is technically illegal, but we
15133 // allow it in cases which are otherwise valid.
15134 // Example: "extern void x; void* y = &x;".
15135 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15136 }
15137
15138 // If the operand has type "type", the result has type "pointer to type".
15139 if (op->getType()->isObjCObjectType())
15140 return Context.getObjCObjectPointerType(op->getType());
15141
15142 // Cannot take the address of WebAssembly references or tables.
15143 if (Context.getTargetInfo().getTriple().isWasm()) {
15144 QualType OpTy = op->getType();
15145 if (OpTy.isWebAssemblyReferenceType()) {
15146 Diag(OpLoc, diag::err_wasm_ca_reference)
15147 << 1 << OrigOp.get()->getSourceRange();
15148 return QualType();
15149 }
15150 if (OpTy->isWebAssemblyTableType()) {
15151 Diag(OpLoc, diag::err_wasm_table_pr)
15152 << 1 << OrigOp.get()->getSourceRange();
15153 return QualType();
15154 }
15155 }
15156
15157 CheckAddressOfPackedMember(op);
15158
15159 return Context.getPointerType(op->getType());
15160}
15161
15162static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15163 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15164 if (!DRE)
15165 return;
15166 const Decl *D = DRE->getDecl();
15167 if (!D)
15168 return;
15169 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15170 if (!Param)
15171 return;
15172 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15173 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15174 return;
15175 if (FunctionScopeInfo *FD = S.getCurFunction())
15176 FD->ModifiedNonNullParams.insert(Param);
15177}
15178
15179/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15181 SourceLocation OpLoc,
15182 bool IsAfterAmp = false) {
15183 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15184 if (ConvResult.isInvalid())
15185 return QualType();
15186 Op = ConvResult.get();
15187 QualType OpTy = Op->getType();
15189
15191 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15192 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15193 Op->getSourceRange());
15194 }
15195
15196 if (const PointerType *PT = OpTy->getAs<PointerType>())
15197 {
15198 Result = PT->getPointeeType();
15199 }
15200 else if (const ObjCObjectPointerType *OPT =
15202 Result = OPT->getPointeeType();
15203 else {
15205 if (PR.isInvalid()) return QualType();
15206 if (PR.get() != Op)
15207 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15208 }
15209
15210 if (Result.isNull()) {
15211 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15212 << OpTy << Op->getSourceRange();
15213 return QualType();
15214 }
15215
15216 if (Result->isVoidType()) {
15217 // C++ [expr.unary.op]p1:
15218 // [...] the expression to which [the unary * operator] is applied shall
15219 // be a pointer to an object type, or a pointer to a function type
15220 LangOptions LO = S.getLangOpts();
15221 if (LO.CPlusPlus)
15222 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15223 << OpTy << Op->getSourceRange();
15224 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15225 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15226 << OpTy << Op->getSourceRange();
15227 }
15228
15229 // Dereferences are usually l-values...
15230 VK = VK_LValue;
15231
15232 // ...except that certain expressions are never l-values in C.
15233 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15234 VK = VK_PRValue;
15235
15236 return Result;
15237}
15238
15239BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15241 switch (Kind) {
15242 default: llvm_unreachable("Unknown binop!");
15243 case tok::periodstar: Opc = BO_PtrMemD; break;
15244 case tok::arrowstar: Opc = BO_PtrMemI; break;
15245 case tok::star: Opc = BO_Mul; break;
15246 case tok::slash: Opc = BO_Div; break;
15247 case tok::percent: Opc = BO_Rem; break;
15248 case tok::plus: Opc = BO_Add; break;
15249 case tok::minus: Opc = BO_Sub; break;
15250 case tok::lessless: Opc = BO_Shl; break;
15251 case tok::greatergreater: Opc = BO_Shr; break;
15252 case tok::lessequal: Opc = BO_LE; break;
15253 case tok::less: Opc = BO_LT; break;
15254 case tok::greaterequal: Opc = BO_GE; break;
15255 case tok::greater: Opc = BO_GT; break;
15256 case tok::exclaimequal: Opc = BO_NE; break;
15257 case tok::equalequal: Opc = BO_EQ; break;
15258 case tok::spaceship: Opc = BO_Cmp; break;
15259 case tok::amp: Opc = BO_And; break;
15260 case tok::caret: Opc = BO_Xor; break;
15261 case tok::pipe: Opc = BO_Or; break;
15262 case tok::ampamp: Opc = BO_LAnd; break;
15263 case tok::pipepipe: Opc = BO_LOr; break;
15264 case tok::equal: Opc = BO_Assign; break;
15265 case tok::starequal: Opc = BO_MulAssign; break;
15266 case tok::slashequal: Opc = BO_DivAssign; break;
15267 case tok::percentequal: Opc = BO_RemAssign; break;
15268 case tok::plusequal: Opc = BO_AddAssign; break;
15269 case tok::minusequal: Opc = BO_SubAssign; break;
15270 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15271 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15272 case tok::ampequal: Opc = BO_AndAssign; break;
15273 case tok::caretequal: Opc = BO_XorAssign; break;
15274 case tok::pipeequal: Opc = BO_OrAssign; break;
15275 case tok::comma: Opc = BO_Comma; break;
15276 }
15277 return Opc;
15278}
15279
15281 tok::TokenKind Kind) {
15283 switch (Kind) {
15284 default: llvm_unreachable("Unknown unary op!");
15285 case tok::plusplus: Opc = UO_PreInc; break;
15286 case tok::minusminus: Opc = UO_PreDec; break;
15287 case tok::amp: Opc = UO_AddrOf; break;
15288 case tok::star: Opc = UO_Deref; break;
15289 case tok::plus: Opc = UO_Plus; break;
15290 case tok::minus: Opc = UO_Minus; break;
15291 case tok::tilde: Opc = UO_Not; break;
15292 case tok::exclaim: Opc = UO_LNot; break;
15293 case tok::kw___real: Opc = UO_Real; break;
15294 case tok::kw___imag: Opc = UO_Imag; break;
15295 case tok::kw___extension__: Opc = UO_Extension; break;
15296 }
15297 return Opc;
15298}
15299
15300const FieldDecl *
15302 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15303 // common for setters.
15304 // struct A {
15305 // int X;
15306 // -void setX(int X) { X = X; }
15307 // +void setX(int X) { this->X = X; }
15308 // };
15309
15310 // Only consider parameters for self assignment fixes.
15311 if (!isa<ParmVarDecl>(SelfAssigned))
15312 return nullptr;
15313 const auto *Method =
15314 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15315 if (!Method)
15316 return nullptr;
15317
15318 const CXXRecordDecl *Parent = Method->getParent();
15319 // In theory this is fixable if the lambda explicitly captures this, but
15320 // that's added complexity that's rarely going to be used.
15321 if (Parent->isLambda())
15322 return nullptr;
15323
15324 // FIXME: Use an actual Lookup operation instead of just traversing fields
15325 // in order to get base class fields.
15326 auto Field =
15327 llvm::find_if(Parent->fields(),
15328 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15329 return F->getDeclName() == Name;
15330 });
15331 return (Field != Parent->field_end()) ? *Field : nullptr;
15332}
15333
15334/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15335/// This warning suppressed in the event of macro expansions.
15336static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15337 SourceLocation OpLoc, bool IsBuiltin) {
15339 return;
15340 if (S.isUnevaluatedContext())
15341 return;
15342 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15343 return;
15344 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15345 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15346 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15347 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15348 if (!LHSDeclRef || !RHSDeclRef ||
15349 LHSDeclRef->getLocation().isMacroID() ||
15350 RHSDeclRef->getLocation().isMacroID())
15351 return;
15352 const ValueDecl *LHSDecl =
15353 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15354 const ValueDecl *RHSDecl =
15355 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15356 if (LHSDecl != RHSDecl)
15357 return;
15358 if (LHSDecl->getType().isVolatileQualified())
15359 return;
15360 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15361 if (RefTy->getPointeeType().isVolatileQualified())
15362 return;
15363
15364 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15365 : diag::warn_self_assignment_overloaded)
15366 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15367 << RHSExpr->getSourceRange();
15368 if (const FieldDecl *SelfAssignField =
15370 Diag << 1 << SelfAssignField
15371 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15372 else
15373 Diag << 0;
15374}
15375
15376/// Check if a bitwise-& is performed on an Objective-C pointer. This
15377/// is usually indicative of introspection within the Objective-C pointer.
15379 SourceLocation OpLoc) {
15380 if (!S.getLangOpts().ObjC)
15381 return;
15382
15383 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15384 const Expr *LHS = L.get();
15385 const Expr *RHS = R.get();
15386
15388 ObjCPointerExpr = LHS;
15389 OtherExpr = RHS;
15390 }
15391 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15392 ObjCPointerExpr = RHS;
15393 OtherExpr = LHS;
15394 }
15395
15396 // This warning is deliberately made very specific to reduce false
15397 // positives with logic that uses '&' for hashing. This logic mainly
15398 // looks for code trying to introspect into tagged pointers, which
15399 // code should generally never do.
15400 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15401 unsigned Diag = diag::warn_objc_pointer_masking;
15402 // Determine if we are introspecting the result of performSelectorXXX.
15403 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15404 // Special case messages to -performSelector and friends, which
15405 // can return non-pointer values boxed in a pointer value.
15406 // Some clients may wish to silence warnings in this subcase.
15407 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15408 Selector S = ME->getSelector();
15409 StringRef SelArg0 = S.getNameForSlot(0);
15410 if (SelArg0.starts_with("performSelector"))
15411 Diag = diag::warn_objc_pointer_masking_performSelector;
15412 }
15413
15414 S.Diag(OpLoc, Diag)
15415 << ObjCPointerExpr->getSourceRange();
15416 }
15417}
15418
15419// This helper function promotes a binary operator's operands (which are of a
15420// half vector type) to a vector of floats and then truncates the result to
15421// a vector of either half or short.
15423 BinaryOperatorKind Opc, QualType ResultTy,
15425 bool IsCompAssign, SourceLocation OpLoc,
15426 FPOptionsOverride FPFeatures) {
15427 auto &Context = S.getASTContext();
15428 assert((isVector(ResultTy, Context.HalfTy) ||
15429 isVector(ResultTy, Context.ShortTy)) &&
15430 "Result must be a vector of half or short");
15431 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15432 isVector(RHS.get()->getType(), Context.HalfTy) &&
15433 "both operands expected to be a half vector");
15434
15435 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15436 QualType BinOpResTy = RHS.get()->getType();
15437
15438 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15439 // change BinOpResTy to a vector of ints.
15440 if (isVector(ResultTy, Context.ShortTy))
15441 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15442
15443 if (IsCompAssign)
15444 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15445 ResultTy, VK, OK, OpLoc, FPFeatures,
15446 BinOpResTy, BinOpResTy);
15447
15448 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15449 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15450 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15451 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15452}
15453
15454/// Returns true if conversion between vectors of halfs and vectors of floats
15455/// is needed.
15456static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15457 Expr *E0, Expr *E1 = nullptr) {
15458 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15460 return false;
15461
15462 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15463 QualType Ty = E->IgnoreImplicit()->getType();
15464
15465 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15466 // to vectors of floats. Although the element type of the vectors is __fp16,
15467 // the vectors shouldn't be treated as storage-only types. See the
15468 // discussion here: https://reviews.llvm.org/rG825235c140e7
15469 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15470 if (VT->getVectorKind() == VectorKind::Neon)
15471 return false;
15472 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15473 }
15474 return false;
15475 };
15476
15477 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15478}
15479
15481 BinaryOperatorKind Opc, Expr *LHSExpr,
15482 Expr *RHSExpr, bool ForFoldExpression) {
15483 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15484 // The syntax only allows initializer lists on the RHS of assignment,
15485 // so we don't need to worry about accepting invalid code for
15486 // non-assignment operators.
15487 // C++11 5.17p9:
15488 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15489 // of x = {} is x = T().
15491 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15492 InitializedEntity Entity =
15494 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15495 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15496 if (Init.isInvalid())
15497 return Init;
15498 RHSExpr = Init.get();
15499 }
15500
15501 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15502 QualType ResultTy; // Result type of the binary operator.
15503 // The following two variables are used for compound assignment operators
15504 QualType CompLHSTy; // Type of LHS after promotions for computation
15505 QualType CompResultTy; // Type of computation result
15508 bool ConvertHalfVec = false;
15509
15510 if (!LHS.isUsable() || !RHS.isUsable())
15511 return ExprError();
15512
15513 if (getLangOpts().OpenCL) {
15514 QualType LHSTy = LHSExpr->getType();
15515 QualType RHSTy = RHSExpr->getType();
15516 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15517 // the ATOMIC_VAR_INIT macro.
15518 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15519 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15520 if (BO_Assign == Opc)
15521 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15522 else
15523 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15524 return ExprError();
15525 }
15526
15527 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15528 // only with a builtin functions and therefore should be disallowed here.
15529 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15530 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15531 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15532 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15533 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15534 return ExprError();
15535 }
15536 }
15537
15538 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15539 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15540
15541 switch (Opc) {
15542 case BO_Assign:
15543 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15544 if (getLangOpts().CPlusPlus &&
15545 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15546 VK = LHS.get()->getValueKind();
15547 OK = LHS.get()->getObjectKind();
15548 }
15549 if (!ResultTy.isNull()) {
15550 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15551 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15552
15553 // Avoid copying a block to the heap if the block is assigned to a local
15554 // auto variable that is declared in the same scope as the block. This
15555 // optimization is unsafe if the local variable is declared in an outer
15556 // scope. For example:
15557 //
15558 // BlockTy b;
15559 // {
15560 // b = ^{...};
15561 // }
15562 // // It is unsafe to invoke the block here if it wasn't copied to the
15563 // // heap.
15564 // b();
15565
15566 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15567 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15568 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15569 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15570 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15571
15573 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15575 }
15576 RecordModifiableNonNullParam(*this, LHS.get());
15577 break;
15578 case BO_PtrMemD:
15579 case BO_PtrMemI:
15580 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15581 Opc == BO_PtrMemI);
15582 break;
15583 case BO_Mul:
15584 case BO_Div:
15585 ConvertHalfVec = true;
15586 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15587 break;
15588 case BO_Rem:
15589 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15590 break;
15591 case BO_Add:
15592 ConvertHalfVec = true;
15593 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15594 break;
15595 case BO_Sub:
15596 ConvertHalfVec = true;
15597 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15598 break;
15599 case BO_Shl:
15600 case BO_Shr:
15601 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15602 break;
15603 case BO_LE:
15604 case BO_LT:
15605 case BO_GE:
15606 case BO_GT:
15607 ConvertHalfVec = true;
15608 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15609
15610 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15611 !ForFoldExpression && BI && BI->isComparisonOp())
15612 Diag(OpLoc, diag::warn_consecutive_comparison)
15613 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15614
15615 break;
15616 case BO_EQ:
15617 case BO_NE:
15618 ConvertHalfVec = true;
15619 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15620 break;
15621 case BO_Cmp:
15622 ConvertHalfVec = true;
15623 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15624 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15625 break;
15626 case BO_And:
15627 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15628 [[fallthrough]];
15629 case BO_Xor:
15630 case BO_Or:
15631 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15632 break;
15633 case BO_LAnd:
15634 case BO_LOr:
15635 ConvertHalfVec = true;
15636 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15637 break;
15638 case BO_MulAssign:
15639 case BO_DivAssign:
15640 ConvertHalfVec = true;
15641 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15642 CompLHSTy = CompResultTy;
15643 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15644 ResultTy =
15645 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15646 break;
15647 case BO_RemAssign:
15648 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15649 CompLHSTy = CompResultTy;
15650 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15651 ResultTy =
15652 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15653 break;
15654 case BO_AddAssign:
15655 ConvertHalfVec = true;
15656 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15657 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15658 ResultTy =
15659 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15660 break;
15661 case BO_SubAssign:
15662 ConvertHalfVec = true;
15663 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15664 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15665 ResultTy =
15666 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15667 break;
15668 case BO_ShlAssign:
15669 case BO_ShrAssign:
15670 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15671 CompLHSTy = CompResultTy;
15672 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15673 ResultTy =
15674 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15675 break;
15676 case BO_AndAssign:
15677 case BO_OrAssign: // fallthrough
15678 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15679 [[fallthrough]];
15680 case BO_XorAssign:
15681 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15682 CompLHSTy = CompResultTy;
15683 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15684 ResultTy =
15685 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15686 break;
15687 case BO_Comma:
15688 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15689 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15690 VK = RHS.get()->getValueKind();
15691 OK = RHS.get()->getObjectKind();
15692 }
15693 break;
15694 }
15695 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15696 return ExprError();
15697
15698 // Some of the binary operations require promoting operands of half vector to
15699 // float vectors and truncating the result back to half vector. For now, we do
15700 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15701 // arm64).
15702 assert(
15703 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15704 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15705 "both sides are half vectors or neither sides are");
15706 ConvertHalfVec =
15707 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15708
15709 // Check for array bounds violations for both sides of the BinaryOperator
15710 CheckArrayAccess(LHS.get());
15711 CheckArrayAccess(RHS.get());
15712
15713 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15714 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15715 &Context.Idents.get("object_setClass"),
15717 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15718 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15719 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15721 "object_setClass(")
15722 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15723 ",")
15724 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15725 }
15726 else
15727 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15728 }
15729 else if (const ObjCIvarRefExpr *OIRE =
15730 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15731 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15732
15733 // Opc is not a compound assignment if CompResultTy is null.
15734 if (CompResultTy.isNull()) {
15735 if (ConvertHalfVec)
15736 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15737 OpLoc, CurFPFeatureOverrides());
15738 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15739 VK, OK, OpLoc, CurFPFeatureOverrides());
15740 }
15741
15742 // Handle compound assignments.
15743 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15745 VK = VK_LValue;
15746 OK = LHS.get()->getObjectKind();
15747 }
15748
15749 // The LHS is not converted to the result type for fixed-point compound
15750 // assignment as the common type is computed on demand. Reset the CompLHSTy
15751 // to the LHS type we would have gotten after unary conversions.
15752 if (CompResultTy->isFixedPointType())
15753 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15754
15755 if (ConvertHalfVec)
15756 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15757 OpLoc, CurFPFeatureOverrides());
15758
15760 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15761 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15762}
15763
15764/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15765/// operators are mixed in a way that suggests that the programmer forgot that
15766/// comparison operators have higher precedence. The most typical example of
15767/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15769 SourceLocation OpLoc, Expr *LHSExpr,
15770 Expr *RHSExpr) {
15771 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15772 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15773
15774 // Check that one of the sides is a comparison operator and the other isn't.
15775 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15776 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15777 if (isLeftComp == isRightComp)
15778 return;
15779
15780 // Bitwise operations are sometimes used as eager logical ops.
15781 // Don't diagnose this.
15782 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15783 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15784 if (isLeftBitwise || isRightBitwise)
15785 return;
15786
15787 SourceRange DiagRange = isLeftComp
15788 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15789 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15790 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15791 SourceRange ParensRange =
15792 isLeftComp
15793 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15794 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15795
15796 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15797 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15798 SuggestParentheses(Self, OpLoc,
15799 Self.PDiag(diag::note_precedence_silence) << OpStr,
15800 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15801 SuggestParentheses(Self, OpLoc,
15802 Self.PDiag(diag::note_precedence_bitwise_first)
15804 ParensRange);
15805}
15806
15807/// It accepts a '&&' expr that is inside a '||' one.
15808/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15809/// in parentheses.
15810static void
15812 BinaryOperator *Bop) {
15813 assert(Bop->getOpcode() == BO_LAnd);
15814 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15815 << Bop->getSourceRange() << OpLoc;
15817 Self.PDiag(diag::note_precedence_silence)
15818 << Bop->getOpcodeStr(),
15819 Bop->getSourceRange());
15820}
15821
15822/// Look for '&&' in the left hand of a '||' expr.
15824 Expr *LHSExpr, Expr *RHSExpr) {
15825 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15826 if (Bop->getOpcode() == BO_LAnd) {
15827 // If it's "string_literal && a || b" don't warn since the precedence
15828 // doesn't matter.
15829 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15830 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15831 } else if (Bop->getOpcode() == BO_LOr) {
15832 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15833 // If it's "a || b && string_literal || c" we didn't warn earlier for
15834 // "a || b && string_literal", but warn now.
15835 if (RBop->getOpcode() == BO_LAnd &&
15836 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15837 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15838 }
15839 }
15840 }
15841}
15842
15843/// Look for '&&' in the right hand of a '||' expr.
15845 Expr *LHSExpr, Expr *RHSExpr) {
15846 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15847 if (Bop->getOpcode() == BO_LAnd) {
15848 // If it's "a || b && string_literal" don't warn since the precedence
15849 // doesn't matter.
15850 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15851 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15852 }
15853 }
15854}
15855
15856/// Look for bitwise op in the left or right hand of a bitwise op with
15857/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15858/// the '&' expression in parentheses.
15860 SourceLocation OpLoc, Expr *SubExpr) {
15861 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15862 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15863 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15864 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15865 << Bop->getSourceRange() << OpLoc;
15866 SuggestParentheses(S, Bop->getOperatorLoc(),
15867 S.PDiag(diag::note_precedence_silence)
15868 << Bop->getOpcodeStr(),
15869 Bop->getSourceRange());
15870 }
15871 }
15872}
15873
15875 Expr *SubExpr, StringRef Shift) {
15876 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15877 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15878 StringRef Op = Bop->getOpcodeStr();
15879 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15880 << Bop->getSourceRange() << OpLoc << Shift << Op;
15881 SuggestParentheses(S, Bop->getOperatorLoc(),
15882 S.PDiag(diag::note_precedence_silence) << Op,
15883 Bop->getSourceRange());
15884 }
15885 }
15886}
15887
15889 Expr *LHSExpr, Expr *RHSExpr) {
15890 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15891 if (!OCE)
15892 return;
15893
15894 FunctionDecl *FD = OCE->getDirectCallee();
15895 if (!FD || !FD->isOverloadedOperator())
15896 return;
15897
15899 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15900 return;
15901
15902 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15903 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15904 << (Kind == OO_LessLess);
15906 S.PDiag(diag::note_precedence_silence)
15907 << (Kind == OO_LessLess ? "<<" : ">>"),
15908 OCE->getSourceRange());
15910 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15911 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15912}
15913
15914/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15915/// precedence.
15917 SourceLocation OpLoc, Expr *LHSExpr,
15918 Expr *RHSExpr){
15919 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15921 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15922
15923 // Diagnose "arg1 & arg2 | arg3"
15924 if ((Opc == BO_Or || Opc == BO_Xor) &&
15925 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15926 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15927 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15928 }
15929
15930 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15931 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15932 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15933 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15934 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15935 }
15936
15937 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15938 || Opc == BO_Shr) {
15939 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15940 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15941 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15942 }
15943
15944 // Warn on overloaded shift operators and comparisons, such as:
15945 // cout << 5 == 4;
15947 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15948}
15949
15951 tok::TokenKind Kind,
15952 Expr *LHSExpr, Expr *RHSExpr) {
15953 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15954 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15955 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15956
15957 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15958 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15959
15963
15964 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15965 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15966
15967 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15968}
15969
15971 UnresolvedSetImpl &Functions) {
15973 if (OverOp != OO_None && OverOp != OO_Equal)
15974 LookupOverloadedOperatorName(OverOp, S, Functions);
15975
15976 // In C++20 onwards, we may have a second operator to look up.
15977 if (getLangOpts().CPlusPlus20) {
15979 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15980 }
15981}
15982
15983/// Build an overloaded binary operator expression in the given scope.
15986 Expr *LHS, Expr *RHS) {
15987 switch (Opc) {
15988 case BO_Assign:
15989 // In the non-overloaded case, we warn about self-assignment (x = x) for
15990 // both simple assignment and certain compound assignments where algebra
15991 // tells us the operation yields a constant result. When the operator is
15992 // overloaded, we can't do the latter because we don't want to assume that
15993 // those algebraic identities still apply; for example, a path-building
15994 // library might use operator/= to append paths. But it's still reasonable
15995 // to assume that simple assignment is just moving/copying values around
15996 // and so self-assignment is likely a bug.
15997 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15998 [[fallthrough]];
15999 case BO_DivAssign:
16000 case BO_RemAssign:
16001 case BO_SubAssign:
16002 case BO_AndAssign:
16003 case BO_OrAssign:
16004 case BO_XorAssign:
16005 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
16006 break;
16007 default:
16008 break;
16009 }
16010
16011 // Find all of the overloaded operators visible from this point.
16012 UnresolvedSet<16> Functions;
16013 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
16014
16015 // Build the (potentially-overloaded, potentially-dependent)
16016 // binary operation.
16017 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16018}
16019
16021 BinaryOperatorKind Opc, Expr *LHSExpr,
16022 Expr *RHSExpr, bool ForFoldExpression) {
16023 if (!LHSExpr || !RHSExpr)
16024 return ExprError();
16025
16026 // We want to end up calling one of SemaPseudoObject::checkAssignment
16027 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16028 // both expressions are overloadable or either is type-dependent),
16029 // or CreateBuiltinBinOp (in any other case). We also want to get
16030 // any placeholder types out of the way.
16031
16032 // Handle pseudo-objects in the LHS.
16033 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16034 // Assignments with a pseudo-object l-value need special analysis.
16035 if (pty->getKind() == BuiltinType::PseudoObject &&
16037 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16038
16039 // Don't resolve overloads if the other type is overloadable.
16040 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16041 // We can't actually test that if we still have a placeholder,
16042 // though. Fortunately, none of the exceptions we see in that
16043 // code below are valid when the LHS is an overload set. Note
16044 // that an overload set can be dependently-typed, but it never
16045 // instantiates to having an overloadable type.
16046 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16047 if (resolvedRHS.isInvalid()) return ExprError();
16048 RHSExpr = resolvedRHS.get();
16049
16050 if (RHSExpr->isTypeDependent() ||
16051 RHSExpr->getType()->isOverloadableType())
16052 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16053 }
16054
16055 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16056 // template, diagnose the missing 'template' keyword instead of diagnosing
16057 // an invalid use of a bound member function.
16058 //
16059 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16060 // to C++1z [over.over]/1.4, but we already checked for that case above.
16061 if (Opc == BO_LT && inTemplateInstantiation() &&
16062 (pty->getKind() == BuiltinType::BoundMember ||
16063 pty->getKind() == BuiltinType::Overload)) {
16064 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16065 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16066 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16067 return isa<FunctionTemplateDecl>(ND);
16068 })) {
16069 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16070 : OE->getNameLoc(),
16071 diag::err_template_kw_missing)
16072 << OE->getName().getAsIdentifierInfo();
16073 return ExprError();
16074 }
16075 }
16076
16077 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16078 if (LHS.isInvalid()) return ExprError();
16079 LHSExpr = LHS.get();
16080 }
16081
16082 // Handle pseudo-objects in the RHS.
16083 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16084 // An overload in the RHS can potentially be resolved by the type
16085 // being assigned to.
16086 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16087 if (getLangOpts().CPlusPlus &&
16088 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16089 LHSExpr->getType()->isOverloadableType()))
16090 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16091
16092 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16093 ForFoldExpression);
16094 }
16095
16096 // Don't resolve overloads if the other type is overloadable.
16097 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16098 LHSExpr->getType()->isOverloadableType())
16099 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16100
16101 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16102 if (!resolvedRHS.isUsable()) return ExprError();
16103 RHSExpr = resolvedRHS.get();
16104 }
16105
16106 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
16107 LHSExpr->getType()->isHLSLResourceRecordArray())) {
16108 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
16109 return ExprError();
16110 }
16111
16112 if (getLangOpts().CPlusPlus) {
16113 // Otherwise, build an overloaded op if either expression is type-dependent
16114 // or has an overloadable type.
16115 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16116 LHSExpr->getType()->isOverloadableType() ||
16117 RHSExpr->getType()->isOverloadableType())
16118 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16119 }
16120
16121 if (getLangOpts().RecoveryAST &&
16122 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16123 assert(!getLangOpts().CPlusPlus);
16124 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16125 "Should only occur in error-recovery path.");
16127 // C [6.15.16] p3:
16128 // An assignment expression has the value of the left operand after the
16129 // assignment, but is not an lvalue.
16131 Context, LHSExpr, RHSExpr, Opc,
16133 OpLoc, CurFPFeatureOverrides());
16134 QualType ResultType;
16135 switch (Opc) {
16136 case BO_Assign:
16137 ResultType = LHSExpr->getType().getUnqualifiedType();
16138 break;
16139 case BO_LT:
16140 case BO_GT:
16141 case BO_LE:
16142 case BO_GE:
16143 case BO_EQ:
16144 case BO_NE:
16145 case BO_LAnd:
16146 case BO_LOr:
16147 // These operators have a fixed result type regardless of operands.
16148 ResultType = Context.IntTy;
16149 break;
16150 case BO_Comma:
16151 ResultType = RHSExpr->getType();
16152 break;
16153 default:
16154 ResultType = Context.DependentTy;
16155 break;
16156 }
16157 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16158 VK_PRValue, OK_Ordinary, OpLoc,
16160 }
16161
16162 // Build a built-in binary operation.
16163 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16164}
16165
16167 if (T.isNull() || T->isDependentType())
16168 return false;
16169
16170 if (!Ctx.isPromotableIntegerType(T))
16171 return true;
16172
16173 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16174}
16175
16177 UnaryOperatorKind Opc, Expr *InputExpr,
16178 bool IsAfterAmp) {
16179 ExprResult Input = InputExpr;
16182 QualType resultType;
16183 bool CanOverflow = false;
16184
16185 bool ConvertHalfVec = false;
16186 if (getLangOpts().OpenCL) {
16187 QualType Ty = InputExpr->getType();
16188 // The only legal unary operation for atomics is '&'.
16189 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16190 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16191 // only with a builtin functions and therefore should be disallowed here.
16192 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16193 || Ty->isBlockPointerType())) {
16194 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16195 << InputExpr->getType()
16196 << Input.get()->getSourceRange());
16197 }
16198 }
16199
16200 if (getLangOpts().HLSL && OpLoc.isValid()) {
16201 if (Opc == UO_AddrOf)
16202 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16203 if (Opc == UO_Deref)
16204 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16205 }
16206
16207 if (InputExpr->isTypeDependent() &&
16208 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
16209 resultType = Context.DependentTy;
16210 } else {
16211 switch (Opc) {
16212 case UO_PreInc:
16213 case UO_PreDec:
16214 case UO_PostInc:
16215 case UO_PostDec:
16216 resultType =
16217 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
16218 Opc == UO_PreInc || Opc == UO_PostInc,
16219 Opc == UO_PreInc || Opc == UO_PreDec);
16220 CanOverflow = isOverflowingIntegerType(Context, resultType);
16221 break;
16222 case UO_AddrOf:
16223 resultType = CheckAddressOfOperand(Input, OpLoc);
16224 CheckAddressOfNoDeref(InputExpr);
16225 RecordModifiableNonNullParam(*this, InputExpr);
16226 break;
16227 case UO_Deref: {
16229 if (Input.isInvalid())
16230 return ExprError();
16231 resultType =
16232 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16233 break;
16234 }
16235 case UO_Plus:
16236 case UO_Minus:
16237 CanOverflow = Opc == UO_Minus &&
16239 Input = UsualUnaryConversions(Input.get());
16240 if (Input.isInvalid())
16241 return ExprError();
16242 // Unary plus and minus require promoting an operand of half vector to a
16243 // float vector and truncating the result back to a half vector. For now,
16244 // we do this only when HalfArgsAndReturns is set (that is, when the
16245 // target is arm or arm64).
16246 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16247
16248 // If the operand is a half vector, promote it to a float vector.
16249 if (ConvertHalfVec)
16250 Input = convertVector(Input.get(), Context.FloatTy, *this);
16251 resultType = Input.get()->getType();
16252 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16253 break;
16254 else if (resultType->isVectorType() &&
16255 // The z vector extensions don't allow + or - with bool vectors.
16256 (!Context.getLangOpts().ZVector ||
16257 resultType->castAs<VectorType>()->getVectorKind() !=
16259 break;
16260 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16261 break;
16262 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16263 Opc == UO_Plus && resultType->isPointerType())
16264 break;
16265
16266 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16267 << resultType << Input.get()->getSourceRange());
16268
16269 case UO_Not: // bitwise complement
16270 Input = UsualUnaryConversions(Input.get());
16271 if (Input.isInvalid())
16272 return ExprError();
16273 resultType = Input.get()->getType();
16274 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16275 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16276 // C99 does not support '~' for complex conjugation.
16277 Diag(OpLoc, diag::ext_integer_complement_complex)
16278 << resultType << Input.get()->getSourceRange();
16279 else if (resultType->hasIntegerRepresentation())
16280 break;
16281 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16282 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16283 // on vector float types.
16284 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16285 if (!T->isIntegerType())
16286 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16287 << resultType << Input.get()->getSourceRange());
16288 } else {
16289 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16290 << resultType << Input.get()->getSourceRange());
16291 }
16292 break;
16293
16294 case UO_LNot: // logical negation
16295 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16297 if (Input.isInvalid())
16298 return ExprError();
16299 resultType = Input.get()->getType();
16300
16301 // Though we still have to promote half FP to float...
16302 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16303 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16304 .get();
16305 resultType = Context.FloatTy;
16306 }
16307
16308 // WebAsembly tables can't be used in unary expressions.
16309 if (resultType->isPointerType() &&
16311 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16312 << resultType << Input.get()->getSourceRange());
16313 }
16314
16315 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16316 // C99 6.5.3.3p1: ok, fallthrough;
16317 if (Context.getLangOpts().CPlusPlus) {
16318 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16319 // operand contextually converted to bool.
16320 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16321 ScalarTypeToBooleanCastKind(resultType));
16322 } else if (Context.getLangOpts().OpenCL &&
16323 Context.getLangOpts().OpenCLVersion < 120) {
16324 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16325 // operate on scalar float types.
16326 if (!resultType->isIntegerType() && !resultType->isPointerType())
16327 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16328 << resultType << Input.get()->getSourceRange());
16329 }
16330 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16331 !resultType->hasBooleanRepresentation()) {
16332 // HLSL unary logical 'not' behaves like C++, which states that the
16333 // operand is converted to bool and the result is bool, however HLSL
16334 // extends this property to vectors.
16335 const VectorType *VTy = resultType->castAs<VectorType>();
16336 resultType =
16337 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16338
16339 Input = ImpCastExprToType(
16340 Input.get(), resultType,
16342 .get();
16343 break;
16344 } else if (resultType->isExtVectorType()) {
16345 if (Context.getLangOpts().OpenCL &&
16346 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16347 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16348 // operate on vector float types.
16349 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16350 if (!T->isIntegerType())
16351 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16352 << resultType << Input.get()->getSourceRange());
16353 }
16354 // Vector logical not returns the signed variant of the operand type.
16355 resultType = GetSignedVectorType(resultType);
16356 break;
16357 } else if (Context.getLangOpts().CPlusPlus &&
16358 resultType->isVectorType()) {
16359 const VectorType *VTy = resultType->castAs<VectorType>();
16360 if (VTy->getVectorKind() != VectorKind::Generic)
16361 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16362 << resultType << Input.get()->getSourceRange());
16363
16364 // Vector logical not returns the signed variant of the operand type.
16365 resultType = GetSignedVectorType(resultType);
16366 break;
16367 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16368 resultType = Context.getLogicalOperationType();
16369 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(InputExpr);
16370 break;
16371 } else {
16372 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16373 << resultType << Input.get()->getSourceRange());
16374 }
16375
16376 // LNot always has type int. C99 6.5.3.3p5.
16377 // In C++, it's bool. C++ 5.3.1p8
16378 resultType = Context.getLogicalOperationType();
16379 break;
16380 case UO_Real:
16381 case UO_Imag:
16382 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16383 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16384 // ordinary complex l-values to ordinary l-values and all other values to
16385 // r-values.
16386 if (Input.isInvalid())
16387 return ExprError();
16388 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16389 if (Input.get()->isGLValue() &&
16390 Input.get()->getObjectKind() == OK_Ordinary)
16391 VK = Input.get()->getValueKind();
16392 } else if (!getLangOpts().CPlusPlus) {
16393 // In C, a volatile scalar is read by __imag. In C++, it is not.
16394 Input = DefaultLvalueConversion(Input.get());
16395 }
16396 break;
16397 case UO_Extension:
16398 resultType = Input.get()->getType();
16399 VK = Input.get()->getValueKind();
16400 OK = Input.get()->getObjectKind();
16401 break;
16402 case UO_Coawait:
16403 // It's unnecessary to represent the pass-through operator co_await in the
16404 // AST; just return the input expression instead.
16405 assert(!Input.get()->getType()->isDependentType() &&
16406 "the co_await expression must be non-dependant before "
16407 "building operator co_await");
16408 return Input;
16409 }
16410 }
16411 if (resultType.isNull() || Input.isInvalid())
16412 return ExprError();
16413
16414 // Check for array bounds violations in the operand of the UnaryOperator,
16415 // except for the '*' and '&' operators that have to be handled specially
16416 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16417 // that are explicitly defined as valid by the standard).
16418 if (Opc != UO_AddrOf && Opc != UO_Deref)
16419 CheckArrayAccess(Input.get());
16420
16421 auto *UO =
16422 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16423 OpLoc, CanOverflow, CurFPFeatureOverrides());
16424
16425 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16426 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16428 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16429
16430 // Convert the result back to a half vector.
16431 if (ConvertHalfVec)
16432 return convertVector(UO, Context.HalfTy, *this);
16433 return UO;
16434}
16435
16437 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16438 if (!DRE->getQualifier())
16439 return false;
16440
16441 ValueDecl *VD = DRE->getDecl();
16442 if (!VD->isCXXClassMember())
16443 return false;
16444
16446 return true;
16447 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16448 return Method->isImplicitObjectMemberFunction();
16449
16450 return false;
16451 }
16452
16453 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16454 if (!ULE->getQualifier())
16455 return false;
16456
16457 for (NamedDecl *D : ULE->decls()) {
16458 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16459 if (Method->isImplicitObjectMemberFunction())
16460 return true;
16461 } else {
16462 // Overload set does not contain methods.
16463 break;
16464 }
16465 }
16466
16467 return false;
16468 }
16469
16470 return false;
16471}
16472
16474 UnaryOperatorKind Opc, Expr *Input,
16475 bool IsAfterAmp) {
16476 // First things first: handle placeholders so that the
16477 // overloaded-operator check considers the right type.
16478 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16479 // Increment and decrement of pseudo-object references.
16480 if (pty->getKind() == BuiltinType::PseudoObject &&
16482 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16483
16484 // extension is always a builtin operator.
16485 if (Opc == UO_Extension)
16486 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16487
16488 // & gets special logic for several kinds of placeholder.
16489 // The builtin code knows what to do.
16490 if (Opc == UO_AddrOf &&
16491 (pty->getKind() == BuiltinType::Overload ||
16492 pty->getKind() == BuiltinType::UnknownAny ||
16493 pty->getKind() == BuiltinType::BoundMember))
16494 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16495
16496 // Anything else needs to be handled now.
16498 if (Result.isInvalid()) return ExprError();
16499 Input = Result.get();
16500 }
16501
16502 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16504 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16505 // Find all of the overloaded operators visible from this point.
16506 UnresolvedSet<16> Functions;
16508 if (S && OverOp != OO_None)
16509 LookupOverloadedOperatorName(OverOp, S, Functions);
16510
16511 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16512 }
16513
16514 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16515}
16516
16518 Expr *Input, bool IsAfterAmp) {
16519 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16520 IsAfterAmp);
16521}
16522
16524 LabelDecl *TheDecl) {
16525 TheDecl->markUsed(Context);
16526 // Create the AST node. The address of a label always has type 'void*'.
16527 auto *Res = new (Context) AddrLabelExpr(
16528 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16529
16530 if (getCurFunction())
16531 getCurFunction()->AddrLabels.push_back(Res);
16532
16533 return Res;
16534}
16535
16538 // Make sure we diagnose jumping into a statement expression.
16540}
16541
16543 // Note that function is also called by TreeTransform when leaving a
16544 // StmtExpr scope without rebuilding anything.
16545
16548}
16549
16551 SourceLocation RPLoc) {
16552 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16553}
16554
16556 SourceLocation RPLoc, unsigned TemplateDepth) {
16557 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16558 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16559
16562 assert(!Cleanup.exprNeedsCleanups() &&
16563 "cleanups within StmtExpr not correctly bound!");
16565
16566 // FIXME: there are a variety of strange constraints to enforce here, for
16567 // example, it is not possible to goto into a stmt expression apparently.
16568 // More semantic analysis is needed.
16569
16570 // If there are sub-stmts in the compound stmt, take the type of the last one
16571 // as the type of the stmtexpr.
16572 QualType Ty = Context.VoidTy;
16573 bool StmtExprMayBindToTemp = false;
16574 if (!Compound->body_empty()) {
16575 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16576 if (const Expr *Value = LastStmt->getExprStmt()) {
16577 StmtExprMayBindToTemp = true;
16578 Ty = Value->getType();
16579 }
16580 }
16581 }
16582
16583 // FIXME: Check that expression type is complete/non-abstract; statement
16584 // expressions are not lvalues.
16585 Expr *ResStmtExpr =
16586 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16587 if (StmtExprMayBindToTemp)
16588 return MaybeBindToTemporary(ResStmtExpr);
16589 return ResStmtExpr;
16590}
16591
16593 if (ER.isInvalid())
16594 return ExprError();
16595
16596 // Do function/array conversion on the last expression, but not
16597 // lvalue-to-rvalue. However, initialize an unqualified type.
16599 if (ER.isInvalid())
16600 return ExprError();
16601 Expr *E = ER.get();
16602
16603 if (E->isTypeDependent())
16604 return E;
16605
16606 // In ARC, if the final expression ends in a consume, splice
16607 // the consume out and bind it later. In the alternate case
16608 // (when dealing with a retainable type), the result
16609 // initialization will create a produce. In both cases the
16610 // result will be +1, and we'll need to balance that out with
16611 // a bind.
16612 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16613 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16614 return Cast->getSubExpr();
16615
16616 // FIXME: Provide a better location for the initialization.
16620 SourceLocation(), E);
16621}
16622
16624 TypeSourceInfo *TInfo,
16625 ArrayRef<OffsetOfComponent> Components,
16626 SourceLocation RParenLoc) {
16627 QualType ArgTy = TInfo->getType();
16628 bool Dependent = ArgTy->isDependentType();
16629 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16630
16631 // We must have at least one component that refers to the type, and the first
16632 // one is known to be a field designator. Verify that the ArgTy represents
16633 // a struct/union/class.
16634 if (!Dependent && !ArgTy->isRecordType())
16635 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16636 << ArgTy << TypeRange);
16637
16638 // Type must be complete per C99 7.17p3 because a declaring a variable
16639 // with an incomplete type would be ill-formed.
16640 if (!Dependent
16641 && RequireCompleteType(BuiltinLoc, ArgTy,
16642 diag::err_offsetof_incomplete_type, TypeRange))
16643 return ExprError();
16644
16645 bool DidWarnAboutNonPOD = false;
16646 QualType CurrentType = ArgTy;
16649 for (const OffsetOfComponent &OC : Components) {
16650 if (OC.isBrackets) {
16651 // Offset of an array sub-field. TODO: Should we allow vector elements?
16652 if (!CurrentType->isDependentType()) {
16653 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16654 if(!AT)
16655 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16656 << CurrentType);
16657 CurrentType = AT->getElementType();
16658 } else
16659 CurrentType = Context.DependentTy;
16660
16661 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16662 if (IdxRval.isInvalid())
16663 return ExprError();
16664 Expr *Idx = IdxRval.get();
16665
16666 // The expression must be an integral expression.
16667 // FIXME: An integral constant expression?
16668 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16669 !Idx->getType()->isIntegerType())
16670 return ExprError(
16671 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16672 << Idx->getSourceRange());
16673
16674 // Record this array index.
16675 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16676 Exprs.push_back(Idx);
16677 continue;
16678 }
16679
16680 // Offset of a field.
16681 if (CurrentType->isDependentType()) {
16682 // We have the offset of a field, but we can't look into the dependent
16683 // type. Just record the identifier of the field.
16684 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16685 CurrentType = Context.DependentTy;
16686 continue;
16687 }
16688
16689 // We need to have a complete type to look into.
16690 if (RequireCompleteType(OC.LocStart, CurrentType,
16691 diag::err_offsetof_incomplete_type))
16692 return ExprError();
16693
16694 // Look for the designated field.
16695 auto *RD = CurrentType->getAsRecordDecl();
16696 if (!RD)
16697 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16698 << CurrentType);
16699
16700 // C++ [lib.support.types]p5:
16701 // The macro offsetof accepts a restricted set of type arguments in this
16702 // International Standard. type shall be a POD structure or a POD union
16703 // (clause 9).
16704 // C++11 [support.types]p4:
16705 // If type is not a standard-layout class (Clause 9), the results are
16706 // undefined.
16707 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16708 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16709 unsigned DiagID =
16710 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16711 : diag::ext_offsetof_non_pod_type;
16712
16713 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16714 Diag(BuiltinLoc, DiagID)
16715 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16716 DidWarnAboutNonPOD = true;
16717 }
16718 }
16719
16720 // Look for the field.
16721 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16722 LookupQualifiedName(R, RD);
16723 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16724 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16725 if (!MemberDecl) {
16726 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16727 MemberDecl = IndirectMemberDecl->getAnonField();
16728 }
16729
16730 if (!MemberDecl) {
16731 // Lookup could be ambiguous when looking up a placeholder variable
16732 // __builtin_offsetof(S, _).
16733 // In that case we would already have emitted a diagnostic
16734 if (!R.isAmbiguous())
16735 Diag(BuiltinLoc, diag::err_no_member)
16736 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16737 return ExprError();
16738 }
16739
16740 // C99 7.17p3:
16741 // (If the specified member is a bit-field, the behavior is undefined.)
16742 //
16743 // We diagnose this as an error.
16744 if (MemberDecl->isBitField()) {
16745 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16746 << MemberDecl->getDeclName()
16747 << SourceRange(BuiltinLoc, RParenLoc);
16748 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16749 return ExprError();
16750 }
16751
16752 RecordDecl *Parent = MemberDecl->getParent();
16753 if (IndirectMemberDecl)
16754 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16755
16756 // If the member was found in a base class, introduce OffsetOfNodes for
16757 // the base class indirections.
16758 CXXBasePaths Paths;
16759 if (IsDerivedFrom(OC.LocStart, CurrentType,
16760 Context.getCanonicalTagType(Parent), Paths)) {
16761 if (Paths.getDetectedVirtual()) {
16762 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16763 << MemberDecl->getDeclName()
16764 << SourceRange(BuiltinLoc, RParenLoc);
16765 return ExprError();
16766 }
16767
16768 CXXBasePath &Path = Paths.front();
16769 for (const CXXBasePathElement &B : Path)
16770 Comps.push_back(OffsetOfNode(B.Base));
16771 }
16772
16773 if (IndirectMemberDecl) {
16774 for (auto *FI : IndirectMemberDecl->chain()) {
16775 assert(isa<FieldDecl>(FI));
16776 Comps.push_back(OffsetOfNode(OC.LocStart,
16777 cast<FieldDecl>(FI), OC.LocEnd));
16778 }
16779 } else
16780 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16781
16782 CurrentType = MemberDecl->getType().getNonReferenceType();
16783 }
16784
16785 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16786 Comps, Exprs, RParenLoc);
16787}
16788
16790 SourceLocation BuiltinLoc,
16792 ParsedType ParsedArgTy,
16793 ArrayRef<OffsetOfComponent> Components,
16794 SourceLocation RParenLoc) {
16795
16796 TypeSourceInfo *ArgTInfo;
16797 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16798 if (ArgTy.isNull())
16799 return ExprError();
16800
16801 if (!ArgTInfo)
16802 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16803
16804 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16805}
16806
16807
16809 Expr *CondExpr,
16810 Expr *LHSExpr, Expr *RHSExpr,
16811 SourceLocation RPLoc) {
16812 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16813
16816 QualType resType;
16817 bool CondIsTrue = false;
16818 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16819 resType = Context.DependentTy;
16820 } else {
16821 // The conditional expression is required to be a constant expression.
16822 llvm::APSInt condEval(32);
16824 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16825 if (CondICE.isInvalid())
16826 return ExprError();
16827 CondExpr = CondICE.get();
16828 CondIsTrue = condEval.getZExtValue();
16829
16830 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16831 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16832
16833 resType = ActiveExpr->getType();
16834 VK = ActiveExpr->getValueKind();
16835 OK = ActiveExpr->getObjectKind();
16836 }
16837
16838 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16839 resType, VK, OK, RPLoc, CondIsTrue);
16840}
16841
16842//===----------------------------------------------------------------------===//
16843// Clang Extensions.
16844//===----------------------------------------------------------------------===//
16845
16846void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16848
16849 if (LangOpts.CPlusPlus) {
16851 Decl *ManglingContextDecl;
16852 std::tie(MCtx, ManglingContextDecl) =
16853 getCurrentMangleNumberContext(Block->getDeclContext());
16854 if (MCtx) {
16855 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16856 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16857 }
16858 }
16859
16860 PushBlockScope(CurScope, Block);
16861 CurContext->addDecl(Block);
16862 if (CurScope)
16863 PushDeclContext(CurScope, Block);
16864 else
16865 CurContext = Block;
16866
16868
16869 // Enter a new evaluation context to insulate the block from any
16870 // cleanups from the enclosing full-expression.
16873}
16874
16876 Scope *CurScope) {
16877 assert(ParamInfo.getIdentifier() == nullptr &&
16878 "block-id should have no identifier!");
16879 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16880 BlockScopeInfo *CurBlock = getCurBlock();
16881
16882 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16883 QualType T = Sig->getType();
16885
16886 // GetTypeForDeclarator always produces a function type for a block
16887 // literal signature. Furthermore, it is always a FunctionProtoType
16888 // unless the function was written with a typedef.
16889 assert(T->isFunctionType() &&
16890 "GetTypeForDeclarator made a non-function block signature");
16891
16892 // Look for an explicit signature in that function type.
16893 FunctionProtoTypeLoc ExplicitSignature;
16894
16895 if ((ExplicitSignature = Sig->getTypeLoc()
16897
16898 // Check whether that explicit signature was synthesized by
16899 // GetTypeForDeclarator. If so, don't save that as part of the
16900 // written signature.
16901 if (ExplicitSignature.getLocalRangeBegin() ==
16902 ExplicitSignature.getLocalRangeEnd()) {
16903 // This would be much cheaper if we stored TypeLocs instead of
16904 // TypeSourceInfos.
16905 TypeLoc Result = ExplicitSignature.getReturnLoc();
16906 unsigned Size = Result.getFullDataSize();
16907 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16908 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16909
16910 ExplicitSignature = FunctionProtoTypeLoc();
16911 }
16912 }
16913
16914 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16915 CurBlock->FunctionType = T;
16916
16917 const auto *Fn = T->castAs<FunctionType>();
16918 QualType RetTy = Fn->getReturnType();
16919 bool isVariadic =
16920 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16921
16922 CurBlock->TheDecl->setIsVariadic(isVariadic);
16923
16924 // Context.DependentTy is used as a placeholder for a missing block
16925 // return type. TODO: what should we do with declarators like:
16926 // ^ * { ... }
16927 // If the answer is "apply template argument deduction"....
16928 if (RetTy != Context.DependentTy) {
16929 CurBlock->ReturnType = RetTy;
16930 CurBlock->TheDecl->setBlockMissingReturnType(false);
16931 CurBlock->HasImplicitReturnType = false;
16932 }
16933
16934 // Push block parameters from the declarator if we had them.
16936 if (ExplicitSignature) {
16937 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16938 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16939 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16940 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16941 // Diagnose this as an extension in C17 and earlier.
16942 if (!getLangOpts().C23)
16943 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16944 }
16945 Params.push_back(Param);
16946 }
16947
16948 // Fake up parameter variables if we have a typedef, like
16949 // ^ fntype { ... }
16950 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16951 for (const auto &I : Fn->param_types()) {
16953 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16954 Params.push_back(Param);
16955 }
16956 }
16957
16958 // Set the parameters on the block decl.
16959 if (!Params.empty()) {
16960 CurBlock->TheDecl->setParams(Params);
16962 /*CheckParameterNames=*/false);
16963 }
16964
16965 // Finally we can process decl attributes.
16966 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16967
16968 // Put the parameter variables in scope.
16969 for (auto *AI : CurBlock->TheDecl->parameters()) {
16970 AI->setOwningFunction(CurBlock->TheDecl);
16971
16972 // If this has an identifier, add it to the scope stack.
16973 if (AI->getIdentifier()) {
16974 CheckShadow(CurBlock->TheScope, AI);
16975
16976 PushOnScopeChains(AI, CurBlock->TheScope);
16977 }
16978
16979 if (AI->isInvalidDecl())
16980 CurBlock->TheDecl->setInvalidDecl();
16981 }
16982}
16983
16984void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16985 // Leave the expression-evaluation context.
16988
16989 // Pop off CurBlock, handle nested blocks.
16992}
16993
16995 Stmt *Body, Scope *CurScope) {
16996 // If blocks are disabled, emit an error.
16997 if (!LangOpts.Blocks)
16998 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16999
17000 // Leave the expression-evaluation context.
17003 assert(!Cleanup.exprNeedsCleanups() &&
17004 "cleanups within block not correctly bound!");
17006
17008 BlockDecl *BD = BSI->TheDecl;
17009
17011
17012 if (BSI->HasImplicitReturnType)
17014
17015 QualType RetTy = Context.VoidTy;
17016 if (!BSI->ReturnType.isNull())
17017 RetTy = BSI->ReturnType;
17018
17019 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17020 QualType BlockTy;
17021
17022 // If the user wrote a function type in some form, try to use that.
17023 if (!BSI->FunctionType.isNull()) {
17024 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17025
17026 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17027 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17028
17029 // Turn protoless block types into nullary block types.
17030 if (isa<FunctionNoProtoType>(FTy)) {
17032 EPI.ExtInfo = Ext;
17033 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17034
17035 // Otherwise, if we don't need to change anything about the function type,
17036 // preserve its sugar structure.
17037 } else if (FTy->getReturnType() == RetTy &&
17038 (!NoReturn || FTy->getNoReturnAttr())) {
17039 BlockTy = BSI->FunctionType;
17040
17041 // Otherwise, make the minimal modifications to the function type.
17042 } else {
17045 EPI.TypeQuals = Qualifiers();
17046 EPI.ExtInfo = Ext;
17047 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17048 }
17049
17050 // If we don't have a function type, just build one from nothing.
17051 } else {
17053 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17054 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17055 }
17056
17058 BlockTy = Context.getBlockPointerType(BlockTy);
17059
17060 // If needed, diagnose invalid gotos and switches in the block.
17061 if (getCurFunction()->NeedsScopeChecking() &&
17062 !PP.isCodeCompletionEnabled())
17064
17065 BD->setBody(cast<CompoundStmt>(Body));
17066
17067 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17069
17070 // Try to apply the named return value optimization. We have to check again
17071 // if we can do this, though, because blocks keep return statements around
17072 // to deduce an implicit return type.
17073 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17074 !BD->isDependentContext())
17075 computeNRVO(Body, BSI);
17076
17082
17084
17085 // Set the captured variables on the block.
17087 for (Capture &Cap : BSI->Captures) {
17088 if (Cap.isInvalid() || Cap.isThisCapture())
17089 continue;
17090 // Cap.getVariable() is always a VarDecl because
17091 // blocks cannot capture structured bindings or other ValueDecl kinds.
17092 auto *Var = cast<VarDecl>(Cap.getVariable());
17093 Expr *CopyExpr = nullptr;
17094 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17095 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17096 // The capture logic needs the destructor, so make sure we mark it.
17097 // Usually this is unnecessary because most local variables have
17098 // their destructors marked at declaration time, but parameters are
17099 // an exception because it's technically only the call site that
17100 // actually requires the destructor.
17101 if (isa<ParmVarDecl>(Var))
17103
17104 // Enter a separate potentially-evaluated context while building block
17105 // initializers to isolate their cleanups from those of the block
17106 // itself.
17107 // FIXME: Is this appropriate even when the block itself occurs in an
17108 // unevaluated operand?
17111
17112 SourceLocation Loc = Cap.getLocation();
17113
17115 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17116
17117 // According to the blocks spec, the capture of a variable from
17118 // the stack requires a const copy constructor. This is not true
17119 // of the copy/move done to move a __block variable to the heap.
17120 if (!Result.isInvalid() &&
17121 !Result.get()->getType().isConstQualified()) {
17123 Result.get()->getType().withConst(),
17124 CK_NoOp, VK_LValue);
17125 }
17126
17127 if (!Result.isInvalid()) {
17129 InitializedEntity::InitializeBlock(Var->getLocation(),
17130 Cap.getCaptureType()),
17131 Loc, Result.get());
17132 }
17133
17134 // Build a full-expression copy expression if initialization
17135 // succeeded and used a non-trivial constructor. Recover from
17136 // errors by pretending that the copy isn't necessary.
17137 if (!Result.isInvalid() &&
17138 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17139 ->isTrivial()) {
17141 CopyExpr = Result.get();
17142 }
17143 }
17144 }
17145
17146 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17147 CopyExpr);
17148 Captures.push_back(NewCap);
17149 }
17150 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17151
17152 // Pop the block scope now but keep it alive to the end of this function.
17154 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
17155 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17156
17157 BlockExpr *Result = new (Context)
17158 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17159
17160 // If the block isn't obviously global, i.e. it captures anything at
17161 // all, then we need to do a few things in the surrounding context:
17162 if (Result->getBlockDecl()->hasCaptures()) {
17163 // First, this expression has a new cleanup object.
17164 ExprCleanupObjects.push_back(Result->getBlockDecl());
17165 Cleanup.setExprNeedsCleanups(true);
17166
17167 // It also gets a branch-protected scope if any of the captured
17168 // variables needs destruction.
17169 for (const auto &CI : Result->getBlockDecl()->captures()) {
17170 const VarDecl *var = CI.getVariable();
17171 if (var->getType().isDestructedType() != QualType::DK_none) {
17173 break;
17174 }
17175 }
17176 }
17177
17178 if (getCurFunction())
17179 getCurFunction()->addBlock(BD);
17180
17181 // This can happen if the block's return type is deduced, but
17182 // the return expression is invalid.
17183 if (BD->isInvalidDecl())
17184 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17185 {Result}, Result->getType());
17186 return Result;
17187}
17188
17190 SourceLocation RPLoc) {
17191 TypeSourceInfo *TInfo;
17192 GetTypeFromParser(Ty, &TInfo);
17193 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17194}
17195
17197 Expr *E, TypeSourceInfo *TInfo,
17198 SourceLocation RPLoc) {
17199 Expr *OrigExpr = E;
17200 bool IsMS = false;
17201
17202 // CUDA device global function does not support varargs.
17203 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17204 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17207 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17208 }
17209 }
17210
17211 // NVPTX does not support va_arg expression.
17212 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17213 Context.getTargetInfo().getTriple().isNVPTX())
17214 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17215
17216 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17217 // as Microsoft ABI on an actual Microsoft platform, where
17218 // __builtin_ms_va_list and __builtin_va_list are the same.)
17219 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17220 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17221 QualType MSVaListType = Context.getBuiltinMSVaListType();
17222 if (Context.hasSameType(MSVaListType, E->getType())) {
17223 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17224 return ExprError();
17225 IsMS = true;
17226 }
17227 }
17228
17229 // Get the va_list type
17230 QualType VaListType = Context.getBuiltinVaListType();
17231 if (!IsMS) {
17232 if (VaListType->isArrayType()) {
17233 // Deal with implicit array decay; for example, on x86-64,
17234 // va_list is an array, but it's supposed to decay to
17235 // a pointer for va_arg.
17236 VaListType = Context.getArrayDecayedType(VaListType);
17237 // Make sure the input expression also decays appropriately.
17239 if (Result.isInvalid())
17240 return ExprError();
17241 E = Result.get();
17242 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17243 // If va_list is a record type and we are compiling in C++ mode,
17244 // check the argument using reference binding.
17246 Context, Context.getLValueReferenceType(VaListType), false);
17248 if (Init.isInvalid())
17249 return ExprError();
17250 E = Init.getAs<Expr>();
17251 } else {
17252 // Otherwise, the va_list argument must be an l-value because
17253 // it is modified by va_arg.
17254 if (!E->isTypeDependent() &&
17255 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17256 return ExprError();
17257 }
17258 }
17259
17260 if (!IsMS && !E->isTypeDependent() &&
17261 !Context.hasSameType(VaListType, E->getType()))
17262 return ExprError(
17263 Diag(E->getBeginLoc(),
17264 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17265 << OrigExpr->getType() << E->getSourceRange());
17266
17267 if (!TInfo->getType()->isDependentType()) {
17268 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17269 diag::err_second_parameter_to_va_arg_incomplete,
17270 TInfo->getTypeLoc()))
17271 return ExprError();
17272
17274 TInfo->getType(),
17275 diag::err_second_parameter_to_va_arg_abstract,
17276 TInfo->getTypeLoc()))
17277 return ExprError();
17278
17279 if (!TInfo->getType().isPODType(Context)) {
17280 Diag(TInfo->getTypeLoc().getBeginLoc(),
17281 TInfo->getType()->isObjCLifetimeType()
17282 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17283 : diag::warn_second_parameter_to_va_arg_not_pod)
17284 << TInfo->getType()
17285 << TInfo->getTypeLoc().getSourceRange();
17286 }
17287
17288 if (TInfo->getType()->isArrayType()) {
17290 PDiag(diag::warn_second_parameter_to_va_arg_array)
17291 << TInfo->getType()
17292 << TInfo->getTypeLoc().getSourceRange());
17293 }
17294
17295 // Check for va_arg where arguments of the given type will be promoted
17296 // (i.e. this va_arg is guaranteed to have undefined behavior).
17297 QualType PromoteType;
17298 if (Context.isPromotableIntegerType(TInfo->getType())) {
17299 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17300 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17301 // and C23 7.16.1.1p2 says, in part:
17302 // If type is not compatible with the type of the actual next argument
17303 // (as promoted according to the default argument promotions), the
17304 // behavior is undefined, except for the following cases:
17305 // - both types are pointers to qualified or unqualified versions of
17306 // compatible types;
17307 // - one type is compatible with a signed integer type, the other
17308 // type is compatible with the corresponding unsigned integer type,
17309 // and the value is representable in both types;
17310 // - one type is pointer to qualified or unqualified void and the
17311 // other is a pointer to a qualified or unqualified character type;
17312 // - or, the type of the next argument is nullptr_t and type is a
17313 // pointer type that has the same representation and alignment
17314 // requirements as a pointer to a character type.
17315 // Given that type compatibility is the primary requirement (ignoring
17316 // qualifications), you would think we could call typesAreCompatible()
17317 // directly to test this. However, in C++, that checks for *same type*,
17318 // which causes false positives when passing an enumeration type to
17319 // va_arg. Instead, get the underlying type of the enumeration and pass
17320 // that.
17321 QualType UnderlyingType = TInfo->getType();
17322 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17323 UnderlyingType = ED->getIntegerType();
17324 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17325 /*CompareUnqualified*/ true))
17326 PromoteType = QualType();
17327
17328 // If the types are still not compatible, we need to test whether the
17329 // promoted type and the underlying type are the same except for
17330 // signedness. Ask the AST for the correctly corresponding type and see
17331 // if that's compatible.
17332 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17333 PromoteType->isUnsignedIntegerType() !=
17334 UnderlyingType->isUnsignedIntegerType()) {
17335 UnderlyingType =
17336 UnderlyingType->isUnsignedIntegerType()
17337 ? Context.getCorrespondingSignedType(UnderlyingType)
17338 : Context.getCorrespondingUnsignedType(UnderlyingType);
17339 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17340 /*CompareUnqualified*/ true))
17341 PromoteType = QualType();
17342 }
17343 }
17344 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17345 PromoteType = Context.DoubleTy;
17346 if (!PromoteType.isNull())
17348 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17349 << TInfo->getType()
17350 << PromoteType
17351 << TInfo->getTypeLoc().getSourceRange());
17352 }
17353
17355 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17356}
17357
17359 // The type of __null will be int or long, depending on the size of
17360 // pointers on the target.
17361 QualType Ty;
17362 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17363 if (pw == Context.getTargetInfo().getIntWidth())
17364 Ty = Context.IntTy;
17365 else if (pw == Context.getTargetInfo().getLongWidth())
17366 Ty = Context.LongTy;
17367 else if (pw == Context.getTargetInfo().getLongLongWidth())
17368 Ty = Context.LongLongTy;
17369 else {
17370 llvm_unreachable("I don't know size of pointer!");
17371 }
17372
17373 return new (Context) GNUNullExpr(Ty, TokenLoc);
17374}
17375
17377 CXXRecordDecl *ImplDecl = nullptr;
17378
17379 // Fetch the std::source_location::__impl decl.
17380 if (NamespaceDecl *Std = S.getStdNamespace()) {
17381 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17383 if (S.LookupQualifiedName(ResultSL, Std)) {
17384 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17385 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17387 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17388 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17389 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17390 }
17391 }
17392 }
17393 }
17394
17395 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17396 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17397 return nullptr;
17398 }
17399
17400 // Verify that __impl is a trivial struct type, with no base classes, and with
17401 // only the four expected fields.
17402 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17403 ImplDecl->getNumBases() != 0) {
17404 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17405 return nullptr;
17406 }
17407
17408 unsigned Count = 0;
17409 for (FieldDecl *F : ImplDecl->fields()) {
17410 StringRef Name = F->getName();
17411
17412 if (Name == "_M_file_name") {
17413 if (F->getType() !=
17415 break;
17416 Count++;
17417 } else if (Name == "_M_function_name") {
17418 if (F->getType() !=
17420 break;
17421 Count++;
17422 } else if (Name == "_M_line") {
17423 if (!F->getType()->isIntegerType())
17424 break;
17425 Count++;
17426 } else if (Name == "_M_column") {
17427 if (!F->getType()->isIntegerType())
17428 break;
17429 Count++;
17430 } else {
17431 Count = 100; // invalid
17432 break;
17433 }
17434 }
17435 if (Count != 4) {
17436 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17437 return nullptr;
17438 }
17439
17440 return ImplDecl;
17441}
17442
17444 SourceLocation BuiltinLoc,
17445 SourceLocation RPLoc) {
17446 QualType ResultTy;
17447 switch (Kind) {
17452 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17453 ResultTy =
17454 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17455 break;
17456 }
17459 ResultTy = Context.UnsignedIntTy;
17460 break;
17464 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17466 return ExprError();
17467 }
17468 ResultTy = Context.getPointerType(
17469 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17470 break;
17471 }
17472
17473 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17474}
17475
17477 SourceLocation BuiltinLoc,
17478 SourceLocation RPLoc,
17479 DeclContext *ParentContext) {
17480 return new (Context)
17481 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17482}
17483
17485 StringLiteral *BinaryData, StringRef FileName) {
17487 Data->BinaryData = BinaryData;
17488 Data->FileName = FileName;
17489 return new (Context)
17490 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17491 Data->getDataElementCount());
17492}
17493
17495 const Expr *SrcExpr) {
17496 if (!DstType->isFunctionPointerType() ||
17497 !SrcExpr->getType()->isFunctionType())
17498 return false;
17499
17500 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17501 if (!DRE)
17502 return false;
17503
17504 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17505 if (!FD)
17506 return false;
17507
17509 /*Complain=*/true,
17510 SrcExpr->getBeginLoc());
17511}
17512
17514 SourceLocation Loc,
17515 QualType DstType, QualType SrcType,
17516 Expr *SrcExpr, AssignmentAction Action,
17517 bool *Complained) {
17518 if (Complained)
17519 *Complained = false;
17520
17521 // Decode the result (notice that AST's are still created for extensions).
17522 bool CheckInferredResultType = false;
17523 bool isInvalid = false;
17524 unsigned DiagKind = 0;
17525 ConversionFixItGenerator ConvHints;
17526 bool MayHaveConvFixit = false;
17527 bool MayHaveFunctionDiff = false;
17528 const ObjCInterfaceDecl *IFace = nullptr;
17529 const ObjCProtocolDecl *PDecl = nullptr;
17530
17531 switch (ConvTy) {
17533 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17534 return false;
17536 // Still a valid conversion, but we may want to diagnose for C++
17537 // compatibility reasons.
17538 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17539 break;
17541 if (getLangOpts().CPlusPlus) {
17542 DiagKind = diag::err_typecheck_convert_pointer_int;
17543 isInvalid = true;
17544 } else {
17545 DiagKind = diag::ext_typecheck_convert_pointer_int;
17546 }
17547 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17548 MayHaveConvFixit = true;
17549 break;
17551 if (getLangOpts().CPlusPlus) {
17552 DiagKind = diag::err_typecheck_convert_int_pointer;
17553 isInvalid = true;
17554 } else {
17555 DiagKind = diag::ext_typecheck_convert_int_pointer;
17556 }
17557 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17558 MayHaveConvFixit = true;
17559 break;
17561 DiagKind =
17562 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17563 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17564 MayHaveConvFixit = true;
17565 break;
17567 if (getLangOpts().CPlusPlus) {
17568 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17569 isInvalid = true;
17570 } else {
17571 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17572 }
17573 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17574 MayHaveConvFixit = true;
17575 break;
17578 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17579 } else if (getLangOpts().CPlusPlus) {
17580 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17581 isInvalid = true;
17582 } else {
17583 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17584 }
17585 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17586 SrcType->isObjCObjectPointerType();
17587 if (CheckInferredResultType) {
17588 SrcType = SrcType.getUnqualifiedType();
17589 DstType = DstType.getUnqualifiedType();
17590 } else {
17591 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17592 }
17593 MayHaveConvFixit = true;
17594 break;
17596 if (getLangOpts().CPlusPlus) {
17597 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17598 isInvalid = true;
17599 } else {
17600 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17601 }
17602 break;
17604 if (getLangOpts().CPlusPlus) {
17605 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17606 isInvalid = true;
17607 } else {
17608 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17609 }
17610 break;
17612 // Perform decay if necessary.
17613 if (SrcType->canDecayToPointerType())
17614 SrcType = Context.getDecayedType(SrcType);
17615
17616 isInvalid = true;
17617
17618 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17619 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17620 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17621 DiagKind = diag::err_typecheck_incompatible_address_space;
17622 break;
17623 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17624 DiagKind = diag::err_typecheck_incompatible_ownership;
17625 break;
17626 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17627 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17628 break;
17629 }
17630
17631 llvm_unreachable("unknown error case for discarding qualifiers!");
17632 // fallthrough
17633 }
17635 if (SrcType->isArrayType())
17636 SrcType = Context.getArrayDecayedType(SrcType);
17637
17638 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17639 break;
17641 // If the qualifiers lost were because we were applying the
17642 // (deprecated) C++ conversion from a string literal to a char*
17643 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17644 // Ideally, this check would be performed in
17645 // checkPointerTypesForAssignment. However, that would require a
17646 // bit of refactoring (so that the second argument is an
17647 // expression, rather than a type), which should be done as part
17648 // of a larger effort to fix checkPointerTypesForAssignment for
17649 // C++ semantics.
17650 if (getLangOpts().CPlusPlus &&
17652 return false;
17653 if (getLangOpts().CPlusPlus) {
17654 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17655 isInvalid = true;
17656 } else {
17657 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17658 }
17659
17660 break;
17662 if (getLangOpts().CPlusPlus) {
17663 isInvalid = true;
17664 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17665 } else {
17666 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17667 }
17668 break;
17670 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17671 isInvalid = true;
17672 break;
17674 DiagKind = diag::err_int_to_block_pointer;
17675 isInvalid = true;
17676 break;
17678 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17679 isInvalid = true;
17680 break;
17682 if (SrcType->isObjCQualifiedIdType()) {
17683 const ObjCObjectPointerType *srcOPT =
17684 SrcType->castAs<ObjCObjectPointerType>();
17685 for (auto *srcProto : srcOPT->quals()) {
17686 PDecl = srcProto;
17687 break;
17688 }
17689 if (const ObjCInterfaceType *IFaceT =
17691 IFace = IFaceT->getDecl();
17692 }
17693 else if (DstType->isObjCQualifiedIdType()) {
17694 const ObjCObjectPointerType *dstOPT =
17695 DstType->castAs<ObjCObjectPointerType>();
17696 for (auto *dstProto : dstOPT->quals()) {
17697 PDecl = dstProto;
17698 break;
17699 }
17700 if (const ObjCInterfaceType *IFaceT =
17702 IFace = IFaceT->getDecl();
17703 }
17704 if (getLangOpts().CPlusPlus) {
17705 DiagKind = diag::err_incompatible_qualified_id;
17706 isInvalid = true;
17707 } else {
17708 DiagKind = diag::warn_incompatible_qualified_id;
17709 }
17710 break;
17711 }
17713 if (getLangOpts().CPlusPlus) {
17714 DiagKind = diag::err_incompatible_vectors;
17715 isInvalid = true;
17716 } else {
17717 DiagKind = diag::warn_incompatible_vectors;
17718 }
17719 break;
17721 DiagKind = diag::err_arc_weak_unavailable_assign;
17722 isInvalid = true;
17723 break;
17725 return false;
17727 assert(!SrcType->isFunctionType() &&
17728 "Unexpected function type found in IncompatibleOBTKinds assignment");
17729 if (SrcType->canDecayToPointerType())
17730 SrcType = Context.getDecayedType(SrcType);
17731
17732 auto getOBTKindName = [](QualType Ty) -> StringRef {
17733 if (Ty->isPointerType())
17734 Ty = Ty->getPointeeType();
17735 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17736 return OBT->getBehaviorKind() ==
17737 OverflowBehaviorType::OverflowBehaviorKind::Trap
17738 ? "__ob_trap"
17739 : "__ob_wrap";
17740 }
17741 llvm_unreachable("OBT kind unhandled");
17742 };
17743
17744 Diag(Loc, diag::err_incompatible_obt_kinds_assignment)
17745 << DstType << SrcType << getOBTKindName(DstType)
17746 << getOBTKindName(SrcType);
17747 isInvalid = true;
17748 return true;
17749 }
17751 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17752 if (Complained)
17753 *Complained = true;
17754 return true;
17755 }
17756
17757 DiagKind = diag::err_typecheck_convert_incompatible;
17758 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17759 MayHaveConvFixit = true;
17760 isInvalid = true;
17761 MayHaveFunctionDiff = true;
17762 break;
17763 }
17764
17765 QualType FirstType, SecondType;
17766 switch (Action) {
17769 // The destination type comes first.
17770 FirstType = DstType;
17771 SecondType = SrcType;
17772 break;
17773
17780 // The source type comes first.
17781 FirstType = SrcType;
17782 SecondType = DstType;
17783 break;
17784 }
17785
17786 PartialDiagnostic FDiag = PDiag(DiagKind);
17787 AssignmentAction ActionForDiag = Action;
17789 ActionForDiag = AssignmentAction::Passing;
17790
17791 FDiag << FirstType << SecondType << ActionForDiag
17792 << SrcExpr->getSourceRange();
17793
17794 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17795 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17796 auto isPlainChar = [](const clang::Type *Type) {
17797 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17798 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17799 };
17800 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17801 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17802 }
17803
17804 // If we can fix the conversion, suggest the FixIts.
17805 if (!ConvHints.isNull()) {
17806 for (FixItHint &H : ConvHints.Hints)
17807 FDiag << H;
17808 }
17809
17810 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17811
17812 if (MayHaveFunctionDiff)
17813 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17814
17815 Diag(Loc, FDiag);
17816 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17817 DiagKind == diag::err_incompatible_qualified_id) &&
17818 PDecl && IFace && !IFace->hasDefinition())
17819 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17820 << IFace << PDecl;
17821
17822 if (SecondType == Context.OverloadTy)
17824 FirstType, /*TakingAddress=*/true);
17825
17826 if (CheckInferredResultType)
17828
17829 if (Action == AssignmentAction::Returning &&
17832
17833 if (Complained)
17834 *Complained = true;
17835 return isInvalid;
17836}
17837
17839 llvm::APSInt *Result,
17840 AllowFoldKind CanFold) {
17841 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17842 public:
17843 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17844 QualType T) override {
17845 return S.Diag(Loc, diag::err_ice_not_integral)
17846 << T << S.LangOpts.CPlusPlus;
17847 }
17848 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17849 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17850 }
17851 } Diagnoser;
17852
17853 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17854}
17855
17857 llvm::APSInt *Result,
17858 unsigned DiagID,
17859 AllowFoldKind CanFold) {
17860 class IDDiagnoser : public VerifyICEDiagnoser {
17861 unsigned DiagID;
17862
17863 public:
17864 IDDiagnoser(unsigned DiagID)
17865 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17866
17867 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17868 return S.Diag(Loc, DiagID);
17869 }
17870 } Diagnoser(DiagID);
17871
17872 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17873}
17874
17880
17883 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17884}
17885
17888 VerifyICEDiagnoser &Diagnoser,
17889 AllowFoldKind CanFold) {
17890 SourceLocation DiagLoc = E->getBeginLoc();
17891
17892 if (getLangOpts().CPlusPlus11) {
17893 // C++11 [expr.const]p5:
17894 // If an expression of literal class type is used in a context where an
17895 // integral constant expression is required, then that class type shall
17896 // have a single non-explicit conversion function to an integral or
17897 // unscoped enumeration type
17898 ExprResult Converted;
17899 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17900 VerifyICEDiagnoser &BaseDiagnoser;
17901 public:
17902 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17903 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17904 BaseDiagnoser.Suppress, true),
17905 BaseDiagnoser(BaseDiagnoser) {}
17906
17907 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17908 QualType T) override {
17909 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17910 }
17911
17912 SemaDiagnosticBuilder diagnoseIncomplete(
17913 Sema &S, SourceLocation Loc, QualType T) override {
17914 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17915 }
17916
17917 SemaDiagnosticBuilder diagnoseExplicitConv(
17918 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17919 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17920 }
17921
17922 SemaDiagnosticBuilder noteExplicitConv(
17923 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17924 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17925 << ConvTy->isEnumeralType() << ConvTy;
17926 }
17927
17928 SemaDiagnosticBuilder diagnoseAmbiguous(
17929 Sema &S, SourceLocation Loc, QualType T) override {
17930 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17931 }
17932
17933 SemaDiagnosticBuilder noteAmbiguous(
17934 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17935 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17936 << ConvTy->isEnumeralType() << ConvTy;
17937 }
17938
17939 SemaDiagnosticBuilder diagnoseConversion(
17940 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17941 llvm_unreachable("conversion functions are permitted");
17942 }
17943 } ConvertDiagnoser(Diagnoser);
17944
17945 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17946 ConvertDiagnoser);
17947 if (Converted.isInvalid())
17948 return Converted;
17949 E = Converted.get();
17950 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17951 // don't try to evaluate it later. We also don't want to return the
17952 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17953 // this function will attempt to use 'Value'.
17954 if (isa<RecoveryExpr>(E))
17955 return ExprError();
17957 return ExprError();
17958 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17959 // An ICE must be of integral or unscoped enumeration type.
17960 if (!Diagnoser.Suppress)
17961 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17962 << E->getSourceRange();
17963 return ExprError();
17964 }
17965
17966 ExprResult RValueExpr = DefaultLvalueConversion(E);
17967 if (RValueExpr.isInvalid())
17968 return ExprError();
17969
17970 E = RValueExpr.get();
17971
17972 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17973 // in the non-ICE case.
17976 if (Result)
17978 if (!isa<ConstantExpr>(E))
17981
17982 if (Notes.empty())
17983 return E;
17984
17985 // If our only note is the usual "invalid subexpression" note, just point
17986 // the caret at its location rather than producing an essentially
17987 // redundant note.
17988 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17989 diag::note_invalid_subexpr_in_const_expr) {
17990 DiagLoc = Notes[0].first;
17991 Notes.clear();
17992 }
17993
17994 if (getLangOpts().CPlusPlus) {
17995 if (!Diagnoser.Suppress) {
17996 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17997 for (const PartialDiagnosticAt &Note : Notes)
17998 Diag(Note.first, Note.second);
17999 }
18000 return ExprError();
18001 }
18002
18003 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18004 for (const PartialDiagnosticAt &Note : Notes)
18005 Diag(Note.first, Note.second);
18006
18007 return E;
18008 }
18009
18010 Expr::EvalResult EvalResult;
18012 EvalResult.Diag = &Notes;
18013
18014 // Try to evaluate the expression, and produce diagnostics explaining why it's
18015 // not a constant expression as a side-effect.
18016 bool Folded =
18017 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
18018 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18019 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18020
18021 if (!isa<ConstantExpr>(E))
18022 E = ConstantExpr::Create(Context, E, EvalResult.Val);
18023
18024 // In C++11, we can rely on diagnostics being produced for any expression
18025 // which is not a constant expression. If no diagnostics were produced, then
18026 // this is a constant expression.
18027 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18028 if (Result)
18029 *Result = EvalResult.Val.getInt();
18030 return E;
18031 }
18032
18033 // If our only note is the usual "invalid subexpression" note, just point
18034 // the caret at its location rather than producing an essentially
18035 // redundant note.
18036 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18037 diag::note_invalid_subexpr_in_const_expr) {
18038 DiagLoc = Notes[0].first;
18039 Notes.clear();
18040 }
18041
18042 if (!Folded || CanFold == AllowFoldKind::No) {
18043 if (!Diagnoser.Suppress) {
18044 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18045 for (const PartialDiagnosticAt &Note : Notes)
18046 Diag(Note.first, Note.second);
18047 }
18048
18049 return ExprError();
18050 }
18051
18052 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18053 for (const PartialDiagnosticAt &Note : Notes)
18054 Diag(Note.first, Note.second);
18055
18056 if (Result)
18057 *Result = EvalResult.Val.getInt();
18058 return E;
18059}
18060
18061namespace {
18062 // Handle the case where we conclude a expression which we speculatively
18063 // considered to be unevaluated is actually evaluated.
18064 class TransformToPE : public TreeTransform<TransformToPE> {
18065 typedef TreeTransform<TransformToPE> BaseTransform;
18066
18067 public:
18068 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18069
18070 // Make sure we redo semantic analysis
18071 bool AlwaysRebuild() { return true; }
18072 bool ReplacingOriginal() { return true; }
18073
18074 // We need to special-case DeclRefExprs referring to FieldDecls which
18075 // are not part of a member pointer formation; normal TreeTransforming
18076 // doesn't catch this case because of the way we represent them in the AST.
18077 // FIXME: This is a bit ugly; is it really the best way to handle this
18078 // case?
18079 //
18080 // Error on DeclRefExprs referring to FieldDecls.
18081 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18082 if (isa<FieldDecl>(E->getDecl()) &&
18083 !SemaRef.isUnevaluatedContext())
18084 return SemaRef.Diag(E->getLocation(),
18085 diag::err_invalid_non_static_member_use)
18086 << E->getDecl() << E->getSourceRange();
18087
18088 return BaseTransform::TransformDeclRefExpr(E);
18089 }
18090
18091 // Exception: filter out member pointer formation
18092 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18093 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18094 return E;
18095
18096 return BaseTransform::TransformUnaryOperator(E);
18097 }
18098
18099 // The body of a lambda-expression is in a separate expression evaluation
18100 // context so never needs to be transformed.
18101 // FIXME: Ideally we wouldn't transform the closure type either, and would
18102 // just recreate the capture expressions and lambda expression.
18103 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18104 return SkipLambdaBody(E, Body);
18105 }
18106 };
18107}
18108
18110 assert(isUnevaluatedContext() &&
18111 "Should only transform unevaluated expressions");
18112 ExprEvalContexts.back().Context =
18113 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18115 return E;
18116 return TransformToPE(*this).TransformExpr(E);
18117}
18118
18120 assert(isUnevaluatedContext() &&
18121 "Should only transform unevaluated expressions");
18124 return TInfo;
18125 return TransformToPE(*this).TransformType(TInfo);
18126}
18127
18128void
18130 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18132 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18133 LambdaContextDecl, ExprContext);
18134
18135 // Discarded statements and immediate contexts nested in other
18136 // discarded statements or immediate context are themselves
18137 // a discarded statement or an immediate context, respectively.
18138 ExprEvalContexts.back().InDiscardedStatement =
18140
18141 // C++23 [expr.const]/p15
18142 // An expression or conversion is in an immediate function context if [...]
18143 // it is a subexpression of a manifestly constant-evaluated expression or
18144 // conversion.
18145 const auto &Prev = parentEvaluationContext();
18146 ExprEvalContexts.back().InImmediateFunctionContext =
18147 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18148
18149 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18150 Prev.InImmediateEscalatingFunctionContext;
18151
18152 Cleanup.reset();
18153 if (!MaybeODRUseExprs.empty())
18154 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18155}
18156
18157void
18161 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18162 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18163}
18164
18166 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18167 // [expr.const]/p14.1
18168 // An expression or conversion is in an immediate function context if it is
18169 // potentially evaluated and either: its innermost enclosing non-block scope
18170 // is a function parameter scope of an immediate function.
18172 FD && FD->isConsteval()
18174 : NewContext);
18178
18179 Current.InDiscardedStatement = false;
18180
18181 if (FD) {
18182
18183 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18184 // context is nested in an immediate function context, so smaller contexts
18185 // that appear inside immediate functions (like variable initializers) are
18186 // considered to be inside an immediate function context even though by
18187 // themselves they are not immediate function contexts. But when a new
18188 // function is entered, we need to reset this tracking, since the entered
18189 // function might be not an immediate function.
18190
18192 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18193
18194 if (isLambdaMethod(FD))
18196 FD->isConsteval() ||
18197 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
18198 Parent.isImmediateFunctionContext()));
18199 else
18201 }
18202}
18203
18205 TypeSourceInfo *TSI) {
18206 return BuildCXXReflectExpr(CaretCaretLoc, TSI);
18207}
18208
18210 TypeSourceInfo *TSI) {
18211 return CXXReflectExpr::Create(Context, CaretCaretLoc, TSI);
18212}
18213
18214namespace {
18215
18216const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18217 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18218 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18219 if (E->getOpcode() == UO_Deref)
18220 return CheckPossibleDeref(S, E->getSubExpr());
18221 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18222 return CheckPossibleDeref(S, E->getBase());
18223 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18224 return CheckPossibleDeref(S, E->getBase());
18225 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18226 QualType Inner;
18227 QualType Ty = E->getType();
18228 if (const auto *Ptr = Ty->getAs<PointerType>())
18229 Inner = Ptr->getPointeeType();
18230 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18231 Inner = Arr->getElementType();
18232 else
18233 return nullptr;
18234
18235 if (Inner->hasAttr(attr::NoDeref))
18236 return E;
18237 }
18238 return nullptr;
18239}
18240
18241} // namespace
18242
18244 for (const Expr *E : Rec.PossibleDerefs) {
18245 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18246 if (DeclRef) {
18247 const ValueDecl *Decl = DeclRef->getDecl();
18248 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18249 << Decl->getName() << E->getSourceRange();
18250 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18251 } else {
18252 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18253 << E->getSourceRange();
18254 }
18255 }
18256 Rec.PossibleDerefs.clear();
18257}
18258
18261 return;
18262
18263 // Note: ignoring parens here is not justified by the standard rules, but
18264 // ignoring parentheses seems like a more reasonable approach, and this only
18265 // drives a deprecation warning so doesn't affect conformance.
18266 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18267 if (BO->getOpcode() == BO_Assign) {
18268 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18269 llvm::erase(LHSs, BO->getLHS());
18270 }
18271 }
18272}
18273
18275 assert(getLangOpts().CPlusPlus20 &&
18276 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18277 "Cannot mark an immediate escalating expression outside of an "
18278 "immediate escalating context");
18279 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18280 Call && Call->getCallee()) {
18281 if (auto *DeclRef =
18282 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18283 DeclRef->setIsImmediateEscalating(true);
18284 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18285 Ctr->setIsImmediateEscalating(true);
18286 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18287 DeclRef->setIsImmediateEscalating(true);
18288 } else {
18289 assert(false && "expected an immediately escalating expression");
18290 }
18292 FI->FoundImmediateEscalatingExpression = true;
18293}
18294
18296 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18297 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18300 return E;
18301
18302 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18303 /// It's OK if this fails; we'll also remove this in
18304 /// HandleImmediateInvocations, but catching it here allows us to avoid
18305 /// walking the AST looking for it in simple cases.
18306 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18307 if (auto *DeclRef =
18308 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18309 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18310
18311 // C++23 [expr.const]/p16
18312 // An expression or conversion is immediate-escalating if it is not initially
18313 // in an immediate function context and it is [...] an immediate invocation
18314 // that is not a constant expression and is not a subexpression of an
18315 // immediate invocation.
18316 APValue Cached;
18317 auto CheckConstantExpressionAndKeepResult = [&]() {
18319 Expr::EvalResult Eval;
18320 Eval.Diag = &Notes;
18321 bool Res = E.get()->EvaluateAsConstantExpr(
18322 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18323 if (Res && Notes.empty()) {
18324 Cached = std::move(Eval.Val);
18325 return true;
18326 }
18327 return false;
18328 };
18329
18330 if (!E.get()->isValueDependent() &&
18331 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18332 !CheckConstantExpressionAndKeepResult()) {
18334 return E;
18335 }
18336
18337 if (Cleanup.exprNeedsCleanups()) {
18338 // Since an immediate invocation is a full expression itself - it requires
18339 // an additional ExprWithCleanups node, but it can participate to a bigger
18340 // full expression which actually requires cleanups to be run after so
18341 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18342 // may discard cleanups for outer expression too early.
18343
18344 // Note that ExprWithCleanups created here must always have empty cleanup
18345 // objects:
18346 // - compound literals do not create cleanup objects in C++ and immediate
18347 // invocations are C++-only.
18348 // - blocks are not allowed inside constant expressions and compiler will
18349 // issue an error if they appear there.
18350 //
18351 // Hence, in correct code any cleanup objects created inside current
18352 // evaluation context must be outside the immediate invocation.
18354 Cleanup.cleanupsHaveSideEffects(), {});
18355 }
18356
18358 getASTContext(), E.get(),
18359 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18360 getASTContext()),
18361 /*IsImmediateInvocation*/ true);
18362 if (Cached.hasValue())
18363 Res->MoveIntoResult(Cached, getASTContext());
18364 /// Value-dependent constant expressions should not be immediately
18365 /// evaluated until they are instantiated.
18366 if (!Res->isValueDependent())
18367 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18368 return Res;
18369}
18370
18374 Expr::EvalResult Eval;
18375 Eval.Diag = &Notes;
18376 ConstantExpr *CE = Candidate.getPointer();
18377 bool Result = CE->EvaluateAsConstantExpr(
18378 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18379 if (!Result || !Notes.empty()) {
18381 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18382 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18383 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18384 FunctionDecl *FD = nullptr;
18385 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18386 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18387 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18388 FD = Call->getConstructor();
18389 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18390 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18391
18392 assert(FD && FD->isImmediateFunction() &&
18393 "could not find an immediate function in this expression");
18394 if (FD->isInvalidDecl())
18395 return;
18396 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18397 << FD << FD->isConsteval();
18398 if (auto Context =
18400 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18401 << Context->Decl;
18402 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18403 }
18404 if (!FD->isConsteval())
18406 for (auto &Note : Notes)
18407 SemaRef.Diag(Note.first, Note.second);
18408 return;
18409 }
18411}
18412
18416 struct ComplexRemove : TreeTransform<ComplexRemove> {
18418 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18421 CurrentII;
18422 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18425 4>::reverse_iterator Current)
18426 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18427 void RemoveImmediateInvocation(ConstantExpr* E) {
18428 auto It = std::find_if(CurrentII, IISet.rend(),
18430 return Elem.getPointer() == E;
18431 });
18432 // It is possible that some subexpression of the current immediate
18433 // invocation was handled from another expression evaluation context. Do
18434 // not handle the current immediate invocation if some of its
18435 // subexpressions failed before.
18436 if (It == IISet.rend()) {
18437 if (SemaRef.FailedImmediateInvocations.contains(E))
18438 CurrentII->setInt(1);
18439 } else {
18440 It->setInt(1); // Mark as deleted
18441 }
18442 }
18443 ExprResult TransformConstantExpr(ConstantExpr *E) {
18444 if (!E->isImmediateInvocation())
18445 return Base::TransformConstantExpr(E);
18446 RemoveImmediateInvocation(E);
18447 return Base::TransformExpr(E->getSubExpr());
18448 }
18449 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18450 /// we need to remove its DeclRefExpr from the DRSet.
18451 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18452 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18453 return Base::TransformCXXOperatorCallExpr(E);
18454 }
18455 /// Base::TransformUserDefinedLiteral doesn't preserve the
18456 /// UserDefinedLiteral node.
18457 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18458 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18459 /// here.
18460 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18461 if (!Init)
18462 return Init;
18463
18464 // We cannot use IgnoreImpCasts because we need to preserve
18465 // full expressions.
18466 while (true) {
18467 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18468 Init = ICE->getSubExpr();
18469 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18470 Init = ICE->getSubExpr();
18471 else
18472 break;
18473 }
18474 /// ConstantExprs are the first layer of implicit node to be removed so if
18475 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18476 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18477 CE && CE->isImmediateInvocation())
18478 RemoveImmediateInvocation(CE);
18479 return Base::TransformInitializer(Init, NotCopyInit);
18480 }
18481 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18482 DRSet.erase(E);
18483 return E;
18484 }
18485 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18486 // Do not rebuild lambdas to avoid creating a new type.
18487 // Lambdas have already been processed inside their eval contexts.
18488 return E;
18489 }
18490 bool AlwaysRebuild() { return false; }
18491 bool ReplacingOriginal() { return true; }
18492 bool AllowSkippingCXXConstructExpr() {
18493 bool Res = AllowSkippingFirstCXXConstructExpr;
18494 AllowSkippingFirstCXXConstructExpr = true;
18495 return Res;
18496 }
18497 bool AllowSkippingFirstCXXConstructExpr = true;
18498 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18500
18501 /// CXXConstructExpr with a single argument are getting skipped by
18502 /// TreeTransform in some situtation because they could be implicit. This
18503 /// can only occur for the top-level CXXConstructExpr because it is used
18504 /// nowhere in the expression being transformed therefore will not be rebuilt.
18505 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18506 /// skipping the first CXXConstructExpr.
18507 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18508 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18509
18510 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18511 // The result may not be usable in case of previous compilation errors.
18512 // In this case evaluation of the expression may result in crash so just
18513 // don't do anything further with the result.
18514 if (Res.isUsable()) {
18516 It->getPointer()->setSubExpr(Res.get());
18517 }
18518}
18519
18520static void
18523 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18524 Rec.ReferenceToConsteval.size() == 0) ||
18526 return;
18527
18528 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18529 // [...]
18530 // - the initializer of a variable that is usable in constant expressions or
18531 // has constant initialization.
18532 if (SemaRef.getLangOpts().CPlusPlus23 &&
18533 Rec.ExprContext ==
18535 auto *VD = dyn_cast<VarDecl>(Rec.ManglingContextDecl);
18536 if (VD && (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18537 VD->hasConstantInitialization())) {
18538 // An expression or conversion is in an 'immediate function context' if it
18539 // is potentially evaluated and either:
18540 // [...]
18541 // - it is a subexpression of a manifestly constant-evaluated expression
18542 // or conversion.
18543 return;
18544 }
18545 }
18546
18547 /// When we have more than 1 ImmediateInvocationCandidates or previously
18548 /// failed immediate invocations, we need to check for nested
18549 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18550 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18551 /// invocation.
18552 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18554
18555 /// Prevent sema calls during the tree transform from adding pointers that
18556 /// are already in the sets.
18557 llvm::SaveAndRestore DisableIITracking(
18559
18560 /// Prevent diagnostic during tree transfrom as they are duplicates
18562
18563 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18564 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18565 if (!It->getInt())
18567 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18568 Rec.ReferenceToConsteval.size()) {
18569 struct SimpleRemove : DynamicRecursiveASTVisitor {
18570 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18571 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18572 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18573 DRSet.erase(E);
18574 return DRSet.size();
18575 }
18576 } Visitor(Rec.ReferenceToConsteval);
18577 Visitor.TraverseStmt(
18578 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18579 }
18580 for (auto CE : Rec.ImmediateInvocationCandidates)
18581 if (!CE.getInt())
18583 for (auto *DR : Rec.ReferenceToConsteval) {
18584 // If the expression is immediate escalating, it is not an error;
18585 // The outer context itself becomes immediate and further errors,
18586 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18587 if (DR->isImmediateEscalating())
18588 continue;
18589 auto *FD = cast<FunctionDecl>(DR->getDecl());
18590 const NamedDecl *ND = FD;
18591 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18592 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18593 ND = MD->getParent();
18594
18595 // C++23 [expr.const]/p16
18596 // An expression or conversion is immediate-escalating if it is not
18597 // initially in an immediate function context and it is [...] a
18598 // potentially-evaluated id-expression that denotes an immediate function
18599 // that is not a subexpression of an immediate invocation.
18600 bool ImmediateEscalating = false;
18601 bool IsPotentiallyEvaluated =
18602 Rec.Context ==
18604 Rec.Context ==
18606 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18607 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18608
18610 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18611 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18612 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18613 if (!FD->getBuiltinID())
18614 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18615 if (auto Context =
18617 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18618 << Context->Decl;
18619 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18620 }
18621 if (FD->isImmediateEscalating() && !FD->isConsteval())
18623
18624 } else {
18626 }
18627 }
18628}
18629
18632 if (!Rec.Lambdas.empty()) {
18634 if (!getLangOpts().CPlusPlus20 &&
18635 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18636 Rec.isUnevaluated() ||
18638 unsigned D;
18639 if (Rec.isUnevaluated()) {
18640 // C++11 [expr.prim.lambda]p2:
18641 // A lambda-expression shall not appear in an unevaluated operand
18642 // (Clause 5).
18643 D = diag::err_lambda_unevaluated_operand;
18644 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18645 // C++1y [expr.const]p2:
18646 // A conditional-expression e is a core constant expression unless the
18647 // evaluation of e, following the rules of the abstract machine, would
18648 // evaluate [...] a lambda-expression.
18649 D = diag::err_lambda_in_constant_expression;
18650 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18651 // C++17 [expr.prim.lamda]p2:
18652 // A lambda-expression shall not appear [...] in a template-argument.
18653 D = diag::err_lambda_in_invalid_context;
18654 } else
18655 llvm_unreachable("Couldn't infer lambda error message.");
18656
18657 for (const auto *L : Rec.Lambdas)
18658 Diag(L->getBeginLoc(), D);
18659 }
18660 }
18661
18662 // Append the collected materialized temporaries into previous context before
18663 // exit if the previous also is a lifetime extending context.
18665 parentEvaluationContext().InLifetimeExtendingContext &&
18666 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18669 }
18670
18672 HandleImmediateInvocations(*this, Rec);
18673
18674 // Warn on any volatile-qualified simple-assignments that are not discarded-
18675 // value expressions nor unevaluated operands (those cases get removed from
18676 // this list by CheckUnusedVolatileAssignment).
18677 for (auto *BO : Rec.VolatileAssignmentLHSs)
18678 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18679 << BO->getType();
18680
18681 // When are coming out of an unevaluated context, clear out any
18682 // temporaries that we may have created as part of the evaluation of
18683 // the expression in that context: they aren't relevant because they
18684 // will never be constructed.
18685 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18687 ExprCleanupObjects.end());
18688 Cleanup = Rec.ParentCleanup;
18691 // Otherwise, merge the contexts together.
18692 } else {
18693 Cleanup.mergeFrom(Rec.ParentCleanup);
18694 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18695 }
18696
18698
18699 // Pop the current expression evaluation context off the stack.
18700 ExprEvalContexts.pop_back();
18701}
18702
18704 ExprCleanupObjects.erase(
18705 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18706 ExprCleanupObjects.end());
18707 Cleanup.reset();
18708 MaybeODRUseExprs.clear();
18709}
18710
18713 if (Result.isInvalid())
18714 return ExprError();
18715 E = Result.get();
18716 if (!E->getType()->isVariablyModifiedType())
18717 return E;
18719}
18720
18721/// Are we in a context that is potentially constant evaluated per C++20
18722/// [expr.const]p12?
18724 /// C++2a [expr.const]p12:
18725 // An expression or conversion is potentially constant evaluated if it is
18726 switch (SemaRef.ExprEvalContexts.back().Context) {
18729
18730 // -- a manifestly constant-evaluated expression,
18734 // -- a potentially-evaluated expression,
18736 // -- an immediate subexpression of a braced-init-list,
18737
18738 // -- [FIXME] an expression of the form & cast-expression that occurs
18739 // within a templated entity
18740 // -- a subexpression of one of the above that is not a subexpression of
18741 // a nested unevaluated operand.
18742 return true;
18743
18746 // Expressions in this context are never evaluated.
18747 return false;
18748 }
18749 llvm_unreachable("Invalid context");
18750}
18751
18752/// Return true if this function has a calling convention that requires mangling
18753/// in the size of the parameter pack.
18755 // These manglings are only applicable for targets whcih use Microsoft
18756 // mangling scheme for C.
18758 return false;
18759
18760 // If this is C++ and this isn't an extern "C" function, parameters do not
18761 // need to be complete. In this case, C++ mangling will apply, which doesn't
18762 // use the size of the parameters.
18763 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18764 return false;
18765
18766 // Stdcall, fastcall, and vectorcall need this special treatment.
18767 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18768 switch (CC) {
18769 case CC_X86StdCall:
18770 case CC_X86FastCall:
18771 case CC_X86VectorCall:
18772 return true;
18773 default:
18774 break;
18775 }
18776 return false;
18777}
18778
18779/// Require that all of the parameter types of function be complete. Normally,
18780/// parameter types are only required to be complete when a function is called
18781/// or defined, but to mangle functions with certain calling conventions, the
18782/// mangler needs to know the size of the parameter list. In this situation,
18783/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18784/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18785/// result in a linker error. Clang doesn't implement this behavior, and instead
18786/// attempts to error at compile time.
18788 SourceLocation Loc) {
18789 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18790 FunctionDecl *FD;
18791 ParmVarDecl *Param;
18792
18793 public:
18794 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18795 : FD(FD), Param(Param) {}
18796
18797 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18798 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18799 StringRef CCName;
18800 switch (CC) {
18801 case CC_X86StdCall:
18802 CCName = "stdcall";
18803 break;
18804 case CC_X86FastCall:
18805 CCName = "fastcall";
18806 break;
18807 case CC_X86VectorCall:
18808 CCName = "vectorcall";
18809 break;
18810 default:
18811 llvm_unreachable("CC does not need mangling");
18812 }
18813
18814 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18815 << Param->getDeclName() << FD->getDeclName() << CCName;
18816 }
18817 };
18818
18819 for (ParmVarDecl *Param : FD->parameters()) {
18820 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18821 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18822 }
18823}
18824
18825namespace {
18826enum class OdrUseContext {
18827 /// Declarations in this context are not odr-used.
18828 None,
18829 /// Declarations in this context are formally odr-used, but this is a
18830 /// dependent context.
18831 Dependent,
18832 /// Declarations in this context are odr-used but not actually used (yet).
18833 FormallyOdrUsed,
18834 /// Declarations in this context are used.
18835 Used
18836};
18837}
18838
18839/// Are we within a context in which references to resolved functions or to
18840/// variables result in odr-use?
18841static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18844
18845 if (Context.isUnevaluated())
18846 return OdrUseContext::None;
18847
18849 return OdrUseContext::Dependent;
18850
18851 if (Context.isDiscardedStatementContext())
18852 return OdrUseContext::FormallyOdrUsed;
18853
18854 else if (Context.Context ==
18856 return OdrUseContext::FormallyOdrUsed;
18857
18858 return OdrUseContext::Used;
18859}
18860
18862 if (!Func->isConstexpr())
18863 return false;
18864
18865 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18866 return true;
18867
18868 // Lambda conversion operators are never user provided.
18869 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18870 return isLambdaConversionOperator(Conv);
18871
18872 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18873 return CCD && CCD->getInheritedConstructor();
18874}
18875
18877 bool MightBeOdrUse) {
18878 assert(Func && "No function?");
18879
18880 Func->setReferenced();
18881
18882 // Recursive functions aren't really used until they're used from some other
18883 // context.
18884 bool IsRecursiveCall = CurContext == Func;
18885
18886 // C++11 [basic.def.odr]p3:
18887 // A function whose name appears as a potentially-evaluated expression is
18888 // odr-used if it is the unique lookup result or the selected member of a
18889 // set of overloaded functions [...].
18890 //
18891 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18892 // can just check that here.
18893 OdrUseContext OdrUse =
18894 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18895 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18896 OdrUse = OdrUseContext::FormallyOdrUsed;
18897
18898 // Trivial default constructors and destructors are never actually used.
18899 // FIXME: What about other special members?
18900 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18901 OdrUse == OdrUseContext::Used) {
18902 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18903 if (Constructor->isDefaultConstructor())
18904 OdrUse = OdrUseContext::FormallyOdrUsed;
18906 OdrUse = OdrUseContext::FormallyOdrUsed;
18907 }
18908
18909 // C++20 [expr.const]p12:
18910 // A function [...] is needed for constant evaluation if it is [...] a
18911 // constexpr function that is named by an expression that is potentially
18912 // constant evaluated
18913 bool NeededForConstantEvaluation =
18916
18917 // Determine whether we require a function definition to exist, per
18918 // C++11 [temp.inst]p3:
18919 // Unless a function template specialization has been explicitly
18920 // instantiated or explicitly specialized, the function template
18921 // specialization is implicitly instantiated when the specialization is
18922 // referenced in a context that requires a function definition to exist.
18923 // C++20 [temp.inst]p7:
18924 // The existence of a definition of a [...] function is considered to
18925 // affect the semantics of the program if the [...] function is needed for
18926 // constant evaluation by an expression
18927 // C++20 [basic.def.odr]p10:
18928 // Every program shall contain exactly one definition of every non-inline
18929 // function or variable that is odr-used in that program outside of a
18930 // discarded statement
18931 // C++20 [special]p1:
18932 // The implementation will implicitly define [defaulted special members]
18933 // if they are odr-used or needed for constant evaluation.
18934 //
18935 // Note that we skip the implicit instantiation of templates that are only
18936 // used in unused default arguments or by recursive calls to themselves.
18937 // This is formally non-conforming, but seems reasonable in practice.
18938 bool NeedDefinition =
18939 !IsRecursiveCall &&
18940 (OdrUse == OdrUseContext::Used ||
18941 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18942
18943 // C++14 [temp.expl.spec]p6:
18944 // If a template [...] is explicitly specialized then that specialization
18945 // shall be declared before the first use of that specialization that would
18946 // cause an implicit instantiation to take place, in every translation unit
18947 // in which such a use occurs
18948 if (NeedDefinition &&
18949 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18950 Func->getMemberSpecializationInfo()))
18952
18953 if (getLangOpts().CUDA)
18954 CUDA().CheckCall(Loc, Func);
18955
18956 // If we need a definition, try to create one.
18957 if (NeedDefinition && !Func->getBody()) {
18960 dyn_cast<CXXConstructorDecl>(Func)) {
18962 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18963 if (Constructor->isDefaultConstructor()) {
18964 if (Constructor->isTrivial() &&
18965 !Constructor->hasAttr<DLLExportAttr>())
18966 return;
18968 } else if (Constructor->isCopyConstructor()) {
18970 } else if (Constructor->isMoveConstructor()) {
18972 }
18973 } else if (Constructor->getInheritedConstructor()) {
18975 }
18976 } else if (CXXDestructorDecl *Destructor =
18977 dyn_cast<CXXDestructorDecl>(Func)) {
18979 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18980 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18981 return;
18983 }
18984 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18985 MarkVTableUsed(Loc, Destructor->getParent());
18986 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18987 if (MethodDecl->isOverloadedOperator() &&
18988 MethodDecl->getOverloadedOperator() == OO_Equal) {
18989 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18990 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18991 if (MethodDecl->isCopyAssignmentOperator())
18992 DefineImplicitCopyAssignment(Loc, MethodDecl);
18993 else if (MethodDecl->isMoveAssignmentOperator())
18994 DefineImplicitMoveAssignment(Loc, MethodDecl);
18995 }
18996 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18997 MethodDecl->getParent()->isLambda()) {
18998 CXXConversionDecl *Conversion =
18999 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
19000 if (Conversion->isLambdaToBlockPointerConversion())
19002 else
19004 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19005 MarkVTableUsed(Loc, MethodDecl->getParent());
19006 }
19007
19008 if (Func->isDefaulted() && !Func->isDeleted()) {
19012 }
19013
19014 // Implicit instantiation of function templates and member functions of
19015 // class templates.
19016 if (Func->isImplicitlyInstantiable()) {
19018 Func->getTemplateSpecializationKindForInstantiation();
19019 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19020 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19021 if (FirstInstantiation) {
19022 PointOfInstantiation = Loc;
19023 if (auto *MSI = Func->getMemberSpecializationInfo())
19024 MSI->setPointOfInstantiation(Loc);
19025 // FIXME: Notify listener.
19026 else
19027 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19028 } else if (TSK != TSK_ImplicitInstantiation) {
19029 // Use the point of use as the point of instantiation, instead of the
19030 // point of explicit instantiation (which we track as the actual point
19031 // of instantiation). This gives better backtraces in diagnostics.
19032 PointOfInstantiation = Loc;
19033 }
19034
19035 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19036 Func->isConstexpr()) {
19037 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19038 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19039 CodeSynthesisContexts.size())
19041 std::make_pair(Func, PointOfInstantiation));
19042 else if (Func->isConstexpr())
19043 // Do not defer instantiations of constexpr functions, to avoid the
19044 // expression evaluator needing to call back into Sema if it sees a
19045 // call to such a function.
19046 InstantiateFunctionDefinition(PointOfInstantiation, Func);
19047 else {
19048 Func->setInstantiationIsPending(true);
19049 PendingInstantiations.push_back(
19050 std::make_pair(Func, PointOfInstantiation));
19051 if (llvm::isTimeTraceVerbose()) {
19052 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
19053 std::string Name;
19054 llvm::raw_string_ostream OS(Name);
19055 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
19056 /*Qualified=*/true);
19057 return Name;
19058 });
19059 }
19060 // Notify the consumer that a function was implicitly instantiated.
19061 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
19062 }
19063 }
19064 } else {
19065 // Walk redefinitions, as some of them may be instantiable.
19066 for (auto *i : Func->redecls()) {
19067 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19068 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19069 }
19070 }
19071 });
19072 }
19073
19074 // If a constructor was defined in the context of a default parameter
19075 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19076 // context), its initializers may not be referenced yet.
19077 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19079 *this,
19080 Constructor->isImmediateFunction()
19083 Constructor);
19084 for (CXXCtorInitializer *Init : Constructor->inits()) {
19085 if (Init->isInClassMemberInitializer())
19086 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19087 MarkDeclarationsReferencedInExpr(Init->getInit());
19088 });
19089 }
19090 }
19091
19092 // C++14 [except.spec]p17:
19093 // An exception-specification is considered to be needed when:
19094 // - the function is odr-used or, if it appears in an unevaluated operand,
19095 // would be odr-used if the expression were potentially-evaluated;
19096 //
19097 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19098 // function is a pure virtual function we're calling, and in that case the
19099 // function was selected by overload resolution and we need to resolve its
19100 // exception specification for a different reason.
19101 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19103 ResolveExceptionSpec(Loc, FPT);
19104
19105 // A callee could be called by a host function then by a device function.
19106 // If we only try recording once, we will miss recording the use on device
19107 // side. Therefore keep trying until it is recorded.
19108 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19109 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19111
19112 // If this is the first "real" use, act on that.
19113 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19114 // Keep track of used but undefined functions.
19115 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19116 if (mightHaveNonExternalLinkage(Func))
19117 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19118 else if (Func->getMostRecentDecl()->isInlined() &&
19119 !LangOpts.GNUInline &&
19120 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19121 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19123 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19124 }
19125
19126 // Some x86 Windows calling conventions mangle the size of the parameter
19127 // pack into the name. Computing the size of the parameters requires the
19128 // parameter types to be complete. Check that now.
19131
19132 // In the MS C++ ABI, the compiler emits destructor variants where they are
19133 // used. If the destructor is used here but defined elsewhere, mark the
19134 // virtual base destructors referenced. If those virtual base destructors
19135 // are inline, this will ensure they are defined when emitting the complete
19136 // destructor variant. This checking may be redundant if the destructor is
19137 // provided later in this TU.
19138 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19139 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19140 CXXRecordDecl *Parent = Dtor->getParent();
19141 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19143 }
19144 }
19145
19146 Func->markUsed(Context);
19147 }
19148}
19149
19150/// Directly mark a variable odr-used. Given a choice, prefer to use
19151/// MarkVariableReferenced since it does additional checks and then
19152/// calls MarkVarDeclODRUsed.
19153/// If the variable must be captured:
19154/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19155/// - else capture it in the DeclContext that maps to the
19156/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19157static void
19159 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19160 // Keep track of used but undefined variables.
19161 // FIXME: We shouldn't suppress this warning for static data members.
19162 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19163 assert(Var && "expected a capturable variable");
19164
19166 (!Var->isExternallyVisible() || Var->isInline() ||
19168 !(Var->isStaticDataMember() && Var->hasInit())) {
19170 if (old.isInvalid())
19171 old = Loc;
19172 }
19173 QualType CaptureType, DeclRefType;
19174 if (SemaRef.LangOpts.OpenMP)
19177 /*EllipsisLoc*/ SourceLocation(),
19178 /*BuildAndDiagnose*/ true, CaptureType,
19179 DeclRefType, FunctionScopeIndexToStopAt);
19180
19181 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19182 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19183 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
19184 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
19185 if (VarTarget == SemaCUDA::CVT_Host &&
19186 (UserTarget == CUDAFunctionTarget::Device ||
19187 UserTarget == CUDAFunctionTarget::HostDevice ||
19188 UserTarget == CUDAFunctionTarget::Global)) {
19189 // Diagnose ODR-use of host global variables in device functions.
19190 // Reference of device global variables in host functions is allowed
19191 // through shadow variables therefore it is not diagnosed.
19192 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19193 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19194 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19196 Var->getType().isConstQualified()
19197 ? diag::note_cuda_const_var_unpromoted
19198 : diag::note_cuda_host_var);
19199 }
19200 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19201 // Also capture __device__ const variables, which are classified
19202 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19203 // an explicit CUDADeviceAttr to distinguish them from plain
19204 // const variables (no __device__), which also get CVT_Both but
19205 // only have an implicit CUDADeviceAttr.
19206 (VarTarget == SemaCUDA::CVT_Both &&
19207 Var->hasAttr<CUDADeviceAttr>() &&
19208 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19209 !Var->hasAttr<CUDASharedAttr>() &&
19210 (UserTarget == CUDAFunctionTarget::Host ||
19211 UserTarget == CUDAFunctionTarget::HostDevice)) {
19212 // Record a CUDA/HIP device side variable if it is ODR-used
19213 // by host code. This is done conservatively, when the variable is
19214 // referenced in any of the following contexts:
19215 // - a non-function context
19216 // - a host function
19217 // - a host device function
19218 // This makes the ODR-use of the device side variable by host code to
19219 // be visible in the device compilation for the compiler to be able to
19220 // emit template variables instantiated by host code only and to
19221 // externalize the static device side variable ODR-used by host code.
19222 if (!Var->hasExternalStorage())
19224 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19225 (!FD || (!FD->getDescribedFunctionTemplate() &&
19229 }
19230 }
19231
19232 V->markUsed(SemaRef.Context);
19233}
19234
19236 SourceLocation Loc,
19237 unsigned CapturingScopeIndex) {
19238 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19239}
19240
19242 SourceLocation loc,
19243 ValueDecl *var) {
19244 DeclContext *VarDC = var->getDeclContext();
19245
19246 // If the parameter still belongs to the translation unit, then
19247 // we're actually just using one parameter in the declaration of
19248 // the next.
19249 if (isa<ParmVarDecl>(var) &&
19251 return;
19252
19253 // For C code, don't diagnose about capture if we're not actually in code
19254 // right now; it's impossible to write a non-constant expression outside of
19255 // function context, so we'll get other (more useful) diagnostics later.
19256 //
19257 // For C++, things get a bit more nasty... it would be nice to suppress this
19258 // diagnostic for certain cases like using a local variable in an array bound
19259 // for a member of a local class, but the correct predicate is not obvious.
19260 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19261 return;
19262
19263 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19264 unsigned ContextKind = 3; // unknown
19265 if (isa<CXXMethodDecl>(VarDC) &&
19266 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19267 ContextKind = 2;
19268 } else if (isa<FunctionDecl>(VarDC)) {
19269 ContextKind = 0;
19270 } else if (isa<BlockDecl>(VarDC)) {
19271 ContextKind = 1;
19272 }
19273
19274 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19275 << var << ValueKind << ContextKind << VarDC;
19276 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19277 << var;
19278
19279 // FIXME: Add additional diagnostic info about class etc. which prevents
19280 // capture.
19281}
19282
19284 ValueDecl *Var,
19285 bool &SubCapturesAreNested,
19286 QualType &CaptureType,
19287 QualType &DeclRefType) {
19288 // Check whether we've already captured it.
19289 if (CSI->CaptureMap.count(Var)) {
19290 // If we found a capture, any subcaptures are nested.
19291 SubCapturesAreNested = true;
19292
19293 // Retrieve the capture type for this variable.
19294 CaptureType = CSI->getCapture(Var).getCaptureType();
19295
19296 // Compute the type of an expression that refers to this variable.
19297 DeclRefType = CaptureType.getNonReferenceType();
19298
19299 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19300 // are mutable in the sense that user can change their value - they are
19301 // private instances of the captured declarations.
19302 const Capture &Cap = CSI->getCapture(Var);
19303 // C++ [expr.prim.lambda]p10:
19304 // The type of such a data member is [...] an lvalue reference to the
19305 // referenced function type if the entity is a reference to a function.
19306 // [...]
19307 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19308 !(isa<LambdaScopeInfo>(CSI) &&
19309 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19311 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19312 DeclRefType.addConst();
19313 return true;
19314 }
19315 return false;
19316}
19317
19318// Only block literals, captured statements, and lambda expressions can
19319// capture; other scopes don't work.
19321 ValueDecl *Var,
19322 SourceLocation Loc,
19323 const bool Diagnose,
19324 Sema &S) {
19327
19328 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19329 if (Underlying) {
19330 if (Underlying->hasLocalStorage() && Diagnose)
19332 }
19333 return nullptr;
19334}
19335
19336// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19337// certain types of variables (unnamed, variably modified types etc.)
19338// so check for eligibility.
19340 SourceLocation Loc, const bool Diagnose,
19341 Sema &S) {
19342
19343 assert((isa<VarDecl, BindingDecl>(Var)) &&
19344 "Only variables and structured bindings can be captured");
19345
19346 bool IsBlock = isa<BlockScopeInfo>(CSI);
19347 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19348
19349 // Lambdas are not allowed to capture unnamed variables
19350 // (e.g. anonymous unions).
19351 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19352 // assuming that's the intent.
19353 if (IsLambda && !Var->getDeclName()) {
19354 if (Diagnose) {
19355 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19356 S.Diag(Var->getLocation(), diag::note_declared_at);
19357 }
19358 return false;
19359 }
19360
19361 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19362 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19363 if (Diagnose) {
19364 S.Diag(Loc, diag::err_ref_vm_type);
19365 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19366 }
19367 return false;
19368 }
19369 // Prohibit structs with flexible array members too.
19370 // We cannot capture what is in the tail end of the struct.
19371 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19372 VTD && VTD->hasFlexibleArrayMember()) {
19373 if (Diagnose) {
19374 if (IsBlock)
19375 S.Diag(Loc, diag::err_ref_flexarray_type);
19376 else
19377 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19378 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19379 }
19380 return false;
19381 }
19382 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19383 // Lambdas and captured statements are not allowed to capture __block
19384 // variables; they don't support the expected semantics.
19385 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19386 if (Diagnose) {
19387 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19388 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19389 }
19390 return false;
19391 }
19392 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19393 if (S.getLangOpts().OpenCL && IsBlock &&
19394 Var->getType()->isBlockPointerType()) {
19395 if (Diagnose)
19396 S.Diag(Loc, diag::err_opencl_block_ref_block);
19397 return false;
19398 }
19399
19400 if (isa<BindingDecl>(Var)) {
19401 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19402 if (Diagnose)
19404 return false;
19405 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19406 S.Diag(Loc, S.LangOpts.CPlusPlus20
19407 ? diag::warn_cxx17_compat_capture_binding
19408 : diag::ext_capture_binding)
19409 << Var;
19410 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19411 }
19412 }
19413
19414 return true;
19415}
19416
19417// Returns true if the capture by block was successful.
19419 SourceLocation Loc, const bool BuildAndDiagnose,
19420 QualType &CaptureType, QualType &DeclRefType,
19421 const bool Nested, Sema &S, bool Invalid) {
19422 bool ByRef = false;
19423
19424 // Blocks are not allowed to capture arrays, excepting OpenCL.
19425 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19426 // (decayed to pointers).
19427 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19428 if (BuildAndDiagnose) {
19429 S.Diag(Loc, diag::err_ref_array_type);
19430 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19431 Invalid = true;
19432 } else {
19433 return false;
19434 }
19435 }
19436
19437 // Forbid the block-capture of autoreleasing variables.
19438 if (!Invalid &&
19440 if (BuildAndDiagnose) {
19441 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19442 << /*block*/ 0;
19443 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19444 Invalid = true;
19445 } else {
19446 return false;
19447 }
19448 }
19449
19450 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19451 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19452 QualType PointeeTy = PT->getPointeeType();
19453
19454 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19456 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19457 if (BuildAndDiagnose) {
19458 SourceLocation VarLoc = Var->getLocation();
19459 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19460 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19461 }
19462 }
19463 }
19464
19465 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19466 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19467 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19468 // Block capture by reference does not change the capture or
19469 // declaration reference types.
19470 ByRef = true;
19471 } else {
19472 // Block capture by copy introduces 'const'.
19473 CaptureType = CaptureType.getNonReferenceType().withConst();
19474 DeclRefType = CaptureType;
19475 }
19476
19477 // Actually capture the variable.
19478 if (BuildAndDiagnose)
19479 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19480 CaptureType, Invalid);
19481
19482 return !Invalid;
19483}
19484
19485/// Capture the given variable in the captured region.
19488 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19489 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19490 Sema &S, bool Invalid) {
19491 // By default, capture variables by reference.
19492 bool ByRef = true;
19493 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19494 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19495 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19496 // Using an LValue reference type is consistent with Lambdas (see below).
19497 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19498 bool HasConst = DeclRefType.isConstQualified();
19499 DeclRefType = DeclRefType.getUnqualifiedType();
19500 // Don't lose diagnostics about assignments to const.
19501 if (HasConst)
19502 DeclRefType.addConst();
19503 }
19504 // Do not capture firstprivates in tasks.
19505 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19506 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19507 return true;
19508 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19509 RSI->OpenMPCaptureLevel);
19510 }
19511
19512 if (ByRef)
19513 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19514 else
19515 CaptureType = DeclRefType;
19516
19517 // Actually capture the variable.
19518 if (BuildAndDiagnose)
19519 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19520 Loc, SourceLocation(), CaptureType, Invalid);
19521
19522 return !Invalid;
19523}
19524
19525/// Capture the given variable in the lambda.
19527 SourceLocation Loc, const bool BuildAndDiagnose,
19528 QualType &CaptureType, QualType &DeclRefType,
19529 const bool RefersToCapturedVariable,
19530 const TryCaptureKind Kind,
19531 SourceLocation EllipsisLoc, const bool IsTopScope,
19532 Sema &S, bool Invalid) {
19533 // Determine whether we are capturing by reference or by value.
19534 bool ByRef = false;
19535 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19536 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19537 } else {
19538 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19539 }
19540
19541 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19543 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19544 Invalid = true;
19545 }
19546
19547 // Compute the type of the field that will capture this variable.
19548 if (ByRef) {
19549 // C++11 [expr.prim.lambda]p15:
19550 // An entity is captured by reference if it is implicitly or
19551 // explicitly captured but not captured by copy. It is
19552 // unspecified whether additional unnamed non-static data
19553 // members are declared in the closure type for entities
19554 // captured by reference.
19555 //
19556 // FIXME: It is not clear whether we want to build an lvalue reference
19557 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19558 // to do the former, while EDG does the latter. Core issue 1249 will
19559 // clarify, but for now we follow GCC because it's a more permissive and
19560 // easily defensible position.
19561 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19562 } else {
19563 // C++11 [expr.prim.lambda]p14:
19564 // For each entity captured by copy, an unnamed non-static
19565 // data member is declared in the closure type. The
19566 // declaration order of these members is unspecified. The type
19567 // of such a data member is the type of the corresponding
19568 // captured entity if the entity is not a reference to an
19569 // object, or the referenced type otherwise. [Note: If the
19570 // captured entity is a reference to a function, the
19571 // corresponding data member is also a reference to a
19572 // function. - end note ]
19573 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19574 if (!RefType->getPointeeType()->isFunctionType())
19575 CaptureType = RefType->getPointeeType();
19576 }
19577
19578 // Forbid the lambda copy-capture of autoreleasing variables.
19579 if (!Invalid &&
19581 if (BuildAndDiagnose) {
19582 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19583 S.Diag(Var->getLocation(), diag::note_previous_decl)
19584 << Var->getDeclName();
19585 Invalid = true;
19586 } else {
19587 return false;
19588 }
19589 }
19590
19591 // Make sure that by-copy captures are of a complete and non-abstract type.
19592 if (!Invalid && BuildAndDiagnose) {
19593 if (!CaptureType->isDependentType() &&
19595 Loc, CaptureType,
19596 diag::err_capture_of_incomplete_or_sizeless_type,
19597 Var->getDeclName()))
19598 Invalid = true;
19599 else if (S.RequireNonAbstractType(Loc, CaptureType,
19600 diag::err_capture_of_abstract_type))
19601 Invalid = true;
19602 }
19603 }
19604
19605 // Compute the type of a reference to this captured variable.
19606 if (ByRef)
19607 DeclRefType = CaptureType.getNonReferenceType();
19608 else {
19609 // C++ [expr.prim.lambda]p5:
19610 // The closure type for a lambda-expression has a public inline
19611 // function call operator [...]. This function call operator is
19612 // declared const (9.3.1) if and only if the lambda-expression's
19613 // parameter-declaration-clause is not followed by mutable.
19614 DeclRefType = CaptureType.getNonReferenceType();
19615 bool Const = LSI->lambdaCaptureShouldBeConst();
19616 // C++ [expr.prim.lambda]p10:
19617 // The type of such a data member is [...] an lvalue reference to the
19618 // referenced function type if the entity is a reference to a function.
19619 // [...]
19620 if (Const && !CaptureType->isReferenceType() &&
19621 !DeclRefType->isFunctionType())
19622 DeclRefType.addConst();
19623 }
19624
19625 // Add the capture.
19626 if (BuildAndDiagnose)
19627 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19628 Loc, EllipsisLoc, CaptureType, Invalid);
19629
19630 return !Invalid;
19631}
19632
19634 const ASTContext &Context) {
19635 // Offer a Copy fix even if the type is dependent.
19636 if (Var->getType()->isDependentType())
19637 return true;
19639 if (T.isTriviallyCopyableType(Context))
19640 return true;
19641 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19642
19643 if (!(RD = RD->getDefinition()))
19644 return false;
19645 if (RD->hasSimpleCopyConstructor())
19646 return true;
19647 if (RD->hasUserDeclaredCopyConstructor())
19648 for (CXXConstructorDecl *Ctor : RD->ctors())
19649 if (Ctor->isCopyConstructor())
19650 return !Ctor->isDeleted();
19651 }
19652 return false;
19653}
19654
19655/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19656/// default capture. Fixes may be omitted if they aren't allowed by the
19657/// standard, for example we can't emit a default copy capture fix-it if we
19658/// already explicitly copy capture capture another variable.
19660 ValueDecl *Var) {
19662 // Don't offer Capture by copy of default capture by copy fixes if Var is
19663 // known not to be copy constructible.
19664 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19665
19666 SmallString<32> FixBuffer;
19667 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19668 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19669 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19670 if (ShouldOfferCopyFix) {
19671 // Offer fixes to insert an explicit capture for the variable.
19672 // [] -> [VarName]
19673 // [OtherCapture] -> [OtherCapture, VarName]
19674 FixBuffer.assign({Separator, Var->getName()});
19675 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19676 << Var << /*value*/ 0
19677 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19678 }
19679 // As above but capture by reference.
19680 FixBuffer.assign({Separator, "&", Var->getName()});
19681 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19682 << Var << /*reference*/ 1
19683 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19684 }
19685
19686 // Only try to offer default capture if there are no captures excluding this
19687 // and init captures.
19688 // [this]: OK.
19689 // [X = Y]: OK.
19690 // [&A, &B]: Don't offer.
19691 // [A, B]: Don't offer.
19692 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19693 return !C.isThisCapture() && !C.isInitCapture();
19694 }))
19695 return;
19696
19697 // The default capture specifiers, '=' or '&', must appear first in the
19698 // capture body.
19699 SourceLocation DefaultInsertLoc =
19701
19702 if (ShouldOfferCopyFix) {
19703 bool CanDefaultCopyCapture = true;
19704 // [=, *this] OK since c++17
19705 // [=, this] OK since c++20
19706 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19707 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19709 : false;
19710 // We can't use default capture by copy if any captures already specified
19711 // capture by copy.
19712 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19713 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19714 })) {
19715 FixBuffer.assign({"=", Separator});
19716 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19717 << /*value*/ 0
19718 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19719 }
19720 }
19721
19722 // We can't use default capture by reference if any captures already specified
19723 // capture by reference.
19724 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19725 return !C.isInitCapture() && C.isReferenceCapture() &&
19726 !C.isThisCapture();
19727 })) {
19728 FixBuffer.assign({"&", Separator});
19729 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19730 << /*reference*/ 1
19731 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19732 }
19733}
19734
19736 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19737 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19738 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19739 // An init-capture is notionally from the context surrounding its
19740 // declaration, but its parent DC is the lambda class.
19741 DeclContext *VarDC = Var->getDeclContext();
19742 DeclContext *DC = CurContext;
19743
19744 // Skip past RequiresExprBodys because they don't constitute function scopes.
19745 while (DC->isRequiresExprBody())
19746 DC = DC->getParent();
19747
19748 // tryCaptureVariable is called every time a DeclRef is formed,
19749 // it can therefore have non-negigible impact on performances.
19750 // For local variables and when there is no capturing scope,
19751 // we can bailout early.
19752 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19753 return true;
19754
19755 // Exception: Function parameters are not tied to the function's DeclContext
19756 // until we enter the function definition. Capturing them anyway would result
19757 // in an out-of-bounds error while traversing DC and its parents.
19758 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19759 return true;
19760
19761 const auto *VD = dyn_cast<VarDecl>(Var);
19762 if (VD) {
19763 if (VD->isInitCapture())
19764 VarDC = VarDC->getParent();
19765 } else {
19767 }
19768 assert(VD && "Cannot capture a null variable");
19769
19770 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19771 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19772 // We need to sync up the Declaration Context with the
19773 // FunctionScopeIndexToStopAt
19774 if (FunctionScopeIndexToStopAt) {
19775 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19776 unsigned FSIndex = FunctionScopes.size() - 1;
19777 // When we're parsing the lambda parameter list, the current DeclContext is
19778 // NOT the lambda but its parent. So move away the current LSI before
19779 // aligning DC and FunctionScopeIndexToStopAt.
19780 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19781 FSIndex && LSI && !LSI->AfterParameterList)
19782 --FSIndex;
19783 assert(MaxFunctionScopesIndex <= FSIndex &&
19784 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19785 "FunctionScopes.");
19786 while (FSIndex != MaxFunctionScopesIndex) {
19788 --FSIndex;
19789 }
19790 }
19791
19792 // Capture global variables if it is required to use private copy of this
19793 // variable.
19794 bool IsGlobal = !VD->hasLocalStorage();
19795 if (IsGlobal && !(LangOpts.OpenMP &&
19796 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19797 MaxFunctionScopesIndex)))
19798 return true;
19799
19800 if (isa<VarDecl>(Var))
19801 Var = cast<VarDecl>(Var->getCanonicalDecl());
19802
19803 // Walk up the stack to determine whether we can capture the variable,
19804 // performing the "simple" checks that don't depend on type. We stop when
19805 // we've either hit the declared scope of the variable or find an existing
19806 // capture of that variable. We start from the innermost capturing-entity
19807 // (the DC) and ensure that all intervening capturing-entities
19808 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19809 // declcontext can either capture the variable or have already captured
19810 // the variable.
19811 CaptureType = Var->getType();
19812 DeclRefType = CaptureType.getNonReferenceType();
19813 bool Nested = false;
19814 bool Explicit = (Kind != TryCaptureKind::Implicit);
19815 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19816 do {
19817
19818 LambdaScopeInfo *LSI = nullptr;
19819 if (!FunctionScopes.empty())
19820 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19821 FunctionScopes[FunctionScopesIndex]);
19822
19823 bool IsInScopeDeclarationContext =
19824 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19825
19826 if (LSI && !LSI->AfterParameterList) {
19827 // This allows capturing parameters from a default value which does not
19828 // seems correct
19829 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19830 return true;
19831 }
19832 // If the variable is declared in the current context, there is no need to
19833 // capture it.
19834 if (IsInScopeDeclarationContext &&
19835 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19836 return true;
19837
19838 // Only block literals, captured statements, and lambda expressions can
19839 // capture; other scopes don't work.
19840 DeclContext *ParentDC =
19841 !IsInScopeDeclarationContext
19842 ? DC->getParent()
19843 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19844 BuildAndDiagnose, *this);
19845 // We need to check for the parent *first* because, if we *have*
19846 // private-captured a global variable, we need to recursively capture it in
19847 // intermediate blocks, lambdas, etc.
19848 if (!ParentDC) {
19849 if (IsGlobal) {
19850 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19851 break;
19852 }
19853 return true;
19854 }
19855
19856 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19858
19859 // Check whether we've already captured it.
19860 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19861 DeclRefType)) {
19862 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19863 break;
19864 }
19865
19866 // When evaluating some attributes (like enable_if) we might refer to a
19867 // function parameter appertaining to the same declaration as that
19868 // attribute.
19869 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19870 Parm && Parm->getDeclContext() == DC)
19871 return true;
19872
19873 // If we are instantiating a generic lambda call operator body,
19874 // we do not want to capture new variables. What was captured
19875 // during either a lambdas transformation or initial parsing
19876 // should be used.
19878 if (BuildAndDiagnose) {
19881 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19882 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19883 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19884 buildLambdaCaptureFixit(*this, LSI, Var);
19885 } else
19887 }
19888 return true;
19889 }
19890
19891 // Try to capture variable-length arrays types.
19892 if (Var->getType()->isVariablyModifiedType()) {
19893 // We're going to walk down into the type and look for VLA
19894 // expressions.
19895 QualType QTy = Var->getType();
19896 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19897 QTy = PVD->getOriginalType();
19899 }
19900
19901 if (getLangOpts().OpenMP) {
19902 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19903 // OpenMP private variables should not be captured in outer scope, so
19904 // just break here. Similarly, global variables that are captured in a
19905 // target region should not be captured outside the scope of the region.
19906 if (RSI->CapRegionKind == CR_OpenMP) {
19907 // FIXME: We should support capturing structured bindings in OpenMP.
19908 if (isa<BindingDecl>(Var)) {
19909 if (BuildAndDiagnose) {
19910 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19911 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19912 }
19913 return true;
19914 }
19915 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19916 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19917 // If the variable is private (i.e. not captured) and has variably
19918 // modified type, we still need to capture the type for correct
19919 // codegen in all regions, associated with the construct. Currently,
19920 // it is captured in the innermost captured region only.
19921 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19922 Var->getType()->isVariablyModifiedType()) {
19923 QualType QTy = Var->getType();
19924 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19925 QTy = PVD->getOriginalType();
19926 for (int I = 1,
19927 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19928 I < E; ++I) {
19929 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19930 FunctionScopes[FunctionScopesIndex - I]);
19931 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19932 "Wrong number of captured regions associated with the "
19933 "OpenMP construct.");
19934 captureVariablyModifiedType(Context, QTy, OuterRSI);
19935 }
19936 }
19937 bool IsTargetCap =
19938 IsOpenMPPrivateDecl != OMPC_private &&
19939 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19940 RSI->OpenMPCaptureLevel);
19941 // Do not capture global if it is not privatized in outer regions.
19942 bool IsGlobalCap =
19943 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19944 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19945
19946 // When we detect target captures we are looking from inside the
19947 // target region, therefore we need to propagate the capture from the
19948 // enclosing region. Therefore, the capture is not initially nested.
19949 if (IsTargetCap)
19950 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19951 RSI->OpenMPLevel);
19952
19953 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19954 (IsGlobal && !IsGlobalCap)) {
19955 Nested = !IsTargetCap;
19956 bool HasConst = DeclRefType.isConstQualified();
19957 DeclRefType = DeclRefType.getUnqualifiedType();
19958 // Don't lose diagnostics about assignments to const.
19959 if (HasConst)
19960 DeclRefType.addConst();
19961 CaptureType = Context.getLValueReferenceType(DeclRefType);
19962 break;
19963 }
19964 }
19965 }
19966 }
19968 // No capture-default, and this is not an explicit capture
19969 // so cannot capture this variable.
19970 if (BuildAndDiagnose) {
19971 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19972 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19973 auto *LSI = cast<LambdaScopeInfo>(CSI);
19974 if (LSI->Lambda) {
19975 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19976 buildLambdaCaptureFixit(*this, LSI, Var);
19977 }
19978 // FIXME: If we error out because an outer lambda can not implicitly
19979 // capture a variable that an inner lambda explicitly captures, we
19980 // should have the inner lambda do the explicit capture - because
19981 // it makes for cleaner diagnostics later. This would purely be done
19982 // so that the diagnostic does not misleadingly claim that a variable
19983 // can not be captured by a lambda implicitly even though it is captured
19984 // explicitly. Suggestion:
19985 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19986 // at the function head
19987 // - cache the StartingDeclContext - this must be a lambda
19988 // - captureInLambda in the innermost lambda the variable.
19989 }
19990 return true;
19991 }
19992 Explicit = false;
19993 FunctionScopesIndex--;
19994 if (IsInScopeDeclarationContext)
19995 DC = ParentDC;
19996 } while (!VarDC->Equals(DC));
19997
19998 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19999 // computing the type of the capture at each step, checking type-specific
20000 // requirements, and adding captures if requested.
20001 // If the variable had already been captured previously, we start capturing
20002 // at the lambda nested within that one.
20003 bool Invalid = false;
20004 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20005 ++I) {
20007
20008 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20009 // certain types of variables (unnamed, variably modified types etc.)
20010 // so check for eligibility.
20011 if (!Invalid)
20012 Invalid =
20013 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
20014
20015 // After encountering an error, if we're actually supposed to capture, keep
20016 // capturing in nested contexts to suppress any follow-on diagnostics.
20017 if (Invalid && !BuildAndDiagnose)
20018 return true;
20019
20020 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
20021 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20022 DeclRefType, Nested, *this, Invalid);
20023 Nested = true;
20024 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20026 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
20027 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
20028 Nested = true;
20029 } else {
20031 Invalid =
20032 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20033 DeclRefType, Nested, Kind, EllipsisLoc,
20034 /*IsTopScope*/ I == N - 1, *this, Invalid);
20035 Nested = true;
20036 }
20037
20038 if (Invalid && !BuildAndDiagnose)
20039 return true;
20040 }
20041 return Invalid;
20042}
20043
20045 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20046 QualType CaptureType;
20047 QualType DeclRefType;
20048 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
20049 /*BuildAndDiagnose=*/true, CaptureType,
20050 DeclRefType, nullptr);
20051}
20052
20054 QualType CaptureType;
20055 QualType DeclRefType;
20056 return !tryCaptureVariable(
20058 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
20059}
20060
20062 assert(Var && "Null value cannot be captured");
20063
20064 QualType CaptureType;
20065 QualType DeclRefType;
20066
20067 // Determine whether we can capture this variable.
20069 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20070 nullptr))
20071 return QualType();
20072
20073 return DeclRefType;
20074}
20075
20076namespace {
20077// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20078// The produced TemplateArgumentListInfo* points to data stored within this
20079// object, so should only be used in contexts where the pointer will not be
20080// used after the CopiedTemplateArgs object is destroyed.
20081class CopiedTemplateArgs {
20082 bool HasArgs;
20083 TemplateArgumentListInfo TemplateArgStorage;
20084public:
20085 template<typename RefExpr>
20086 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20087 if (HasArgs)
20088 E->copyTemplateArgumentsInto(TemplateArgStorage);
20089 }
20090 operator TemplateArgumentListInfo*()
20091#ifdef __has_cpp_attribute
20092#if __has_cpp_attribute(clang::lifetimebound)
20093 [[clang::lifetimebound]]
20094#endif
20095#endif
20096 {
20097 return HasArgs ? &TemplateArgStorage : nullptr;
20098 }
20099};
20100}
20101
20102/// Walk the set of potential results of an expression and mark them all as
20103/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20104///
20105/// \return A new expression if we found any potential results, ExprEmpty() if
20106/// not, and ExprError() if we diagnosed an error.
20108 NonOdrUseReason NOUR) {
20109 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20110 // an object that satisfies the requirements for appearing in a
20111 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20112 // is immediately applied." This function handles the lvalue-to-rvalue
20113 // conversion part.
20114 //
20115 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20116 // transform it into the relevant kind of non-odr-use node and rebuild the
20117 // tree of nodes leading to it.
20118 //
20119 // This is a mini-TreeTransform that only transforms a restricted subset of
20120 // nodes (and only certain operands of them).
20121
20122 // Rebuild a subexpression.
20123 auto Rebuild = [&](Expr *Sub) {
20124 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20125 };
20126
20127 // Check whether a potential result satisfies the requirements of NOUR.
20128 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20129 // Any entity other than a VarDecl is always odr-used whenever it's named
20130 // in a potentially-evaluated expression.
20131 auto *VD = dyn_cast<VarDecl>(D);
20132 if (!VD)
20133 return true;
20134
20135 // C++2a [basic.def.odr]p4:
20136 // A variable x whose name appears as a potentially-evalauted expression
20137 // e is odr-used by e unless
20138 // -- x is a reference that is usable in constant expressions, or
20139 // -- x is a variable of non-reference type that is usable in constant
20140 // expressions and has no mutable subobjects, and e is an element of
20141 // the set of potential results of an expression of
20142 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20143 // conversion is applied, or
20144 // -- x is a variable of non-reference type, and e is an element of the
20145 // set of potential results of a discarded-value expression to which
20146 // the lvalue-to-rvalue conversion is not applied
20147 //
20148 // We check the first bullet and the "potentially-evaluated" condition in
20149 // BuildDeclRefExpr. We check the type requirements in the second bullet
20150 // in CheckLValueToRValueConversionOperand below.
20151 switch (NOUR) {
20152 case NOUR_None:
20153 case NOUR_Unevaluated:
20154 llvm_unreachable("unexpected non-odr-use-reason");
20155
20156 case NOUR_Constant:
20157 // Constant references were handled when they were built.
20158 if (VD->getType()->isReferenceType())
20159 return true;
20160 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20161 if (RD->hasDefinition() && RD->hasMutableFields())
20162 return true;
20163 if (!VD->isUsableInConstantExpressions(S.Context))
20164 return true;
20165 break;
20166
20167 case NOUR_Discarded:
20168 if (VD->getType()->isReferenceType())
20169 return true;
20170 break;
20171 }
20172 return false;
20173 };
20174
20175 // Check whether this expression may be odr-used in CUDA/HIP.
20176 auto MaybeCUDAODRUsed = [&]() -> bool {
20177 if (!S.LangOpts.CUDA)
20178 return false;
20179 LambdaScopeInfo *LSI = S.getCurLambda();
20180 if (!LSI)
20181 return false;
20182 auto *DRE = dyn_cast<DeclRefExpr>(E);
20183 if (!DRE)
20184 return false;
20185 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
20186 if (!VD)
20187 return false;
20188 return LSI->CUDAPotentialODRUsedVars.count(VD);
20189 };
20190
20191 // Mark that this expression does not constitute an odr-use.
20192 auto MarkNotOdrUsed = [&] {
20193 if (!MaybeCUDAODRUsed()) {
20194 S.MaybeODRUseExprs.remove(E);
20195 if (LambdaScopeInfo *LSI = S.getCurLambda())
20196 LSI->markVariableExprAsNonODRUsed(E);
20197 }
20198 };
20199
20200 // C++2a [basic.def.odr]p2:
20201 // The set of potential results of an expression e is defined as follows:
20202 switch (E->getStmtClass()) {
20203 // -- If e is an id-expression, ...
20204 case Expr::DeclRefExprClass: {
20205 auto *DRE = cast<DeclRefExpr>(E);
20206 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20207 break;
20208
20209 // Rebuild as a non-odr-use DeclRefExpr.
20210 MarkNotOdrUsed();
20211 return DeclRefExpr::Create(
20212 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20213 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20214 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20215 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20216 }
20217
20218 case Expr::FunctionParmPackExprClass: {
20219 auto *FPPE = cast<FunctionParmPackExpr>(E);
20220 // If any of the declarations in the pack is odr-used, then the expression
20221 // as a whole constitutes an odr-use.
20222 for (ValueDecl *D : *FPPE)
20223 if (IsPotentialResultOdrUsed(D))
20224 return ExprEmpty();
20225
20226 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20227 // nothing cares about whether we marked this as an odr-use, but it might
20228 // be useful for non-compiler tools.
20229 MarkNotOdrUsed();
20230 break;
20231 }
20232
20233 // -- If e is a subscripting operation with an array operand...
20234 case Expr::ArraySubscriptExprClass: {
20235 auto *ASE = cast<ArraySubscriptExpr>(E);
20236 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20237 if (!OldBase->getType()->isArrayType())
20238 break;
20239 ExprResult Base = Rebuild(OldBase);
20240 if (!Base.isUsable())
20241 return Base;
20242 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20243 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20244 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20245 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20246 ASE->getRBracketLoc());
20247 }
20248
20249 case Expr::MemberExprClass: {
20250 auto *ME = cast<MemberExpr>(E);
20251 // -- If e is a class member access expression [...] naming a non-static
20252 // data member...
20253 if (isa<FieldDecl>(ME->getMemberDecl())) {
20254 ExprResult Base = Rebuild(ME->getBase());
20255 if (!Base.isUsable())
20256 return Base;
20257 return MemberExpr::Create(
20258 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20259 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20260 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20261 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20262 ME->getObjectKind(), ME->isNonOdrUse());
20263 }
20264
20265 if (ME->getMemberDecl()->isCXXInstanceMember())
20266 break;
20267
20268 // -- If e is a class member access expression naming a static data member,
20269 // ...
20270 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20271 break;
20272
20273 // Rebuild as a non-odr-use MemberExpr.
20274 MarkNotOdrUsed();
20275 return MemberExpr::Create(
20276 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20277 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20278 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20279 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20280 }
20281
20282 case Expr::BinaryOperatorClass: {
20283 auto *BO = cast<BinaryOperator>(E);
20284 Expr *LHS = BO->getLHS();
20285 Expr *RHS = BO->getRHS();
20286 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20287 if (BO->getOpcode() == BO_PtrMemD) {
20288 ExprResult Sub = Rebuild(LHS);
20289 if (!Sub.isUsable())
20290 return Sub;
20291 BO->setLHS(Sub.get());
20292 // -- If e is a comma expression, ...
20293 } else if (BO->getOpcode() == BO_Comma) {
20294 ExprResult Sub = Rebuild(RHS);
20295 if (!Sub.isUsable())
20296 return Sub;
20297 BO->setRHS(Sub.get());
20298 } else {
20299 break;
20300 }
20301 return ExprResult(BO);
20302 }
20303
20304 // -- If e has the form (e1)...
20305 case Expr::ParenExprClass: {
20306 auto *PE = cast<ParenExpr>(E);
20307 ExprResult Sub = Rebuild(PE->getSubExpr());
20308 if (!Sub.isUsable())
20309 return Sub;
20310 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20311 }
20312
20313 // -- If e is a glvalue conditional expression, ...
20314 // We don't apply this to a binary conditional operator. FIXME: Should we?
20315 case Expr::ConditionalOperatorClass: {
20316 auto *CO = cast<ConditionalOperator>(E);
20317 ExprResult LHS = Rebuild(CO->getLHS());
20318 if (LHS.isInvalid())
20319 return ExprError();
20320 ExprResult RHS = Rebuild(CO->getRHS());
20321 if (RHS.isInvalid())
20322 return ExprError();
20323 if (!LHS.isUsable() && !RHS.isUsable())
20324 return ExprEmpty();
20325 if (!LHS.isUsable())
20326 LHS = CO->getLHS();
20327 if (!RHS.isUsable())
20328 RHS = CO->getRHS();
20329 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20330 CO->getCond(), LHS.get(), RHS.get());
20331 }
20332
20333 // [Clang extension]
20334 // -- If e has the form __extension__ e1...
20335 case Expr::UnaryOperatorClass: {
20336 auto *UO = cast<UnaryOperator>(E);
20337 if (UO->getOpcode() != UO_Extension)
20338 break;
20339 ExprResult Sub = Rebuild(UO->getSubExpr());
20340 if (!Sub.isUsable())
20341 return Sub;
20342 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20343 Sub.get());
20344 }
20345
20346 // [Clang extension]
20347 // -- If e has the form _Generic(...), the set of potential results is the
20348 // union of the sets of potential results of the associated expressions.
20349 case Expr::GenericSelectionExprClass: {
20350 auto *GSE = cast<GenericSelectionExpr>(E);
20351
20352 SmallVector<Expr *, 4> AssocExprs;
20353 bool AnyChanged = false;
20354 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20355 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20356 if (AssocExpr.isInvalid())
20357 return ExprError();
20358 if (AssocExpr.isUsable()) {
20359 AssocExprs.push_back(AssocExpr.get());
20360 AnyChanged = true;
20361 } else {
20362 AssocExprs.push_back(OrigAssocExpr);
20363 }
20364 }
20365
20366 void *ExOrTy = nullptr;
20367 bool IsExpr = GSE->isExprPredicate();
20368 if (IsExpr)
20369 ExOrTy = GSE->getControllingExpr();
20370 else
20371 ExOrTy = GSE->getControllingType();
20372 return AnyChanged ? S.CreateGenericSelectionExpr(
20373 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20374 GSE->getRParenLoc(), IsExpr, ExOrTy,
20375 GSE->getAssocTypeSourceInfos(), AssocExprs)
20376 : ExprEmpty();
20377 }
20378
20379 // [Clang extension]
20380 // -- If e has the form __builtin_choose_expr(...), the set of potential
20381 // results is the union of the sets of potential results of the
20382 // second and third subexpressions.
20383 case Expr::ChooseExprClass: {
20384 auto *CE = cast<ChooseExpr>(E);
20385
20386 ExprResult LHS = Rebuild(CE->getLHS());
20387 if (LHS.isInvalid())
20388 return ExprError();
20389
20390 ExprResult RHS = Rebuild(CE->getLHS());
20391 if (RHS.isInvalid())
20392 return ExprError();
20393
20394 if (!LHS.get() && !RHS.get())
20395 return ExprEmpty();
20396 if (!LHS.isUsable())
20397 LHS = CE->getLHS();
20398 if (!RHS.isUsable())
20399 RHS = CE->getRHS();
20400
20401 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20402 RHS.get(), CE->getRParenLoc());
20403 }
20404
20405 // Step through non-syntactic nodes.
20406 case Expr::ConstantExprClass: {
20407 auto *CE = cast<ConstantExpr>(E);
20408 ExprResult Sub = Rebuild(CE->getSubExpr());
20409 if (!Sub.isUsable())
20410 return Sub;
20411 return ConstantExpr::Create(S.Context, Sub.get());
20412 }
20413
20414 // We could mostly rely on the recursive rebuilding to rebuild implicit
20415 // casts, but not at the top level, so rebuild them here.
20416 case Expr::ImplicitCastExprClass: {
20417 auto *ICE = cast<ImplicitCastExpr>(E);
20418 // Only step through the narrow set of cast kinds we expect to encounter.
20419 // Anything else suggests we've left the region in which potential results
20420 // can be found.
20421 switch (ICE->getCastKind()) {
20422 case CK_NoOp:
20423 case CK_DerivedToBase:
20424 case CK_UncheckedDerivedToBase: {
20425 ExprResult Sub = Rebuild(ICE->getSubExpr());
20426 if (!Sub.isUsable())
20427 return Sub;
20428 CXXCastPath Path(ICE->path());
20429 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20430 ICE->getValueKind(), &Path);
20431 }
20432
20433 default:
20434 break;
20435 }
20436 break;
20437 }
20438
20439 default:
20440 break;
20441 }
20442
20443 // Can't traverse through this node. Nothing to do.
20444 return ExprEmpty();
20445}
20446
20448 // Check whether the operand is or contains an object of non-trivial C union
20449 // type.
20450 if (E->getType().isVolatileQualified() &&
20456
20457 // C++2a [basic.def.odr]p4:
20458 // [...] an expression of non-volatile-qualified non-class type to which
20459 // the lvalue-to-rvalue conversion is applied [...]
20460 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20461 return E;
20462
20465 if (Result.isInvalid())
20466 return ExprError();
20467 return Result.get() ? Result : E;
20468}
20469
20471 if (!Res.isUsable())
20472 return Res;
20473
20474 // If a constant-expression is a reference to a variable where we delay
20475 // deciding whether it is an odr-use, just assume we will apply the
20476 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20477 // (a non-type template argument), we have special handling anyway.
20479}
20480
20482 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20483 // call.
20484 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20485 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20486
20487 for (Expr *E : LocalMaybeODRUseExprs) {
20488 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20489 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20490 DRE->getLocation(), *this);
20491 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20492 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20493 *this);
20494 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20495 for (ValueDecl *VD : *FP)
20496 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20497 } else {
20498 llvm_unreachable("Unexpected expression");
20499 }
20500 }
20501
20502 assert(MaybeODRUseExprs.empty() &&
20503 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20504}
20505
20507 ValueDecl *Var, Expr *E) {
20509 if (!VD)
20510 return;
20511
20512 const bool RefersToEnclosingScope =
20513 (SemaRef.CurContext != VD->getDeclContext() &&
20515 if (RefersToEnclosingScope) {
20516 LambdaScopeInfo *const LSI =
20517 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20518 if (LSI && (!LSI->CallOperator ||
20519 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20520 // If a variable could potentially be odr-used, defer marking it so
20521 // until we finish analyzing the full expression for any
20522 // lvalue-to-rvalue
20523 // or discarded value conversions that would obviate odr-use.
20524 // Add it to the list of potential captures that will be analyzed
20525 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20526 // unless the variable is a reference that was initialized by a constant
20527 // expression (this will never need to be captured or odr-used).
20528 //
20529 // FIXME: We can simplify this a lot after implementing P0588R1.
20530 assert(E && "Capture variable should be used in an expression.");
20531 if (!Var->getType()->isReferenceType() ||
20534 }
20535 }
20536}
20537
20539 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20540 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20541 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20543 "Invalid Expr argument to DoMarkVarDeclReferenced");
20544 Var->setReferenced();
20545
20546 if (Var->isInvalidDecl())
20547 return;
20548
20549 auto *MSI = Var->getMemberSpecializationInfo();
20550 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20552
20553 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20554 bool UsableInConstantExpr =
20556
20557 // Only track variables with internal linkage or local scope.
20558 // Use canonical decl so in-class declarations and out-of-class definitions
20559 // of static data members in anonymous namespaces are tracked as a single
20560 // entry.
20561 const VarDecl *CanonVar = Var->getCanonicalDecl();
20562 if ((CanonVar->isLocalVarDeclOrParm() ||
20563 CanonVar->isInternalLinkageFileVar()) &&
20564 !CanonVar->hasExternalStorage()) {
20565 RefsMinusAssignments.insert({CanonVar, 0}).first->getSecond()++;
20566 }
20567
20568 // C++20 [expr.const]p12:
20569 // A variable [...] is needed for constant evaluation if it is [...] a
20570 // variable whose name appears as a potentially constant evaluated
20571 // expression that is either a contexpr variable or is of non-volatile
20572 // const-qualified integral type or of reference type
20573 bool NeededForConstantEvaluation =
20574 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20575
20576 bool NeedDefinition =
20577 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20578 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20579 Var->getType()->isUndeducedType());
20580
20582 "Can't instantiate a partial template specialization.");
20583
20584 // If this might be a member specialization of a static data member, check
20585 // the specialization is visible. We already did the checks for variable
20586 // template specializations when we created them.
20587 if (NeedDefinition && TSK != TSK_Undeclared &&
20590
20591 // Perform implicit instantiation of static data members, static data member
20592 // templates of class templates, and variable template specializations. Delay
20593 // instantiations of variable templates, except for those that could be used
20594 // in a constant expression.
20595 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20596 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20597 // instantiation declaration if a variable is usable in a constant
20598 // expression (among other cases).
20599 bool TryInstantiating =
20601 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20602
20603 if (TryInstantiating) {
20604 SourceLocation PointOfInstantiation =
20605 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20606 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20607 if (FirstInstantiation) {
20608 PointOfInstantiation = Loc;
20609 if (MSI)
20610 MSI->setPointOfInstantiation(PointOfInstantiation);
20611 // FIXME: Notify listener.
20612 else
20613 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20614 }
20615
20616 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20617 // Do not defer instantiations of variables that could be used in a
20618 // constant expression.
20619 // The type deduction also needs a complete initializer.
20620 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20621 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20622 });
20623
20624 // The size of an incomplete array type can be updated by
20625 // instantiating the initializer. The DeclRefExpr's type should be
20626 // updated accordingly too, or users of it would be confused!
20627 if (E)
20629
20630 // Re-set the member to trigger a recomputation of the dependence bits
20631 // for the expression.
20632 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20633 DRE->setDecl(DRE->getDecl());
20634 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20635 ME->setMemberDecl(ME->getMemberDecl());
20636 } else if (FirstInstantiation) {
20638 .push_back(std::make_pair(Var, PointOfInstantiation));
20639 } else {
20640 bool Inserted = false;
20641 for (auto &I : SemaRef.SavedPendingInstantiations) {
20642 auto Iter = llvm::find_if(
20643 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20644 return P.first == Var;
20645 });
20646 if (Iter != I.end()) {
20647 SemaRef.PendingInstantiations.push_back(*Iter);
20648 I.erase(Iter);
20649 Inserted = true;
20650 break;
20651 }
20652 }
20653
20654 // FIXME: For a specialization of a variable template, we don't
20655 // distinguish between "declaration and type implicitly instantiated"
20656 // and "implicit instantiation of definition requested", so we have
20657 // no direct way to avoid enqueueing the pending instantiation
20658 // multiple times.
20659 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20661 .push_back(std::make_pair(Var, PointOfInstantiation));
20662 }
20663 }
20664 }
20665
20666 // C++2a [basic.def.odr]p4:
20667 // A variable x whose name appears as a potentially-evaluated expression e
20668 // is odr-used by e unless
20669 // -- x is a reference that is usable in constant expressions
20670 // -- x is a variable of non-reference type that is usable in constant
20671 // expressions and has no mutable subobjects [FIXME], and e is an
20672 // element of the set of potential results of an expression of
20673 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20674 // conversion is applied
20675 // -- x is a variable of non-reference type, and e is an element of the set
20676 // of potential results of a discarded-value expression to which the
20677 // lvalue-to-rvalue conversion is not applied [FIXME]
20678 //
20679 // We check the first part of the second bullet here, and
20680 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20681 // FIXME: To get the third bullet right, we need to delay this even for
20682 // variables that are not usable in constant expressions.
20683
20684 // If we already know this isn't an odr-use, there's nothing more to do.
20685 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20686 if (DRE->isNonOdrUse())
20687 return;
20688 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20689 if (ME->isNonOdrUse())
20690 return;
20691
20692 switch (OdrUse) {
20693 case OdrUseContext::None:
20694 // In some cases, a variable may not have been marked unevaluated, if it
20695 // appears in a defaukt initializer.
20696 assert((!E || isa<FunctionParmPackExpr>(E) ||
20698 "missing non-odr-use marking for unevaluated decl ref");
20699 break;
20700
20701 case OdrUseContext::FormallyOdrUsed:
20702 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20703 // behavior.
20704 break;
20705
20706 case OdrUseContext::Used:
20707 // If we might later find that this expression isn't actually an odr-use,
20708 // delay the marking.
20710 SemaRef.MaybeODRUseExprs.insert(E);
20711 else
20712 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20713 break;
20714
20715 case OdrUseContext::Dependent:
20716 // If this is a dependent context, we don't need to mark variables as
20717 // odr-used, but we may still need to track them for lambda capture.
20718 // FIXME: Do we also need to do this inside dependent typeid expressions
20719 // (which are modeled as unevaluated at this point)?
20720 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20721 break;
20722 }
20723}
20724
20726 BindingDecl *BD, Expr *E) {
20727 BD->setReferenced();
20728
20729 if (BD->isInvalidDecl())
20730 return;
20731
20732 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20733 if (OdrUse == OdrUseContext::Used) {
20734 QualType CaptureType, DeclRefType;
20736 /*EllipsisLoc*/ SourceLocation(),
20737 /*BuildAndDiagnose*/ true, CaptureType,
20738 DeclRefType,
20739 /*FunctionScopeIndexToStopAt*/ nullptr);
20740 } else if (OdrUse == OdrUseContext::Dependent) {
20741 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20742 }
20743}
20744
20746 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20747}
20748
20749// C++ [temp.dep.expr]p3:
20750// An id-expression is type-dependent if it contains:
20751// - an identifier associated by name lookup with an entity captured by copy
20752// in a lambda-expression that has an explicit object parameter whose type
20753// is dependent ([dcl.fct]),
20755 Sema &SemaRef, ValueDecl *D, Expr *E) {
20756 auto *ID = dyn_cast<DeclRefExpr>(E);
20757 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20758 return;
20759
20760 // If any enclosing lambda with a dependent explicit object parameter either
20761 // explicitly captures the variable by value, or has a capture default of '='
20762 // and does not capture the variable by reference, then the type of the DRE
20763 // is dependent on the type of that lambda's explicit object parameter.
20764 auto IsDependent = [&]() {
20765 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20766 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20767 if (!LSI)
20768 continue;
20769
20770 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20771 LSI->AfterParameterList)
20772 return false;
20773
20774 const auto *MD = LSI->CallOperator;
20775 if (MD->getType().isNull())
20776 continue;
20777
20778 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20779 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20780 !Ty->getParamType(0)->isDependentType())
20781 continue;
20782
20783 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20784 if (C->isCopyCapture())
20785 return true;
20786 continue;
20787 }
20788
20789 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20790 return true;
20791 }
20792 return false;
20793 }();
20794
20795 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20796 IsDependent, SemaRef.getASTContext());
20797}
20798
20799static void
20801 bool MightBeOdrUse,
20802 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20805
20806 if (SemaRef.getLangOpts().OpenACC)
20807 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20808
20809 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20811 if (SemaRef.getLangOpts().CPlusPlus)
20813 Var, E);
20814 return;
20815 }
20816
20817 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20819 if (SemaRef.getLangOpts().CPlusPlus)
20821 Decl, E);
20822 return;
20823 }
20824 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20825
20826 // If this is a call to a method via a cast, also mark the method in the
20827 // derived class used in case codegen can devirtualize the call.
20828 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20829 if (!ME)
20830 return;
20831 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20832 if (!MD)
20833 return;
20834 // Only attempt to devirtualize if this is truly a virtual call.
20835 bool IsVirtualCall = MD->isVirtual() &&
20837 if (!IsVirtualCall)
20838 return;
20839
20840 // If it's possible to devirtualize the call, mark the called function
20841 // referenced.
20843 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20844 if (DM)
20845 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20846}
20847
20849 // [basic.def.odr] (CWG 1614)
20850 // A function is named by an expression or conversion [...]
20851 // unless it is a pure virtual function and either the expression is not an
20852 // id-expression naming the function with an explicitly qualified name or
20853 // the expression forms a pointer to member
20854 bool OdrUse = true;
20855 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20856 if (Method->isVirtual() &&
20857 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20858 OdrUse = false;
20859
20860 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20864 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20865 !FD->isDependentContext())
20866 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20867 }
20868 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20870}
20871
20873 // C++11 [basic.def.odr]p2:
20874 // A non-overloaded function whose name appears as a potentially-evaluated
20875 // expression or a member of a set of candidate functions, if selected by
20876 // overload resolution when referred to from a potentially-evaluated
20877 // expression, is odr-used, unless it is a pure virtual function and its
20878 // name is not explicitly qualified.
20879 bool MightBeOdrUse = true;
20881 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20882 if (Method->isPureVirtual())
20883 MightBeOdrUse = false;
20884 }
20885 SourceLocation Loc =
20886 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20887 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20889}
20890
20896
20897/// Perform marking for a reference to an arbitrary declaration. It
20898/// marks the declaration referenced, and performs odr-use checking for
20899/// functions and variables. This method should not be used when building a
20900/// normal expression which refers to a variable.
20902 bool MightBeOdrUse) {
20903 if (MightBeOdrUse) {
20904 if (auto *VD = dyn_cast<VarDecl>(D)) {
20905 MarkVariableReferenced(Loc, VD);
20906 return;
20907 }
20908 }
20909 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20910 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20911 return;
20912 }
20913 D->setReferenced();
20914}
20915
20916namespace {
20917 // Mark all of the declarations used by a type as referenced.
20918 // FIXME: Not fully implemented yet! We need to have a better understanding
20919 // of when we're entering a context we should not recurse into.
20920 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20921 // TreeTransforms rebuilding the type in a new context. Rather than
20922 // duplicating the TreeTransform logic, we should consider reusing it here.
20923 // Currently that causes problems when rebuilding LambdaExprs.
20924class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20925 Sema &S;
20926 SourceLocation Loc;
20927
20928public:
20929 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20930
20931 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20932};
20933}
20934
20935bool MarkReferencedDecls::TraverseTemplateArgument(
20936 const TemplateArgument &Arg) {
20937 {
20938 // A non-type template argument is a constant-evaluated context.
20939 EnterExpressionEvaluationContext Evaluated(
20942 if (Decl *D = Arg.getAsDecl())
20943 S.MarkAnyDeclReferenced(Loc, D, true);
20944 } else if (Arg.getKind() == TemplateArgument::Expression) {
20946 }
20947 }
20948
20950}
20951
20953 MarkReferencedDecls Marker(*this, Loc);
20954 Marker.TraverseType(T);
20955}
20956
20957namespace {
20958/// Helper class that marks all of the declarations referenced by
20959/// potentially-evaluated subexpressions as "referenced".
20960class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20961public:
20962 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20963 bool SkipLocalVariables;
20965
20966 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20968 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20969
20970 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20972 }
20973
20974 void Visit(Expr *E) {
20975 if (llvm::is_contained(StopAt, E))
20976 return;
20977 Inherited::Visit(E);
20978 }
20979
20980 void VisitConstantExpr(ConstantExpr *E) {
20981 // Don't mark declarations within a ConstantExpression, as this expression
20982 // will be evaluated and folded to a value.
20983 }
20984
20985 void VisitDeclRefExpr(DeclRefExpr *E) {
20986 // If we were asked not to visit local variables, don't.
20987 if (SkipLocalVariables) {
20988 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20989 if (VD->hasLocalStorage())
20990 return;
20991 }
20992
20993 // FIXME: This can trigger the instantiation of the initializer of a
20994 // variable, which can cause the expression to become value-dependent
20995 // or error-dependent. Do we need to propagate the new dependence bits?
20997 }
20998
20999 void VisitMemberExpr(MemberExpr *E) {
21001 Visit(E->getBase());
21002 }
21003};
21004} // namespace
21005
21007 bool SkipLocalVariables,
21008 ArrayRef<const Expr*> StopAt) {
21009 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21010}
21011
21012/// Emit a diagnostic when statements are reachable.
21014 const PartialDiagnostic &PD) {
21015 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21016 // The initializer of a constexpr variable or of the first declaration of a
21017 // static data member is not syntactically a constant evaluated constant,
21018 // but nonetheless is always required to be a constant expression, so we
21019 // can skip diagnosing.
21020 if (Decl &&
21021 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21022 Decl->isFirstDecl() && !Decl->isInline())))
21023 return false;
21024
21025 if (Stmts.empty()) {
21026 Diag(Loc, PD);
21027 return true;
21028 }
21029
21030 if (getCurFunction()) {
21031 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21032 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21033 return true;
21034 }
21035
21036 // For non-constexpr file-scope variables with reachability context (non-empty
21037 // Stmts), build a CFG for the initializer and check whether the context in
21038 // question is reachable.
21039 if (Decl && Decl->isFileVarDecl()) {
21040 AnalysisWarnings.registerVarDeclWarning(
21041 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21042 return true;
21043 }
21044
21045 Diag(Loc, PD);
21046 return true;
21047}
21048
21049/// Emit a diagnostic that describes an effect on the run-time behavior
21050/// of the program being compiled.
21051///
21052/// This routine emits the given diagnostic when the code currently being
21053/// type-checked is "potentially evaluated", meaning that there is a
21054/// possibility that the code will actually be executable. Code in sizeof()
21055/// expressions, code used only during overload resolution, etc., are not
21056/// potentially evaluated. This routine will suppress such diagnostics or,
21057/// in the absolutely nutty case of potentially potentially evaluated
21058/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21059/// later.
21060///
21061/// This routine should be used for all diagnostics that describe the run-time
21062/// behavior of a program, such as passing a non-POD value through an ellipsis.
21063/// Failure to do so will likely result in spurious diagnostics or failures
21064/// during overload resolution or within sizeof/alignof/typeof/typeid.
21066 const PartialDiagnostic &PD) {
21067
21068 if (ExprEvalContexts.back().isDiscardedStatementContext())
21069 return false;
21070
21071 switch (ExprEvalContexts.back().Context) {
21076 // The argument will never be evaluated, so don't complain.
21077 break;
21078
21081 // Relevant diagnostics should be produced by constant evaluation.
21082 break;
21083
21086 return DiagIfReachable(Loc, Stmts, PD);
21087 }
21088
21089 return false;
21090}
21091
21093 const PartialDiagnostic &PD) {
21094 return DiagRuntimeBehavior(
21095 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21096 PD);
21097}
21098
21100 CallExpr *CE, FunctionDecl *FD) {
21101 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21102 return false;
21103
21104 // If we're inside a decltype's expression, don't check for a valid return
21105 // type or construct temporaries until we know whether this is the last call.
21106 if (ExprEvalContexts.back().ExprContext ==
21108 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21109 return false;
21110 }
21111
21112 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21113 FunctionDecl *FD;
21114 CallExpr *CE;
21115
21116 public:
21117 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21118 : FD(FD), CE(CE) { }
21119
21120 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21121 if (!FD) {
21122 S.Diag(Loc, diag::err_call_incomplete_return)
21123 << T << CE->getSourceRange();
21124 return;
21125 }
21126
21127 S.Diag(Loc, diag::err_call_function_incomplete_return)
21128 << CE->getSourceRange() << FD << T;
21129 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21130 << FD->getDeclName();
21131 }
21132 } Diagnoser(FD, CE);
21133
21134 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21135 return true;
21136
21137 return false;
21138}
21139
21140// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21141// will prevent this condition from triggering, which is what we want.
21143 SourceLocation Loc;
21144
21145 unsigned diagnostic = diag::warn_condition_is_assignment;
21146 bool IsOrAssign = false;
21147
21148 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21149 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21150 return;
21151
21152 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21153
21154 // Greylist some idioms by putting them into a warning subcategory.
21155 if (ObjCMessageExpr *ME
21156 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21157 Selector Sel = ME->getSelector();
21158
21159 // self = [<foo> init...]
21160 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21161 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21162
21163 // <foo> = [<bar> nextObject]
21164 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21165 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21166 }
21167
21168 Loc = Op->getOperatorLoc();
21169 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21170 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21171 return;
21172
21173 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21174 Loc = Op->getOperatorLoc();
21175 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21176 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21177 else {
21178 // Not an assignment.
21179 return;
21180 }
21181
21182 Diag(Loc, diagnostic) << E->getSourceRange();
21183
21186 Diag(Loc, diag::note_condition_assign_silence)
21188 << FixItHint::CreateInsertion(Close, ")");
21189
21190 if (IsOrAssign)
21191 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21192 << FixItHint::CreateReplacement(Loc, "!=");
21193 else
21194 Diag(Loc, diag::note_condition_assign_to_comparison)
21195 << FixItHint::CreateReplacement(Loc, "==");
21196}
21197
21199 // Don't warn if the parens came from a macro.
21200 SourceLocation parenLoc = ParenE->getBeginLoc();
21201 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21202 return;
21203 // Don't warn for dependent expressions.
21204 if (ParenE->isTypeDependent())
21205 return;
21206
21207 Expr *E = ParenE->IgnoreParens();
21208 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21209 return;
21210
21211 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21212 if (opE->getOpcode() == BO_EQ &&
21213 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21214 == Expr::MLV_Valid) {
21215 SourceLocation Loc = opE->getOperatorLoc();
21216
21217 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21218 SourceRange ParenERange = ParenE->getSourceRange();
21219 Diag(Loc, diag::note_equality_comparison_silence)
21220 << FixItHint::CreateRemoval(ParenERange.getBegin())
21221 << FixItHint::CreateRemoval(ParenERange.getEnd());
21222 Diag(Loc, diag::note_equality_comparison_to_assign)
21223 << FixItHint::CreateReplacement(Loc, "=");
21224 }
21225}
21226
21228 bool IsConstexpr) {
21230 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21232
21233 ExprResult result = CheckPlaceholderExpr(E);
21234 if (result.isInvalid()) return ExprError();
21235 E = result.get();
21236
21237 if (!E->isTypeDependent()) {
21238 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21240
21241 if (getLangOpts().CPlusPlus)
21242 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21243
21245 if (ERes.isInvalid())
21246 return ExprError();
21247 E = ERes.get();
21248
21249 QualType T = E->getType();
21250 if (!T->isScalarType()) { // C99 6.8.4.1p1
21251 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21252 << T << E->getSourceRange();
21253 return ExprError();
21254 }
21255 CheckBoolLikeConversion(E, Loc);
21256 }
21257
21258 return E;
21259}
21260
21262 Expr *SubExpr, ConditionKind CK,
21263 bool MissingOK) {
21264 // MissingOK indicates whether having no condition expression is valid
21265 // (for loop) or invalid (e.g. while loop).
21266 if (!SubExpr)
21267 return MissingOK ? ConditionResult() : ConditionError();
21268
21270 switch (CK) {
21272 Cond = CheckBooleanCondition(Loc, SubExpr);
21273 break;
21274
21276 // Note: this might produce a FullExpr
21277 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21278 break;
21279
21281 Cond = CheckSwitchCondition(Loc, SubExpr);
21282 break;
21283 }
21284 if (Cond.isInvalid()) {
21285 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21286 {SubExpr}, PreferredConditionType(CK));
21287 if (!Cond.get())
21288 return ConditionError();
21289 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
21290 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
21291
21292 if (!Cond.isUsable())
21293 return ConditionError();
21294
21295 return ConditionResult(*this, nullptr, Cond,
21297}
21298
21299namespace {
21300 /// A visitor for rebuilding a call to an __unknown_any expression
21301 /// to have an appropriate type.
21302 struct RebuildUnknownAnyFunction
21303 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21304
21305 Sema &S;
21306
21307 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21308
21309 ExprResult VisitStmt(Stmt *S) {
21310 llvm_unreachable("unexpected statement!");
21311 }
21312
21313 ExprResult VisitExpr(Expr *E) {
21314 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21315 << E->getSourceRange();
21316 return ExprError();
21317 }
21318
21319 /// Rebuild an expression which simply semantically wraps another
21320 /// expression which it shares the type and value kind of.
21321 template <class T> ExprResult rebuildSugarExpr(T *E) {
21322 ExprResult SubResult = Visit(E->getSubExpr());
21323 if (SubResult.isInvalid()) return ExprError();
21324
21325 Expr *SubExpr = SubResult.get();
21326 E->setSubExpr(SubExpr);
21327 E->setType(SubExpr->getType());
21328 E->setValueKind(SubExpr->getValueKind());
21329 assert(E->getObjectKind() == OK_Ordinary);
21330 return E;
21331 }
21332
21333 ExprResult VisitParenExpr(ParenExpr *E) {
21334 return rebuildSugarExpr(E);
21335 }
21336
21337 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21338 return rebuildSugarExpr(E);
21339 }
21340
21341 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21342 ExprResult SubResult = Visit(E->getSubExpr());
21343 if (SubResult.isInvalid()) return ExprError();
21344
21345 Expr *SubExpr = SubResult.get();
21346 E->setSubExpr(SubExpr);
21347 E->setType(S.Context.getPointerType(SubExpr->getType()));
21348 assert(E->isPRValue());
21349 assert(E->getObjectKind() == OK_Ordinary);
21350 return E;
21351 }
21352
21353 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21354 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21355
21356 E->setType(VD->getType());
21357
21358 assert(E->isPRValue());
21359 if (S.getLangOpts().CPlusPlus &&
21360 !(isa<CXXMethodDecl>(VD) &&
21361 cast<CXXMethodDecl>(VD)->isInstance()))
21363
21364 return E;
21365 }
21366
21367 ExprResult VisitMemberExpr(MemberExpr *E) {
21368 return resolveDecl(E, E->getMemberDecl());
21369 }
21370
21371 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21372 return resolveDecl(E, E->getDecl());
21373 }
21374 };
21375}
21376
21377/// Given a function expression of unknown-any type, try to rebuild it
21378/// to have a function type.
21380 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21381 if (Result.isInvalid()) return ExprError();
21382 return S.DefaultFunctionArrayConversion(Result.get());
21383}
21384
21385namespace {
21386 /// A visitor for rebuilding an expression of type __unknown_anytype
21387 /// into one which resolves the type directly on the referring
21388 /// expression. Strict preservation of the original source
21389 /// structure is not a goal.
21390 struct RebuildUnknownAnyExpr
21391 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21392
21393 Sema &S;
21394
21395 /// The current destination type.
21396 QualType DestType;
21397
21398 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21399 : S(S), DestType(CastType) {}
21400
21401 ExprResult VisitStmt(Stmt *S) {
21402 llvm_unreachable("unexpected statement!");
21403 }
21404
21405 ExprResult VisitExpr(Expr *E) {
21406 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21407 << E->getSourceRange();
21408 return ExprError();
21409 }
21410
21411 ExprResult VisitCallExpr(CallExpr *E);
21412 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21413
21414 /// Rebuild an expression which simply semantically wraps another
21415 /// expression which it shares the type and value kind of.
21416 template <class T> ExprResult rebuildSugarExpr(T *E) {
21417 ExprResult SubResult = Visit(E->getSubExpr());
21418 if (SubResult.isInvalid()) return ExprError();
21419 Expr *SubExpr = SubResult.get();
21420 E->setSubExpr(SubExpr);
21421 E->setType(SubExpr->getType());
21422 E->setValueKind(SubExpr->getValueKind());
21423 assert(E->getObjectKind() == OK_Ordinary);
21424 return E;
21425 }
21426
21427 ExprResult VisitParenExpr(ParenExpr *E) {
21428 return rebuildSugarExpr(E);
21429 }
21430
21431 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21432 return rebuildSugarExpr(E);
21433 }
21434
21435 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21436 const PointerType *Ptr = DestType->getAs<PointerType>();
21437 if (!Ptr) {
21438 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21439 << E->getSourceRange();
21440 return ExprError();
21441 }
21442
21443 if (isa<CallExpr>(E->getSubExpr())) {
21444 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21445 << E->getSourceRange();
21446 return ExprError();
21447 }
21448
21449 assert(E->isPRValue());
21450 assert(E->getObjectKind() == OK_Ordinary);
21451 E->setType(DestType);
21452
21453 // Build the sub-expression as if it were an object of the pointee type.
21454 DestType = Ptr->getPointeeType();
21455 ExprResult SubResult = Visit(E->getSubExpr());
21456 if (SubResult.isInvalid()) return ExprError();
21457 E->setSubExpr(SubResult.get());
21458 return E;
21459 }
21460
21461 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21462
21463 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21464
21465 ExprResult VisitMemberExpr(MemberExpr *E) {
21466 return resolveDecl(E, E->getMemberDecl());
21467 }
21468
21469 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21470 return resolveDecl(E, E->getDecl());
21471 }
21472 };
21473}
21474
21475/// Rebuilds a call expression which yielded __unknown_anytype.
21476ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21477 Expr *CalleeExpr = E->getCallee();
21478
21479 enum FnKind {
21480 FK_MemberFunction,
21481 FK_FunctionPointer,
21482 FK_BlockPointer
21483 };
21484
21485 FnKind Kind;
21486 QualType CalleeType = CalleeExpr->getType();
21487 if (CalleeType == S.Context.BoundMemberTy) {
21489 Kind = FK_MemberFunction;
21490 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21491 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21492 CalleeType = Ptr->getPointeeType();
21493 Kind = FK_FunctionPointer;
21494 } else {
21495 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21496 Kind = FK_BlockPointer;
21497 }
21498 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21499
21500 // Verify that this is a legal result type of a function.
21501 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21502 DestType->isFunctionType()) {
21503 unsigned diagID = diag::err_func_returning_array_function;
21504 if (Kind == FK_BlockPointer)
21505 diagID = diag::err_block_returning_array_function;
21506
21507 S.Diag(E->getExprLoc(), diagID)
21508 << DestType->isFunctionType() << DestType;
21509 return ExprError();
21510 }
21511
21512 // Otherwise, go ahead and set DestType as the call's result.
21513 E->setType(DestType.getNonLValueExprType(S.Context));
21515 assert(E->getObjectKind() == OK_Ordinary);
21516
21517 // Rebuild the function type, replacing the result type with DestType.
21518 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21519 if (Proto) {
21520 // __unknown_anytype(...) is a special case used by the debugger when
21521 // it has no idea what a function's signature is.
21522 //
21523 // We want to build this call essentially under the K&R
21524 // unprototyped rules, but making a FunctionNoProtoType in C++
21525 // would foul up all sorts of assumptions. However, we cannot
21526 // simply pass all arguments as variadic arguments, nor can we
21527 // portably just call the function under a non-variadic type; see
21528 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21529 // However, it turns out that in practice it is generally safe to
21530 // call a function declared as "A foo(B,C,D);" under the prototype
21531 // "A foo(B,C,D,...);". The only known exception is with the
21532 // Windows ABI, where any variadic function is implicitly cdecl
21533 // regardless of its normal CC. Therefore we change the parameter
21534 // types to match the types of the arguments.
21535 //
21536 // This is a hack, but it is far superior to moving the
21537 // corresponding target-specific code from IR-gen to Sema/AST.
21538
21539 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21540 SmallVector<QualType, 8> ArgTypes;
21541 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21542 ArgTypes.reserve(E->getNumArgs());
21543 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21544 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21545 }
21546 ParamTypes = ArgTypes;
21547 }
21548 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21549 Proto->getExtProtoInfo());
21550 } else {
21551 DestType = S.Context.getFunctionNoProtoType(DestType,
21552 FnType->getExtInfo());
21553 }
21554
21555 // Rebuild the appropriate pointer-to-function type.
21556 switch (Kind) {
21557 case FK_MemberFunction:
21558 // Nothing to do.
21559 break;
21560
21561 case FK_FunctionPointer:
21562 DestType = S.Context.getPointerType(DestType);
21563 break;
21564
21565 case FK_BlockPointer:
21566 DestType = S.Context.getBlockPointerType(DestType);
21567 break;
21568 }
21569
21570 // Finally, we can recurse.
21571 ExprResult CalleeResult = Visit(CalleeExpr);
21572 if (!CalleeResult.isUsable()) return ExprError();
21573 E->setCallee(CalleeResult.get());
21574
21575 // Bind a temporary if necessary.
21576 return S.MaybeBindToTemporary(E);
21577}
21578
21579ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21580 // Verify that this is a legal result type of a call.
21581 if (DestType->isArrayType() || DestType->isFunctionType()) {
21582 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21583 << DestType->isFunctionType() << DestType;
21584 return ExprError();
21585 }
21586
21587 // Rewrite the method result type if available.
21588 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21589 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21590 Method->setReturnType(DestType);
21591 }
21592
21593 // Change the type of the message.
21594 E->setType(DestType.getNonReferenceType());
21596
21597 return S.MaybeBindToTemporary(E);
21598}
21599
21600ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21601 // The only case we should ever see here is a function-to-pointer decay.
21602 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21603 assert(E->isPRValue());
21604 assert(E->getObjectKind() == OK_Ordinary);
21605
21606 E->setType(DestType);
21607
21608 // Rebuild the sub-expression as the pointee (function) type.
21609 DestType = DestType->castAs<PointerType>()->getPointeeType();
21610
21611 ExprResult Result = Visit(E->getSubExpr());
21612 if (!Result.isUsable()) return ExprError();
21613
21614 E->setSubExpr(Result.get());
21615 return E;
21616 } else if (E->getCastKind() == CK_LValueToRValue) {
21617 assert(E->isPRValue());
21618 assert(E->getObjectKind() == OK_Ordinary);
21619
21620 assert(isa<BlockPointerType>(E->getType()));
21621
21622 E->setType(DestType);
21623
21624 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21625 DestType = S.Context.getLValueReferenceType(DestType);
21626
21627 ExprResult Result = Visit(E->getSubExpr());
21628 if (!Result.isUsable()) return ExprError();
21629
21630 E->setSubExpr(Result.get());
21631 return E;
21632 } else {
21633 llvm_unreachable("Unhandled cast type!");
21634 }
21635}
21636
21637ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21638 ExprValueKind ValueKind = VK_LValue;
21639 QualType Type = DestType;
21640
21641 // We know how to make this work for certain kinds of decls:
21642
21643 // - functions
21644 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21645 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21646 DestType = Ptr->getPointeeType();
21647 ExprResult Result = resolveDecl(E, VD);
21648 if (Result.isInvalid()) return ExprError();
21649 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21650 VK_PRValue);
21651 }
21652
21653 if (!Type->isFunctionType()) {
21654 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21655 << VD << E->getSourceRange();
21656 return ExprError();
21657 }
21658 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21659 // We must match the FunctionDecl's type to the hack introduced in
21660 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21661 // type. See the lengthy commentary in that routine.
21662 QualType FDT = FD->getType();
21663 const FunctionType *FnType = FDT->castAs<FunctionType>();
21664 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21665 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21666 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21667 SourceLocation Loc = FD->getLocation();
21668 FunctionDecl *NewFD = FunctionDecl::Create(
21669 S.Context, FD->getDeclContext(), Loc, Loc,
21670 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21672 false /*isInlineSpecified*/, FD->hasPrototype(),
21673 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21674
21675 if (FD->getQualifier())
21676 NewFD->setQualifierInfo(FD->getQualifierLoc());
21677
21678 SmallVector<ParmVarDecl*, 16> Params;
21679 for (const auto &AI : FT->param_types()) {
21680 ParmVarDecl *Param =
21681 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21682 Param->setScopeInfo(0, Params.size());
21683 Params.push_back(Param);
21684 }
21685 NewFD->setParams(Params);
21686 DRE->setDecl(NewFD);
21687 VD = DRE->getDecl();
21688 }
21689 }
21690
21691 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21692 if (MD->isInstance()) {
21693 ValueKind = VK_PRValue;
21695 }
21696
21697 // Function references aren't l-values in C.
21698 if (!S.getLangOpts().CPlusPlus)
21699 ValueKind = VK_PRValue;
21700
21701 // - variables
21702 } else if (isa<VarDecl>(VD)) {
21703 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21704 Type = RefTy->getPointeeType();
21705 } else if (Type->isFunctionType()) {
21706 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21707 << VD << E->getSourceRange();
21708 return ExprError();
21709 }
21710
21711 // - nothing else
21712 } else {
21713 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21714 << VD << E->getSourceRange();
21715 return ExprError();
21716 }
21717
21718 // Modifying the declaration like this is friendly to IR-gen but
21719 // also really dangerous.
21720 VD->setType(DestType);
21721 E->setType(Type);
21722 E->setValueKind(ValueKind);
21723 return E;
21724}
21725
21728 ExprValueKind &VK, CXXCastPath &Path) {
21729 // The type we're casting to must be either void or complete.
21730 if (!CastType->isVoidType() &&
21732 diag::err_typecheck_cast_to_incomplete))
21733 return ExprError();
21734
21735 // Rewrite the casted expression from scratch.
21736 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21737 if (!result.isUsable()) return ExprError();
21738
21739 CastExpr = result.get();
21741 CastKind = CK_NoOp;
21742
21743 return CastExpr;
21744}
21745
21747 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21748}
21749
21751 Expr *arg, QualType &paramType) {
21752 // If the syntactic form of the argument is not an explicit cast of
21753 // any sort, just do default argument promotion.
21754 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21755 if (!castArg) {
21757 if (result.isInvalid()) return ExprError();
21758 paramType = result.get()->getType();
21759 return result;
21760 }
21761
21762 // Otherwise, use the type that was written in the explicit cast.
21763 assert(!arg->hasPlaceholderType());
21764 paramType = castArg->getTypeAsWritten();
21765
21766 // Copy-initialize a parameter of that type.
21767 InitializedEntity entity =
21769 /*consumed*/ false);
21770 return PerformCopyInitialization(entity, callLoc, arg);
21771}
21772
21774 Expr *orig = E;
21775 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21776 while (true) {
21777 E = E->IgnoreParenImpCasts();
21778 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21779 E = call->getCallee();
21780 diagID = diag::err_uncasted_call_of_unknown_any;
21781 } else {
21782 break;
21783 }
21784 }
21785
21786 SourceLocation loc;
21787 NamedDecl *d;
21788 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21789 loc = ref->getLocation();
21790 d = ref->getDecl();
21791 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21792 loc = mem->getMemberLoc();
21793 d = mem->getMemberDecl();
21794 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21795 diagID = diag::err_uncasted_call_of_unknown_any;
21796 loc = msg->getSelectorStartLoc();
21797 d = msg->getMethodDecl();
21798 if (!d) {
21799 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21800 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21801 << orig->getSourceRange();
21802 return ExprError();
21803 }
21804 } else {
21805 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21806 << E->getSourceRange();
21807 return ExprError();
21808 }
21809
21810 S.Diag(loc, diagID) << d << orig->getSourceRange();
21811
21812 // Never recoverable.
21813 return ExprError();
21814}
21815
21817 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21818 if (!placeholderType) return E;
21819
21820 switch (placeholderType->getKind()) {
21821 case BuiltinType::UnresolvedTemplate: {
21822 auto *ULE = cast<UnresolvedLookupExpr>(E->IgnoreParens());
21823 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21824 // There's only one FoundDecl for UnresolvedTemplate type. See
21825 // BuildTemplateIdExpr.
21826 NamedDecl *Temp = *ULE->decls_begin();
21827 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21828
21829 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21830 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21831 // as it models only the unqualified-id case, where this case can clearly be
21832 // qualified. Thus we can't just qualify an assumed template.
21833 TemplateName TN;
21834 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21835 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21836 TemplateName(TD));
21837 else
21838 TN = Context.getAssumedTemplateName(NameInfo.getName());
21839
21840 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21841 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21842 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21843 << IsTypeAliasTemplateDecl;
21844
21845 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21846 bool HasAnyDependentTA = false;
21847 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21848 HasAnyDependentTA |= Arg.getArgument().isDependent();
21849 TAL.addArgument(Arg);
21850 }
21851
21852 QualType TST;
21853 {
21854 SFINAETrap Trap(*this);
21855 TST = CheckTemplateIdType(
21856 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
21857 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21858 }
21859 if (TST.isNull())
21860 TST = Context.getTemplateSpecializationType(
21861 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21862 /*CanonicalArgs=*/{},
21863 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21864 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21865 TST);
21866 }
21867
21868 // Overloaded expressions.
21869 case BuiltinType::Overload: {
21870 // Try to resolve a single function template specialization.
21871 // This is obligatory.
21872 ExprResult Result = E;
21874 return Result;
21875
21876 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21877 // leaves Result unchanged on failure.
21878 Result = E;
21880 return Result;
21881
21882 // If that failed, try to recover with a call.
21883 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21884 /*complain*/ true);
21885 return Result;
21886 }
21887
21888 // Bound member functions.
21889 case BuiltinType::BoundMember: {
21890 ExprResult result = E;
21891 const Expr *BME = E->IgnoreParens();
21892 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21893 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21895 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21896 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21897 if (ME->getMemberNameInfo().getName().getNameKind() ==
21899 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21900 }
21901 tryToRecoverWithCall(result, PD,
21902 /*complain*/ true);
21903 return result;
21904 }
21905
21906 // ARC unbridged casts.
21907 case BuiltinType::ARCUnbridgedCast: {
21908 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21909 ObjC().diagnoseARCUnbridgedCast(realCast);
21910 return realCast;
21911 }
21912
21913 // Expressions of unknown type.
21914 case BuiltinType::UnknownAny:
21915 return diagnoseUnknownAnyExpr(*this, E);
21916
21917 // Pseudo-objects.
21918 case BuiltinType::PseudoObject:
21919 return PseudoObject().checkRValue(E);
21920
21921 case BuiltinType::BuiltinFn: {
21922 // Accept __noop without parens by implicitly converting it to a call expr.
21923 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21924 if (DRE) {
21925 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21926 unsigned BuiltinID = FD->getBuiltinID();
21927 if (BuiltinID == Builtin::BI__noop) {
21928 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21929 CK_BuiltinFnToFnPtr)
21930 .get();
21931 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21934 }
21935
21936 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21937 // Any use of these other than a direct call is ill-formed as of C++20,
21938 // because they are not addressable functions. In earlier language
21939 // modes, warn and force an instantiation of the real body.
21940 Diag(E->getBeginLoc(),
21942 ? diag::err_use_of_unaddressable_function
21943 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21944 if (FD->isImplicitlyInstantiable()) {
21945 // Require a definition here because a normal attempt at
21946 // instantiation for a builtin will be ignored, and we won't try
21947 // again later. We assume that the definition of the template
21948 // precedes this use.
21950 /*Recursive=*/false,
21951 /*DefinitionRequired=*/true,
21952 /*AtEndOfTU=*/false);
21953 }
21954 // Produce a properly-typed reference to the function.
21955 CXXScopeSpec SS;
21956 SS.Adopt(DRE->getQualifierLoc());
21957 TemplateArgumentListInfo TemplateArgs;
21958 DRE->copyTemplateArgumentsInto(TemplateArgs);
21959 return BuildDeclRefExpr(
21960 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21961 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21962 DRE->getTemplateKeywordLoc(),
21963 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21964 }
21965 }
21966
21967 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21968 return ExprError();
21969 }
21970
21971 case BuiltinType::IncompleteMatrixIdx: {
21972 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
21973 // At this point, we know there was no second [] to complete the operator.
21974 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
21975 if (getLangOpts().HLSL) {
21977 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
21978 }
21979 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
21980 return ExprError();
21981 }
21982
21983 // Expressions of unknown type.
21984 case BuiltinType::ArraySection:
21985 // If we've already diagnosed something on the array section type, we
21986 // shouldn't need to do any further diagnostic here.
21987 if (!E->containsErrors())
21988 Diag(E->getBeginLoc(), diag::err_array_section_use)
21989 << cast<ArraySectionExpr>(E->IgnoreParens())->isOMPArraySection();
21990 return ExprError();
21991
21992 // Expressions of unknown type.
21993 case BuiltinType::OMPArrayShaping:
21994 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21995
21996 case BuiltinType::OMPIterator:
21997 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21998
21999 // Everything else should be impossible.
22000#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22001 case BuiltinType::Id:
22002#include "clang/Basic/OpenCLImageTypes.def"
22003#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22004 case BuiltinType::Id:
22005#include "clang/Basic/OpenCLExtensionTypes.def"
22006#define SVE_TYPE(Name, Id, SingletonId) \
22007 case BuiltinType::Id:
22008#include "clang/Basic/AArch64ACLETypes.def"
22009#define PPC_VECTOR_TYPE(Name, Id, Size) \
22010 case BuiltinType::Id:
22011#include "clang/Basic/PPCTypes.def"
22012#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22013#include "clang/Basic/RISCVVTypes.def"
22014#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22015#include "clang/Basic/WebAssemblyReferenceTypes.def"
22016#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22017#include "clang/Basic/AMDGPUTypes.def"
22018#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22019#include "clang/Basic/HLSLIntangibleTypes.def"
22020#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22021#define PLACEHOLDER_TYPE(Id, SingletonId)
22022#include "clang/AST/BuiltinTypes.def"
22023 break;
22024 }
22025
22026 llvm_unreachable("invalid placeholder type!");
22027}
22028
22030 if (E->isTypeDependent())
22031 return true;
22033 return E->getType()->isIntegralOrEnumerationType();
22034 return false;
22035}
22036
22038 ArrayRef<Expr *> SubExprs, QualType T) {
22039 if (!Context.getLangOpts().RecoveryAST)
22040 return ExprError();
22041
22042 if (isSFINAEContext())
22043 return ExprError();
22044
22045 if (T.isNull() || T->isUndeducedType() ||
22046 !Context.getLangOpts().RecoveryASTType)
22047 // We don't know the concrete type, fallback to dependent type.
22048 T = Context.DependentTy;
22049
22050 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
22051}
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 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.
static DeclT * getDefinitionOrSelf(DeclT *D)
Definition Decl.cpp:2670
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:50
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 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 Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
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:149
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:165
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:562
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 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:587
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 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:111
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, 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 for Objective-C.
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.
Defines enumerations for the type traits support.
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:122
APSInt & getInt()
Definition APValue.h:508
bool hasValue() const
Definition APValue.h:483
bool isInt() const
Definition APValue.h:485
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:227
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:809
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:805
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:927
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.
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...
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:924
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:4553
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2724
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2779
Wrapper for source info for arrays.
Definition TypeLoc.h:1777
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3784
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3798
QualType getElementType() const
Definition TypeBase.h:3796
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition Expr.h:6733
Attr - This represents one attribute.
Definition Attr.h:46
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4456
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
Expr * getLHS() const
Definition Expr.h:4091
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4135
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2185
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4141
StringRef getOpcodeStr() const
Definition Expr.h:4107
bool isRelationalOp() const
Definition Expr.h:4136
SourceLocation getOperatorLoc() const
Definition Expr.h:4083
bool isMultiplicativeOp() const
Definition Expr.h:4126
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2138
bool isShiftOp() const
Definition Expr.h:4130
Expr * getRHS() const
Definition Expr.h:4093
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:5102
bool isBitwiseOp() const
Definition Expr.h:4133
bool isAdditiveOp() const
Definition Expr.h:4128
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4177
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4182
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:2210
Opcode getOpcode() const
Definition Expr.h:4086
bool isAssignmentOp() const
Definition Expr.h:4180
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2147
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4138
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4132
BinaryOperatorKind Opcode
Definition Expr.h:4046
A binding in a decomposition declaration.
Definition DeclCXX.h:4190
A class which contains all the information about a particular captured value.
Definition Decl.h:4696
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4690
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.cpp:5441
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition Decl.h:4772
void setBlockMissingReturnType(bool val=true)
Definition Decl.h:4829
void setIsVariadic(bool value)
Definition Decl.h:4766
SourceLocation getCaretLocation() const
Definition Decl.h:4763
void setBody(CompoundStmt *B)
Definition Decl.h:4770
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4776
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition Decl.cpp:5452
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5645
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6672
Pointer to a block type.
Definition TypeBase.h:3604
This class is used for builtin types like 'int'.
Definition TypeBase.h:3226
bool isSVEBool() const
Definition TypeBase.h:3303
Kind getKind() const
Definition TypeBase.h:3274
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:1979
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:1552
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
Represents a C++ constructor within a class.
Definition DeclCXX.h:2620
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2952
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition DeclCXX.cpp:3289
Represents a C++ base or member initializer.
Definition DeclCXX.h:2385
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition ExprCXX.cpp:1046
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1381
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:1100
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1112
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:1557
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
bool isVirtual() const
Definition DeclCXX.h:2187
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2271
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:2526
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:156
SourceRange getSourceRange() const
Definition ExprCXX.h:168
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:2010
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2749
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:1225
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:603
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:2085
bool hasDefinition() const
Definition DeclCXX.h:561
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
static CXXReflectExpr * Create(ASTContext &C, SourceLocation OperatorLoc, TypeSourceInfo *TL)
Definition ExprCXX.cpp:1955
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
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:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
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:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
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:1158
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3163
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:1522
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
Expr * getCallee()
Definition Expr.h:3093
void computeDependence()
Compute and set dependence bits.
Definition Expr.h:3169
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
void setCallee(Expr *F)
Definition Expr.h:3095
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:3679
CastKind getCastKind() const
Definition Expr.h:3723
const char * getCastKindName() const
Definition Expr.h:3727
void setSubExpr(Expr *E)
Definition Expr.h:3731
Expr * getSubExpr()
Definition Expr.h:3729
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)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1632
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4851
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3337
QualType getElementType() const
Definition TypeBase.h:3347
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:5124
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3608
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1750
bool body_empty() const
Definition Stmt.h:1794
Stmt * body_back()
Definition Stmt.h:1818
ConditionalOperator - The ?
Definition Expr.h:4394
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3822
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3878
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3898
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1085
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition Expr.cpp:307
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition Expr.cpp:383
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1135
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:355
bool isImmediateInvocation() const
Definition Expr.h:1157
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4449
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4468
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4465
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:1474
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:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2251
bool isRequiresExprBody() const
Definition DeclBase.h:2207
DeclContextLookupResult lookup_result
Definition DeclBase.h:2590
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:2202
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.
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
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.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1384
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition Expr.h:1428
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1374
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1477
void setDecl(ValueDecl *NewD)
Definition Expr.cpp:549
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition Expr.h:1432
DeclarationNameInfo getNameInfo() const
Definition Expr.h:1345
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition Expr.h:1400
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:493
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition Expr.h:1362
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1366
ValueDecl * getDecl()
Definition Expr.h:1341
SourceLocation getBeginLoc() const
Definition Expr.h:1352
SourceLocation getLocation() const
Definition Expr.h:1349
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:581
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition DeclBase.cpp:776
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:591
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition DeclBase.h:1083
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setReferenced(bool R=true)
Definition DeclBase.h:631
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
Kind getKind() const
Definition DeclBase.h:450
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:2015
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1948
DeclaratorContext getContext() const
Definition DeclSpec.h:2120
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2131
bool isInvalidType() const
Definition DeclSpec.h:2762
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2378
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:549
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:960
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:729
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Represents a reference to emded data.
Definition Expr.h:5129
RAII object that enters a new expression evaluation context.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4202
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3931
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3958
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1471
This represents one expression.
Definition Expr.h:112
LValueClassification
Definition Expr.h:289
@ LV_ArrayTemporary
Definition Expr.h:300
@ LV_ClassTemporary
Definition Expr.h:299
@ LV_MemberFunction
Definition Expr.h:297
@ LV_IncompleteVoidType
Definition Expr.h:292
@ LV_Valid
Definition Expr.h:290
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:287
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:3124
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:677
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition Expr.cpp:3053
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:3102
void setType(QualType t)
Definition Expr.h:145
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:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition Expr.h:241
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3097
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3106
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3093
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3346
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:830
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:838
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
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:3695
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3077
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:805
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:814
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:817
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition Expr.h:820
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:807
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:4075
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:271
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:464
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:282
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:4327
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:467
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
isModifiableLvalueResult
Definition Expr.h:305
@ MLV_DuplicateVectorComponents
Definition Expr.h:309
@ MLV_LValueCast
Definition Expr.h:312
@ MLV_InvalidMessageExpression
Definition Expr.h:321
@ MLV_DuplicateMatrixComponents
Definition Expr.h:310
@ MLV_ConstQualifiedField
Definition Expr.h:315
@ MLV_InvalidExpression
Definition Expr.h:311
@ MLV_IncompleteType
Definition Expr.h:313
@ MLV_Valid
Definition Expr.h:306
@ MLV_ConstQualified
Definition Expr.h:314
@ MLV_NoSetterProperty
Definition Expr.h:318
@ MLV_ArrayTemporary
Definition Expr.h:323
@ MLV_SubObjCPropertySetting
Definition Expr.h:320
@ MLV_ConstAddrSpace
Definition Expr.h:316
@ MLV_MemberFunction
Definition Expr.h:319
@ MLV_NotObjectType
Definition Expr.h:307
@ MLV_ArrayType
Definition Expr.h:317
@ MLV_ClassTemporary
Definition Expr.h:322
@ MLV_IncompleteVoidType
Definition Expr.h:308
QualType getType() const
Definition Expr.h:144
bool isOrdinaryOrBitFieldObject() const
Definition Expr.h:458
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:137
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6610
ExtVectorType - Extended vector type.
Definition TypeBase.h:4329
Represents difference between two FPOptions values.
bool isFPConstrained() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3178
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3281
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3358
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3414
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:104
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:1002
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1081
const Expr * getSubExpr() const
Definition Expr.h:1065
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
Represents a function declaration or definition.
Definition Decl.h:2018
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2207
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3842
bool isImmediateFunction() const
Definition Decl.cpp:3335
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4019
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3757
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3860
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2939
QualType getReturnType() const
Definition Decl.h:2863
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2792
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2461
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3613
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isImmediateEscalating() const
Definition Decl.cpp:3306
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2951
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4125
bool isConsteval() const
Definition Decl.h:2500
size_t param_size() const
Definition Decl.h:2808
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3194
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition Decl.cpp:4035
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition Decl.h:2899
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4841
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4870
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5369
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5873
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5676
bool isParamConsumed(unsigned I) const
Definition TypeBase.h:5887
unsigned getNumParams() const
Definition TypeBase.h:5647
QualType getParamType(unsigned i) const
Definition TypeBase.h:5649
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5773
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5658
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5654
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5809
Declaration of a template function.
unsigned getNumParams() const
Definition TypeLoc.h:1716
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1722
SourceLocation getLocalRangeEnd() const
Definition TypeLoc.h:1668
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1725
SourceLocation getLocalRangeBegin() const
Definition TypeLoc.h:1660
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4676
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4747
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4604
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4565
ExtInfo getExtInfo() const
Definition TypeBase.h:4921
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4913
bool getCFIUncheckedCalleeAttr() const
Determine whether this is a function prototype that includes the cfi_unchecked_callee attribute.
Definition Type.cpp:3694
QualType getReturnType() const
Definition TypeBase.h:4905
bool getCmseNSCallAttr() const
Definition TypeBase.h:4919
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4933
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4926
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition Expr.cpp:4723
One of these records is kept for each identifier that is lexed.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1734
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3856
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2078
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3485
Describes an C or C++ initializer list.
Definition Expr.h:5302
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, QualType Type)
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:980
Represents the declaration of a label.
Definition Decl.h:524
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1972
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition ExprCXX.cpp:1411
FPEvalMethodKind
Possible float expression evaluation method choices.
@ FEM_Extended
Use extended type for fp arithmetic.
@ FEM_Double
Use the type double for fp arithmetic.
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
@ FEM_Source
Use the declared type for fp arithmetic.
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
@ None
Permit no implicit vector bitcasts.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
bool isSignedOverflowDefined() const
bool allowArrayReturnTypes() const
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1075
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition Lexer.h:407
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition Lexer.cpp:320
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
A global _GUID constant.
Definition DeclCXX.h:4403
MS property subscript expression.
Definition ExprCXX.h:1010
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
MatrixSingleSubscriptExpr - Matrix single subscript expression for the MatrixType extension when you ...
Definition Expr.h:2798
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2868
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4399
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4413
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3556
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
Definition Expr.cpp:1755
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3585
Expr * getBase() const
Definition Expr.h:3444
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1799
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1681
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
bool isExternallyVisible() const
Definition Decl.h:433
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:397
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier, or null.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber,...
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1528
ivar_iterator ivar_begin() const
Definition DeclObjC.h:1453
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8007
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition ExprObjC.h:1529
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:580
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprObjC.h:626
SourceLocation getLocation() const
Definition ExprObjC.h:623
SourceLocation getOpLoc() const
Definition ExprObjC.h:631
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:610
bool isArrow() const
Definition ExprObjC.h:618
SourceLocation getEndLoc() const LLVM_READONLY
Definition ExprObjC.h:629
const Expr * getBase() const
Definition ExprObjC.h:614
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:971
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1395
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition DeclObjC.h:418
bool isClassMethod() const
Definition DeclObjC.h:434
Represents a pointer to an Objective C object.
Definition TypeBase.h:8063
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1889
qual_range quals() const
Definition TypeBase.h:8182
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2084
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition Expr.cpp:1658
Helper class for OffsetOfExpr.
Definition Expr.h:2424
void * getAsOpaquePtr() const
Definition Ownership.h:91
static OpaquePtr getFromOpaquePtr(void *P)
Definition Ownership.h:92
PtrTy get() const
Definition Ownership.h:81
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3132
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3193
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2206
const Expr * getSubExpr() const
Definition Expr.h:2202
bool isProducedByFoldExpansion() const
Definition Expr.h:2227
Expr * getExpr(unsigned Init)
Definition Expr.h:6112
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4974
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6110
SourceLocation getLParenLoc() const
Definition Expr.h:6129
SourceLocation getRParenLoc() const
Definition Expr.h:6130
Represents a parameter to a function.
Definition Decl.h:1808
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1841
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2952
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3390
QualType getPointeeType() const
Definition TypeBase.h:3400
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition Expr.cpp:638
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition Expr.cpp:678
bool isMacroDefined(StringRef Id)
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6804
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8529
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8534
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:85
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3678
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:3019
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition TypeBase.h:1431
QualType withConst() const
Definition TypeBase.h:1174
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1171
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8445
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8571
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition Type.h:79
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8485
bool isCXX98PODType(const ASTContext &Context) const
Return true if this is a POD type according to the rules of the C++98 standard, regardless of the cur...
Definition Type.cpp:2796
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8630
QualType getCanonicalType() const
Definition TypeBase.h:8497
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8539
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:3038
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1194
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition TypeBase.h:8637
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8518
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
bool isCanonical() const
Definition TypeBase.h:8502
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1324
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2788
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8610
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8477
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition Type.h:73
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
void removeObjCLifetime()
Definition TypeBase.h:551
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
void removeAddressSpace()
Definition TypeBase.h:596
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:533
Qualifiers withoutObjCGCAttr() const
Definition TypeBase.h:528
LangAS getAddressSpace() const
Definition TypeBase.h:571
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:750
Represents a struct/union/class.
Definition Decl.h:4343
bool hasFlexibleArrayMember() const
Definition Decl.h:4376
field_iterator field_end() const
Definition Decl.h:4549
field_range fields() const
Definition Decl.h:4546
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition Expr.cpp:5460
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3635
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:428
bool Contains(const Scope &rhs) const
Returns if rhs has a higher scope depth than this.
Definition Scope.h:637
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
bool isInCFunctionScope() const
isInObjcMethodScope - Return true if this scope is, or is contained, in an C function body.
Definition Scope.h:448
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:487
@ ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition Scope.h:59
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition Scope.h:66
@ BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it.
Definition Scope.h:55
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
Expr * ExpandAMDGPUPredicateBuiltIn(Expr *CE)
Expand a valid use of the feature identification builtins into its corresponding sequence of instruct...
void AddPotentiallyUnguardedBuiltinUser(FunctionDecl *FD)
Diagnose unguarded usages of AMDGPU builtins and recommend guarding with __builtin_amdgcn_is_invocabl...
bool checkSVETypeSupport(QualType Ty, SourceLocation Loc, const FunctionDecl *FD, const llvm::StringMap< bool > &FeatureMap)
Definition SemaARM.cpp:1758
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:90
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void RecordImplicitHostDeviceFuncUsedByDevice(const FunctionDecl *FD)
Record FD if it is a CUDA/HIP implicit host device function used on device side in device compilation...
Definition SemaCUDA.cpp:808
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition SemaCUDA.cpp:984
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition SemaCUDA.h:121
@ CVT_Both
Emitted on host side only.
Definition SemaCUDA.h:122
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition SemaObjC.h:855
ObjCLiteralKind CheckLiteralKind(Expr *FromE)