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 if (getCurScope()->isControlScope())
14640 return;
14641
14642 // If there are multiple comma operators used together, get the RHS of the
14643 // of the comma operator as the LHS.
14644 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14645 if (BO->getOpcode() != BO_Comma)
14646 break;
14647 LHS = BO->getRHS();
14648 }
14649
14650 // Only allow some expressions on LHS to not warn.
14651 if (IgnoreCommaOperand(LHS, Context))
14652 return;
14653
14654 Diag(Loc, diag::warn_comma_operator);
14655 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14656 << LHS->getSourceRange()
14658 LangOpts.CPlusPlus ? "static_cast<void>("
14659 : "(void)(")
14660 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14661 ")");
14662}
14663
14664// C99 6.5.17
14666 SourceLocation Loc) {
14667 LHS = S.CheckPlaceholderExpr(LHS.get());
14668 RHS = S.CheckPlaceholderExpr(RHS.get());
14669 if (LHS.isInvalid() || RHS.isInvalid())
14670 return QualType();
14671
14672 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14673 // operands, but not unary promotions.
14674 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14675
14676 // So we treat the LHS as a ignored value, and in C++ we allow the
14677 // containing site to determine what should be done with the RHS.
14678 LHS = S.IgnoredValueConversions(LHS.get());
14679 if (LHS.isInvalid())
14680 return QualType();
14681
14682 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14683
14684 if (!S.getLangOpts().CPlusPlus) {
14686 if (RHS.isInvalid())
14687 return QualType();
14688 if (!RHS.get()->getType()->isVoidType())
14689 S.RequireCompleteType(Loc, RHS.get()->getType(),
14690 diag::err_incomplete_type);
14691 }
14692
14693 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14694 S.DiagnoseCommaOperator(LHS.get(), Loc);
14695
14696 return RHS.get()->getType();
14697}
14698
14699/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14700/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14703 ExprObjectKind &OK,
14704 SourceLocation OpLoc, bool IsInc,
14705 bool IsPrefix) {
14706 QualType ResType = Op->getType();
14707 // Atomic types can be used for increment / decrement where the non-atomic
14708 // versions can, so ignore the _Atomic() specifier for the purpose of
14709 // checking.
14710 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14711 ResType = ResAtomicType->getValueType();
14712
14713 assert(!ResType.isNull() && "no type for increment/decrement expression");
14714
14715 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14716 // Decrement of bool is not allowed.
14717 if (!IsInc) {
14718 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14719 return QualType();
14720 }
14721 // Increment of bool sets it to true, but is deprecated.
14722 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14723 : diag::warn_increment_bool)
14724 << Op->getSourceRange();
14725 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14726 // Error on enum increments and decrements in C++ mode
14727 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14728 return QualType();
14729 } else if (ResType->isRealType()) {
14730 // OK!
14731 } else if (ResType->isPointerType()) {
14732 // C99 6.5.2.4p2, 6.5.6p2
14733 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14734 return QualType();
14735 } else if (ResType->isOverflowBehaviorType()) {
14736 // OK!
14737 } else if (ResType->isObjCObjectPointerType()) {
14738 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14739 // Otherwise, we just need a complete type.
14740 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14741 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14742 return QualType();
14743 } else if (ResType->isAnyComplexType()) {
14744 // C99 does not support ++/-- on complex types, we allow as an extension.
14745 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14746 : diag::ext_c2y_increment_complex)
14747 << IsInc << Op->getSourceRange();
14748 } else if (ResType->isPlaceholderType()) {
14750 if (PR.isInvalid()) return QualType();
14751 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14752 IsInc, IsPrefix);
14753 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14754 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14755 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14756 (ResType->castAs<VectorType>()->getVectorKind() !=
14758 // The z vector extensions allow ++ and -- for non-bool vectors.
14759 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14760 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14761 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14762 } else {
14763 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14764 << ResType << int(IsInc) << Op->getSourceRange();
14765 return QualType();
14766 }
14767 // At this point, we know we have a real, complex or pointer type.
14768 // Now make sure the operand is a modifiable lvalue.
14769 if (CheckForModifiableLvalue(Op, OpLoc, S))
14770 return QualType();
14771 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14772 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14773 // An operand with volatile-qualified type is deprecated
14774 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14775 << IsInc << ResType;
14776 }
14777 // In C++, a prefix increment is the same type as the operand. Otherwise
14778 // (in C or with postfix), the increment is the unqualified type of the
14779 // operand.
14780 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14781 VK = VK_LValue;
14782 OK = Op->getObjectKind();
14783 return ResType;
14784 } else {
14785 VK = VK_PRValue;
14786 return ResType.getUnqualifiedType();
14787 }
14788}
14789
14790/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14791/// This routine allows us to typecheck complex/recursive expressions
14792/// where the declaration is needed for type checking. We only need to
14793/// handle cases when the expression references a function designator
14794/// or is an lvalue. Here are some examples:
14795/// - &(x) => x
14796/// - &*****f => f for f a function designator.
14797/// - &s.xx => s
14798/// - &s.zz[1].yy -> s, if zz is an array
14799/// - *(x + 1) -> x, if x is an array
14800/// - &"123"[2] -> 0
14801/// - & __real__ x -> x
14802///
14803/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14804/// members.
14806 switch (E->getStmtClass()) {
14807 case Stmt::DeclRefExprClass:
14808 return cast<DeclRefExpr>(E)->getDecl();
14809 case Stmt::MemberExprClass:
14810 // If this is an arrow operator, the address is an offset from
14811 // the base's value, so the object the base refers to is
14812 // irrelevant.
14813 if (cast<MemberExpr>(E)->isArrow())
14814 return nullptr;
14815 // Otherwise, the expression refers to a part of the base
14816 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14817 case Stmt::ArraySubscriptExprClass: {
14818 // FIXME: This code shouldn't be necessary! We should catch the implicit
14819 // promotion of register arrays earlier.
14820 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14821 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14822 if (ICE->getSubExpr()->getType()->isArrayType())
14823 return getPrimaryDecl(ICE->getSubExpr());
14824 }
14825 return nullptr;
14826 }
14827 case Stmt::UnaryOperatorClass: {
14829
14830 switch(UO->getOpcode()) {
14831 case UO_Real:
14832 case UO_Imag:
14833 case UO_Extension:
14834 return getPrimaryDecl(UO->getSubExpr());
14835 default:
14836 return nullptr;
14837 }
14838 }
14839 case Stmt::ParenExprClass:
14840 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14841 case Stmt::ImplicitCastExprClass:
14842 // If the result of an implicit cast is an l-value, we care about
14843 // the sub-expression; otherwise, the result here doesn't matter.
14844 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14845 case Stmt::CXXUuidofExprClass:
14846 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14847 default:
14848 return nullptr;
14849 }
14850}
14851
14852namespace {
14853enum {
14854 AO_Bit_Field = 0,
14855 AO_Vector_Element = 1,
14856 AO_Property_Expansion = 2,
14857 AO_Register_Variable = 3,
14858 AO_Matrix_Element = 4,
14859 AO_No_Error = 5
14860};
14861}
14862/// Diagnose invalid operand for address of operations.
14863///
14864/// \param Type The type of operand which cannot have its address taken.
14866 Expr *E, unsigned Type) {
14867 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14868}
14869
14871 const Expr *Op,
14872 const CXXMethodDecl *MD) {
14873 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14874
14875 if (Op != DRE)
14876 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14877 << Op->getSourceRange();
14878
14879 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14880 if (isa<CXXDestructorDecl>(MD))
14881 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14882 << DRE->getSourceRange();
14883
14884 if (DRE->getQualifier())
14885 return false;
14886
14887 if (MD->getParent()->getName().empty())
14888 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14889 << DRE->getSourceRange();
14890
14891 SmallString<32> Str;
14892 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14893 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14894 << DRE->getSourceRange()
14895 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14896}
14897
14899 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14900 if (PTy->getKind() == BuiltinType::Overload) {
14901 Expr *E = OrigOp.get()->IgnoreParens();
14902 if (!isa<OverloadExpr>(E)) {
14903 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14904 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14905 << OrigOp.get()->getSourceRange();
14906 return QualType();
14907 }
14908
14912 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14913 << OrigOp.get()->getSourceRange();
14914 return QualType();
14915 }
14916
14917 return Context.OverloadTy;
14918 }
14919
14920 if (PTy->getKind() == BuiltinType::UnknownAny)
14921 return Context.UnknownAnyTy;
14922
14923 if (PTy->getKind() == BuiltinType::BoundMember) {
14924 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14925 << OrigOp.get()->getSourceRange();
14926 return QualType();
14927 }
14928
14929 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14930 if (OrigOp.isInvalid()) return QualType();
14931 }
14932
14933 if (OrigOp.get()->isTypeDependent())
14934 return Context.DependentTy;
14935
14936 assert(!OrigOp.get()->hasPlaceholderType());
14937
14938 // Make sure to ignore parentheses in subsequent checks
14939 Expr *op = OrigOp.get()->IgnoreParens();
14940
14941 // In OpenCL captures for blocks called as lambda functions
14942 // are located in the private address space. Blocks used in
14943 // enqueue_kernel can be located in a different address space
14944 // depending on a vendor implementation. Thus preventing
14945 // taking an address of the capture to avoid invalid AS casts.
14946 if (LangOpts.OpenCL) {
14947 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14948 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14949 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14950 return QualType();
14951 }
14952 }
14953
14954 if (getLangOpts().C99) {
14955 // Implement C99-only parts of addressof rules.
14956 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14957 if (uOp->getOpcode() == UO_Deref)
14958 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14959 // (assuming the deref expression is valid).
14960 return uOp->getSubExpr()->getType();
14961 }
14962 // Technically, there should be a check for array subscript
14963 // expressions here, but the result of one is always an lvalue anyway.
14964 }
14965 ValueDecl *dcl = getPrimaryDecl(op);
14966
14967 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14968 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14969 op->getBeginLoc()))
14970 return QualType();
14971
14973 unsigned AddressOfError = AO_No_Error;
14974
14975 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14976 bool IsError = isSFINAEContext();
14977 Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary
14978 : diag::ext_typecheck_addrof_temporary)
14979 << op->getType() << op->getSourceRange();
14980 if (IsError)
14981 return QualType();
14982 // Materialize the temporary as an lvalue so that we can take its address.
14983 OrigOp = op =
14984 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14985 } else if (isa<ObjCSelectorExpr>(op)) {
14986 return Context.getPointerType(op->getType());
14987 } else if (lval == Expr::LV_MemberFunction) {
14988 // If it's an instance method, make a member pointer.
14989 // The expression must have exactly the form &A::foo.
14990
14991 // If the underlying expression isn't a decl ref, give up.
14992 if (!isa<DeclRefExpr>(op)) {
14993 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14994 << OrigOp.get()->getSourceRange();
14995 return QualType();
14996 }
14997 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14999
15000 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15001 QualType MPTy = Context.getMemberPointerType(
15002 op->getType(), DRE->getQualifier(), MD->getParent());
15003
15004 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15005 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15006 // When pointer authentication is enabled, argument and return types of
15007 // vitual member functions must be complete. This is because vitrual
15008 // member function pointers are implemented using virtual dispatch
15009 // thunks and the thunks cannot be emitted if the argument or return
15010 // types are incomplete.
15011 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15012 SourceLocation DeclRefLoc,
15013 SourceLocation RetArgTypeLoc) {
15014 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
15015 Diag(DeclRefLoc,
15016 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15017 Diag(RetArgTypeLoc,
15018 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15019 << T;
15020 return true;
15021 }
15022 return false;
15023 };
15024 QualType RetTy = MD->getReturnType();
15025 bool IsIncomplete =
15026 !RetTy->isVoidType() &&
15027 ReturnOrParamTypeIsIncomplete(
15028 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15029 for (auto *PVD : MD->parameters())
15030 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15031 PVD->getBeginLoc());
15032 if (IsIncomplete)
15033 return QualType();
15034 }
15035
15036 // Under the MS ABI, lock down the inheritance model now.
15037 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15038 (void)isCompleteType(OpLoc, MPTy);
15039 return MPTy;
15040 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15041 // C99 6.5.3.2p1
15042 // The operand must be either an l-value or a function designator
15043 if (!op->getType()->isFunctionType()) {
15044 // Use a special diagnostic for loads from property references.
15045 if (isa<PseudoObjectExpr>(op)) {
15046 AddressOfError = AO_Property_Expansion;
15047 } else {
15048 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15049 << op->getType() << op->getSourceRange();
15050 return QualType();
15051 }
15052 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
15053 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
15054 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15055 }
15056
15057 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15058 // The operand cannot be a bit-field
15059 AddressOfError = AO_Bit_Field;
15060 } else if (op->getObjectKind() == OK_VectorComponent) {
15061 // The operand cannot be an element of a vector
15062 AddressOfError = AO_Vector_Element;
15063 } else if (op->getObjectKind() == OK_MatrixComponent) {
15064 // The operand cannot be an element of a matrix.
15065 AddressOfError = AO_Matrix_Element;
15066 } else if (dcl) { // C99 6.5.3.2p1
15067 // We have an lvalue with a decl. Make sure the decl is not declared
15068 // with the register storage-class specifier.
15069 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15070 // in C++ it is not error to take address of a register
15071 // variable (c++03 7.1.1P3)
15072 if (vd->getStorageClass() == SC_Register &&
15074 AddressOfError = AO_Register_Variable;
15075 }
15076 } else if (isa<MSPropertyDecl>(dcl)) {
15077 AddressOfError = AO_Property_Expansion;
15078 } else if (isa<FunctionTemplateDecl>(dcl)) {
15079 return Context.OverloadTy;
15080 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15081 // Okay: we can take the address of a field.
15082 // Could be a pointer to member, though, if there is an explicit
15083 // scope qualifier for the class.
15084
15085 // [C++26] [expr.prim.id.general]
15086 // If an id-expression E denotes a non-static non-type member
15087 // of some class C [...] and if E is a qualified-id, E is
15088 // not the un-parenthesized operand of the unary & operator [...]
15089 // the id-expression is transformed into a class member access expression.
15090 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
15091 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
15092 DeclContext *Ctx = dcl->getDeclContext();
15093 if (Ctx && Ctx->isRecord()) {
15094 if (dcl->getType()->isReferenceType()) {
15095 Diag(OpLoc,
15096 diag::err_cannot_form_pointer_to_member_of_reference_type)
15097 << dcl->getDeclName() << dcl->getType();
15098 return QualType();
15099 }
15100
15101 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15102 Ctx = Ctx->getParent();
15103
15104 QualType MPTy = Context.getMemberPointerType(
15105 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
15106 // Under the MS ABI, lock down the inheritance model now.
15107 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15108 (void)isCompleteType(OpLoc, MPTy);
15109 return MPTy;
15110 }
15111 }
15115 llvm_unreachable("Unknown/unexpected decl type");
15116 }
15117
15118 if (AddressOfError != AO_No_Error) {
15119 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15120 return QualType();
15121 }
15122
15123 if (lval == Expr::LV_IncompleteVoidType) {
15124 // Taking the address of a void variable is technically illegal, but we
15125 // allow it in cases which are otherwise valid.
15126 // Example: "extern void x; void* y = &x;".
15127 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15128 }
15129
15130 // If the operand has type "type", the result has type "pointer to type".
15131 if (op->getType()->isObjCObjectType())
15132 return Context.getObjCObjectPointerType(op->getType());
15133
15134 // Cannot take the address of WebAssembly references or tables.
15135 if (Context.getTargetInfo().getTriple().isWasm()) {
15136 QualType OpTy = op->getType();
15137 if (OpTy.isWebAssemblyReferenceType()) {
15138 Diag(OpLoc, diag::err_wasm_ca_reference)
15139 << 1 << OrigOp.get()->getSourceRange();
15140 return QualType();
15141 }
15142 if (OpTy->isWebAssemblyTableType()) {
15143 Diag(OpLoc, diag::err_wasm_table_pr)
15144 << 1 << OrigOp.get()->getSourceRange();
15145 return QualType();
15146 }
15147 }
15148
15149 CheckAddressOfPackedMember(op);
15150
15151 return Context.getPointerType(op->getType());
15152}
15153
15154static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15155 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15156 if (!DRE)
15157 return;
15158 const Decl *D = DRE->getDecl();
15159 if (!D)
15160 return;
15161 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15162 if (!Param)
15163 return;
15164 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15165 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15166 return;
15167 if (FunctionScopeInfo *FD = S.getCurFunction())
15168 FD->ModifiedNonNullParams.insert(Param);
15169}
15170
15171/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15173 SourceLocation OpLoc,
15174 bool IsAfterAmp = false) {
15175 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15176 if (ConvResult.isInvalid())
15177 return QualType();
15178 Op = ConvResult.get();
15179 QualType OpTy = Op->getType();
15181
15183 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15184 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15185 Op->getSourceRange());
15186 }
15187
15188 if (const PointerType *PT = OpTy->getAs<PointerType>())
15189 {
15190 Result = PT->getPointeeType();
15191 }
15192 else if (const ObjCObjectPointerType *OPT =
15194 Result = OPT->getPointeeType();
15195 else {
15197 if (PR.isInvalid()) return QualType();
15198 if (PR.get() != Op)
15199 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15200 }
15201
15202 if (Result.isNull()) {
15203 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15204 << OpTy << Op->getSourceRange();
15205 return QualType();
15206 }
15207
15208 if (Result->isVoidType()) {
15209 // C++ [expr.unary.op]p1:
15210 // [...] the expression to which [the unary * operator] is applied shall
15211 // be a pointer to an object type, or a pointer to a function type
15212 LangOptions LO = S.getLangOpts();
15213 if (LO.CPlusPlus)
15214 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15215 << OpTy << Op->getSourceRange();
15216 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15217 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15218 << OpTy << Op->getSourceRange();
15219 }
15220
15221 // Dereferences are usually l-values...
15222 VK = VK_LValue;
15223
15224 // ...except that certain expressions are never l-values in C.
15225 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15226 VK = VK_PRValue;
15227
15228 return Result;
15229}
15230
15231BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15233 switch (Kind) {
15234 default: llvm_unreachable("Unknown binop!");
15235 case tok::periodstar: Opc = BO_PtrMemD; break;
15236 case tok::arrowstar: Opc = BO_PtrMemI; break;
15237 case tok::star: Opc = BO_Mul; break;
15238 case tok::slash: Opc = BO_Div; break;
15239 case tok::percent: Opc = BO_Rem; break;
15240 case tok::plus: Opc = BO_Add; break;
15241 case tok::minus: Opc = BO_Sub; break;
15242 case tok::lessless: Opc = BO_Shl; break;
15243 case tok::greatergreater: Opc = BO_Shr; break;
15244 case tok::lessequal: Opc = BO_LE; break;
15245 case tok::less: Opc = BO_LT; break;
15246 case tok::greaterequal: Opc = BO_GE; break;
15247 case tok::greater: Opc = BO_GT; break;
15248 case tok::exclaimequal: Opc = BO_NE; break;
15249 case tok::equalequal: Opc = BO_EQ; break;
15250 case tok::spaceship: Opc = BO_Cmp; break;
15251 case tok::amp: Opc = BO_And; break;
15252 case tok::caret: Opc = BO_Xor; break;
15253 case tok::pipe: Opc = BO_Or; break;
15254 case tok::ampamp: Opc = BO_LAnd; break;
15255 case tok::pipepipe: Opc = BO_LOr; break;
15256 case tok::equal: Opc = BO_Assign; break;
15257 case tok::starequal: Opc = BO_MulAssign; break;
15258 case tok::slashequal: Opc = BO_DivAssign; break;
15259 case tok::percentequal: Opc = BO_RemAssign; break;
15260 case tok::plusequal: Opc = BO_AddAssign; break;
15261 case tok::minusequal: Opc = BO_SubAssign; break;
15262 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15263 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15264 case tok::ampequal: Opc = BO_AndAssign; break;
15265 case tok::caretequal: Opc = BO_XorAssign; break;
15266 case tok::pipeequal: Opc = BO_OrAssign; break;
15267 case tok::comma: Opc = BO_Comma; break;
15268 }
15269 return Opc;
15270}
15271
15273 tok::TokenKind Kind) {
15275 switch (Kind) {
15276 default: llvm_unreachable("Unknown unary op!");
15277 case tok::plusplus: Opc = UO_PreInc; break;
15278 case tok::minusminus: Opc = UO_PreDec; break;
15279 case tok::amp: Opc = UO_AddrOf; break;
15280 case tok::star: Opc = UO_Deref; break;
15281 case tok::plus: Opc = UO_Plus; break;
15282 case tok::minus: Opc = UO_Minus; break;
15283 case tok::tilde: Opc = UO_Not; break;
15284 case tok::exclaim: Opc = UO_LNot; break;
15285 case tok::kw___real: Opc = UO_Real; break;
15286 case tok::kw___imag: Opc = UO_Imag; break;
15287 case tok::kw___extension__: Opc = UO_Extension; break;
15288 }
15289 return Opc;
15290}
15291
15292const FieldDecl *
15294 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15295 // common for setters.
15296 // struct A {
15297 // int X;
15298 // -void setX(int X) { X = X; }
15299 // +void setX(int X) { this->X = X; }
15300 // };
15301
15302 // Only consider parameters for self assignment fixes.
15303 if (!isa<ParmVarDecl>(SelfAssigned))
15304 return nullptr;
15305 const auto *Method =
15306 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15307 if (!Method)
15308 return nullptr;
15309
15310 const CXXRecordDecl *Parent = Method->getParent();
15311 // In theory this is fixable if the lambda explicitly captures this, but
15312 // that's added complexity that's rarely going to be used.
15313 if (Parent->isLambda())
15314 return nullptr;
15315
15316 // FIXME: Use an actual Lookup operation instead of just traversing fields
15317 // in order to get base class fields.
15318 auto Field =
15319 llvm::find_if(Parent->fields(),
15320 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15321 return F->getDeclName() == Name;
15322 });
15323 return (Field != Parent->field_end()) ? *Field : nullptr;
15324}
15325
15326/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15327/// This warning suppressed in the event of macro expansions.
15328static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15329 SourceLocation OpLoc, bool IsBuiltin) {
15331 return;
15332 if (S.isUnevaluatedContext())
15333 return;
15334 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15335 return;
15336 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15337 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15338 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15339 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15340 if (!LHSDeclRef || !RHSDeclRef ||
15341 LHSDeclRef->getLocation().isMacroID() ||
15342 RHSDeclRef->getLocation().isMacroID())
15343 return;
15344 const ValueDecl *LHSDecl =
15345 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15346 const ValueDecl *RHSDecl =
15347 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15348 if (LHSDecl != RHSDecl)
15349 return;
15350 if (LHSDecl->getType().isVolatileQualified())
15351 return;
15352 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15353 if (RefTy->getPointeeType().isVolatileQualified())
15354 return;
15355
15356 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15357 : diag::warn_self_assignment_overloaded)
15358 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15359 << RHSExpr->getSourceRange();
15360 if (const FieldDecl *SelfAssignField =
15362 Diag << 1 << SelfAssignField
15363 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15364 else
15365 Diag << 0;
15366}
15367
15368/// Check if a bitwise-& is performed on an Objective-C pointer. This
15369/// is usually indicative of introspection within the Objective-C pointer.
15371 SourceLocation OpLoc) {
15372 if (!S.getLangOpts().ObjC)
15373 return;
15374
15375 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15376 const Expr *LHS = L.get();
15377 const Expr *RHS = R.get();
15378
15380 ObjCPointerExpr = LHS;
15381 OtherExpr = RHS;
15382 }
15383 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15384 ObjCPointerExpr = RHS;
15385 OtherExpr = LHS;
15386 }
15387
15388 // This warning is deliberately made very specific to reduce false
15389 // positives with logic that uses '&' for hashing. This logic mainly
15390 // looks for code trying to introspect into tagged pointers, which
15391 // code should generally never do.
15392 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15393 unsigned Diag = diag::warn_objc_pointer_masking;
15394 // Determine if we are introspecting the result of performSelectorXXX.
15395 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15396 // Special case messages to -performSelector and friends, which
15397 // can return non-pointer values boxed in a pointer value.
15398 // Some clients may wish to silence warnings in this subcase.
15399 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15400 Selector S = ME->getSelector();
15401 StringRef SelArg0 = S.getNameForSlot(0);
15402 if (SelArg0.starts_with("performSelector"))
15403 Diag = diag::warn_objc_pointer_masking_performSelector;
15404 }
15405
15406 S.Diag(OpLoc, Diag)
15407 << ObjCPointerExpr->getSourceRange();
15408 }
15409}
15410
15411// This helper function promotes a binary operator's operands (which are of a
15412// half vector type) to a vector of floats and then truncates the result to
15413// a vector of either half or short.
15415 BinaryOperatorKind Opc, QualType ResultTy,
15417 bool IsCompAssign, SourceLocation OpLoc,
15418 FPOptionsOverride FPFeatures) {
15419 auto &Context = S.getASTContext();
15420 assert((isVector(ResultTy, Context.HalfTy) ||
15421 isVector(ResultTy, Context.ShortTy)) &&
15422 "Result must be a vector of half or short");
15423 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15424 isVector(RHS.get()->getType(), Context.HalfTy) &&
15425 "both operands expected to be a half vector");
15426
15427 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15428 QualType BinOpResTy = RHS.get()->getType();
15429
15430 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15431 // change BinOpResTy to a vector of ints.
15432 if (isVector(ResultTy, Context.ShortTy))
15433 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15434
15435 if (IsCompAssign)
15436 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15437 ResultTy, VK, OK, OpLoc, FPFeatures,
15438 BinOpResTy, BinOpResTy);
15439
15440 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15441 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15442 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15443 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15444}
15445
15446/// Returns true if conversion between vectors of halfs and vectors of floats
15447/// is needed.
15448static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15449 Expr *E0, Expr *E1 = nullptr) {
15450 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15452 return false;
15453
15454 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15455 QualType Ty = E->IgnoreImplicit()->getType();
15456
15457 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15458 // to vectors of floats. Although the element type of the vectors is __fp16,
15459 // the vectors shouldn't be treated as storage-only types. See the
15460 // discussion here: https://reviews.llvm.org/rG825235c140e7
15461 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15462 if (VT->getVectorKind() == VectorKind::Neon)
15463 return false;
15464 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15465 }
15466 return false;
15467 };
15468
15469 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15470}
15471
15473 BinaryOperatorKind Opc, Expr *LHSExpr,
15474 Expr *RHSExpr, bool ForFoldExpression) {
15475 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15476 // The syntax only allows initializer lists on the RHS of assignment,
15477 // so we don't need to worry about accepting invalid code for
15478 // non-assignment operators.
15479 // C++11 5.17p9:
15480 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15481 // of x = {} is x = T().
15483 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15484 InitializedEntity Entity =
15486 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15487 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15488 if (Init.isInvalid())
15489 return Init;
15490 RHSExpr = Init.get();
15491 }
15492
15493 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15494 QualType ResultTy; // Result type of the binary operator.
15495 // The following two variables are used for compound assignment operators
15496 QualType CompLHSTy; // Type of LHS after promotions for computation
15497 QualType CompResultTy; // Type of computation result
15500 bool ConvertHalfVec = false;
15501
15502 if (!LHS.isUsable() || !RHS.isUsable())
15503 return ExprError();
15504
15505 if (getLangOpts().OpenCL) {
15506 QualType LHSTy = LHSExpr->getType();
15507 QualType RHSTy = RHSExpr->getType();
15508 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15509 // the ATOMIC_VAR_INIT macro.
15510 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15511 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15512 if (BO_Assign == Opc)
15513 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15514 else
15515 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15516 return ExprError();
15517 }
15518
15519 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15520 // only with a builtin functions and therefore should be disallowed here.
15521 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15522 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15523 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15524 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15525 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15526 return ExprError();
15527 }
15528 }
15529
15530 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15531 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15532
15533 switch (Opc) {
15534 case BO_Assign:
15535 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15536 if (getLangOpts().CPlusPlus &&
15537 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15538 VK = LHS.get()->getValueKind();
15539 OK = LHS.get()->getObjectKind();
15540 }
15541 if (!ResultTy.isNull()) {
15542 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15543 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15544
15545 // Avoid copying a block to the heap if the block is assigned to a local
15546 // auto variable that is declared in the same scope as the block. This
15547 // optimization is unsafe if the local variable is declared in an outer
15548 // scope. For example:
15549 //
15550 // BlockTy b;
15551 // {
15552 // b = ^{...};
15553 // }
15554 // // It is unsafe to invoke the block here if it wasn't copied to the
15555 // // heap.
15556 // b();
15557
15558 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15559 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15560 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15561 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15562 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15563
15565 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15567 }
15568 RecordModifiableNonNullParam(*this, LHS.get());
15569 break;
15570 case BO_PtrMemD:
15571 case BO_PtrMemI:
15572 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15573 Opc == BO_PtrMemI);
15574 break;
15575 case BO_Mul:
15576 case BO_Div:
15577 ConvertHalfVec = true;
15578 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15579 break;
15580 case BO_Rem:
15581 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15582 break;
15583 case BO_Add:
15584 ConvertHalfVec = true;
15585 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15586 break;
15587 case BO_Sub:
15588 ConvertHalfVec = true;
15589 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15590 break;
15591 case BO_Shl:
15592 case BO_Shr:
15593 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15594 break;
15595 case BO_LE:
15596 case BO_LT:
15597 case BO_GE:
15598 case BO_GT:
15599 ConvertHalfVec = true;
15600 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15601
15602 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15603 !ForFoldExpression && BI && BI->isComparisonOp())
15604 Diag(OpLoc, diag::warn_consecutive_comparison)
15605 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15606
15607 break;
15608 case BO_EQ:
15609 case BO_NE:
15610 ConvertHalfVec = true;
15611 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15612 break;
15613 case BO_Cmp:
15614 ConvertHalfVec = true;
15615 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15616 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15617 break;
15618 case BO_And:
15619 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15620 [[fallthrough]];
15621 case BO_Xor:
15622 case BO_Or:
15623 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15624 break;
15625 case BO_LAnd:
15626 case BO_LOr:
15627 ConvertHalfVec = true;
15628 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15629 break;
15630 case BO_MulAssign:
15631 case BO_DivAssign:
15632 ConvertHalfVec = true;
15633 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15634 CompLHSTy = CompResultTy;
15635 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15636 ResultTy =
15637 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15638 break;
15639 case BO_RemAssign:
15640 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15641 CompLHSTy = CompResultTy;
15642 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15643 ResultTy =
15644 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15645 break;
15646 case BO_AddAssign:
15647 ConvertHalfVec = true;
15648 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15649 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15650 ResultTy =
15651 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15652 break;
15653 case BO_SubAssign:
15654 ConvertHalfVec = true;
15655 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15656 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15657 ResultTy =
15658 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15659 break;
15660 case BO_ShlAssign:
15661 case BO_ShrAssign:
15662 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15663 CompLHSTy = CompResultTy;
15664 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15665 ResultTy =
15666 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15667 break;
15668 case BO_AndAssign:
15669 case BO_OrAssign: // fallthrough
15670 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15671 [[fallthrough]];
15672 case BO_XorAssign:
15673 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15674 CompLHSTy = CompResultTy;
15675 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15676 ResultTy =
15677 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15678 break;
15679 case BO_Comma:
15680 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15681 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15682 VK = RHS.get()->getValueKind();
15683 OK = RHS.get()->getObjectKind();
15684 }
15685 break;
15686 }
15687 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15688 return ExprError();
15689
15690 // Some of the binary operations require promoting operands of half vector to
15691 // float vectors and truncating the result back to half vector. For now, we do
15692 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15693 // arm64).
15694 assert(
15695 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15696 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15697 "both sides are half vectors or neither sides are");
15698 ConvertHalfVec =
15699 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15700
15701 // Check for array bounds violations for both sides of the BinaryOperator
15702 CheckArrayAccess(LHS.get());
15703 CheckArrayAccess(RHS.get());
15704
15705 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15706 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15707 &Context.Idents.get("object_setClass"),
15709 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15710 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15711 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15713 "object_setClass(")
15714 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15715 ",")
15716 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15717 }
15718 else
15719 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15720 }
15721 else if (const ObjCIvarRefExpr *OIRE =
15722 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15723 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15724
15725 // Opc is not a compound assignment if CompResultTy is null.
15726 if (CompResultTy.isNull()) {
15727 if (ConvertHalfVec)
15728 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15729 OpLoc, CurFPFeatureOverrides());
15730 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15731 VK, OK, OpLoc, CurFPFeatureOverrides());
15732 }
15733
15734 // Handle compound assignments.
15735 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15737 VK = VK_LValue;
15738 OK = LHS.get()->getObjectKind();
15739 }
15740
15741 // The LHS is not converted to the result type for fixed-point compound
15742 // assignment as the common type is computed on demand. Reset the CompLHSTy
15743 // to the LHS type we would have gotten after unary conversions.
15744 if (CompResultTy->isFixedPointType())
15745 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15746
15747 if (ConvertHalfVec)
15748 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15749 OpLoc, CurFPFeatureOverrides());
15750
15752 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15753 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15754}
15755
15756/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15757/// operators are mixed in a way that suggests that the programmer forgot that
15758/// comparison operators have higher precedence. The most typical example of
15759/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15761 SourceLocation OpLoc, Expr *LHSExpr,
15762 Expr *RHSExpr) {
15763 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15764 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15765
15766 // Check that one of the sides is a comparison operator and the other isn't.
15767 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15768 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15769 if (isLeftComp == isRightComp)
15770 return;
15771
15772 // Bitwise operations are sometimes used as eager logical ops.
15773 // Don't diagnose this.
15774 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15775 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15776 if (isLeftBitwise || isRightBitwise)
15777 return;
15778
15779 SourceRange DiagRange = isLeftComp
15780 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15781 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15782 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15783 SourceRange ParensRange =
15784 isLeftComp
15785 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15786 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15787
15788 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15789 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15790 SuggestParentheses(Self, OpLoc,
15791 Self.PDiag(diag::note_precedence_silence) << OpStr,
15792 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15793 SuggestParentheses(Self, OpLoc,
15794 Self.PDiag(diag::note_precedence_bitwise_first)
15796 ParensRange);
15797}
15798
15799/// It accepts a '&&' expr that is inside a '||' one.
15800/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15801/// in parentheses.
15802static void
15804 BinaryOperator *Bop) {
15805 assert(Bop->getOpcode() == BO_LAnd);
15806 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15807 << Bop->getSourceRange() << OpLoc;
15809 Self.PDiag(diag::note_precedence_silence)
15810 << Bop->getOpcodeStr(),
15811 Bop->getSourceRange());
15812}
15813
15814/// Look for '&&' in the left hand of a '||' expr.
15816 Expr *LHSExpr, Expr *RHSExpr) {
15817 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15818 if (Bop->getOpcode() == BO_LAnd) {
15819 // If it's "string_literal && a || b" don't warn since the precedence
15820 // doesn't matter.
15821 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15822 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15823 } else if (Bop->getOpcode() == BO_LOr) {
15824 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15825 // If it's "a || b && string_literal || c" we didn't warn earlier for
15826 // "a || b && string_literal", but warn now.
15827 if (RBop->getOpcode() == BO_LAnd &&
15828 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15829 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15830 }
15831 }
15832 }
15833}
15834
15835/// Look for '&&' in the right hand of a '||' expr.
15837 Expr *LHSExpr, Expr *RHSExpr) {
15838 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15839 if (Bop->getOpcode() == BO_LAnd) {
15840 // If it's "a || b && string_literal" don't warn since the precedence
15841 // doesn't matter.
15842 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15843 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15844 }
15845 }
15846}
15847
15848/// Look for bitwise op in the left or right hand of a bitwise op with
15849/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15850/// the '&' expression in parentheses.
15852 SourceLocation OpLoc, Expr *SubExpr) {
15853 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15854 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15855 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15856 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15857 << Bop->getSourceRange() << OpLoc;
15858 SuggestParentheses(S, Bop->getOperatorLoc(),
15859 S.PDiag(diag::note_precedence_silence)
15860 << Bop->getOpcodeStr(),
15861 Bop->getSourceRange());
15862 }
15863 }
15864}
15865
15867 Expr *SubExpr, StringRef Shift) {
15868 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15869 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15870 StringRef Op = Bop->getOpcodeStr();
15871 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15872 << Bop->getSourceRange() << OpLoc << Shift << Op;
15873 SuggestParentheses(S, Bop->getOperatorLoc(),
15874 S.PDiag(diag::note_precedence_silence) << Op,
15875 Bop->getSourceRange());
15876 }
15877 }
15878}
15879
15881 Expr *LHSExpr, Expr *RHSExpr) {
15882 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15883 if (!OCE)
15884 return;
15885
15886 FunctionDecl *FD = OCE->getDirectCallee();
15887 if (!FD || !FD->isOverloadedOperator())
15888 return;
15889
15891 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15892 return;
15893
15894 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15895 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15896 << (Kind == OO_LessLess);
15898 S.PDiag(diag::note_precedence_silence)
15899 << (Kind == OO_LessLess ? "<<" : ">>"),
15900 OCE->getSourceRange());
15902 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15903 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15904}
15905
15906/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15907/// precedence.
15909 SourceLocation OpLoc, Expr *LHSExpr,
15910 Expr *RHSExpr){
15911 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15913 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15914
15915 // Diagnose "arg1 & arg2 | arg3"
15916 if ((Opc == BO_Or || Opc == BO_Xor) &&
15917 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15918 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15919 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15920 }
15921
15922 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15923 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15924 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15925 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15926 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15927 }
15928
15929 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15930 || Opc == BO_Shr) {
15931 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15932 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15933 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15934 }
15935
15936 // Warn on overloaded shift operators and comparisons, such as:
15937 // cout << 5 == 4;
15939 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15940}
15941
15943 tok::TokenKind Kind,
15944 Expr *LHSExpr, Expr *RHSExpr) {
15945 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15946 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15947 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15948
15949 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15950 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15951
15955
15956 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15957 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15958
15959 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15960}
15961
15963 UnresolvedSetImpl &Functions) {
15965 if (OverOp != OO_None && OverOp != OO_Equal)
15966 LookupOverloadedOperatorName(OverOp, S, Functions);
15967
15968 // In C++20 onwards, we may have a second operator to look up.
15969 if (getLangOpts().CPlusPlus20) {
15971 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15972 }
15973}
15974
15975/// Build an overloaded binary operator expression in the given scope.
15978 Expr *LHS, Expr *RHS) {
15979 switch (Opc) {
15980 case BO_Assign:
15981 // In the non-overloaded case, we warn about self-assignment (x = x) for
15982 // both simple assignment and certain compound assignments where algebra
15983 // tells us the operation yields a constant result. When the operator is
15984 // overloaded, we can't do the latter because we don't want to assume that
15985 // those algebraic identities still apply; for example, a path-building
15986 // library might use operator/= to append paths. But it's still reasonable
15987 // to assume that simple assignment is just moving/copying values around
15988 // and so self-assignment is likely a bug.
15989 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15990 [[fallthrough]];
15991 case BO_DivAssign:
15992 case BO_RemAssign:
15993 case BO_SubAssign:
15994 case BO_AndAssign:
15995 case BO_OrAssign:
15996 case BO_XorAssign:
15997 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15998 break;
15999 default:
16000 break;
16001 }
16002
16003 // Find all of the overloaded operators visible from this point.
16004 UnresolvedSet<16> Functions;
16005 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
16006
16007 // Build the (potentially-overloaded, potentially-dependent)
16008 // binary operation.
16009 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16010}
16011
16013 BinaryOperatorKind Opc, Expr *LHSExpr,
16014 Expr *RHSExpr, bool ForFoldExpression) {
16015 if (!LHSExpr || !RHSExpr)
16016 return ExprError();
16017
16018 // We want to end up calling one of SemaPseudoObject::checkAssignment
16019 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16020 // both expressions are overloadable or either is type-dependent),
16021 // or CreateBuiltinBinOp (in any other case). We also want to get
16022 // any placeholder types out of the way.
16023
16024 // Handle pseudo-objects in the LHS.
16025 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16026 // Assignments with a pseudo-object l-value need special analysis.
16027 if (pty->getKind() == BuiltinType::PseudoObject &&
16029 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16030
16031 // Don't resolve overloads if the other type is overloadable.
16032 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16033 // We can't actually test that if we still have a placeholder,
16034 // though. Fortunately, none of the exceptions we see in that
16035 // code below are valid when the LHS is an overload set. Note
16036 // that an overload set can be dependently-typed, but it never
16037 // instantiates to having an overloadable type.
16038 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16039 if (resolvedRHS.isInvalid()) return ExprError();
16040 RHSExpr = resolvedRHS.get();
16041
16042 if (RHSExpr->isTypeDependent() ||
16043 RHSExpr->getType()->isOverloadableType())
16044 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16045 }
16046
16047 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16048 // template, diagnose the missing 'template' keyword instead of diagnosing
16049 // an invalid use of a bound member function.
16050 //
16051 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16052 // to C++1z [over.over]/1.4, but we already checked for that case above.
16053 if (Opc == BO_LT && inTemplateInstantiation() &&
16054 (pty->getKind() == BuiltinType::BoundMember ||
16055 pty->getKind() == BuiltinType::Overload)) {
16056 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16057 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16058 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16059 return isa<FunctionTemplateDecl>(ND);
16060 })) {
16061 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16062 : OE->getNameLoc(),
16063 diag::err_template_kw_missing)
16064 << OE->getName().getAsIdentifierInfo();
16065 return ExprError();
16066 }
16067 }
16068
16069 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16070 if (LHS.isInvalid()) return ExprError();
16071 LHSExpr = LHS.get();
16072 }
16073
16074 // Handle pseudo-objects in the RHS.
16075 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16076 // An overload in the RHS can potentially be resolved by the type
16077 // being assigned to.
16078 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16079 if (getLangOpts().CPlusPlus &&
16080 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16081 LHSExpr->getType()->isOverloadableType()))
16082 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16083
16084 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16085 ForFoldExpression);
16086 }
16087
16088 // Don't resolve overloads if the other type is overloadable.
16089 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16090 LHSExpr->getType()->isOverloadableType())
16091 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16092
16093 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16094 if (!resolvedRHS.isUsable()) return ExprError();
16095 RHSExpr = resolvedRHS.get();
16096 }
16097
16098 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
16099 LHSExpr->getType()->isHLSLResourceRecordArray())) {
16100 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
16101 return ExprError();
16102 }
16103
16104 if (getLangOpts().CPlusPlus) {
16105 // Otherwise, build an overloaded op if either expression is type-dependent
16106 // or has an overloadable type.
16107 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16108 LHSExpr->getType()->isOverloadableType() ||
16109 RHSExpr->getType()->isOverloadableType())
16110 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16111 }
16112
16113 if (getLangOpts().RecoveryAST &&
16114 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16115 assert(!getLangOpts().CPlusPlus);
16116 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16117 "Should only occur in error-recovery path.");
16119 // C [6.15.16] p3:
16120 // An assignment expression has the value of the left operand after the
16121 // assignment, but is not an lvalue.
16123 Context, LHSExpr, RHSExpr, Opc,
16125 OpLoc, CurFPFeatureOverrides());
16126 QualType ResultType;
16127 switch (Opc) {
16128 case BO_Assign:
16129 ResultType = LHSExpr->getType().getUnqualifiedType();
16130 break;
16131 case BO_LT:
16132 case BO_GT:
16133 case BO_LE:
16134 case BO_GE:
16135 case BO_EQ:
16136 case BO_NE:
16137 case BO_LAnd:
16138 case BO_LOr:
16139 // These operators have a fixed result type regardless of operands.
16140 ResultType = Context.IntTy;
16141 break;
16142 case BO_Comma:
16143 ResultType = RHSExpr->getType();
16144 break;
16145 default:
16146 ResultType = Context.DependentTy;
16147 break;
16148 }
16149 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16150 VK_PRValue, OK_Ordinary, OpLoc,
16152 }
16153
16154 // Build a built-in binary operation.
16155 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16156}
16157
16159 if (T.isNull() || T->isDependentType())
16160 return false;
16161
16162 if (!Ctx.isPromotableIntegerType(T))
16163 return true;
16164
16165 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16166}
16167
16169 UnaryOperatorKind Opc, Expr *InputExpr,
16170 bool IsAfterAmp) {
16171 ExprResult Input = InputExpr;
16174 QualType resultType;
16175 bool CanOverflow = false;
16176
16177 bool ConvertHalfVec = false;
16178 if (getLangOpts().OpenCL) {
16179 QualType Ty = InputExpr->getType();
16180 // The only legal unary operation for atomics is '&'.
16181 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16182 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16183 // only with a builtin functions and therefore should be disallowed here.
16184 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16185 || Ty->isBlockPointerType())) {
16186 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16187 << InputExpr->getType()
16188 << Input.get()->getSourceRange());
16189 }
16190 }
16191
16192 if (getLangOpts().HLSL && OpLoc.isValid()) {
16193 if (Opc == UO_AddrOf)
16194 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16195 if (Opc == UO_Deref)
16196 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16197 }
16198
16199 if (InputExpr->isTypeDependent() &&
16200 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
16201 resultType = Context.DependentTy;
16202 } else {
16203 switch (Opc) {
16204 case UO_PreInc:
16205 case UO_PreDec:
16206 case UO_PostInc:
16207 case UO_PostDec:
16208 resultType =
16209 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
16210 Opc == UO_PreInc || Opc == UO_PostInc,
16211 Opc == UO_PreInc || Opc == UO_PreDec);
16212 CanOverflow = isOverflowingIntegerType(Context, resultType);
16213 break;
16214 case UO_AddrOf:
16215 resultType = CheckAddressOfOperand(Input, OpLoc);
16216 CheckAddressOfNoDeref(InputExpr);
16217 RecordModifiableNonNullParam(*this, InputExpr);
16218 break;
16219 case UO_Deref: {
16221 if (Input.isInvalid())
16222 return ExprError();
16223 resultType =
16224 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16225 break;
16226 }
16227 case UO_Plus:
16228 case UO_Minus:
16229 CanOverflow = Opc == UO_Minus &&
16231 Input = UsualUnaryConversions(Input.get());
16232 if (Input.isInvalid())
16233 return ExprError();
16234 // Unary plus and minus require promoting an operand of half vector to a
16235 // float vector and truncating the result back to a half vector. For now,
16236 // we do this only when HalfArgsAndReturns is set (that is, when the
16237 // target is arm or arm64).
16238 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16239
16240 // If the operand is a half vector, promote it to a float vector.
16241 if (ConvertHalfVec)
16242 Input = convertVector(Input.get(), Context.FloatTy, *this);
16243 resultType = Input.get()->getType();
16244 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16245 break;
16246 else if (resultType->isVectorType() &&
16247 // The z vector extensions don't allow + or - with bool vectors.
16248 (!Context.getLangOpts().ZVector ||
16249 resultType->castAs<VectorType>()->getVectorKind() !=
16251 break;
16252 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16253 break;
16254 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16255 Opc == UO_Plus && resultType->isPointerType())
16256 break;
16257
16258 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16259 << resultType << Input.get()->getSourceRange());
16260
16261 case UO_Not: // bitwise complement
16262 Input = UsualUnaryConversions(Input.get());
16263 if (Input.isInvalid())
16264 return ExprError();
16265 resultType = Input.get()->getType();
16266 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16267 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16268 // C99 does not support '~' for complex conjugation.
16269 Diag(OpLoc, diag::ext_integer_complement_complex)
16270 << resultType << Input.get()->getSourceRange();
16271 else if (resultType->hasIntegerRepresentation())
16272 break;
16273 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16274 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16275 // on vector float types.
16276 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16277 if (!T->isIntegerType())
16278 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16279 << resultType << Input.get()->getSourceRange());
16280 } else {
16281 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16282 << resultType << Input.get()->getSourceRange());
16283 }
16284 break;
16285
16286 case UO_LNot: // logical negation
16287 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16289 if (Input.isInvalid())
16290 return ExprError();
16291 resultType = Input.get()->getType();
16292
16293 // Though we still have to promote half FP to float...
16294 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16295 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16296 .get();
16297 resultType = Context.FloatTy;
16298 }
16299
16300 // WebAsembly tables can't be used in unary expressions.
16301 if (resultType->isPointerType() &&
16303 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16304 << resultType << Input.get()->getSourceRange());
16305 }
16306
16307 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16308 // C99 6.5.3.3p1: ok, fallthrough;
16309 if (Context.getLangOpts().CPlusPlus) {
16310 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16311 // operand contextually converted to bool.
16312 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16313 ScalarTypeToBooleanCastKind(resultType));
16314 } else if (Context.getLangOpts().OpenCL &&
16315 Context.getLangOpts().OpenCLVersion < 120) {
16316 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16317 // operate on scalar float types.
16318 if (!resultType->isIntegerType() && !resultType->isPointerType())
16319 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16320 << resultType << Input.get()->getSourceRange());
16321 }
16322 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16323 !resultType->hasBooleanRepresentation()) {
16324 // HLSL unary logical 'not' behaves like C++, which states that the
16325 // operand is converted to bool and the result is bool, however HLSL
16326 // extends this property to vectors.
16327 const VectorType *VTy = resultType->castAs<VectorType>();
16328 resultType =
16329 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16330
16331 Input = ImpCastExprToType(
16332 Input.get(), resultType,
16334 .get();
16335 break;
16336 } else if (resultType->isExtVectorType()) {
16337 if (Context.getLangOpts().OpenCL &&
16338 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16339 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16340 // operate on vector float types.
16341 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16342 if (!T->isIntegerType())
16343 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16344 << resultType << Input.get()->getSourceRange());
16345 }
16346 // Vector logical not returns the signed variant of the operand type.
16347 resultType = GetSignedVectorType(resultType);
16348 break;
16349 } else if (Context.getLangOpts().CPlusPlus &&
16350 resultType->isVectorType()) {
16351 const VectorType *VTy = resultType->castAs<VectorType>();
16352 if (VTy->getVectorKind() != VectorKind::Generic)
16353 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16354 << resultType << Input.get()->getSourceRange());
16355
16356 // Vector logical not returns the signed variant of the operand type.
16357 resultType = GetSignedVectorType(resultType);
16358 break;
16359 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16360 resultType = Context.getLogicalOperationType();
16361 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(InputExpr);
16362 break;
16363 } else {
16364 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16365 << resultType << Input.get()->getSourceRange());
16366 }
16367
16368 // LNot always has type int. C99 6.5.3.3p5.
16369 // In C++, it's bool. C++ 5.3.1p8
16370 resultType = Context.getLogicalOperationType();
16371 break;
16372 case UO_Real:
16373 case UO_Imag:
16374 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16375 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16376 // ordinary complex l-values to ordinary l-values and all other values to
16377 // r-values.
16378 if (Input.isInvalid())
16379 return ExprError();
16380 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16381 if (Input.get()->isGLValue() &&
16382 Input.get()->getObjectKind() == OK_Ordinary)
16383 VK = Input.get()->getValueKind();
16384 } else if (!getLangOpts().CPlusPlus) {
16385 // In C, a volatile scalar is read by __imag. In C++, it is not.
16386 Input = DefaultLvalueConversion(Input.get());
16387 }
16388 break;
16389 case UO_Extension:
16390 resultType = Input.get()->getType();
16391 VK = Input.get()->getValueKind();
16392 OK = Input.get()->getObjectKind();
16393 break;
16394 case UO_Coawait:
16395 // It's unnecessary to represent the pass-through operator co_await in the
16396 // AST; just return the input expression instead.
16397 assert(!Input.get()->getType()->isDependentType() &&
16398 "the co_await expression must be non-dependant before "
16399 "building operator co_await");
16400 return Input;
16401 }
16402 }
16403 if (resultType.isNull() || Input.isInvalid())
16404 return ExprError();
16405
16406 // Check for array bounds violations in the operand of the UnaryOperator,
16407 // except for the '*' and '&' operators that have to be handled specially
16408 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16409 // that are explicitly defined as valid by the standard).
16410 if (Opc != UO_AddrOf && Opc != UO_Deref)
16411 CheckArrayAccess(Input.get());
16412
16413 auto *UO =
16414 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16415 OpLoc, CanOverflow, CurFPFeatureOverrides());
16416
16417 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16418 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16420 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16421
16422 // Convert the result back to a half vector.
16423 if (ConvertHalfVec)
16424 return convertVector(UO, Context.HalfTy, *this);
16425 return UO;
16426}
16427
16429 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16430 if (!DRE->getQualifier())
16431 return false;
16432
16433 ValueDecl *VD = DRE->getDecl();
16434 if (!VD->isCXXClassMember())
16435 return false;
16436
16438 return true;
16439 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16440 return Method->isImplicitObjectMemberFunction();
16441
16442 return false;
16443 }
16444
16445 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16446 if (!ULE->getQualifier())
16447 return false;
16448
16449 for (NamedDecl *D : ULE->decls()) {
16450 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16451 if (Method->isImplicitObjectMemberFunction())
16452 return true;
16453 } else {
16454 // Overload set does not contain methods.
16455 break;
16456 }
16457 }
16458
16459 return false;
16460 }
16461
16462 return false;
16463}
16464
16466 UnaryOperatorKind Opc, Expr *Input,
16467 bool IsAfterAmp) {
16468 // First things first: handle placeholders so that the
16469 // overloaded-operator check considers the right type.
16470 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16471 // Increment and decrement of pseudo-object references.
16472 if (pty->getKind() == BuiltinType::PseudoObject &&
16474 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16475
16476 // extension is always a builtin operator.
16477 if (Opc == UO_Extension)
16478 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16479
16480 // & gets special logic for several kinds of placeholder.
16481 // The builtin code knows what to do.
16482 if (Opc == UO_AddrOf &&
16483 (pty->getKind() == BuiltinType::Overload ||
16484 pty->getKind() == BuiltinType::UnknownAny ||
16485 pty->getKind() == BuiltinType::BoundMember))
16486 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16487
16488 // Anything else needs to be handled now.
16490 if (Result.isInvalid()) return ExprError();
16491 Input = Result.get();
16492 }
16493
16494 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16496 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16497 // Find all of the overloaded operators visible from this point.
16498 UnresolvedSet<16> Functions;
16500 if (S && OverOp != OO_None)
16501 LookupOverloadedOperatorName(OverOp, S, Functions);
16502
16503 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16504 }
16505
16506 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16507}
16508
16510 Expr *Input, bool IsAfterAmp) {
16511 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16512 IsAfterAmp);
16513}
16514
16516 LabelDecl *TheDecl) {
16517 TheDecl->markUsed(Context);
16518 // Create the AST node. The address of a label always has type 'void*'.
16519 auto *Res = new (Context) AddrLabelExpr(
16520 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16521
16522 if (getCurFunction())
16523 getCurFunction()->AddrLabels.push_back(Res);
16524
16525 return Res;
16526}
16527
16530 // Make sure we diagnose jumping into a statement expression.
16532}
16533
16535 // Note that function is also called by TreeTransform when leaving a
16536 // StmtExpr scope without rebuilding anything.
16537
16540}
16541
16543 SourceLocation RPLoc) {
16544 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16545}
16546
16548 SourceLocation RPLoc, unsigned TemplateDepth) {
16549 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16550 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16551
16554 assert(!Cleanup.exprNeedsCleanups() &&
16555 "cleanups within StmtExpr not correctly bound!");
16557
16558 // FIXME: there are a variety of strange constraints to enforce here, for
16559 // example, it is not possible to goto into a stmt expression apparently.
16560 // More semantic analysis is needed.
16561
16562 // If there are sub-stmts in the compound stmt, take the type of the last one
16563 // as the type of the stmtexpr.
16564 QualType Ty = Context.VoidTy;
16565 bool StmtExprMayBindToTemp = false;
16566 if (!Compound->body_empty()) {
16567 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16568 if (const Expr *Value = LastStmt->getExprStmt()) {
16569 StmtExprMayBindToTemp = true;
16570 Ty = Value->getType();
16571 }
16572 }
16573 }
16574
16575 // FIXME: Check that expression type is complete/non-abstract; statement
16576 // expressions are not lvalues.
16577 Expr *ResStmtExpr =
16578 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16579 if (StmtExprMayBindToTemp)
16580 return MaybeBindToTemporary(ResStmtExpr);
16581 return ResStmtExpr;
16582}
16583
16585 if (ER.isInvalid())
16586 return ExprError();
16587
16588 // Do function/array conversion on the last expression, but not
16589 // lvalue-to-rvalue. However, initialize an unqualified type.
16591 if (ER.isInvalid())
16592 return ExprError();
16593 Expr *E = ER.get();
16594
16595 if (E->isTypeDependent())
16596 return E;
16597
16598 // In ARC, if the final expression ends in a consume, splice
16599 // the consume out and bind it later. In the alternate case
16600 // (when dealing with a retainable type), the result
16601 // initialization will create a produce. In both cases the
16602 // result will be +1, and we'll need to balance that out with
16603 // a bind.
16604 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16605 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16606 return Cast->getSubExpr();
16607
16608 // FIXME: Provide a better location for the initialization.
16612 SourceLocation(), E);
16613}
16614
16616 TypeSourceInfo *TInfo,
16617 ArrayRef<OffsetOfComponent> Components,
16618 SourceLocation RParenLoc) {
16619 QualType ArgTy = TInfo->getType();
16620 bool Dependent = ArgTy->isDependentType();
16621 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16622
16623 // We must have at least one component that refers to the type, and the first
16624 // one is known to be a field designator. Verify that the ArgTy represents
16625 // a struct/union/class.
16626 if (!Dependent && !ArgTy->isRecordType())
16627 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16628 << ArgTy << TypeRange);
16629
16630 // Type must be complete per C99 7.17p3 because a declaring a variable
16631 // with an incomplete type would be ill-formed.
16632 if (!Dependent
16633 && RequireCompleteType(BuiltinLoc, ArgTy,
16634 diag::err_offsetof_incomplete_type, TypeRange))
16635 return ExprError();
16636
16637 bool DidWarnAboutNonPOD = false;
16638 QualType CurrentType = ArgTy;
16641 for (const OffsetOfComponent &OC : Components) {
16642 if (OC.isBrackets) {
16643 // Offset of an array sub-field. TODO: Should we allow vector elements?
16644 if (!CurrentType->isDependentType()) {
16645 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16646 if(!AT)
16647 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16648 << CurrentType);
16649 CurrentType = AT->getElementType();
16650 } else
16651 CurrentType = Context.DependentTy;
16652
16653 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16654 if (IdxRval.isInvalid())
16655 return ExprError();
16656 Expr *Idx = IdxRval.get();
16657
16658 // The expression must be an integral expression.
16659 // FIXME: An integral constant expression?
16660 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16661 !Idx->getType()->isIntegerType())
16662 return ExprError(
16663 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16664 << Idx->getSourceRange());
16665
16666 // Record this array index.
16667 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16668 Exprs.push_back(Idx);
16669 continue;
16670 }
16671
16672 // Offset of a field.
16673 if (CurrentType->isDependentType()) {
16674 // We have the offset of a field, but we can't look into the dependent
16675 // type. Just record the identifier of the field.
16676 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16677 CurrentType = Context.DependentTy;
16678 continue;
16679 }
16680
16681 // We need to have a complete type to look into.
16682 if (RequireCompleteType(OC.LocStart, CurrentType,
16683 diag::err_offsetof_incomplete_type))
16684 return ExprError();
16685
16686 // Look for the designated field.
16687 auto *RD = CurrentType->getAsRecordDecl();
16688 if (!RD)
16689 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16690 << CurrentType);
16691
16692 // C++ [lib.support.types]p5:
16693 // The macro offsetof accepts a restricted set of type arguments in this
16694 // International Standard. type shall be a POD structure or a POD union
16695 // (clause 9).
16696 // C++11 [support.types]p4:
16697 // If type is not a standard-layout class (Clause 9), the results are
16698 // undefined.
16699 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16700 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16701 unsigned DiagID =
16702 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16703 : diag::ext_offsetof_non_pod_type;
16704
16705 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16706 Diag(BuiltinLoc, DiagID)
16707 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16708 DidWarnAboutNonPOD = true;
16709 }
16710 }
16711
16712 // Look for the field.
16713 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16714 LookupQualifiedName(R, RD);
16715 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16716 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16717 if (!MemberDecl) {
16718 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16719 MemberDecl = IndirectMemberDecl->getAnonField();
16720 }
16721
16722 if (!MemberDecl) {
16723 // Lookup could be ambiguous when looking up a placeholder variable
16724 // __builtin_offsetof(S, _).
16725 // In that case we would already have emitted a diagnostic
16726 if (!R.isAmbiguous())
16727 Diag(BuiltinLoc, diag::err_no_member)
16728 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16729 return ExprError();
16730 }
16731
16732 // C99 7.17p3:
16733 // (If the specified member is a bit-field, the behavior is undefined.)
16734 //
16735 // We diagnose this as an error.
16736 if (MemberDecl->isBitField()) {
16737 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16738 << MemberDecl->getDeclName()
16739 << SourceRange(BuiltinLoc, RParenLoc);
16740 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16741 return ExprError();
16742 }
16743
16744 RecordDecl *Parent = MemberDecl->getParent();
16745 if (IndirectMemberDecl)
16746 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16747
16748 // If the member was found in a base class, introduce OffsetOfNodes for
16749 // the base class indirections.
16750 CXXBasePaths Paths;
16751 if (IsDerivedFrom(OC.LocStart, CurrentType,
16752 Context.getCanonicalTagType(Parent), Paths)) {
16753 if (Paths.getDetectedVirtual()) {
16754 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16755 << MemberDecl->getDeclName()
16756 << SourceRange(BuiltinLoc, RParenLoc);
16757 return ExprError();
16758 }
16759
16760 CXXBasePath &Path = Paths.front();
16761 for (const CXXBasePathElement &B : Path)
16762 Comps.push_back(OffsetOfNode(B.Base));
16763 }
16764
16765 if (IndirectMemberDecl) {
16766 for (auto *FI : IndirectMemberDecl->chain()) {
16767 assert(isa<FieldDecl>(FI));
16768 Comps.push_back(OffsetOfNode(OC.LocStart,
16769 cast<FieldDecl>(FI), OC.LocEnd));
16770 }
16771 } else
16772 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16773
16774 CurrentType = MemberDecl->getType().getNonReferenceType();
16775 }
16776
16777 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16778 Comps, Exprs, RParenLoc);
16779}
16780
16782 SourceLocation BuiltinLoc,
16784 ParsedType ParsedArgTy,
16785 ArrayRef<OffsetOfComponent> Components,
16786 SourceLocation RParenLoc) {
16787
16788 TypeSourceInfo *ArgTInfo;
16789 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16790 if (ArgTy.isNull())
16791 return ExprError();
16792
16793 if (!ArgTInfo)
16794 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16795
16796 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16797}
16798
16799
16801 Expr *CondExpr,
16802 Expr *LHSExpr, Expr *RHSExpr,
16803 SourceLocation RPLoc) {
16804 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16805
16808 QualType resType;
16809 bool CondIsTrue = false;
16810 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16811 resType = Context.DependentTy;
16812 } else {
16813 // The conditional expression is required to be a constant expression.
16814 llvm::APSInt condEval(32);
16816 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16817 if (CondICE.isInvalid())
16818 return ExprError();
16819 CondExpr = CondICE.get();
16820 CondIsTrue = condEval.getZExtValue();
16821
16822 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16823 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16824
16825 resType = ActiveExpr->getType();
16826 VK = ActiveExpr->getValueKind();
16827 OK = ActiveExpr->getObjectKind();
16828 }
16829
16830 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16831 resType, VK, OK, RPLoc, CondIsTrue);
16832}
16833
16834//===----------------------------------------------------------------------===//
16835// Clang Extensions.
16836//===----------------------------------------------------------------------===//
16837
16838void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16840
16841 if (LangOpts.CPlusPlus) {
16843 Decl *ManglingContextDecl;
16844 std::tie(MCtx, ManglingContextDecl) =
16845 getCurrentMangleNumberContext(Block->getDeclContext());
16846 if (MCtx) {
16847 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16848 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16849 }
16850 }
16851
16852 PushBlockScope(CurScope, Block);
16853 CurContext->addDecl(Block);
16854 if (CurScope)
16855 PushDeclContext(CurScope, Block);
16856 else
16857 CurContext = Block;
16858
16860
16861 // Enter a new evaluation context to insulate the block from any
16862 // cleanups from the enclosing full-expression.
16865}
16866
16868 Scope *CurScope) {
16869 assert(ParamInfo.getIdentifier() == nullptr &&
16870 "block-id should have no identifier!");
16871 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16872 BlockScopeInfo *CurBlock = getCurBlock();
16873
16874 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16875 QualType T = Sig->getType();
16877
16878 // GetTypeForDeclarator always produces a function type for a block
16879 // literal signature. Furthermore, it is always a FunctionProtoType
16880 // unless the function was written with a typedef.
16881 assert(T->isFunctionType() &&
16882 "GetTypeForDeclarator made a non-function block signature");
16883
16884 // Look for an explicit signature in that function type.
16885 FunctionProtoTypeLoc ExplicitSignature;
16886
16887 if ((ExplicitSignature = Sig->getTypeLoc()
16889
16890 // Check whether that explicit signature was synthesized by
16891 // GetTypeForDeclarator. If so, don't save that as part of the
16892 // written signature.
16893 if (ExplicitSignature.getLocalRangeBegin() ==
16894 ExplicitSignature.getLocalRangeEnd()) {
16895 // This would be much cheaper if we stored TypeLocs instead of
16896 // TypeSourceInfos.
16897 TypeLoc Result = ExplicitSignature.getReturnLoc();
16898 unsigned Size = Result.getFullDataSize();
16899 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16900 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16901
16902 ExplicitSignature = FunctionProtoTypeLoc();
16903 }
16904 }
16905
16906 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16907 CurBlock->FunctionType = T;
16908
16909 const auto *Fn = T->castAs<FunctionType>();
16910 QualType RetTy = Fn->getReturnType();
16911 bool isVariadic =
16912 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16913
16914 CurBlock->TheDecl->setIsVariadic(isVariadic);
16915
16916 // Context.DependentTy is used as a placeholder for a missing block
16917 // return type. TODO: what should we do with declarators like:
16918 // ^ * { ... }
16919 // If the answer is "apply template argument deduction"....
16920 if (RetTy != Context.DependentTy) {
16921 CurBlock->ReturnType = RetTy;
16922 CurBlock->TheDecl->setBlockMissingReturnType(false);
16923 CurBlock->HasImplicitReturnType = false;
16924 }
16925
16926 // Push block parameters from the declarator if we had them.
16928 if (ExplicitSignature) {
16929 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16930 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16931 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16932 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16933 // Diagnose this as an extension in C17 and earlier.
16934 if (!getLangOpts().C23)
16935 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16936 }
16937 Params.push_back(Param);
16938 }
16939
16940 // Fake up parameter variables if we have a typedef, like
16941 // ^ fntype { ... }
16942 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16943 for (const auto &I : Fn->param_types()) {
16945 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16946 Params.push_back(Param);
16947 }
16948 }
16949
16950 // Set the parameters on the block decl.
16951 if (!Params.empty()) {
16952 CurBlock->TheDecl->setParams(Params);
16954 /*CheckParameterNames=*/false);
16955 }
16956
16957 // Finally we can process decl attributes.
16958 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16959
16960 // Put the parameter variables in scope.
16961 for (auto *AI : CurBlock->TheDecl->parameters()) {
16962 AI->setOwningFunction(CurBlock->TheDecl);
16963
16964 // If this has an identifier, add it to the scope stack.
16965 if (AI->getIdentifier()) {
16966 CheckShadow(CurBlock->TheScope, AI);
16967
16968 PushOnScopeChains(AI, CurBlock->TheScope);
16969 }
16970
16971 if (AI->isInvalidDecl())
16972 CurBlock->TheDecl->setInvalidDecl();
16973 }
16974}
16975
16976void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16977 // Leave the expression-evaluation context.
16980
16981 // Pop off CurBlock, handle nested blocks.
16984}
16985
16987 Stmt *Body, Scope *CurScope) {
16988 // If blocks are disabled, emit an error.
16989 if (!LangOpts.Blocks)
16990 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16991
16992 // Leave the expression-evaluation context.
16995 assert(!Cleanup.exprNeedsCleanups() &&
16996 "cleanups within block not correctly bound!");
16998
17000 BlockDecl *BD = BSI->TheDecl;
17001
17003
17004 if (BSI->HasImplicitReturnType)
17006
17007 QualType RetTy = Context.VoidTy;
17008 if (!BSI->ReturnType.isNull())
17009 RetTy = BSI->ReturnType;
17010
17011 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17012 QualType BlockTy;
17013
17014 // If the user wrote a function type in some form, try to use that.
17015 if (!BSI->FunctionType.isNull()) {
17016 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17017
17018 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17019 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17020
17021 // Turn protoless block types into nullary block types.
17022 if (isa<FunctionNoProtoType>(FTy)) {
17024 EPI.ExtInfo = Ext;
17025 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17026
17027 // Otherwise, if we don't need to change anything about the function type,
17028 // preserve its sugar structure.
17029 } else if (FTy->getReturnType() == RetTy &&
17030 (!NoReturn || FTy->getNoReturnAttr())) {
17031 BlockTy = BSI->FunctionType;
17032
17033 // Otherwise, make the minimal modifications to the function type.
17034 } else {
17037 EPI.TypeQuals = Qualifiers();
17038 EPI.ExtInfo = Ext;
17039 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17040 }
17041
17042 // If we don't have a function type, just build one from nothing.
17043 } else {
17045 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17046 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17047 }
17048
17050 BlockTy = Context.getBlockPointerType(BlockTy);
17051
17052 // If needed, diagnose invalid gotos and switches in the block.
17053 if (getCurFunction()->NeedsScopeChecking() &&
17054 !PP.isCodeCompletionEnabled())
17056
17057 BD->setBody(cast<CompoundStmt>(Body));
17058
17059 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17061
17062 // Try to apply the named return value optimization. We have to check again
17063 // if we can do this, though, because blocks keep return statements around
17064 // to deduce an implicit return type.
17065 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17066 !BD->isDependentContext())
17067 computeNRVO(Body, BSI);
17068
17074
17076
17077 // Set the captured variables on the block.
17079 for (Capture &Cap : BSI->Captures) {
17080 if (Cap.isInvalid() || Cap.isThisCapture())
17081 continue;
17082 // Cap.getVariable() is always a VarDecl because
17083 // blocks cannot capture structured bindings or other ValueDecl kinds.
17084 auto *Var = cast<VarDecl>(Cap.getVariable());
17085 Expr *CopyExpr = nullptr;
17086 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17087 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17088 // The capture logic needs the destructor, so make sure we mark it.
17089 // Usually this is unnecessary because most local variables have
17090 // their destructors marked at declaration time, but parameters are
17091 // an exception because it's technically only the call site that
17092 // actually requires the destructor.
17093 if (isa<ParmVarDecl>(Var))
17095
17096 // Enter a separate potentially-evaluated context while building block
17097 // initializers to isolate their cleanups from those of the block
17098 // itself.
17099 // FIXME: Is this appropriate even when the block itself occurs in an
17100 // unevaluated operand?
17103
17104 SourceLocation Loc = Cap.getLocation();
17105
17107 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17108
17109 // According to the blocks spec, the capture of a variable from
17110 // the stack requires a const copy constructor. This is not true
17111 // of the copy/move done to move a __block variable to the heap.
17112 if (!Result.isInvalid() &&
17113 !Result.get()->getType().isConstQualified()) {
17115 Result.get()->getType().withConst(),
17116 CK_NoOp, VK_LValue);
17117 }
17118
17119 if (!Result.isInvalid()) {
17121 InitializedEntity::InitializeBlock(Var->getLocation(),
17122 Cap.getCaptureType()),
17123 Loc, Result.get());
17124 }
17125
17126 // Build a full-expression copy expression if initialization
17127 // succeeded and used a non-trivial constructor. Recover from
17128 // errors by pretending that the copy isn't necessary.
17129 if (!Result.isInvalid() &&
17130 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17131 ->isTrivial()) {
17133 CopyExpr = Result.get();
17134 }
17135 }
17136 }
17137
17138 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17139 CopyExpr);
17140 Captures.push_back(NewCap);
17141 }
17142 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17143
17144 // Pop the block scope now but keep it alive to the end of this function.
17146 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
17147 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17148
17149 BlockExpr *Result = new (Context)
17150 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17151
17152 // If the block isn't obviously global, i.e. it captures anything at
17153 // all, then we need to do a few things in the surrounding context:
17154 if (Result->getBlockDecl()->hasCaptures()) {
17155 // First, this expression has a new cleanup object.
17156 ExprCleanupObjects.push_back(Result->getBlockDecl());
17157 Cleanup.setExprNeedsCleanups(true);
17158
17159 // It also gets a branch-protected scope if any of the captured
17160 // variables needs destruction.
17161 for (const auto &CI : Result->getBlockDecl()->captures()) {
17162 const VarDecl *var = CI.getVariable();
17163 if (var->getType().isDestructedType() != QualType::DK_none) {
17165 break;
17166 }
17167 }
17168 }
17169
17170 if (getCurFunction())
17171 getCurFunction()->addBlock(BD);
17172
17173 // This can happen if the block's return type is deduced, but
17174 // the return expression is invalid.
17175 if (BD->isInvalidDecl())
17176 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17177 {Result}, Result->getType());
17178 return Result;
17179}
17180
17182 SourceLocation RPLoc) {
17183 TypeSourceInfo *TInfo;
17184 GetTypeFromParser(Ty, &TInfo);
17185 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17186}
17187
17189 Expr *E, TypeSourceInfo *TInfo,
17190 SourceLocation RPLoc) {
17191 Expr *OrigExpr = E;
17192 bool IsMS = false;
17193
17194 // CUDA device global function does not support varargs.
17195 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17196 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17199 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17200 }
17201 }
17202
17203 // NVPTX does not support va_arg expression.
17204 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17205 Context.getTargetInfo().getTriple().isNVPTX())
17206 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17207
17208 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17209 // as Microsoft ABI on an actual Microsoft platform, where
17210 // __builtin_ms_va_list and __builtin_va_list are the same.)
17211 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17212 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17213 QualType MSVaListType = Context.getBuiltinMSVaListType();
17214 if (Context.hasSameType(MSVaListType, E->getType())) {
17215 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17216 return ExprError();
17217 IsMS = true;
17218 }
17219 }
17220
17221 // Get the va_list type
17222 QualType VaListType = Context.getBuiltinVaListType();
17223 if (!IsMS) {
17224 if (VaListType->isArrayType()) {
17225 // Deal with implicit array decay; for example, on x86-64,
17226 // va_list is an array, but it's supposed to decay to
17227 // a pointer for va_arg.
17228 VaListType = Context.getArrayDecayedType(VaListType);
17229 // Make sure the input expression also decays appropriately.
17231 if (Result.isInvalid())
17232 return ExprError();
17233 E = Result.get();
17234 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17235 // If va_list is a record type and we are compiling in C++ mode,
17236 // check the argument using reference binding.
17238 Context, Context.getLValueReferenceType(VaListType), false);
17240 if (Init.isInvalid())
17241 return ExprError();
17242 E = Init.getAs<Expr>();
17243 } else {
17244 // Otherwise, the va_list argument must be an l-value because
17245 // it is modified by va_arg.
17246 if (!E->isTypeDependent() &&
17247 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17248 return ExprError();
17249 }
17250 }
17251
17252 if (!IsMS && !E->isTypeDependent() &&
17253 !Context.hasSameType(VaListType, E->getType()))
17254 return ExprError(
17255 Diag(E->getBeginLoc(),
17256 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17257 << OrigExpr->getType() << E->getSourceRange());
17258
17259 if (!TInfo->getType()->isDependentType()) {
17260 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17261 diag::err_second_parameter_to_va_arg_incomplete,
17262 TInfo->getTypeLoc()))
17263 return ExprError();
17264
17266 TInfo->getType(),
17267 diag::err_second_parameter_to_va_arg_abstract,
17268 TInfo->getTypeLoc()))
17269 return ExprError();
17270
17271 if (!TInfo->getType().isPODType(Context)) {
17272 Diag(TInfo->getTypeLoc().getBeginLoc(),
17273 TInfo->getType()->isObjCLifetimeType()
17274 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17275 : diag::warn_second_parameter_to_va_arg_not_pod)
17276 << TInfo->getType()
17277 << TInfo->getTypeLoc().getSourceRange();
17278 }
17279
17280 if (TInfo->getType()->isArrayType()) {
17282 PDiag(diag::warn_second_parameter_to_va_arg_array)
17283 << TInfo->getType()
17284 << TInfo->getTypeLoc().getSourceRange());
17285 }
17286
17287 // Check for va_arg where arguments of the given type will be promoted
17288 // (i.e. this va_arg is guaranteed to have undefined behavior).
17289 QualType PromoteType;
17290 if (Context.isPromotableIntegerType(TInfo->getType())) {
17291 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17292 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17293 // and C23 7.16.1.1p2 says, in part:
17294 // If type is not compatible with the type of the actual next argument
17295 // (as promoted according to the default argument promotions), the
17296 // behavior is undefined, except for the following cases:
17297 // - both types are pointers to qualified or unqualified versions of
17298 // compatible types;
17299 // - one type is compatible with a signed integer type, the other
17300 // type is compatible with the corresponding unsigned integer type,
17301 // and the value is representable in both types;
17302 // - one type is pointer to qualified or unqualified void and the
17303 // other is a pointer to a qualified or unqualified character type;
17304 // - or, the type of the next argument is nullptr_t and type is a
17305 // pointer type that has the same representation and alignment
17306 // requirements as a pointer to a character type.
17307 // Given that type compatibility is the primary requirement (ignoring
17308 // qualifications), you would think we could call typesAreCompatible()
17309 // directly to test this. However, in C++, that checks for *same type*,
17310 // which causes false positives when passing an enumeration type to
17311 // va_arg. Instead, get the underlying type of the enumeration and pass
17312 // that.
17313 QualType UnderlyingType = TInfo->getType();
17314 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17315 UnderlyingType = ED->getIntegerType();
17316 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17317 /*CompareUnqualified*/ true))
17318 PromoteType = QualType();
17319
17320 // If the types are still not compatible, we need to test whether the
17321 // promoted type and the underlying type are the same except for
17322 // signedness. Ask the AST for the correctly corresponding type and see
17323 // if that's compatible.
17324 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17325 PromoteType->isUnsignedIntegerType() !=
17326 UnderlyingType->isUnsignedIntegerType()) {
17327 UnderlyingType =
17328 UnderlyingType->isUnsignedIntegerType()
17329 ? Context.getCorrespondingSignedType(UnderlyingType)
17330 : Context.getCorrespondingUnsignedType(UnderlyingType);
17331 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17332 /*CompareUnqualified*/ true))
17333 PromoteType = QualType();
17334 }
17335 }
17336 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17337 PromoteType = Context.DoubleTy;
17338 if (!PromoteType.isNull())
17340 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17341 << TInfo->getType()
17342 << PromoteType
17343 << TInfo->getTypeLoc().getSourceRange());
17344 }
17345
17347 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17348}
17349
17351 // The type of __null will be int or long, depending on the size of
17352 // pointers on the target.
17353 QualType Ty;
17354 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17355 if (pw == Context.getTargetInfo().getIntWidth())
17356 Ty = Context.IntTy;
17357 else if (pw == Context.getTargetInfo().getLongWidth())
17358 Ty = Context.LongTy;
17359 else if (pw == Context.getTargetInfo().getLongLongWidth())
17360 Ty = Context.LongLongTy;
17361 else {
17362 llvm_unreachable("I don't know size of pointer!");
17363 }
17364
17365 return new (Context) GNUNullExpr(Ty, TokenLoc);
17366}
17367
17369 CXXRecordDecl *ImplDecl = nullptr;
17370
17371 // Fetch the std::source_location::__impl decl.
17372 if (NamespaceDecl *Std = S.getStdNamespace()) {
17373 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17375 if (S.LookupQualifiedName(ResultSL, Std)) {
17376 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17377 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17379 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17380 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17381 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17382 }
17383 }
17384 }
17385 }
17386
17387 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17388 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17389 return nullptr;
17390 }
17391
17392 // Verify that __impl is a trivial struct type, with no base classes, and with
17393 // only the four expected fields.
17394 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17395 ImplDecl->getNumBases() != 0) {
17396 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17397 return nullptr;
17398 }
17399
17400 unsigned Count = 0;
17401 for (FieldDecl *F : ImplDecl->fields()) {
17402 StringRef Name = F->getName();
17403
17404 if (Name == "_M_file_name") {
17405 if (F->getType() !=
17407 break;
17408 Count++;
17409 } else if (Name == "_M_function_name") {
17410 if (F->getType() !=
17412 break;
17413 Count++;
17414 } else if (Name == "_M_line") {
17415 if (!F->getType()->isIntegerType())
17416 break;
17417 Count++;
17418 } else if (Name == "_M_column") {
17419 if (!F->getType()->isIntegerType())
17420 break;
17421 Count++;
17422 } else {
17423 Count = 100; // invalid
17424 break;
17425 }
17426 }
17427 if (Count != 4) {
17428 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17429 return nullptr;
17430 }
17431
17432 return ImplDecl;
17433}
17434
17436 SourceLocation BuiltinLoc,
17437 SourceLocation RPLoc) {
17438 QualType ResultTy;
17439 switch (Kind) {
17444 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17445 ResultTy =
17446 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17447 break;
17448 }
17451 ResultTy = Context.UnsignedIntTy;
17452 break;
17456 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17458 return ExprError();
17459 }
17460 ResultTy = Context.getPointerType(
17461 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17462 break;
17463 }
17464
17465 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17466}
17467
17469 SourceLocation BuiltinLoc,
17470 SourceLocation RPLoc,
17471 DeclContext *ParentContext) {
17472 return new (Context)
17473 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17474}
17475
17477 StringLiteral *BinaryData, StringRef FileName) {
17479 Data->BinaryData = BinaryData;
17480 Data->FileName = FileName;
17481 return new (Context)
17482 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17483 Data->getDataElementCount());
17484}
17485
17487 const Expr *SrcExpr) {
17488 if (!DstType->isFunctionPointerType() ||
17489 !SrcExpr->getType()->isFunctionType())
17490 return false;
17491
17492 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17493 if (!DRE)
17494 return false;
17495
17496 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17497 if (!FD)
17498 return false;
17499
17501 /*Complain=*/true,
17502 SrcExpr->getBeginLoc());
17503}
17504
17506 SourceLocation Loc,
17507 QualType DstType, QualType SrcType,
17508 Expr *SrcExpr, AssignmentAction Action,
17509 bool *Complained) {
17510 if (Complained)
17511 *Complained = false;
17512
17513 // Decode the result (notice that AST's are still created for extensions).
17514 bool CheckInferredResultType = false;
17515 bool isInvalid = false;
17516 unsigned DiagKind = 0;
17517 ConversionFixItGenerator ConvHints;
17518 bool MayHaveConvFixit = false;
17519 bool MayHaveFunctionDiff = false;
17520 const ObjCInterfaceDecl *IFace = nullptr;
17521 const ObjCProtocolDecl *PDecl = nullptr;
17522
17523 switch (ConvTy) {
17525 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17526 return false;
17528 // Still a valid conversion, but we may want to diagnose for C++
17529 // compatibility reasons.
17530 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17531 break;
17533 if (getLangOpts().CPlusPlus) {
17534 DiagKind = diag::err_typecheck_convert_pointer_int;
17535 isInvalid = true;
17536 } else {
17537 DiagKind = diag::ext_typecheck_convert_pointer_int;
17538 }
17539 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17540 MayHaveConvFixit = true;
17541 break;
17543 if (getLangOpts().CPlusPlus) {
17544 DiagKind = diag::err_typecheck_convert_int_pointer;
17545 isInvalid = true;
17546 } else {
17547 DiagKind = diag::ext_typecheck_convert_int_pointer;
17548 }
17549 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17550 MayHaveConvFixit = true;
17551 break;
17553 DiagKind =
17554 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17555 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17556 MayHaveConvFixit = true;
17557 break;
17559 if (getLangOpts().CPlusPlus) {
17560 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17561 isInvalid = true;
17562 } else {
17563 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17564 }
17565 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17566 MayHaveConvFixit = true;
17567 break;
17570 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17571 } else if (getLangOpts().CPlusPlus) {
17572 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17573 isInvalid = true;
17574 } else {
17575 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17576 }
17577 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17578 SrcType->isObjCObjectPointerType();
17579 if (CheckInferredResultType) {
17580 SrcType = SrcType.getUnqualifiedType();
17581 DstType = DstType.getUnqualifiedType();
17582 } else {
17583 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17584 }
17585 MayHaveConvFixit = true;
17586 break;
17588 if (getLangOpts().CPlusPlus) {
17589 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17590 isInvalid = true;
17591 } else {
17592 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17593 }
17594 break;
17596 if (getLangOpts().CPlusPlus) {
17597 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17598 isInvalid = true;
17599 } else {
17600 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17601 }
17602 break;
17604 // Perform decay if necessary.
17605 if (SrcType->canDecayToPointerType())
17606 SrcType = Context.getDecayedType(SrcType);
17607
17608 isInvalid = true;
17609
17610 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17611 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17612 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17613 DiagKind = diag::err_typecheck_incompatible_address_space;
17614 break;
17615 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17616 DiagKind = diag::err_typecheck_incompatible_ownership;
17617 break;
17618 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17619 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17620 break;
17621 }
17622
17623 llvm_unreachable("unknown error case for discarding qualifiers!");
17624 // fallthrough
17625 }
17627 if (SrcType->isArrayType())
17628 SrcType = Context.getArrayDecayedType(SrcType);
17629
17630 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17631 break;
17633 // If the qualifiers lost were because we were applying the
17634 // (deprecated) C++ conversion from a string literal to a char*
17635 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17636 // Ideally, this check would be performed in
17637 // checkPointerTypesForAssignment. However, that would require a
17638 // bit of refactoring (so that the second argument is an
17639 // expression, rather than a type), which should be done as part
17640 // of a larger effort to fix checkPointerTypesForAssignment for
17641 // C++ semantics.
17642 if (getLangOpts().CPlusPlus &&
17644 return false;
17645 if (getLangOpts().CPlusPlus) {
17646 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17647 isInvalid = true;
17648 } else {
17649 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17650 }
17651
17652 break;
17654 if (getLangOpts().CPlusPlus) {
17655 isInvalid = true;
17656 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17657 } else {
17658 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17659 }
17660 break;
17662 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17663 isInvalid = true;
17664 break;
17666 DiagKind = diag::err_int_to_block_pointer;
17667 isInvalid = true;
17668 break;
17670 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17671 isInvalid = true;
17672 break;
17674 if (SrcType->isObjCQualifiedIdType()) {
17675 const ObjCObjectPointerType *srcOPT =
17676 SrcType->castAs<ObjCObjectPointerType>();
17677 for (auto *srcProto : srcOPT->quals()) {
17678 PDecl = srcProto;
17679 break;
17680 }
17681 if (const ObjCInterfaceType *IFaceT =
17683 IFace = IFaceT->getDecl();
17684 }
17685 else if (DstType->isObjCQualifiedIdType()) {
17686 const ObjCObjectPointerType *dstOPT =
17687 DstType->castAs<ObjCObjectPointerType>();
17688 for (auto *dstProto : dstOPT->quals()) {
17689 PDecl = dstProto;
17690 break;
17691 }
17692 if (const ObjCInterfaceType *IFaceT =
17694 IFace = IFaceT->getDecl();
17695 }
17696 if (getLangOpts().CPlusPlus) {
17697 DiagKind = diag::err_incompatible_qualified_id;
17698 isInvalid = true;
17699 } else {
17700 DiagKind = diag::warn_incompatible_qualified_id;
17701 }
17702 break;
17703 }
17705 if (getLangOpts().CPlusPlus) {
17706 DiagKind = diag::err_incompatible_vectors;
17707 isInvalid = true;
17708 } else {
17709 DiagKind = diag::warn_incompatible_vectors;
17710 }
17711 break;
17713 DiagKind = diag::err_arc_weak_unavailable_assign;
17714 isInvalid = true;
17715 break;
17717 return false;
17719 assert(!SrcType->isFunctionType() &&
17720 "Unexpected function type found in IncompatibleOBTKinds assignment");
17721 if (SrcType->canDecayToPointerType())
17722 SrcType = Context.getDecayedType(SrcType);
17723
17724 auto getOBTKindName = [](QualType Ty) -> StringRef {
17725 if (Ty->isPointerType())
17726 Ty = Ty->getPointeeType();
17727 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17728 return OBT->getBehaviorKind() ==
17729 OverflowBehaviorType::OverflowBehaviorKind::Trap
17730 ? "__ob_trap"
17731 : "__ob_wrap";
17732 }
17733 llvm_unreachable("OBT kind unhandled");
17734 };
17735
17736 Diag(Loc, diag::err_incompatible_obt_kinds_assignment)
17737 << DstType << SrcType << getOBTKindName(DstType)
17738 << getOBTKindName(SrcType);
17739 isInvalid = true;
17740 return true;
17741 }
17743 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17744 if (Complained)
17745 *Complained = true;
17746 return true;
17747 }
17748
17749 DiagKind = diag::err_typecheck_convert_incompatible;
17750 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17751 MayHaveConvFixit = true;
17752 isInvalid = true;
17753 MayHaveFunctionDiff = true;
17754 break;
17755 }
17756
17757 QualType FirstType, SecondType;
17758 switch (Action) {
17761 // The destination type comes first.
17762 FirstType = DstType;
17763 SecondType = SrcType;
17764 break;
17765
17772 // The source type comes first.
17773 FirstType = SrcType;
17774 SecondType = DstType;
17775 break;
17776 }
17777
17778 PartialDiagnostic FDiag = PDiag(DiagKind);
17779 AssignmentAction ActionForDiag = Action;
17781 ActionForDiag = AssignmentAction::Passing;
17782
17783 FDiag << FirstType << SecondType << ActionForDiag
17784 << SrcExpr->getSourceRange();
17785
17786 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17787 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17788 auto isPlainChar = [](const clang::Type *Type) {
17789 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17790 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17791 };
17792 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17793 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17794 }
17795
17796 // If we can fix the conversion, suggest the FixIts.
17797 if (!ConvHints.isNull()) {
17798 for (FixItHint &H : ConvHints.Hints)
17799 FDiag << H;
17800 }
17801
17802 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17803
17804 if (MayHaveFunctionDiff)
17805 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17806
17807 Diag(Loc, FDiag);
17808 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17809 DiagKind == diag::err_incompatible_qualified_id) &&
17810 PDecl && IFace && !IFace->hasDefinition())
17811 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17812 << IFace << PDecl;
17813
17814 if (SecondType == Context.OverloadTy)
17816 FirstType, /*TakingAddress=*/true);
17817
17818 if (CheckInferredResultType)
17820
17821 if (Action == AssignmentAction::Returning &&
17824
17825 if (Complained)
17826 *Complained = true;
17827 return isInvalid;
17828}
17829
17831 llvm::APSInt *Result,
17832 AllowFoldKind CanFold) {
17833 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17834 public:
17835 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17836 QualType T) override {
17837 return S.Diag(Loc, diag::err_ice_not_integral)
17838 << T << S.LangOpts.CPlusPlus;
17839 }
17840 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17841 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17842 }
17843 } Diagnoser;
17844
17845 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17846}
17847
17849 llvm::APSInt *Result,
17850 unsigned DiagID,
17851 AllowFoldKind CanFold) {
17852 class IDDiagnoser : public VerifyICEDiagnoser {
17853 unsigned DiagID;
17854
17855 public:
17856 IDDiagnoser(unsigned DiagID)
17857 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17858
17859 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17860 return S.Diag(Loc, DiagID);
17861 }
17862 } Diagnoser(DiagID);
17863
17864 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17865}
17866
17872
17875 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17876}
17877
17880 VerifyICEDiagnoser &Diagnoser,
17881 AllowFoldKind CanFold) {
17882 SourceLocation DiagLoc = E->getBeginLoc();
17883
17884 if (getLangOpts().CPlusPlus11) {
17885 // C++11 [expr.const]p5:
17886 // If an expression of literal class type is used in a context where an
17887 // integral constant expression is required, then that class type shall
17888 // have a single non-explicit conversion function to an integral or
17889 // unscoped enumeration type
17890 ExprResult Converted;
17891 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17892 VerifyICEDiagnoser &BaseDiagnoser;
17893 public:
17894 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17895 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17896 BaseDiagnoser.Suppress, true),
17897 BaseDiagnoser(BaseDiagnoser) {}
17898
17899 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17900 QualType T) override {
17901 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17902 }
17903
17904 SemaDiagnosticBuilder diagnoseIncomplete(
17905 Sema &S, SourceLocation Loc, QualType T) override {
17906 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17907 }
17908
17909 SemaDiagnosticBuilder diagnoseExplicitConv(
17910 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17911 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17912 }
17913
17914 SemaDiagnosticBuilder noteExplicitConv(
17915 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17916 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17917 << ConvTy->isEnumeralType() << ConvTy;
17918 }
17919
17920 SemaDiagnosticBuilder diagnoseAmbiguous(
17921 Sema &S, SourceLocation Loc, QualType T) override {
17922 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17923 }
17924
17925 SemaDiagnosticBuilder noteAmbiguous(
17926 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17927 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17928 << ConvTy->isEnumeralType() << ConvTy;
17929 }
17930
17931 SemaDiagnosticBuilder diagnoseConversion(
17932 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17933 llvm_unreachable("conversion functions are permitted");
17934 }
17935 } ConvertDiagnoser(Diagnoser);
17936
17937 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17938 ConvertDiagnoser);
17939 if (Converted.isInvalid())
17940 return Converted;
17941 E = Converted.get();
17942 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17943 // don't try to evaluate it later. We also don't want to return the
17944 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17945 // this function will attempt to use 'Value'.
17946 if (isa<RecoveryExpr>(E))
17947 return ExprError();
17949 return ExprError();
17950 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17951 // An ICE must be of integral or unscoped enumeration type.
17952 if (!Diagnoser.Suppress)
17953 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17954 << E->getSourceRange();
17955 return ExprError();
17956 }
17957
17958 ExprResult RValueExpr = DefaultLvalueConversion(E);
17959 if (RValueExpr.isInvalid())
17960 return ExprError();
17961
17962 E = RValueExpr.get();
17963
17964 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17965 // in the non-ICE case.
17968 if (Result)
17970 if (!isa<ConstantExpr>(E))
17973
17974 if (Notes.empty())
17975 return E;
17976
17977 // If our only note is the usual "invalid subexpression" note, just point
17978 // the caret at its location rather than producing an essentially
17979 // redundant note.
17980 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17981 diag::note_invalid_subexpr_in_const_expr) {
17982 DiagLoc = Notes[0].first;
17983 Notes.clear();
17984 }
17985
17986 if (getLangOpts().CPlusPlus) {
17987 if (!Diagnoser.Suppress) {
17988 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17989 for (const PartialDiagnosticAt &Note : Notes)
17990 Diag(Note.first, Note.second);
17991 }
17992 return ExprError();
17993 }
17994
17995 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17996 for (const PartialDiagnosticAt &Note : Notes)
17997 Diag(Note.first, Note.second);
17998
17999 return E;
18000 }
18001
18002 Expr::EvalResult EvalResult;
18004 EvalResult.Diag = &Notes;
18005
18006 // Try to evaluate the expression, and produce diagnostics explaining why it's
18007 // not a constant expression as a side-effect.
18008 bool Folded =
18009 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
18010 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18011 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18012
18013 if (!isa<ConstantExpr>(E))
18014 E = ConstantExpr::Create(Context, E, EvalResult.Val);
18015
18016 // In C++11, we can rely on diagnostics being produced for any expression
18017 // which is not a constant expression. If no diagnostics were produced, then
18018 // this is a constant expression.
18019 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18020 if (Result)
18021 *Result = EvalResult.Val.getInt();
18022 return E;
18023 }
18024
18025 // If our only note is the usual "invalid subexpression" note, just point
18026 // the caret at its location rather than producing an essentially
18027 // redundant note.
18028 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18029 diag::note_invalid_subexpr_in_const_expr) {
18030 DiagLoc = Notes[0].first;
18031 Notes.clear();
18032 }
18033
18034 if (!Folded || CanFold == AllowFoldKind::No) {
18035 if (!Diagnoser.Suppress) {
18036 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18037 for (const PartialDiagnosticAt &Note : Notes)
18038 Diag(Note.first, Note.second);
18039 }
18040
18041 return ExprError();
18042 }
18043
18044 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18045 for (const PartialDiagnosticAt &Note : Notes)
18046 Diag(Note.first, Note.second);
18047
18048 if (Result)
18049 *Result = EvalResult.Val.getInt();
18050 return E;
18051}
18052
18053namespace {
18054 // Handle the case where we conclude a expression which we speculatively
18055 // considered to be unevaluated is actually evaluated.
18056 class TransformToPE : public TreeTransform<TransformToPE> {
18057 typedef TreeTransform<TransformToPE> BaseTransform;
18058
18059 public:
18060 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18061
18062 // Make sure we redo semantic analysis
18063 bool AlwaysRebuild() { return true; }
18064 bool ReplacingOriginal() { return true; }
18065
18066 // We need to special-case DeclRefExprs referring to FieldDecls which
18067 // are not part of a member pointer formation; normal TreeTransforming
18068 // doesn't catch this case because of the way we represent them in the AST.
18069 // FIXME: This is a bit ugly; is it really the best way to handle this
18070 // case?
18071 //
18072 // Error on DeclRefExprs referring to FieldDecls.
18073 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18074 if (isa<FieldDecl>(E->getDecl()) &&
18075 !SemaRef.isUnevaluatedContext())
18076 return SemaRef.Diag(E->getLocation(),
18077 diag::err_invalid_non_static_member_use)
18078 << E->getDecl() << E->getSourceRange();
18079
18080 return BaseTransform::TransformDeclRefExpr(E);
18081 }
18082
18083 // Exception: filter out member pointer formation
18084 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18085 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18086 return E;
18087
18088 return BaseTransform::TransformUnaryOperator(E);
18089 }
18090
18091 // The body of a lambda-expression is in a separate expression evaluation
18092 // context so never needs to be transformed.
18093 // FIXME: Ideally we wouldn't transform the closure type either, and would
18094 // just recreate the capture expressions and lambda expression.
18095 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18096 return SkipLambdaBody(E, Body);
18097 }
18098 };
18099}
18100
18102 assert(isUnevaluatedContext() &&
18103 "Should only transform unevaluated expressions");
18104 ExprEvalContexts.back().Context =
18105 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18107 return E;
18108 return TransformToPE(*this).TransformExpr(E);
18109}
18110
18112 assert(isUnevaluatedContext() &&
18113 "Should only transform unevaluated expressions");
18116 return TInfo;
18117 return TransformToPE(*this).TransformType(TInfo);
18118}
18119
18120void
18122 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18124 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18125 LambdaContextDecl, ExprContext);
18126
18127 // Discarded statements and immediate contexts nested in other
18128 // discarded statements or immediate context are themselves
18129 // a discarded statement or an immediate context, respectively.
18130 ExprEvalContexts.back().InDiscardedStatement =
18132
18133 // C++23 [expr.const]/p15
18134 // An expression or conversion is in an immediate function context if [...]
18135 // it is a subexpression of a manifestly constant-evaluated expression or
18136 // conversion.
18137 const auto &Prev = parentEvaluationContext();
18138 ExprEvalContexts.back().InImmediateFunctionContext =
18139 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18140
18141 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18142 Prev.InImmediateEscalatingFunctionContext;
18143
18144 Cleanup.reset();
18145 if (!MaybeODRUseExprs.empty())
18146 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18147}
18148
18149void
18153 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18154 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18155}
18156
18158 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18159 // [expr.const]/p14.1
18160 // An expression or conversion is in an immediate function context if it is
18161 // potentially evaluated and either: its innermost enclosing non-block scope
18162 // is a function parameter scope of an immediate function.
18164 FD && FD->isConsteval()
18166 : NewContext);
18170
18171 Current.InDiscardedStatement = false;
18172
18173 if (FD) {
18174
18175 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18176 // context is nested in an immediate function context, so smaller contexts
18177 // that appear inside immediate functions (like variable initializers) are
18178 // considered to be inside an immediate function context even though by
18179 // themselves they are not immediate function contexts. But when a new
18180 // function is entered, we need to reset this tracking, since the entered
18181 // function might be not an immediate function.
18182
18184 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18185
18186 if (isLambdaMethod(FD))
18188 FD->isConsteval() ||
18189 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
18190 Parent.isImmediateFunctionContext()));
18191 else
18193 }
18194}
18195
18197 TypeSourceInfo *TSI) {
18198 return BuildCXXReflectExpr(CaretCaretLoc, TSI);
18199}
18200
18202 TypeSourceInfo *TSI) {
18203 return CXXReflectExpr::Create(Context, CaretCaretLoc, TSI);
18204}
18205
18206namespace {
18207
18208const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18209 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18210 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18211 if (E->getOpcode() == UO_Deref)
18212 return CheckPossibleDeref(S, E->getSubExpr());
18213 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18214 return CheckPossibleDeref(S, E->getBase());
18215 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18216 return CheckPossibleDeref(S, E->getBase());
18217 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18218 QualType Inner;
18219 QualType Ty = E->getType();
18220 if (const auto *Ptr = Ty->getAs<PointerType>())
18221 Inner = Ptr->getPointeeType();
18222 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18223 Inner = Arr->getElementType();
18224 else
18225 return nullptr;
18226
18227 if (Inner->hasAttr(attr::NoDeref))
18228 return E;
18229 }
18230 return nullptr;
18231}
18232
18233} // namespace
18234
18236 for (const Expr *E : Rec.PossibleDerefs) {
18237 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18238 if (DeclRef) {
18239 const ValueDecl *Decl = DeclRef->getDecl();
18240 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18241 << Decl->getName() << E->getSourceRange();
18242 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18243 } else {
18244 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18245 << E->getSourceRange();
18246 }
18247 }
18248 Rec.PossibleDerefs.clear();
18249}
18250
18253 return;
18254
18255 // Note: ignoring parens here is not justified by the standard rules, but
18256 // ignoring parentheses seems like a more reasonable approach, and this only
18257 // drives a deprecation warning so doesn't affect conformance.
18258 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18259 if (BO->getOpcode() == BO_Assign) {
18260 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18261 llvm::erase(LHSs, BO->getLHS());
18262 }
18263 }
18264}
18265
18267 assert(getLangOpts().CPlusPlus20 &&
18268 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18269 "Cannot mark an immediate escalating expression outside of an "
18270 "immediate escalating context");
18271 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18272 Call && Call->getCallee()) {
18273 if (auto *DeclRef =
18274 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18275 DeclRef->setIsImmediateEscalating(true);
18276 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18277 Ctr->setIsImmediateEscalating(true);
18278 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18279 DeclRef->setIsImmediateEscalating(true);
18280 } else {
18281 assert(false && "expected an immediately escalating expression");
18282 }
18284 FI->FoundImmediateEscalatingExpression = true;
18285}
18286
18288 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18289 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18292 return E;
18293
18294 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18295 /// It's OK if this fails; we'll also remove this in
18296 /// HandleImmediateInvocations, but catching it here allows us to avoid
18297 /// walking the AST looking for it in simple cases.
18298 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18299 if (auto *DeclRef =
18300 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18301 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18302
18303 // C++23 [expr.const]/p16
18304 // An expression or conversion is immediate-escalating if it is not initially
18305 // in an immediate function context and it is [...] an immediate invocation
18306 // that is not a constant expression and is not a subexpression of an
18307 // immediate invocation.
18308 APValue Cached;
18309 auto CheckConstantExpressionAndKeepResult = [&]() {
18311 Expr::EvalResult Eval;
18312 Eval.Diag = &Notes;
18313 bool Res = E.get()->EvaluateAsConstantExpr(
18314 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18315 if (Res && Notes.empty()) {
18316 Cached = std::move(Eval.Val);
18317 return true;
18318 }
18319 return false;
18320 };
18321
18322 if (!E.get()->isValueDependent() &&
18323 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18324 !CheckConstantExpressionAndKeepResult()) {
18326 return E;
18327 }
18328
18329 if (Cleanup.exprNeedsCleanups()) {
18330 // Since an immediate invocation is a full expression itself - it requires
18331 // an additional ExprWithCleanups node, but it can participate to a bigger
18332 // full expression which actually requires cleanups to be run after so
18333 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18334 // may discard cleanups for outer expression too early.
18335
18336 // Note that ExprWithCleanups created here must always have empty cleanup
18337 // objects:
18338 // - compound literals do not create cleanup objects in C++ and immediate
18339 // invocations are C++-only.
18340 // - blocks are not allowed inside constant expressions and compiler will
18341 // issue an error if they appear there.
18342 //
18343 // Hence, in correct code any cleanup objects created inside current
18344 // evaluation context must be outside the immediate invocation.
18346 Cleanup.cleanupsHaveSideEffects(), {});
18347 }
18348
18350 getASTContext(), E.get(),
18351 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18352 getASTContext()),
18353 /*IsImmediateInvocation*/ true);
18354 if (Cached.hasValue())
18355 Res->MoveIntoResult(Cached, getASTContext());
18356 /// Value-dependent constant expressions should not be immediately
18357 /// evaluated until they are instantiated.
18358 if (!Res->isValueDependent())
18359 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18360 return Res;
18361}
18362
18366 Expr::EvalResult Eval;
18367 Eval.Diag = &Notes;
18368 ConstantExpr *CE = Candidate.getPointer();
18369 bool Result = CE->EvaluateAsConstantExpr(
18370 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18371 if (!Result || !Notes.empty()) {
18373 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18374 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18375 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18376 FunctionDecl *FD = nullptr;
18377 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18378 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18379 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18380 FD = Call->getConstructor();
18381 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18382 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18383
18384 assert(FD && FD->isImmediateFunction() &&
18385 "could not find an immediate function in this expression");
18386 if (FD->isInvalidDecl())
18387 return;
18388 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18389 << FD << FD->isConsteval();
18390 if (auto Context =
18392 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18393 << Context->Decl;
18394 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18395 }
18396 if (!FD->isConsteval())
18398 for (auto &Note : Notes)
18399 SemaRef.Diag(Note.first, Note.second);
18400 return;
18401 }
18403}
18404
18408 struct ComplexRemove : TreeTransform<ComplexRemove> {
18410 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18413 CurrentII;
18414 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18417 4>::reverse_iterator Current)
18418 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18419 void RemoveImmediateInvocation(ConstantExpr* E) {
18420 auto It = std::find_if(CurrentII, IISet.rend(),
18422 return Elem.getPointer() == E;
18423 });
18424 // It is possible that some subexpression of the current immediate
18425 // invocation was handled from another expression evaluation context. Do
18426 // not handle the current immediate invocation if some of its
18427 // subexpressions failed before.
18428 if (It == IISet.rend()) {
18429 if (SemaRef.FailedImmediateInvocations.contains(E))
18430 CurrentII->setInt(1);
18431 } else {
18432 It->setInt(1); // Mark as deleted
18433 }
18434 }
18435 ExprResult TransformConstantExpr(ConstantExpr *E) {
18436 if (!E->isImmediateInvocation())
18437 return Base::TransformConstantExpr(E);
18438 RemoveImmediateInvocation(E);
18439 return Base::TransformExpr(E->getSubExpr());
18440 }
18441 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18442 /// we need to remove its DeclRefExpr from the DRSet.
18443 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18444 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18445 return Base::TransformCXXOperatorCallExpr(E);
18446 }
18447 /// Base::TransformUserDefinedLiteral doesn't preserve the
18448 /// UserDefinedLiteral node.
18449 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18450 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18451 /// here.
18452 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18453 if (!Init)
18454 return Init;
18455
18456 // We cannot use IgnoreImpCasts because we need to preserve
18457 // full expressions.
18458 while (true) {
18459 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18460 Init = ICE->getSubExpr();
18461 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18462 Init = ICE->getSubExpr();
18463 else
18464 break;
18465 }
18466 /// ConstantExprs are the first layer of implicit node to be removed so if
18467 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18468 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18469 CE && CE->isImmediateInvocation())
18470 RemoveImmediateInvocation(CE);
18471 return Base::TransformInitializer(Init, NotCopyInit);
18472 }
18473 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18474 DRSet.erase(E);
18475 return E;
18476 }
18477 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18478 // Do not rebuild lambdas to avoid creating a new type.
18479 // Lambdas have already been processed inside their eval contexts.
18480 return E;
18481 }
18482 bool AlwaysRebuild() { return false; }
18483 bool ReplacingOriginal() { return true; }
18484 bool AllowSkippingCXXConstructExpr() {
18485 bool Res = AllowSkippingFirstCXXConstructExpr;
18486 AllowSkippingFirstCXXConstructExpr = true;
18487 return Res;
18488 }
18489 bool AllowSkippingFirstCXXConstructExpr = true;
18490 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18492
18493 /// CXXConstructExpr with a single argument are getting skipped by
18494 /// TreeTransform in some situtation because they could be implicit. This
18495 /// can only occur for the top-level CXXConstructExpr because it is used
18496 /// nowhere in the expression being transformed therefore will not be rebuilt.
18497 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18498 /// skipping the first CXXConstructExpr.
18499 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18500 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18501
18502 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18503 // The result may not be usable in case of previous compilation errors.
18504 // In this case evaluation of the expression may result in crash so just
18505 // don't do anything further with the result.
18506 if (Res.isUsable()) {
18508 It->getPointer()->setSubExpr(Res.get());
18509 }
18510}
18511
18512static void
18515 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18516 Rec.ReferenceToConsteval.size() == 0) ||
18518 return;
18519
18520 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18521 // [...]
18522 // - the initializer of a variable that is usable in constant expressions or
18523 // has constant initialization.
18524 if (SemaRef.getLangOpts().CPlusPlus23 &&
18525 Rec.ExprContext ==
18527 auto *VD = dyn_cast<VarDecl>(Rec.ManglingContextDecl);
18528 if (VD && (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18529 VD->hasConstantInitialization())) {
18530 // An expression or conversion is in an 'immediate function context' if it
18531 // is potentially evaluated and either:
18532 // [...]
18533 // - it is a subexpression of a manifestly constant-evaluated expression
18534 // or conversion.
18535 return;
18536 }
18537 }
18538
18539 /// When we have more than 1 ImmediateInvocationCandidates or previously
18540 /// failed immediate invocations, we need to check for nested
18541 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18542 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18543 /// invocation.
18544 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18546
18547 /// Prevent sema calls during the tree transform from adding pointers that
18548 /// are already in the sets.
18549 llvm::SaveAndRestore DisableIITracking(
18551
18552 /// Prevent diagnostic during tree transfrom as they are duplicates
18554
18555 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18556 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18557 if (!It->getInt())
18559 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18560 Rec.ReferenceToConsteval.size()) {
18561 struct SimpleRemove : DynamicRecursiveASTVisitor {
18562 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18563 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18564 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18565 DRSet.erase(E);
18566 return DRSet.size();
18567 }
18568 } Visitor(Rec.ReferenceToConsteval);
18569 Visitor.TraverseStmt(
18570 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18571 }
18572 for (auto CE : Rec.ImmediateInvocationCandidates)
18573 if (!CE.getInt())
18575 for (auto *DR : Rec.ReferenceToConsteval) {
18576 // If the expression is immediate escalating, it is not an error;
18577 // The outer context itself becomes immediate and further errors,
18578 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18579 if (DR->isImmediateEscalating())
18580 continue;
18581 auto *FD = cast<FunctionDecl>(DR->getDecl());
18582 const NamedDecl *ND = FD;
18583 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18584 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18585 ND = MD->getParent();
18586
18587 // C++23 [expr.const]/p16
18588 // An expression or conversion is immediate-escalating if it is not
18589 // initially in an immediate function context and it is [...] a
18590 // potentially-evaluated id-expression that denotes an immediate function
18591 // that is not a subexpression of an immediate invocation.
18592 bool ImmediateEscalating = false;
18593 bool IsPotentiallyEvaluated =
18594 Rec.Context ==
18596 Rec.Context ==
18598 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18599 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18600
18602 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18603 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18604 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18605 if (!FD->getBuiltinID())
18606 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18607 if (auto Context =
18609 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18610 << Context->Decl;
18611 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18612 }
18613 if (FD->isImmediateEscalating() && !FD->isConsteval())
18615
18616 } else {
18618 }
18619 }
18620}
18621
18624 if (!Rec.Lambdas.empty()) {
18626 if (!getLangOpts().CPlusPlus20 &&
18627 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18628 Rec.isUnevaluated() ||
18630 unsigned D;
18631 if (Rec.isUnevaluated()) {
18632 // C++11 [expr.prim.lambda]p2:
18633 // A lambda-expression shall not appear in an unevaluated operand
18634 // (Clause 5).
18635 D = diag::err_lambda_unevaluated_operand;
18636 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18637 // C++1y [expr.const]p2:
18638 // A conditional-expression e is a core constant expression unless the
18639 // evaluation of e, following the rules of the abstract machine, would
18640 // evaluate [...] a lambda-expression.
18641 D = diag::err_lambda_in_constant_expression;
18642 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18643 // C++17 [expr.prim.lamda]p2:
18644 // A lambda-expression shall not appear [...] in a template-argument.
18645 D = diag::err_lambda_in_invalid_context;
18646 } else
18647 llvm_unreachable("Couldn't infer lambda error message.");
18648
18649 for (const auto *L : Rec.Lambdas)
18650 Diag(L->getBeginLoc(), D);
18651 }
18652 }
18653
18654 // Append the collected materialized temporaries into previous context before
18655 // exit if the previous also is a lifetime extending context.
18657 parentEvaluationContext().InLifetimeExtendingContext &&
18658 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18661 }
18662
18664 HandleImmediateInvocations(*this, Rec);
18665
18666 // Warn on any volatile-qualified simple-assignments that are not discarded-
18667 // value expressions nor unevaluated operands (those cases get removed from
18668 // this list by CheckUnusedVolatileAssignment).
18669 for (auto *BO : Rec.VolatileAssignmentLHSs)
18670 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18671 << BO->getType();
18672
18673 // When are coming out of an unevaluated context, clear out any
18674 // temporaries that we may have created as part of the evaluation of
18675 // the expression in that context: they aren't relevant because they
18676 // will never be constructed.
18677 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18679 ExprCleanupObjects.end());
18680 Cleanup = Rec.ParentCleanup;
18683 // Otherwise, merge the contexts together.
18684 } else {
18685 Cleanup.mergeFrom(Rec.ParentCleanup);
18686 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18687 }
18688
18690
18691 // Pop the current expression evaluation context off the stack.
18692 ExprEvalContexts.pop_back();
18693}
18694
18696 ExprCleanupObjects.erase(
18697 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18698 ExprCleanupObjects.end());
18699 Cleanup.reset();
18700 MaybeODRUseExprs.clear();
18701}
18702
18705 if (Result.isInvalid())
18706 return ExprError();
18707 E = Result.get();
18708 if (!E->getType()->isVariablyModifiedType())
18709 return E;
18711}
18712
18713/// Are we in a context that is potentially constant evaluated per C++20
18714/// [expr.const]p12?
18716 /// C++2a [expr.const]p12:
18717 // An expression or conversion is potentially constant evaluated if it is
18718 switch (SemaRef.ExprEvalContexts.back().Context) {
18721
18722 // -- a manifestly constant-evaluated expression,
18726 // -- a potentially-evaluated expression,
18728 // -- an immediate subexpression of a braced-init-list,
18729
18730 // -- [FIXME] an expression of the form & cast-expression that occurs
18731 // within a templated entity
18732 // -- a subexpression of one of the above that is not a subexpression of
18733 // a nested unevaluated operand.
18734 return true;
18735
18738 // Expressions in this context are never evaluated.
18739 return false;
18740 }
18741 llvm_unreachable("Invalid context");
18742}
18743
18744/// Return true if this function has a calling convention that requires mangling
18745/// in the size of the parameter pack.
18747 // These manglings are only applicable for targets whcih use Microsoft
18748 // mangling scheme for C.
18750 return false;
18751
18752 // If this is C++ and this isn't an extern "C" function, parameters do not
18753 // need to be complete. In this case, C++ mangling will apply, which doesn't
18754 // use the size of the parameters.
18755 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18756 return false;
18757
18758 // Stdcall, fastcall, and vectorcall need this special treatment.
18759 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18760 switch (CC) {
18761 case CC_X86StdCall:
18762 case CC_X86FastCall:
18763 case CC_X86VectorCall:
18764 return true;
18765 default:
18766 break;
18767 }
18768 return false;
18769}
18770
18771/// Require that all of the parameter types of function be complete. Normally,
18772/// parameter types are only required to be complete when a function is called
18773/// or defined, but to mangle functions with certain calling conventions, the
18774/// mangler needs to know the size of the parameter list. In this situation,
18775/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18776/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18777/// result in a linker error. Clang doesn't implement this behavior, and instead
18778/// attempts to error at compile time.
18780 SourceLocation Loc) {
18781 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18782 FunctionDecl *FD;
18783 ParmVarDecl *Param;
18784
18785 public:
18786 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18787 : FD(FD), Param(Param) {}
18788
18789 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18790 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18791 StringRef CCName;
18792 switch (CC) {
18793 case CC_X86StdCall:
18794 CCName = "stdcall";
18795 break;
18796 case CC_X86FastCall:
18797 CCName = "fastcall";
18798 break;
18799 case CC_X86VectorCall:
18800 CCName = "vectorcall";
18801 break;
18802 default:
18803 llvm_unreachable("CC does not need mangling");
18804 }
18805
18806 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18807 << Param->getDeclName() << FD->getDeclName() << CCName;
18808 }
18809 };
18810
18811 for (ParmVarDecl *Param : FD->parameters()) {
18812 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18813 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18814 }
18815}
18816
18817namespace {
18818enum class OdrUseContext {
18819 /// Declarations in this context are not odr-used.
18820 None,
18821 /// Declarations in this context are formally odr-used, but this is a
18822 /// dependent context.
18823 Dependent,
18824 /// Declarations in this context are odr-used but not actually used (yet).
18825 FormallyOdrUsed,
18826 /// Declarations in this context are used.
18827 Used
18828};
18829}
18830
18831/// Are we within a context in which references to resolved functions or to
18832/// variables result in odr-use?
18833static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18836
18837 if (Context.isUnevaluated())
18838 return OdrUseContext::None;
18839
18841 return OdrUseContext::Dependent;
18842
18843 if (Context.isDiscardedStatementContext())
18844 return OdrUseContext::FormallyOdrUsed;
18845
18846 else if (Context.Context ==
18848 return OdrUseContext::FormallyOdrUsed;
18849
18850 return OdrUseContext::Used;
18851}
18852
18854 if (!Func->isConstexpr())
18855 return false;
18856
18857 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18858 return true;
18859
18860 // Lambda conversion operators are never user provided.
18861 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18862 return isLambdaConversionOperator(Conv);
18863
18864 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18865 return CCD && CCD->getInheritedConstructor();
18866}
18867
18869 bool MightBeOdrUse) {
18870 assert(Func && "No function?");
18871
18872 Func->setReferenced();
18873
18874 // Recursive functions aren't really used until they're used from some other
18875 // context.
18876 bool IsRecursiveCall = CurContext == Func;
18877
18878 // C++11 [basic.def.odr]p3:
18879 // A function whose name appears as a potentially-evaluated expression is
18880 // odr-used if it is the unique lookup result or the selected member of a
18881 // set of overloaded functions [...].
18882 //
18883 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18884 // can just check that here.
18885 OdrUseContext OdrUse =
18886 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18887 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18888 OdrUse = OdrUseContext::FormallyOdrUsed;
18889
18890 // Trivial default constructors and destructors are never actually used.
18891 // FIXME: What about other special members?
18892 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18893 OdrUse == OdrUseContext::Used) {
18894 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18895 if (Constructor->isDefaultConstructor())
18896 OdrUse = OdrUseContext::FormallyOdrUsed;
18898 OdrUse = OdrUseContext::FormallyOdrUsed;
18899 }
18900
18901 // C++20 [expr.const]p12:
18902 // A function [...] is needed for constant evaluation if it is [...] a
18903 // constexpr function that is named by an expression that is potentially
18904 // constant evaluated
18905 bool NeededForConstantEvaluation =
18908
18909 // Determine whether we require a function definition to exist, per
18910 // C++11 [temp.inst]p3:
18911 // Unless a function template specialization has been explicitly
18912 // instantiated or explicitly specialized, the function template
18913 // specialization is implicitly instantiated when the specialization is
18914 // referenced in a context that requires a function definition to exist.
18915 // C++20 [temp.inst]p7:
18916 // The existence of a definition of a [...] function is considered to
18917 // affect the semantics of the program if the [...] function is needed for
18918 // constant evaluation by an expression
18919 // C++20 [basic.def.odr]p10:
18920 // Every program shall contain exactly one definition of every non-inline
18921 // function or variable that is odr-used in that program outside of a
18922 // discarded statement
18923 // C++20 [special]p1:
18924 // The implementation will implicitly define [defaulted special members]
18925 // if they are odr-used or needed for constant evaluation.
18926 //
18927 // Note that we skip the implicit instantiation of templates that are only
18928 // used in unused default arguments or by recursive calls to themselves.
18929 // This is formally non-conforming, but seems reasonable in practice.
18930 bool NeedDefinition =
18931 !IsRecursiveCall &&
18932 (OdrUse == OdrUseContext::Used ||
18933 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18934
18935 // C++14 [temp.expl.spec]p6:
18936 // If a template [...] is explicitly specialized then that specialization
18937 // shall be declared before the first use of that specialization that would
18938 // cause an implicit instantiation to take place, in every translation unit
18939 // in which such a use occurs
18940 if (NeedDefinition &&
18941 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18942 Func->getMemberSpecializationInfo()))
18944
18945 if (getLangOpts().CUDA)
18946 CUDA().CheckCall(Loc, Func);
18947
18948 // If we need a definition, try to create one.
18949 if (NeedDefinition && !Func->getBody()) {
18952 dyn_cast<CXXConstructorDecl>(Func)) {
18954 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18955 if (Constructor->isDefaultConstructor()) {
18956 if (Constructor->isTrivial() &&
18957 !Constructor->hasAttr<DLLExportAttr>())
18958 return;
18960 } else if (Constructor->isCopyConstructor()) {
18962 } else if (Constructor->isMoveConstructor()) {
18964 }
18965 } else if (Constructor->getInheritedConstructor()) {
18967 }
18968 } else if (CXXDestructorDecl *Destructor =
18969 dyn_cast<CXXDestructorDecl>(Func)) {
18971 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18972 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18973 return;
18975 }
18976 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18977 MarkVTableUsed(Loc, Destructor->getParent());
18978 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18979 if (MethodDecl->isOverloadedOperator() &&
18980 MethodDecl->getOverloadedOperator() == OO_Equal) {
18981 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18982 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18983 if (MethodDecl->isCopyAssignmentOperator())
18984 DefineImplicitCopyAssignment(Loc, MethodDecl);
18985 else if (MethodDecl->isMoveAssignmentOperator())
18986 DefineImplicitMoveAssignment(Loc, MethodDecl);
18987 }
18988 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18989 MethodDecl->getParent()->isLambda()) {
18990 CXXConversionDecl *Conversion =
18991 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18992 if (Conversion->isLambdaToBlockPointerConversion())
18994 else
18996 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18997 MarkVTableUsed(Loc, MethodDecl->getParent());
18998 }
18999
19000 if (Func->isDefaulted() && !Func->isDeleted()) {
19004 }
19005
19006 // Implicit instantiation of function templates and member functions of
19007 // class templates.
19008 if (Func->isImplicitlyInstantiable()) {
19010 Func->getTemplateSpecializationKindForInstantiation();
19011 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19012 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19013 if (FirstInstantiation) {
19014 PointOfInstantiation = Loc;
19015 if (auto *MSI = Func->getMemberSpecializationInfo())
19016 MSI->setPointOfInstantiation(Loc);
19017 // FIXME: Notify listener.
19018 else
19019 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19020 } else if (TSK != TSK_ImplicitInstantiation) {
19021 // Use the point of use as the point of instantiation, instead of the
19022 // point of explicit instantiation (which we track as the actual point
19023 // of instantiation). This gives better backtraces in diagnostics.
19024 PointOfInstantiation = Loc;
19025 }
19026
19027 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19028 Func->isConstexpr()) {
19029 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19030 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19031 CodeSynthesisContexts.size())
19033 std::make_pair(Func, PointOfInstantiation));
19034 else if (Func->isConstexpr())
19035 // Do not defer instantiations of constexpr functions, to avoid the
19036 // expression evaluator needing to call back into Sema if it sees a
19037 // call to such a function.
19038 InstantiateFunctionDefinition(PointOfInstantiation, Func);
19039 else {
19040 Func->setInstantiationIsPending(true);
19041 PendingInstantiations.push_back(
19042 std::make_pair(Func, PointOfInstantiation));
19043 if (llvm::isTimeTraceVerbose()) {
19044 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
19045 std::string Name;
19046 llvm::raw_string_ostream OS(Name);
19047 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
19048 /*Qualified=*/true);
19049 return Name;
19050 });
19051 }
19052 // Notify the consumer that a function was implicitly instantiated.
19053 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
19054 }
19055 }
19056 } else {
19057 // Walk redefinitions, as some of them may be instantiable.
19058 for (auto *i : Func->redecls()) {
19059 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19060 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19061 }
19062 }
19063 });
19064 }
19065
19066 // If a constructor was defined in the context of a default parameter
19067 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19068 // context), its initializers may not be referenced yet.
19069 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19071 *this,
19072 Constructor->isImmediateFunction()
19075 Constructor);
19076 for (CXXCtorInitializer *Init : Constructor->inits()) {
19077 if (Init->isInClassMemberInitializer())
19078 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19079 MarkDeclarationsReferencedInExpr(Init->getInit());
19080 });
19081 }
19082 }
19083
19084 // C++14 [except.spec]p17:
19085 // An exception-specification is considered to be needed when:
19086 // - the function is odr-used or, if it appears in an unevaluated operand,
19087 // would be odr-used if the expression were potentially-evaluated;
19088 //
19089 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19090 // function is a pure virtual function we're calling, and in that case the
19091 // function was selected by overload resolution and we need to resolve its
19092 // exception specification for a different reason.
19093 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19095 ResolveExceptionSpec(Loc, FPT);
19096
19097 // A callee could be called by a host function then by a device function.
19098 // If we only try recording once, we will miss recording the use on device
19099 // side. Therefore keep trying until it is recorded.
19100 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19101 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19103
19104 // If this is the first "real" use, act on that.
19105 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19106 // Keep track of used but undefined functions.
19107 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19108 if (mightHaveNonExternalLinkage(Func))
19109 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19110 else if (Func->getMostRecentDecl()->isInlined() &&
19111 !LangOpts.GNUInline &&
19112 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19113 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19115 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19116 }
19117
19118 // Some x86 Windows calling conventions mangle the size of the parameter
19119 // pack into the name. Computing the size of the parameters requires the
19120 // parameter types to be complete. Check that now.
19123
19124 // In the MS C++ ABI, the compiler emits destructor variants where they are
19125 // used. If the destructor is used here but defined elsewhere, mark the
19126 // virtual base destructors referenced. If those virtual base destructors
19127 // are inline, this will ensure they are defined when emitting the complete
19128 // destructor variant. This checking may be redundant if the destructor is
19129 // provided later in this TU.
19130 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19131 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19132 CXXRecordDecl *Parent = Dtor->getParent();
19133 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19135 }
19136 }
19137
19138 Func->markUsed(Context);
19139 }
19140}
19141
19142/// Directly mark a variable odr-used. Given a choice, prefer to use
19143/// MarkVariableReferenced since it does additional checks and then
19144/// calls MarkVarDeclODRUsed.
19145/// If the variable must be captured:
19146/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19147/// - else capture it in the DeclContext that maps to the
19148/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19149static void
19151 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19152 // Keep track of used but undefined variables.
19153 // FIXME: We shouldn't suppress this warning for static data members.
19154 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19155 assert(Var && "expected a capturable variable");
19156
19158 (!Var->isExternallyVisible() || Var->isInline() ||
19160 !(Var->isStaticDataMember() && Var->hasInit())) {
19162 if (old.isInvalid())
19163 old = Loc;
19164 }
19165 QualType CaptureType, DeclRefType;
19166 if (SemaRef.LangOpts.OpenMP)
19169 /*EllipsisLoc*/ SourceLocation(),
19170 /*BuildAndDiagnose*/ true, CaptureType,
19171 DeclRefType, FunctionScopeIndexToStopAt);
19172
19173 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19174 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19175 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
19176 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
19177 if (VarTarget == SemaCUDA::CVT_Host &&
19178 (UserTarget == CUDAFunctionTarget::Device ||
19179 UserTarget == CUDAFunctionTarget::HostDevice ||
19180 UserTarget == CUDAFunctionTarget::Global)) {
19181 // Diagnose ODR-use of host global variables in device functions.
19182 // Reference of device global variables in host functions is allowed
19183 // through shadow variables therefore it is not diagnosed.
19184 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19185 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19186 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19188 Var->getType().isConstQualified()
19189 ? diag::note_cuda_const_var_unpromoted
19190 : diag::note_cuda_host_var);
19191 }
19192 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19193 // Also capture __device__ const variables, which are classified
19194 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19195 // an explicit CUDADeviceAttr to distinguish them from plain
19196 // const variables (no __device__), which also get CVT_Both but
19197 // only have an implicit CUDADeviceAttr.
19198 (VarTarget == SemaCUDA::CVT_Both &&
19199 Var->hasAttr<CUDADeviceAttr>() &&
19200 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19201 !Var->hasAttr<CUDASharedAttr>() &&
19202 (UserTarget == CUDAFunctionTarget::Host ||
19203 UserTarget == CUDAFunctionTarget::HostDevice)) {
19204 // Record a CUDA/HIP device side variable if it is ODR-used
19205 // by host code. This is done conservatively, when the variable is
19206 // referenced in any of the following contexts:
19207 // - a non-function context
19208 // - a host function
19209 // - a host device function
19210 // This makes the ODR-use of the device side variable by host code to
19211 // be visible in the device compilation for the compiler to be able to
19212 // emit template variables instantiated by host code only and to
19213 // externalize the static device side variable ODR-used by host code.
19214 if (!Var->hasExternalStorage())
19216 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19217 (!FD || (!FD->getDescribedFunctionTemplate() &&
19221 }
19222 }
19223
19224 V->markUsed(SemaRef.Context);
19225}
19226
19228 SourceLocation Loc,
19229 unsigned CapturingScopeIndex) {
19230 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19231}
19232
19234 SourceLocation loc,
19235 ValueDecl *var) {
19236 DeclContext *VarDC = var->getDeclContext();
19237
19238 // If the parameter still belongs to the translation unit, then
19239 // we're actually just using one parameter in the declaration of
19240 // the next.
19241 if (isa<ParmVarDecl>(var) &&
19243 return;
19244
19245 // For C code, don't diagnose about capture if we're not actually in code
19246 // right now; it's impossible to write a non-constant expression outside of
19247 // function context, so we'll get other (more useful) diagnostics later.
19248 //
19249 // For C++, things get a bit more nasty... it would be nice to suppress this
19250 // diagnostic for certain cases like using a local variable in an array bound
19251 // for a member of a local class, but the correct predicate is not obvious.
19252 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19253 return;
19254
19255 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19256 unsigned ContextKind = 3; // unknown
19257 if (isa<CXXMethodDecl>(VarDC) &&
19258 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19259 ContextKind = 2;
19260 } else if (isa<FunctionDecl>(VarDC)) {
19261 ContextKind = 0;
19262 } else if (isa<BlockDecl>(VarDC)) {
19263 ContextKind = 1;
19264 }
19265
19266 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19267 << var << ValueKind << ContextKind << VarDC;
19268 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19269 << var;
19270
19271 // FIXME: Add additional diagnostic info about class etc. which prevents
19272 // capture.
19273}
19274
19276 ValueDecl *Var,
19277 bool &SubCapturesAreNested,
19278 QualType &CaptureType,
19279 QualType &DeclRefType) {
19280 // Check whether we've already captured it.
19281 if (CSI->CaptureMap.count(Var)) {
19282 // If we found a capture, any subcaptures are nested.
19283 SubCapturesAreNested = true;
19284
19285 // Retrieve the capture type for this variable.
19286 CaptureType = CSI->getCapture(Var).getCaptureType();
19287
19288 // Compute the type of an expression that refers to this variable.
19289 DeclRefType = CaptureType.getNonReferenceType();
19290
19291 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19292 // are mutable in the sense that user can change their value - they are
19293 // private instances of the captured declarations.
19294 const Capture &Cap = CSI->getCapture(Var);
19295 // C++ [expr.prim.lambda]p10:
19296 // The type of such a data member is [...] an lvalue reference to the
19297 // referenced function type if the entity is a reference to a function.
19298 // [...]
19299 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19300 !(isa<LambdaScopeInfo>(CSI) &&
19301 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19303 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19304 DeclRefType.addConst();
19305 return true;
19306 }
19307 return false;
19308}
19309
19310// Only block literals, captured statements, and lambda expressions can
19311// capture; other scopes don't work.
19313 ValueDecl *Var,
19314 SourceLocation Loc,
19315 const bool Diagnose,
19316 Sema &S) {
19319
19320 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19321 if (Underlying) {
19322 if (Underlying->hasLocalStorage() && Diagnose)
19324 }
19325 return nullptr;
19326}
19327
19328// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19329// certain types of variables (unnamed, variably modified types etc.)
19330// so check for eligibility.
19332 SourceLocation Loc, const bool Diagnose,
19333 Sema &S) {
19334
19335 assert((isa<VarDecl, BindingDecl>(Var)) &&
19336 "Only variables and structured bindings can be captured");
19337
19338 bool IsBlock = isa<BlockScopeInfo>(CSI);
19339 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19340
19341 // Lambdas are not allowed to capture unnamed variables
19342 // (e.g. anonymous unions).
19343 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19344 // assuming that's the intent.
19345 if (IsLambda && !Var->getDeclName()) {
19346 if (Diagnose) {
19347 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19348 S.Diag(Var->getLocation(), diag::note_declared_at);
19349 }
19350 return false;
19351 }
19352
19353 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19354 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19355 if (Diagnose) {
19356 S.Diag(Loc, diag::err_ref_vm_type);
19357 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19358 }
19359 return false;
19360 }
19361 // Prohibit structs with flexible array members too.
19362 // We cannot capture what is in the tail end of the struct.
19363 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19364 VTD && VTD->hasFlexibleArrayMember()) {
19365 if (Diagnose) {
19366 if (IsBlock)
19367 S.Diag(Loc, diag::err_ref_flexarray_type);
19368 else
19369 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19370 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19371 }
19372 return false;
19373 }
19374 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19375 // Lambdas and captured statements are not allowed to capture __block
19376 // variables; they don't support the expected semantics.
19377 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19378 if (Diagnose) {
19379 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19380 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19381 }
19382 return false;
19383 }
19384 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19385 if (S.getLangOpts().OpenCL && IsBlock &&
19386 Var->getType()->isBlockPointerType()) {
19387 if (Diagnose)
19388 S.Diag(Loc, diag::err_opencl_block_ref_block);
19389 return false;
19390 }
19391
19392 if (isa<BindingDecl>(Var)) {
19393 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19394 if (Diagnose)
19396 return false;
19397 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19398 S.Diag(Loc, S.LangOpts.CPlusPlus20
19399 ? diag::warn_cxx17_compat_capture_binding
19400 : diag::ext_capture_binding)
19401 << Var;
19402 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19403 }
19404 }
19405
19406 return true;
19407}
19408
19409// Returns true if the capture by block was successful.
19411 SourceLocation Loc, const bool BuildAndDiagnose,
19412 QualType &CaptureType, QualType &DeclRefType,
19413 const bool Nested, Sema &S, bool Invalid) {
19414 bool ByRef = false;
19415
19416 // Blocks are not allowed to capture arrays, excepting OpenCL.
19417 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19418 // (decayed to pointers).
19419 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19420 if (BuildAndDiagnose) {
19421 S.Diag(Loc, diag::err_ref_array_type);
19422 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19423 Invalid = true;
19424 } else {
19425 return false;
19426 }
19427 }
19428
19429 // Forbid the block-capture of autoreleasing variables.
19430 if (!Invalid &&
19432 if (BuildAndDiagnose) {
19433 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19434 << /*block*/ 0;
19435 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19436 Invalid = true;
19437 } else {
19438 return false;
19439 }
19440 }
19441
19442 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19443 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19444 QualType PointeeTy = PT->getPointeeType();
19445
19446 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19448 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19449 if (BuildAndDiagnose) {
19450 SourceLocation VarLoc = Var->getLocation();
19451 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19452 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19453 }
19454 }
19455 }
19456
19457 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19458 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19459 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19460 // Block capture by reference does not change the capture or
19461 // declaration reference types.
19462 ByRef = true;
19463 } else {
19464 // Block capture by copy introduces 'const'.
19465 CaptureType = CaptureType.getNonReferenceType().withConst();
19466 DeclRefType = CaptureType;
19467 }
19468
19469 // Actually capture the variable.
19470 if (BuildAndDiagnose)
19471 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19472 CaptureType, Invalid);
19473
19474 return !Invalid;
19475}
19476
19477/// Capture the given variable in the captured region.
19480 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19481 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19482 Sema &S, bool Invalid) {
19483 // By default, capture variables by reference.
19484 bool ByRef = true;
19485 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19486 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19487 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19488 // Using an LValue reference type is consistent with Lambdas (see below).
19489 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19490 bool HasConst = DeclRefType.isConstQualified();
19491 DeclRefType = DeclRefType.getUnqualifiedType();
19492 // Don't lose diagnostics about assignments to const.
19493 if (HasConst)
19494 DeclRefType.addConst();
19495 }
19496 // Do not capture firstprivates in tasks.
19497 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19498 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19499 return true;
19500 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19501 RSI->OpenMPCaptureLevel);
19502 }
19503
19504 if (ByRef)
19505 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19506 else
19507 CaptureType = DeclRefType;
19508
19509 // Actually capture the variable.
19510 if (BuildAndDiagnose)
19511 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19512 Loc, SourceLocation(), CaptureType, Invalid);
19513
19514 return !Invalid;
19515}
19516
19517/// Capture the given variable in the lambda.
19519 SourceLocation Loc, const bool BuildAndDiagnose,
19520 QualType &CaptureType, QualType &DeclRefType,
19521 const bool RefersToCapturedVariable,
19522 const TryCaptureKind Kind,
19523 SourceLocation EllipsisLoc, const bool IsTopScope,
19524 Sema &S, bool Invalid) {
19525 // Determine whether we are capturing by reference or by value.
19526 bool ByRef = false;
19527 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19528 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19529 } else {
19530 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19531 }
19532
19533 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19535 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19536 Invalid = true;
19537 }
19538
19539 // Compute the type of the field that will capture this variable.
19540 if (ByRef) {
19541 // C++11 [expr.prim.lambda]p15:
19542 // An entity is captured by reference if it is implicitly or
19543 // explicitly captured but not captured by copy. It is
19544 // unspecified whether additional unnamed non-static data
19545 // members are declared in the closure type for entities
19546 // captured by reference.
19547 //
19548 // FIXME: It is not clear whether we want to build an lvalue reference
19549 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19550 // to do the former, while EDG does the latter. Core issue 1249 will
19551 // clarify, but for now we follow GCC because it's a more permissive and
19552 // easily defensible position.
19553 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19554 } else {
19555 // C++11 [expr.prim.lambda]p14:
19556 // For each entity captured by copy, an unnamed non-static
19557 // data member is declared in the closure type. The
19558 // declaration order of these members is unspecified. The type
19559 // of such a data member is the type of the corresponding
19560 // captured entity if the entity is not a reference to an
19561 // object, or the referenced type otherwise. [Note: If the
19562 // captured entity is a reference to a function, the
19563 // corresponding data member is also a reference to a
19564 // function. - end note ]
19565 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19566 if (!RefType->getPointeeType()->isFunctionType())
19567 CaptureType = RefType->getPointeeType();
19568 }
19569
19570 // Forbid the lambda copy-capture of autoreleasing variables.
19571 if (!Invalid &&
19573 if (BuildAndDiagnose) {
19574 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19575 S.Diag(Var->getLocation(), diag::note_previous_decl)
19576 << Var->getDeclName();
19577 Invalid = true;
19578 } else {
19579 return false;
19580 }
19581 }
19582
19583 // Make sure that by-copy captures are of a complete and non-abstract type.
19584 if (!Invalid && BuildAndDiagnose) {
19585 if (!CaptureType->isDependentType() &&
19587 Loc, CaptureType,
19588 diag::err_capture_of_incomplete_or_sizeless_type,
19589 Var->getDeclName()))
19590 Invalid = true;
19591 else if (S.RequireNonAbstractType(Loc, CaptureType,
19592 diag::err_capture_of_abstract_type))
19593 Invalid = true;
19594 }
19595 }
19596
19597 // Compute the type of a reference to this captured variable.
19598 if (ByRef)
19599 DeclRefType = CaptureType.getNonReferenceType();
19600 else {
19601 // C++ [expr.prim.lambda]p5:
19602 // The closure type for a lambda-expression has a public inline
19603 // function call operator [...]. This function call operator is
19604 // declared const (9.3.1) if and only if the lambda-expression's
19605 // parameter-declaration-clause is not followed by mutable.
19606 DeclRefType = CaptureType.getNonReferenceType();
19607 bool Const = LSI->lambdaCaptureShouldBeConst();
19608 // C++ [expr.prim.lambda]p10:
19609 // The type of such a data member is [...] an lvalue reference to the
19610 // referenced function type if the entity is a reference to a function.
19611 // [...]
19612 if (Const && !CaptureType->isReferenceType() &&
19613 !DeclRefType->isFunctionType())
19614 DeclRefType.addConst();
19615 }
19616
19617 // Add the capture.
19618 if (BuildAndDiagnose)
19619 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19620 Loc, EllipsisLoc, CaptureType, Invalid);
19621
19622 return !Invalid;
19623}
19624
19626 const ASTContext &Context) {
19627 // Offer a Copy fix even if the type is dependent.
19628 if (Var->getType()->isDependentType())
19629 return true;
19631 if (T.isTriviallyCopyableType(Context))
19632 return true;
19633 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19634
19635 if (!(RD = RD->getDefinition()))
19636 return false;
19637 if (RD->hasSimpleCopyConstructor())
19638 return true;
19639 if (RD->hasUserDeclaredCopyConstructor())
19640 for (CXXConstructorDecl *Ctor : RD->ctors())
19641 if (Ctor->isCopyConstructor())
19642 return !Ctor->isDeleted();
19643 }
19644 return false;
19645}
19646
19647/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19648/// default capture. Fixes may be omitted if they aren't allowed by the
19649/// standard, for example we can't emit a default copy capture fix-it if we
19650/// already explicitly copy capture capture another variable.
19652 ValueDecl *Var) {
19654 // Don't offer Capture by copy of default capture by copy fixes if Var is
19655 // known not to be copy constructible.
19656 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19657
19658 SmallString<32> FixBuffer;
19659 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19660 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19661 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19662 if (ShouldOfferCopyFix) {
19663 // Offer fixes to insert an explicit capture for the variable.
19664 // [] -> [VarName]
19665 // [OtherCapture] -> [OtherCapture, VarName]
19666 FixBuffer.assign({Separator, Var->getName()});
19667 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19668 << Var << /*value*/ 0
19669 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19670 }
19671 // As above but capture by reference.
19672 FixBuffer.assign({Separator, "&", Var->getName()});
19673 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19674 << Var << /*reference*/ 1
19675 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19676 }
19677
19678 // Only try to offer default capture if there are no captures excluding this
19679 // and init captures.
19680 // [this]: OK.
19681 // [X = Y]: OK.
19682 // [&A, &B]: Don't offer.
19683 // [A, B]: Don't offer.
19684 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19685 return !C.isThisCapture() && !C.isInitCapture();
19686 }))
19687 return;
19688
19689 // The default capture specifiers, '=' or '&', must appear first in the
19690 // capture body.
19691 SourceLocation DefaultInsertLoc =
19693
19694 if (ShouldOfferCopyFix) {
19695 bool CanDefaultCopyCapture = true;
19696 // [=, *this] OK since c++17
19697 // [=, this] OK since c++20
19698 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19699 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19701 : false;
19702 // We can't use default capture by copy if any captures already specified
19703 // capture by copy.
19704 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19705 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19706 })) {
19707 FixBuffer.assign({"=", Separator});
19708 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19709 << /*value*/ 0
19710 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19711 }
19712 }
19713
19714 // We can't use default capture by reference if any captures already specified
19715 // capture by reference.
19716 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19717 return !C.isInitCapture() && C.isReferenceCapture() &&
19718 !C.isThisCapture();
19719 })) {
19720 FixBuffer.assign({"&", Separator});
19721 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19722 << /*reference*/ 1
19723 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19724 }
19725}
19726
19728 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19729 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19730 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19731 // An init-capture is notionally from the context surrounding its
19732 // declaration, but its parent DC is the lambda class.
19733 DeclContext *VarDC = Var->getDeclContext();
19734 DeclContext *DC = CurContext;
19735
19736 // Skip past RequiresExprBodys because they don't constitute function scopes.
19737 while (DC->isRequiresExprBody())
19738 DC = DC->getParent();
19739
19740 // tryCaptureVariable is called every time a DeclRef is formed,
19741 // it can therefore have non-negigible impact on performances.
19742 // For local variables and when there is no capturing scope,
19743 // we can bailout early.
19744 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19745 return true;
19746
19747 // Exception: Function parameters are not tied to the function's DeclContext
19748 // until we enter the function definition. Capturing them anyway would result
19749 // in an out-of-bounds error while traversing DC and its parents.
19750 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19751 return true;
19752
19753 const auto *VD = dyn_cast<VarDecl>(Var);
19754 if (VD) {
19755 if (VD->isInitCapture())
19756 VarDC = VarDC->getParent();
19757 } else {
19759 }
19760 assert(VD && "Cannot capture a null variable");
19761
19762 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19763 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19764 // We need to sync up the Declaration Context with the
19765 // FunctionScopeIndexToStopAt
19766 if (FunctionScopeIndexToStopAt) {
19767 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19768 unsigned FSIndex = FunctionScopes.size() - 1;
19769 // When we're parsing the lambda parameter list, the current DeclContext is
19770 // NOT the lambda but its parent. So move away the current LSI before
19771 // aligning DC and FunctionScopeIndexToStopAt.
19772 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19773 FSIndex && LSI && !LSI->AfterParameterList)
19774 --FSIndex;
19775 assert(MaxFunctionScopesIndex <= FSIndex &&
19776 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19777 "FunctionScopes.");
19778 while (FSIndex != MaxFunctionScopesIndex) {
19780 --FSIndex;
19781 }
19782 }
19783
19784 // Capture global variables if it is required to use private copy of this
19785 // variable.
19786 bool IsGlobal = !VD->hasLocalStorage();
19787 if (IsGlobal && !(LangOpts.OpenMP &&
19788 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19789 MaxFunctionScopesIndex)))
19790 return true;
19791
19792 if (isa<VarDecl>(Var))
19793 Var = cast<VarDecl>(Var->getCanonicalDecl());
19794
19795 // Walk up the stack to determine whether we can capture the variable,
19796 // performing the "simple" checks that don't depend on type. We stop when
19797 // we've either hit the declared scope of the variable or find an existing
19798 // capture of that variable. We start from the innermost capturing-entity
19799 // (the DC) and ensure that all intervening capturing-entities
19800 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19801 // declcontext can either capture the variable or have already captured
19802 // the variable.
19803 CaptureType = Var->getType();
19804 DeclRefType = CaptureType.getNonReferenceType();
19805 bool Nested = false;
19806 bool Explicit = (Kind != TryCaptureKind::Implicit);
19807 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19808 do {
19809
19810 LambdaScopeInfo *LSI = nullptr;
19811 if (!FunctionScopes.empty())
19812 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19813 FunctionScopes[FunctionScopesIndex]);
19814
19815 bool IsInScopeDeclarationContext =
19816 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19817
19818 if (LSI && !LSI->AfterParameterList) {
19819 // This allows capturing parameters from a default value which does not
19820 // seems correct
19821 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19822 return true;
19823 }
19824 // If the variable is declared in the current context, there is no need to
19825 // capture it.
19826 if (IsInScopeDeclarationContext &&
19827 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19828 return true;
19829
19830 // Only block literals, captured statements, and lambda expressions can
19831 // capture; other scopes don't work.
19832 DeclContext *ParentDC =
19833 !IsInScopeDeclarationContext
19834 ? DC->getParent()
19835 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19836 BuildAndDiagnose, *this);
19837 // We need to check for the parent *first* because, if we *have*
19838 // private-captured a global variable, we need to recursively capture it in
19839 // intermediate blocks, lambdas, etc.
19840 if (!ParentDC) {
19841 if (IsGlobal) {
19842 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19843 break;
19844 }
19845 return true;
19846 }
19847
19848 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19850
19851 // Check whether we've already captured it.
19852 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19853 DeclRefType)) {
19854 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19855 break;
19856 }
19857
19858 // When evaluating some attributes (like enable_if) we might refer to a
19859 // function parameter appertaining to the same declaration as that
19860 // attribute.
19861 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19862 Parm && Parm->getDeclContext() == DC)
19863 return true;
19864
19865 // If we are instantiating a generic lambda call operator body,
19866 // we do not want to capture new variables. What was captured
19867 // during either a lambdas transformation or initial parsing
19868 // should be used.
19870 if (BuildAndDiagnose) {
19873 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19874 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19875 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19876 buildLambdaCaptureFixit(*this, LSI, Var);
19877 } else
19879 }
19880 return true;
19881 }
19882
19883 // Try to capture variable-length arrays types.
19884 if (Var->getType()->isVariablyModifiedType()) {
19885 // We're going to walk down into the type and look for VLA
19886 // expressions.
19887 QualType QTy = Var->getType();
19888 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19889 QTy = PVD->getOriginalType();
19891 }
19892
19893 if (getLangOpts().OpenMP) {
19894 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19895 // OpenMP private variables should not be captured in outer scope, so
19896 // just break here. Similarly, global variables that are captured in a
19897 // target region should not be captured outside the scope of the region.
19898 if (RSI->CapRegionKind == CR_OpenMP) {
19899 // FIXME: We should support capturing structured bindings in OpenMP.
19900 if (isa<BindingDecl>(Var)) {
19901 if (BuildAndDiagnose) {
19902 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19903 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19904 }
19905 return true;
19906 }
19907 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19908 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19909 // If the variable is private (i.e. not captured) and has variably
19910 // modified type, we still need to capture the type for correct
19911 // codegen in all regions, associated with the construct. Currently,
19912 // it is captured in the innermost captured region only.
19913 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19914 Var->getType()->isVariablyModifiedType()) {
19915 QualType QTy = Var->getType();
19916 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19917 QTy = PVD->getOriginalType();
19918 for (int I = 1,
19919 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19920 I < E; ++I) {
19921 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19922 FunctionScopes[FunctionScopesIndex - I]);
19923 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19924 "Wrong number of captured regions associated with the "
19925 "OpenMP construct.");
19926 captureVariablyModifiedType(Context, QTy, OuterRSI);
19927 }
19928 }
19929 bool IsTargetCap =
19930 IsOpenMPPrivateDecl != OMPC_private &&
19931 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19932 RSI->OpenMPCaptureLevel);
19933 // Do not capture global if it is not privatized in outer regions.
19934 bool IsGlobalCap =
19935 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19936 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19937
19938 // When we detect target captures we are looking from inside the
19939 // target region, therefore we need to propagate the capture from the
19940 // enclosing region. Therefore, the capture is not initially nested.
19941 if (IsTargetCap)
19942 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19943 RSI->OpenMPLevel);
19944
19945 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19946 (IsGlobal && !IsGlobalCap)) {
19947 Nested = !IsTargetCap;
19948 bool HasConst = DeclRefType.isConstQualified();
19949 DeclRefType = DeclRefType.getUnqualifiedType();
19950 // Don't lose diagnostics about assignments to const.
19951 if (HasConst)
19952 DeclRefType.addConst();
19953 CaptureType = Context.getLValueReferenceType(DeclRefType);
19954 break;
19955 }
19956 }
19957 }
19958 }
19960 // No capture-default, and this is not an explicit capture
19961 // so cannot capture this variable.
19962 if (BuildAndDiagnose) {
19963 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19964 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19965 auto *LSI = cast<LambdaScopeInfo>(CSI);
19966 if (LSI->Lambda) {
19967 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19968 buildLambdaCaptureFixit(*this, LSI, Var);
19969 }
19970 // FIXME: If we error out because an outer lambda can not implicitly
19971 // capture a variable that an inner lambda explicitly captures, we
19972 // should have the inner lambda do the explicit capture - because
19973 // it makes for cleaner diagnostics later. This would purely be done
19974 // so that the diagnostic does not misleadingly claim that a variable
19975 // can not be captured by a lambda implicitly even though it is captured
19976 // explicitly. Suggestion:
19977 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19978 // at the function head
19979 // - cache the StartingDeclContext - this must be a lambda
19980 // - captureInLambda in the innermost lambda the variable.
19981 }
19982 return true;
19983 }
19984 Explicit = false;
19985 FunctionScopesIndex--;
19986 if (IsInScopeDeclarationContext)
19987 DC = ParentDC;
19988 } while (!VarDC->Equals(DC));
19989
19990 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19991 // computing the type of the capture at each step, checking type-specific
19992 // requirements, and adding captures if requested.
19993 // If the variable had already been captured previously, we start capturing
19994 // at the lambda nested within that one.
19995 bool Invalid = false;
19996 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19997 ++I) {
19999
20000 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20001 // certain types of variables (unnamed, variably modified types etc.)
20002 // so check for eligibility.
20003 if (!Invalid)
20004 Invalid =
20005 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
20006
20007 // After encountering an error, if we're actually supposed to capture, keep
20008 // capturing in nested contexts to suppress any follow-on diagnostics.
20009 if (Invalid && !BuildAndDiagnose)
20010 return true;
20011
20012 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
20013 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20014 DeclRefType, Nested, *this, Invalid);
20015 Nested = true;
20016 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20018 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
20019 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
20020 Nested = true;
20021 } else {
20023 Invalid =
20024 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20025 DeclRefType, Nested, Kind, EllipsisLoc,
20026 /*IsTopScope*/ I == N - 1, *this, Invalid);
20027 Nested = true;
20028 }
20029
20030 if (Invalid && !BuildAndDiagnose)
20031 return true;
20032 }
20033 return Invalid;
20034}
20035
20037 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20038 QualType CaptureType;
20039 QualType DeclRefType;
20040 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
20041 /*BuildAndDiagnose=*/true, CaptureType,
20042 DeclRefType, nullptr);
20043}
20044
20046 QualType CaptureType;
20047 QualType DeclRefType;
20048 return !tryCaptureVariable(
20050 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
20051}
20052
20054 assert(Var && "Null value cannot be captured");
20055
20056 QualType CaptureType;
20057 QualType DeclRefType;
20058
20059 // Determine whether we can capture this variable.
20061 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20062 nullptr))
20063 return QualType();
20064
20065 return DeclRefType;
20066}
20067
20068namespace {
20069// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20070// The produced TemplateArgumentListInfo* points to data stored within this
20071// object, so should only be used in contexts where the pointer will not be
20072// used after the CopiedTemplateArgs object is destroyed.
20073class CopiedTemplateArgs {
20074 bool HasArgs;
20075 TemplateArgumentListInfo TemplateArgStorage;
20076public:
20077 template<typename RefExpr>
20078 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20079 if (HasArgs)
20080 E->copyTemplateArgumentsInto(TemplateArgStorage);
20081 }
20082 operator TemplateArgumentListInfo*()
20083#ifdef __has_cpp_attribute
20084#if __has_cpp_attribute(clang::lifetimebound)
20085 [[clang::lifetimebound]]
20086#endif
20087#endif
20088 {
20089 return HasArgs ? &TemplateArgStorage : nullptr;
20090 }
20091};
20092}
20093
20094/// Walk the set of potential results of an expression and mark them all as
20095/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20096///
20097/// \return A new expression if we found any potential results, ExprEmpty() if
20098/// not, and ExprError() if we diagnosed an error.
20100 NonOdrUseReason NOUR) {
20101 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20102 // an object that satisfies the requirements for appearing in a
20103 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20104 // is immediately applied." This function handles the lvalue-to-rvalue
20105 // conversion part.
20106 //
20107 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20108 // transform it into the relevant kind of non-odr-use node and rebuild the
20109 // tree of nodes leading to it.
20110 //
20111 // This is a mini-TreeTransform that only transforms a restricted subset of
20112 // nodes (and only certain operands of them).
20113
20114 // Rebuild a subexpression.
20115 auto Rebuild = [&](Expr *Sub) {
20116 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20117 };
20118
20119 // Check whether a potential result satisfies the requirements of NOUR.
20120 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20121 // Any entity other than a VarDecl is always odr-used whenever it's named
20122 // in a potentially-evaluated expression.
20123 auto *VD = dyn_cast<VarDecl>(D);
20124 if (!VD)
20125 return true;
20126
20127 // C++2a [basic.def.odr]p4:
20128 // A variable x whose name appears as a potentially-evalauted expression
20129 // e is odr-used by e unless
20130 // -- x is a reference that is usable in constant expressions, or
20131 // -- x is a variable of non-reference type that is usable in constant
20132 // expressions and has no mutable subobjects, and e is an element of
20133 // the set of potential results of an expression of
20134 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20135 // conversion is applied, or
20136 // -- x is a variable of non-reference type, and e is an element of the
20137 // set of potential results of a discarded-value expression to which
20138 // the lvalue-to-rvalue conversion is not applied
20139 //
20140 // We check the first bullet and the "potentially-evaluated" condition in
20141 // BuildDeclRefExpr. We check the type requirements in the second bullet
20142 // in CheckLValueToRValueConversionOperand below.
20143 switch (NOUR) {
20144 case NOUR_None:
20145 case NOUR_Unevaluated:
20146 llvm_unreachable("unexpected non-odr-use-reason");
20147
20148 case NOUR_Constant:
20149 // Constant references were handled when they were built.
20150 if (VD->getType()->isReferenceType())
20151 return true;
20152 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20153 if (RD->hasDefinition() && RD->hasMutableFields())
20154 return true;
20155 if (!VD->isUsableInConstantExpressions(S.Context))
20156 return true;
20157 break;
20158
20159 case NOUR_Discarded:
20160 if (VD->getType()->isReferenceType())
20161 return true;
20162 break;
20163 }
20164 return false;
20165 };
20166
20167 // Check whether this expression may be odr-used in CUDA/HIP.
20168 auto MaybeCUDAODRUsed = [&]() -> bool {
20169 if (!S.LangOpts.CUDA)
20170 return false;
20171 LambdaScopeInfo *LSI = S.getCurLambda();
20172 if (!LSI)
20173 return false;
20174 auto *DRE = dyn_cast<DeclRefExpr>(E);
20175 if (!DRE)
20176 return false;
20177 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
20178 if (!VD)
20179 return false;
20180 return LSI->CUDAPotentialODRUsedVars.count(VD);
20181 };
20182
20183 // Mark that this expression does not constitute an odr-use.
20184 auto MarkNotOdrUsed = [&] {
20185 if (!MaybeCUDAODRUsed()) {
20186 S.MaybeODRUseExprs.remove(E);
20187 if (LambdaScopeInfo *LSI = S.getCurLambda())
20188 LSI->markVariableExprAsNonODRUsed(E);
20189 }
20190 };
20191
20192 // C++2a [basic.def.odr]p2:
20193 // The set of potential results of an expression e is defined as follows:
20194 switch (E->getStmtClass()) {
20195 // -- If e is an id-expression, ...
20196 case Expr::DeclRefExprClass: {
20197 auto *DRE = cast<DeclRefExpr>(E);
20198 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20199 break;
20200
20201 // Rebuild as a non-odr-use DeclRefExpr.
20202 MarkNotOdrUsed();
20203 return DeclRefExpr::Create(
20204 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20205 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20206 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20207 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20208 }
20209
20210 case Expr::FunctionParmPackExprClass: {
20211 auto *FPPE = cast<FunctionParmPackExpr>(E);
20212 // If any of the declarations in the pack is odr-used, then the expression
20213 // as a whole constitutes an odr-use.
20214 for (ValueDecl *D : *FPPE)
20215 if (IsPotentialResultOdrUsed(D))
20216 return ExprEmpty();
20217
20218 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20219 // nothing cares about whether we marked this as an odr-use, but it might
20220 // be useful for non-compiler tools.
20221 MarkNotOdrUsed();
20222 break;
20223 }
20224
20225 // -- If e is a subscripting operation with an array operand...
20226 case Expr::ArraySubscriptExprClass: {
20227 auto *ASE = cast<ArraySubscriptExpr>(E);
20228 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20229 if (!OldBase->getType()->isArrayType())
20230 break;
20231 ExprResult Base = Rebuild(OldBase);
20232 if (!Base.isUsable())
20233 return Base;
20234 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20235 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20236 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20237 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20238 ASE->getRBracketLoc());
20239 }
20240
20241 case Expr::MemberExprClass: {
20242 auto *ME = cast<MemberExpr>(E);
20243 // -- If e is a class member access expression [...] naming a non-static
20244 // data member...
20245 if (isa<FieldDecl>(ME->getMemberDecl())) {
20246 ExprResult Base = Rebuild(ME->getBase());
20247 if (!Base.isUsable())
20248 return Base;
20249 return MemberExpr::Create(
20250 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20251 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20252 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20253 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20254 ME->getObjectKind(), ME->isNonOdrUse());
20255 }
20256
20257 if (ME->getMemberDecl()->isCXXInstanceMember())
20258 break;
20259
20260 // -- If e is a class member access expression naming a static data member,
20261 // ...
20262 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20263 break;
20264
20265 // Rebuild as a non-odr-use MemberExpr.
20266 MarkNotOdrUsed();
20267 return MemberExpr::Create(
20268 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20269 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20270 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20271 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20272 }
20273
20274 case Expr::BinaryOperatorClass: {
20275 auto *BO = cast<BinaryOperator>(E);
20276 Expr *LHS = BO->getLHS();
20277 Expr *RHS = BO->getRHS();
20278 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20279 if (BO->getOpcode() == BO_PtrMemD) {
20280 ExprResult Sub = Rebuild(LHS);
20281 if (!Sub.isUsable())
20282 return Sub;
20283 BO->setLHS(Sub.get());
20284 // -- If e is a comma expression, ...
20285 } else if (BO->getOpcode() == BO_Comma) {
20286 ExprResult Sub = Rebuild(RHS);
20287 if (!Sub.isUsable())
20288 return Sub;
20289 BO->setRHS(Sub.get());
20290 } else {
20291 break;
20292 }
20293 return ExprResult(BO);
20294 }
20295
20296 // -- If e has the form (e1)...
20297 case Expr::ParenExprClass: {
20298 auto *PE = cast<ParenExpr>(E);
20299 ExprResult Sub = Rebuild(PE->getSubExpr());
20300 if (!Sub.isUsable())
20301 return Sub;
20302 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20303 }
20304
20305 // -- If e is a glvalue conditional expression, ...
20306 // We don't apply this to a binary conditional operator. FIXME: Should we?
20307 case Expr::ConditionalOperatorClass: {
20308 auto *CO = cast<ConditionalOperator>(E);
20309 ExprResult LHS = Rebuild(CO->getLHS());
20310 if (LHS.isInvalid())
20311 return ExprError();
20312 ExprResult RHS = Rebuild(CO->getRHS());
20313 if (RHS.isInvalid())
20314 return ExprError();
20315 if (!LHS.isUsable() && !RHS.isUsable())
20316 return ExprEmpty();
20317 if (!LHS.isUsable())
20318 LHS = CO->getLHS();
20319 if (!RHS.isUsable())
20320 RHS = CO->getRHS();
20321 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20322 CO->getCond(), LHS.get(), RHS.get());
20323 }
20324
20325 // [Clang extension]
20326 // -- If e has the form __extension__ e1...
20327 case Expr::UnaryOperatorClass: {
20328 auto *UO = cast<UnaryOperator>(E);
20329 if (UO->getOpcode() != UO_Extension)
20330 break;
20331 ExprResult Sub = Rebuild(UO->getSubExpr());
20332 if (!Sub.isUsable())
20333 return Sub;
20334 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20335 Sub.get());
20336 }
20337
20338 // [Clang extension]
20339 // -- If e has the form _Generic(...), the set of potential results is the
20340 // union of the sets of potential results of the associated expressions.
20341 case Expr::GenericSelectionExprClass: {
20342 auto *GSE = cast<GenericSelectionExpr>(E);
20343
20344 SmallVector<Expr *, 4> AssocExprs;
20345 bool AnyChanged = false;
20346 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20347 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20348 if (AssocExpr.isInvalid())
20349 return ExprError();
20350 if (AssocExpr.isUsable()) {
20351 AssocExprs.push_back(AssocExpr.get());
20352 AnyChanged = true;
20353 } else {
20354 AssocExprs.push_back(OrigAssocExpr);
20355 }
20356 }
20357
20358 void *ExOrTy = nullptr;
20359 bool IsExpr = GSE->isExprPredicate();
20360 if (IsExpr)
20361 ExOrTy = GSE->getControllingExpr();
20362 else
20363 ExOrTy = GSE->getControllingType();
20364 return AnyChanged ? S.CreateGenericSelectionExpr(
20365 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20366 GSE->getRParenLoc(), IsExpr, ExOrTy,
20367 GSE->getAssocTypeSourceInfos(), AssocExprs)
20368 : ExprEmpty();
20369 }
20370
20371 // [Clang extension]
20372 // -- If e has the form __builtin_choose_expr(...), the set of potential
20373 // results is the union of the sets of potential results of the
20374 // second and third subexpressions.
20375 case Expr::ChooseExprClass: {
20376 auto *CE = cast<ChooseExpr>(E);
20377
20378 ExprResult LHS = Rebuild(CE->getLHS());
20379 if (LHS.isInvalid())
20380 return ExprError();
20381
20382 ExprResult RHS = Rebuild(CE->getLHS());
20383 if (RHS.isInvalid())
20384 return ExprError();
20385
20386 if (!LHS.get() && !RHS.get())
20387 return ExprEmpty();
20388 if (!LHS.isUsable())
20389 LHS = CE->getLHS();
20390 if (!RHS.isUsable())
20391 RHS = CE->getRHS();
20392
20393 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20394 RHS.get(), CE->getRParenLoc());
20395 }
20396
20397 // Step through non-syntactic nodes.
20398 case Expr::ConstantExprClass: {
20399 auto *CE = cast<ConstantExpr>(E);
20400 ExprResult Sub = Rebuild(CE->getSubExpr());
20401 if (!Sub.isUsable())
20402 return Sub;
20403 return ConstantExpr::Create(S.Context, Sub.get());
20404 }
20405
20406 // We could mostly rely on the recursive rebuilding to rebuild implicit
20407 // casts, but not at the top level, so rebuild them here.
20408 case Expr::ImplicitCastExprClass: {
20409 auto *ICE = cast<ImplicitCastExpr>(E);
20410 // Only step through the narrow set of cast kinds we expect to encounter.
20411 // Anything else suggests we've left the region in which potential results
20412 // can be found.
20413 switch (ICE->getCastKind()) {
20414 case CK_NoOp:
20415 case CK_DerivedToBase:
20416 case CK_UncheckedDerivedToBase: {
20417 ExprResult Sub = Rebuild(ICE->getSubExpr());
20418 if (!Sub.isUsable())
20419 return Sub;
20420 CXXCastPath Path(ICE->path());
20421 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20422 ICE->getValueKind(), &Path);
20423 }
20424
20425 default:
20426 break;
20427 }
20428 break;
20429 }
20430
20431 default:
20432 break;
20433 }
20434
20435 // Can't traverse through this node. Nothing to do.
20436 return ExprEmpty();
20437}
20438
20440 // Check whether the operand is or contains an object of non-trivial C union
20441 // type.
20442 if (E->getType().isVolatileQualified() &&
20448
20449 // C++2a [basic.def.odr]p4:
20450 // [...] an expression of non-volatile-qualified non-class type to which
20451 // the lvalue-to-rvalue conversion is applied [...]
20452 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20453 return E;
20454
20457 if (Result.isInvalid())
20458 return ExprError();
20459 return Result.get() ? Result : E;
20460}
20461
20463 if (!Res.isUsable())
20464 return Res;
20465
20466 // If a constant-expression is a reference to a variable where we delay
20467 // deciding whether it is an odr-use, just assume we will apply the
20468 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20469 // (a non-type template argument), we have special handling anyway.
20471}
20472
20474 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20475 // call.
20476 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20477 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20478
20479 for (Expr *E : LocalMaybeODRUseExprs) {
20480 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20481 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20482 DRE->getLocation(), *this);
20483 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20484 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20485 *this);
20486 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20487 for (ValueDecl *VD : *FP)
20488 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20489 } else {
20490 llvm_unreachable("Unexpected expression");
20491 }
20492 }
20493
20494 assert(MaybeODRUseExprs.empty() &&
20495 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20496}
20497
20499 ValueDecl *Var, Expr *E) {
20501 if (!VD)
20502 return;
20503
20504 const bool RefersToEnclosingScope =
20505 (SemaRef.CurContext != VD->getDeclContext() &&
20507 if (RefersToEnclosingScope) {
20508 LambdaScopeInfo *const LSI =
20509 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20510 if (LSI && (!LSI->CallOperator ||
20511 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20512 // If a variable could potentially be odr-used, defer marking it so
20513 // until we finish analyzing the full expression for any
20514 // lvalue-to-rvalue
20515 // or discarded value conversions that would obviate odr-use.
20516 // Add it to the list of potential captures that will be analyzed
20517 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20518 // unless the variable is a reference that was initialized by a constant
20519 // expression (this will never need to be captured or odr-used).
20520 //
20521 // FIXME: We can simplify this a lot after implementing P0588R1.
20522 assert(E && "Capture variable should be used in an expression.");
20523 if (!Var->getType()->isReferenceType() ||
20526 }
20527 }
20528}
20529
20531 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20532 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20533 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20535 "Invalid Expr argument to DoMarkVarDeclReferenced");
20536 Var->setReferenced();
20537
20538 if (Var->isInvalidDecl())
20539 return;
20540
20541 auto *MSI = Var->getMemberSpecializationInfo();
20542 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20544
20545 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20546 bool UsableInConstantExpr =
20548
20549 // Only track variables with internal linkage or local scope.
20550 // Use canonical decl so in-class declarations and out-of-class definitions
20551 // of static data members in anonymous namespaces are tracked as a single
20552 // entry.
20553 const VarDecl *CanonVar = Var->getCanonicalDecl();
20554 if ((CanonVar->isLocalVarDeclOrParm() ||
20555 CanonVar->isInternalLinkageFileVar()) &&
20556 !CanonVar->hasExternalStorage()) {
20557 RefsMinusAssignments.insert({CanonVar, 0}).first->getSecond()++;
20558 }
20559
20560 // C++20 [expr.const]p12:
20561 // A variable [...] is needed for constant evaluation if it is [...] a
20562 // variable whose name appears as a potentially constant evaluated
20563 // expression that is either a contexpr variable or is of non-volatile
20564 // const-qualified integral type or of reference type
20565 bool NeededForConstantEvaluation =
20566 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20567
20568 bool NeedDefinition =
20569 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20570 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20571 Var->getType()->isUndeducedType());
20572
20574 "Can't instantiate a partial template specialization.");
20575
20576 // If this might be a member specialization of a static data member, check
20577 // the specialization is visible. We already did the checks for variable
20578 // template specializations when we created them.
20579 if (NeedDefinition && TSK != TSK_Undeclared &&
20582
20583 // Perform implicit instantiation of static data members, static data member
20584 // templates of class templates, and variable template specializations. Delay
20585 // instantiations of variable templates, except for those that could be used
20586 // in a constant expression.
20587 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20588 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20589 // instantiation declaration if a variable is usable in a constant
20590 // expression (among other cases).
20591 bool TryInstantiating =
20593 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20594
20595 if (TryInstantiating) {
20596 SourceLocation PointOfInstantiation =
20597 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20598 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20599 if (FirstInstantiation) {
20600 PointOfInstantiation = Loc;
20601 if (MSI)
20602 MSI->setPointOfInstantiation(PointOfInstantiation);
20603 // FIXME: Notify listener.
20604 else
20605 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20606 }
20607
20608 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20609 // Do not defer instantiations of variables that could be used in a
20610 // constant expression.
20611 // The type deduction also needs a complete initializer.
20612 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20613 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20614 });
20615
20616 // The size of an incomplete array type can be updated by
20617 // instantiating the initializer. The DeclRefExpr's type should be
20618 // updated accordingly too, or users of it would be confused!
20619 if (E)
20621
20622 // Re-set the member to trigger a recomputation of the dependence bits
20623 // for the expression.
20624 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20625 DRE->setDecl(DRE->getDecl());
20626 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20627 ME->setMemberDecl(ME->getMemberDecl());
20628 } else if (FirstInstantiation) {
20630 .push_back(std::make_pair(Var, PointOfInstantiation));
20631 } else {
20632 bool Inserted = false;
20633 for (auto &I : SemaRef.SavedPendingInstantiations) {
20634 auto Iter = llvm::find_if(
20635 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20636 return P.first == Var;
20637 });
20638 if (Iter != I.end()) {
20639 SemaRef.PendingInstantiations.push_back(*Iter);
20640 I.erase(Iter);
20641 Inserted = true;
20642 break;
20643 }
20644 }
20645
20646 // FIXME: For a specialization of a variable template, we don't
20647 // distinguish between "declaration and type implicitly instantiated"
20648 // and "implicit instantiation of definition requested", so we have
20649 // no direct way to avoid enqueueing the pending instantiation
20650 // multiple times.
20651 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20653 .push_back(std::make_pair(Var, PointOfInstantiation));
20654 }
20655 }
20656 }
20657
20658 // C++2a [basic.def.odr]p4:
20659 // A variable x whose name appears as a potentially-evaluated expression e
20660 // is odr-used by e unless
20661 // -- x is a reference that is usable in constant expressions
20662 // -- x is a variable of non-reference type that is usable in constant
20663 // expressions and has no mutable subobjects [FIXME], and e is an
20664 // element of the set of potential results of an expression of
20665 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20666 // conversion is applied
20667 // -- x is a variable of non-reference type, and e is an element of the set
20668 // of potential results of a discarded-value expression to which the
20669 // lvalue-to-rvalue conversion is not applied [FIXME]
20670 //
20671 // We check the first part of the second bullet here, and
20672 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20673 // FIXME: To get the third bullet right, we need to delay this even for
20674 // variables that are not usable in constant expressions.
20675
20676 // If we already know this isn't an odr-use, there's nothing more to do.
20677 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20678 if (DRE->isNonOdrUse())
20679 return;
20680 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20681 if (ME->isNonOdrUse())
20682 return;
20683
20684 switch (OdrUse) {
20685 case OdrUseContext::None:
20686 // In some cases, a variable may not have been marked unevaluated, if it
20687 // appears in a defaukt initializer.
20688 assert((!E || isa<FunctionParmPackExpr>(E) ||
20690 "missing non-odr-use marking for unevaluated decl ref");
20691 break;
20692
20693 case OdrUseContext::FormallyOdrUsed:
20694 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20695 // behavior.
20696 break;
20697
20698 case OdrUseContext::Used:
20699 // If we might later find that this expression isn't actually an odr-use,
20700 // delay the marking.
20702 SemaRef.MaybeODRUseExprs.insert(E);
20703 else
20704 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20705 break;
20706
20707 case OdrUseContext::Dependent:
20708 // If this is a dependent context, we don't need to mark variables as
20709 // odr-used, but we may still need to track them for lambda capture.
20710 // FIXME: Do we also need to do this inside dependent typeid expressions
20711 // (which are modeled as unevaluated at this point)?
20712 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20713 break;
20714 }
20715}
20716
20718 BindingDecl *BD, Expr *E) {
20719 BD->setReferenced();
20720
20721 if (BD->isInvalidDecl())
20722 return;
20723
20724 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20725 if (OdrUse == OdrUseContext::Used) {
20726 QualType CaptureType, DeclRefType;
20728 /*EllipsisLoc*/ SourceLocation(),
20729 /*BuildAndDiagnose*/ true, CaptureType,
20730 DeclRefType,
20731 /*FunctionScopeIndexToStopAt*/ nullptr);
20732 } else if (OdrUse == OdrUseContext::Dependent) {
20733 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20734 }
20735}
20736
20738 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20739}
20740
20741// C++ [temp.dep.expr]p3:
20742// An id-expression is type-dependent if it contains:
20743// - an identifier associated by name lookup with an entity captured by copy
20744// in a lambda-expression that has an explicit object parameter whose type
20745// is dependent ([dcl.fct]),
20747 Sema &SemaRef, ValueDecl *D, Expr *E) {
20748 auto *ID = dyn_cast<DeclRefExpr>(E);
20749 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20750 return;
20751
20752 // If any enclosing lambda with a dependent explicit object parameter either
20753 // explicitly captures the variable by value, or has a capture default of '='
20754 // and does not capture the variable by reference, then the type of the DRE
20755 // is dependent on the type of that lambda's explicit object parameter.
20756 auto IsDependent = [&]() {
20757 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20758 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20759 if (!LSI)
20760 continue;
20761
20762 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20763 LSI->AfterParameterList)
20764 return false;
20765
20766 const auto *MD = LSI->CallOperator;
20767 if (MD->getType().isNull())
20768 continue;
20769
20770 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20771 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20772 !Ty->getParamType(0)->isDependentType())
20773 continue;
20774
20775 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20776 if (C->isCopyCapture())
20777 return true;
20778 continue;
20779 }
20780
20781 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20782 return true;
20783 }
20784 return false;
20785 }();
20786
20787 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20788 IsDependent, SemaRef.getASTContext());
20789}
20790
20791static void
20793 bool MightBeOdrUse,
20794 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20797
20798 if (SemaRef.getLangOpts().OpenACC)
20799 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20800
20801 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20803 if (SemaRef.getLangOpts().CPlusPlus)
20805 Var, E);
20806 return;
20807 }
20808
20809 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20811 if (SemaRef.getLangOpts().CPlusPlus)
20813 Decl, E);
20814 return;
20815 }
20816 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20817
20818 // If this is a call to a method via a cast, also mark the method in the
20819 // derived class used in case codegen can devirtualize the call.
20820 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20821 if (!ME)
20822 return;
20823 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20824 if (!MD)
20825 return;
20826 // Only attempt to devirtualize if this is truly a virtual call.
20827 bool IsVirtualCall = MD->isVirtual() &&
20829 if (!IsVirtualCall)
20830 return;
20831
20832 // If it's possible to devirtualize the call, mark the called function
20833 // referenced.
20835 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20836 if (DM)
20837 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20838}
20839
20841 // [basic.def.odr] (CWG 1614)
20842 // A function is named by an expression or conversion [...]
20843 // unless it is a pure virtual function and either the expression is not an
20844 // id-expression naming the function with an explicitly qualified name or
20845 // the expression forms a pointer to member
20846 bool OdrUse = true;
20847 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20848 if (Method->isVirtual() &&
20849 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20850 OdrUse = false;
20851
20852 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20856 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20857 !FD->isDependentContext())
20858 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20859 }
20860 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20862}
20863
20865 // C++11 [basic.def.odr]p2:
20866 // A non-overloaded function whose name appears as a potentially-evaluated
20867 // expression or a member of a set of candidate functions, if selected by
20868 // overload resolution when referred to from a potentially-evaluated
20869 // expression, is odr-used, unless it is a pure virtual function and its
20870 // name is not explicitly qualified.
20871 bool MightBeOdrUse = true;
20873 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20874 if (Method->isPureVirtual())
20875 MightBeOdrUse = false;
20876 }
20877 SourceLocation Loc =
20878 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20879 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20881}
20882
20888
20889/// Perform marking for a reference to an arbitrary declaration. It
20890/// marks the declaration referenced, and performs odr-use checking for
20891/// functions and variables. This method should not be used when building a
20892/// normal expression which refers to a variable.
20894 bool MightBeOdrUse) {
20895 if (MightBeOdrUse) {
20896 if (auto *VD = dyn_cast<VarDecl>(D)) {
20897 MarkVariableReferenced(Loc, VD);
20898 return;
20899 }
20900 }
20901 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20902 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20903 return;
20904 }
20905 D->setReferenced();
20906}
20907
20908namespace {
20909 // Mark all of the declarations used by a type as referenced.
20910 // FIXME: Not fully implemented yet! We need to have a better understanding
20911 // of when we're entering a context we should not recurse into.
20912 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20913 // TreeTransforms rebuilding the type in a new context. Rather than
20914 // duplicating the TreeTransform logic, we should consider reusing it here.
20915 // Currently that causes problems when rebuilding LambdaExprs.
20916class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20917 Sema &S;
20918 SourceLocation Loc;
20919
20920public:
20921 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20922
20923 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20924};
20925}
20926
20927bool MarkReferencedDecls::TraverseTemplateArgument(
20928 const TemplateArgument &Arg) {
20929 {
20930 // A non-type template argument is a constant-evaluated context.
20931 EnterExpressionEvaluationContext Evaluated(
20934 if (Decl *D = Arg.getAsDecl())
20935 S.MarkAnyDeclReferenced(Loc, D, true);
20936 } else if (Arg.getKind() == TemplateArgument::Expression) {
20938 }
20939 }
20940
20942}
20943
20945 MarkReferencedDecls Marker(*this, Loc);
20946 Marker.TraverseType(T);
20947}
20948
20949namespace {
20950/// Helper class that marks all of the declarations referenced by
20951/// potentially-evaluated subexpressions as "referenced".
20952class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20953public:
20954 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20955 bool SkipLocalVariables;
20957
20958 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20960 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20961
20962 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20964 }
20965
20966 void Visit(Expr *E) {
20967 if (llvm::is_contained(StopAt, E))
20968 return;
20969 Inherited::Visit(E);
20970 }
20971
20972 void VisitConstantExpr(ConstantExpr *E) {
20973 // Don't mark declarations within a ConstantExpression, as this expression
20974 // will be evaluated and folded to a value.
20975 }
20976
20977 void VisitDeclRefExpr(DeclRefExpr *E) {
20978 // If we were asked not to visit local variables, don't.
20979 if (SkipLocalVariables) {
20980 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20981 if (VD->hasLocalStorage())
20982 return;
20983 }
20984
20985 // FIXME: This can trigger the instantiation of the initializer of a
20986 // variable, which can cause the expression to become value-dependent
20987 // or error-dependent. Do we need to propagate the new dependence bits?
20989 }
20990
20991 void VisitMemberExpr(MemberExpr *E) {
20993 Visit(E->getBase());
20994 }
20995};
20996} // namespace
20997
20999 bool SkipLocalVariables,
21000 ArrayRef<const Expr*> StopAt) {
21001 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21002}
21003
21004/// Emit a diagnostic when statements are reachable.
21006 const PartialDiagnostic &PD) {
21007 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21008 // The initializer of a constexpr variable or of the first declaration of a
21009 // static data member is not syntactically a constant evaluated constant,
21010 // but nonetheless is always required to be a constant expression, so we
21011 // can skip diagnosing.
21012 if (Decl &&
21013 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21014 Decl->isFirstDecl() && !Decl->isInline())))
21015 return false;
21016
21017 if (Stmts.empty()) {
21018 Diag(Loc, PD);
21019 return true;
21020 }
21021
21022 if (getCurFunction()) {
21023 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21024 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21025 return true;
21026 }
21027
21028 // For non-constexpr file-scope variables with reachability context (non-empty
21029 // Stmts), build a CFG for the initializer and check whether the context in
21030 // question is reachable.
21031 if (Decl && Decl->isFileVarDecl()) {
21032 AnalysisWarnings.registerVarDeclWarning(
21033 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21034 return true;
21035 }
21036
21037 Diag(Loc, PD);
21038 return true;
21039}
21040
21041/// Emit a diagnostic that describes an effect on the run-time behavior
21042/// of the program being compiled.
21043///
21044/// This routine emits the given diagnostic when the code currently being
21045/// type-checked is "potentially evaluated", meaning that there is a
21046/// possibility that the code will actually be executable. Code in sizeof()
21047/// expressions, code used only during overload resolution, etc., are not
21048/// potentially evaluated. This routine will suppress such diagnostics or,
21049/// in the absolutely nutty case of potentially potentially evaluated
21050/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21051/// later.
21052///
21053/// This routine should be used for all diagnostics that describe the run-time
21054/// behavior of a program, such as passing a non-POD value through an ellipsis.
21055/// Failure to do so will likely result in spurious diagnostics or failures
21056/// during overload resolution or within sizeof/alignof/typeof/typeid.
21058 const PartialDiagnostic &PD) {
21059
21060 if (ExprEvalContexts.back().isDiscardedStatementContext())
21061 return false;
21062
21063 switch (ExprEvalContexts.back().Context) {
21068 // The argument will never be evaluated, so don't complain.
21069 break;
21070
21073 // Relevant diagnostics should be produced by constant evaluation.
21074 break;
21075
21078 return DiagIfReachable(Loc, Stmts, PD);
21079 }
21080
21081 return false;
21082}
21083
21085 const PartialDiagnostic &PD) {
21086 return DiagRuntimeBehavior(
21087 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21088 PD);
21089}
21090
21092 CallExpr *CE, FunctionDecl *FD) {
21093 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21094 return false;
21095
21096 // If we're inside a decltype's expression, don't check for a valid return
21097 // type or construct temporaries until we know whether this is the last call.
21098 if (ExprEvalContexts.back().ExprContext ==
21100 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21101 return false;
21102 }
21103
21104 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21105 FunctionDecl *FD;
21106 CallExpr *CE;
21107
21108 public:
21109 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21110 : FD(FD), CE(CE) { }
21111
21112 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21113 if (!FD) {
21114 S.Diag(Loc, diag::err_call_incomplete_return)
21115 << T << CE->getSourceRange();
21116 return;
21117 }
21118
21119 S.Diag(Loc, diag::err_call_function_incomplete_return)
21120 << CE->getSourceRange() << FD << T;
21121 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21122 << FD->getDeclName();
21123 }
21124 } Diagnoser(FD, CE);
21125
21126 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21127 return true;
21128
21129 return false;
21130}
21131
21132// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21133// will prevent this condition from triggering, which is what we want.
21135 SourceLocation Loc;
21136
21137 unsigned diagnostic = diag::warn_condition_is_assignment;
21138 bool IsOrAssign = false;
21139
21140 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21141 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21142 return;
21143
21144 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21145
21146 // Greylist some idioms by putting them into a warning subcategory.
21147 if (ObjCMessageExpr *ME
21148 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21149 Selector Sel = ME->getSelector();
21150
21151 // self = [<foo> init...]
21152 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21153 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21154
21155 // <foo> = [<bar> nextObject]
21156 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21157 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21158 }
21159
21160 Loc = Op->getOperatorLoc();
21161 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21162 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21163 return;
21164
21165 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21166 Loc = Op->getOperatorLoc();
21167 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21168 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21169 else {
21170 // Not an assignment.
21171 return;
21172 }
21173
21174 Diag(Loc, diagnostic) << E->getSourceRange();
21175
21178 Diag(Loc, diag::note_condition_assign_silence)
21180 << FixItHint::CreateInsertion(Close, ")");
21181
21182 if (IsOrAssign)
21183 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21184 << FixItHint::CreateReplacement(Loc, "!=");
21185 else
21186 Diag(Loc, diag::note_condition_assign_to_comparison)
21187 << FixItHint::CreateReplacement(Loc, "==");
21188}
21189
21191 // Don't warn if the parens came from a macro.
21192 SourceLocation parenLoc = ParenE->getBeginLoc();
21193 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21194 return;
21195 // Don't warn for dependent expressions.
21196 if (ParenE->isTypeDependent())
21197 return;
21198
21199 Expr *E = ParenE->IgnoreParens();
21200 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21201 return;
21202
21203 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21204 if (opE->getOpcode() == BO_EQ &&
21205 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21206 == Expr::MLV_Valid) {
21207 SourceLocation Loc = opE->getOperatorLoc();
21208
21209 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21210 SourceRange ParenERange = ParenE->getSourceRange();
21211 Diag(Loc, diag::note_equality_comparison_silence)
21212 << FixItHint::CreateRemoval(ParenERange.getBegin())
21213 << FixItHint::CreateRemoval(ParenERange.getEnd());
21214 Diag(Loc, diag::note_equality_comparison_to_assign)
21215 << FixItHint::CreateReplacement(Loc, "=");
21216 }
21217}
21218
21220 bool IsConstexpr) {
21222 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21224
21225 ExprResult result = CheckPlaceholderExpr(E);
21226 if (result.isInvalid()) return ExprError();
21227 E = result.get();
21228
21229 if (!E->isTypeDependent()) {
21230 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21232
21233 if (getLangOpts().CPlusPlus)
21234 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21235
21237 if (ERes.isInvalid())
21238 return ExprError();
21239 E = ERes.get();
21240
21241 QualType T = E->getType();
21242 if (!T->isScalarType()) { // C99 6.8.4.1p1
21243 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21244 << T << E->getSourceRange();
21245 return ExprError();
21246 }
21247 CheckBoolLikeConversion(E, Loc);
21248 }
21249
21250 return E;
21251}
21252
21254 Expr *SubExpr, ConditionKind CK,
21255 bool MissingOK) {
21256 // MissingOK indicates whether having no condition expression is valid
21257 // (for loop) or invalid (e.g. while loop).
21258 if (!SubExpr)
21259 return MissingOK ? ConditionResult() : ConditionError();
21260
21262 switch (CK) {
21264 Cond = CheckBooleanCondition(Loc, SubExpr);
21265 break;
21266
21268 // Note: this might produce a FullExpr
21269 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21270 break;
21271
21273 Cond = CheckSwitchCondition(Loc, SubExpr);
21274 break;
21275 }
21276 if (Cond.isInvalid()) {
21277 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21278 {SubExpr}, PreferredConditionType(CK));
21279 if (!Cond.get())
21280 return ConditionError();
21281 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
21282 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
21283
21284 if (!Cond.isUsable())
21285 return ConditionError();
21286
21287 return ConditionResult(*this, nullptr, Cond,
21289}
21290
21291namespace {
21292 /// A visitor for rebuilding a call to an __unknown_any expression
21293 /// to have an appropriate type.
21294 struct RebuildUnknownAnyFunction
21295 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21296
21297 Sema &S;
21298
21299 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21300
21301 ExprResult VisitStmt(Stmt *S) {
21302 llvm_unreachable("unexpected statement!");
21303 }
21304
21305 ExprResult VisitExpr(Expr *E) {
21306 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21307 << E->getSourceRange();
21308 return ExprError();
21309 }
21310
21311 /// Rebuild an expression which simply semantically wraps another
21312 /// expression which it shares the type and value kind of.
21313 template <class T> ExprResult rebuildSugarExpr(T *E) {
21314 ExprResult SubResult = Visit(E->getSubExpr());
21315 if (SubResult.isInvalid()) return ExprError();
21316
21317 Expr *SubExpr = SubResult.get();
21318 E->setSubExpr(SubExpr);
21319 E->setType(SubExpr->getType());
21320 E->setValueKind(SubExpr->getValueKind());
21321 assert(E->getObjectKind() == OK_Ordinary);
21322 return E;
21323 }
21324
21325 ExprResult VisitParenExpr(ParenExpr *E) {
21326 return rebuildSugarExpr(E);
21327 }
21328
21329 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21330 return rebuildSugarExpr(E);
21331 }
21332
21333 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21334 ExprResult SubResult = Visit(E->getSubExpr());
21335 if (SubResult.isInvalid()) return ExprError();
21336
21337 Expr *SubExpr = SubResult.get();
21338 E->setSubExpr(SubExpr);
21339 E->setType(S.Context.getPointerType(SubExpr->getType()));
21340 assert(E->isPRValue());
21341 assert(E->getObjectKind() == OK_Ordinary);
21342 return E;
21343 }
21344
21345 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21346 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21347
21348 E->setType(VD->getType());
21349
21350 assert(E->isPRValue());
21351 if (S.getLangOpts().CPlusPlus &&
21352 !(isa<CXXMethodDecl>(VD) &&
21353 cast<CXXMethodDecl>(VD)->isInstance()))
21355
21356 return E;
21357 }
21358
21359 ExprResult VisitMemberExpr(MemberExpr *E) {
21360 return resolveDecl(E, E->getMemberDecl());
21361 }
21362
21363 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21364 return resolveDecl(E, E->getDecl());
21365 }
21366 };
21367}
21368
21369/// Given a function expression of unknown-any type, try to rebuild it
21370/// to have a function type.
21372 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21373 if (Result.isInvalid()) return ExprError();
21374 return S.DefaultFunctionArrayConversion(Result.get());
21375}
21376
21377namespace {
21378 /// A visitor for rebuilding an expression of type __unknown_anytype
21379 /// into one which resolves the type directly on the referring
21380 /// expression. Strict preservation of the original source
21381 /// structure is not a goal.
21382 struct RebuildUnknownAnyExpr
21383 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21384
21385 Sema &S;
21386
21387 /// The current destination type.
21388 QualType DestType;
21389
21390 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21391 : S(S), DestType(CastType) {}
21392
21393 ExprResult VisitStmt(Stmt *S) {
21394 llvm_unreachable("unexpected statement!");
21395 }
21396
21397 ExprResult VisitExpr(Expr *E) {
21398 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21399 << E->getSourceRange();
21400 return ExprError();
21401 }
21402
21403 ExprResult VisitCallExpr(CallExpr *E);
21404 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21405
21406 /// Rebuild an expression which simply semantically wraps another
21407 /// expression which it shares the type and value kind of.
21408 template <class T> ExprResult rebuildSugarExpr(T *E) {
21409 ExprResult SubResult = Visit(E->getSubExpr());
21410 if (SubResult.isInvalid()) return ExprError();
21411 Expr *SubExpr = SubResult.get();
21412 E->setSubExpr(SubExpr);
21413 E->setType(SubExpr->getType());
21414 E->setValueKind(SubExpr->getValueKind());
21415 assert(E->getObjectKind() == OK_Ordinary);
21416 return E;
21417 }
21418
21419 ExprResult VisitParenExpr(ParenExpr *E) {
21420 return rebuildSugarExpr(E);
21421 }
21422
21423 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21424 return rebuildSugarExpr(E);
21425 }
21426
21427 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21428 const PointerType *Ptr = DestType->getAs<PointerType>();
21429 if (!Ptr) {
21430 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21431 << E->getSourceRange();
21432 return ExprError();
21433 }
21434
21435 if (isa<CallExpr>(E->getSubExpr())) {
21436 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21437 << E->getSourceRange();
21438 return ExprError();
21439 }
21440
21441 assert(E->isPRValue());
21442 assert(E->getObjectKind() == OK_Ordinary);
21443 E->setType(DestType);
21444
21445 // Build the sub-expression as if it were an object of the pointee type.
21446 DestType = Ptr->getPointeeType();
21447 ExprResult SubResult = Visit(E->getSubExpr());
21448 if (SubResult.isInvalid()) return ExprError();
21449 E->setSubExpr(SubResult.get());
21450 return E;
21451 }
21452
21453 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21454
21455 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21456
21457 ExprResult VisitMemberExpr(MemberExpr *E) {
21458 return resolveDecl(E, E->getMemberDecl());
21459 }
21460
21461 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21462 return resolveDecl(E, E->getDecl());
21463 }
21464 };
21465}
21466
21467/// Rebuilds a call expression which yielded __unknown_anytype.
21468ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21469 Expr *CalleeExpr = E->getCallee();
21470
21471 enum FnKind {
21472 FK_MemberFunction,
21473 FK_FunctionPointer,
21474 FK_BlockPointer
21475 };
21476
21477 FnKind Kind;
21478 QualType CalleeType = CalleeExpr->getType();
21479 if (CalleeType == S.Context.BoundMemberTy) {
21481 Kind = FK_MemberFunction;
21482 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21483 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21484 CalleeType = Ptr->getPointeeType();
21485 Kind = FK_FunctionPointer;
21486 } else {
21487 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21488 Kind = FK_BlockPointer;
21489 }
21490 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21491
21492 // Verify that this is a legal result type of a function.
21493 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21494 DestType->isFunctionType()) {
21495 unsigned diagID = diag::err_func_returning_array_function;
21496 if (Kind == FK_BlockPointer)
21497 diagID = diag::err_block_returning_array_function;
21498
21499 S.Diag(E->getExprLoc(), diagID)
21500 << DestType->isFunctionType() << DestType;
21501 return ExprError();
21502 }
21503
21504 // Otherwise, go ahead and set DestType as the call's result.
21505 E->setType(DestType.getNonLValueExprType(S.Context));
21507 assert(E->getObjectKind() == OK_Ordinary);
21508
21509 // Rebuild the function type, replacing the result type with DestType.
21510 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21511 if (Proto) {
21512 // __unknown_anytype(...) is a special case used by the debugger when
21513 // it has no idea what a function's signature is.
21514 //
21515 // We want to build this call essentially under the K&R
21516 // unprototyped rules, but making a FunctionNoProtoType in C++
21517 // would foul up all sorts of assumptions. However, we cannot
21518 // simply pass all arguments as variadic arguments, nor can we
21519 // portably just call the function under a non-variadic type; see
21520 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21521 // However, it turns out that in practice it is generally safe to
21522 // call a function declared as "A foo(B,C,D);" under the prototype
21523 // "A foo(B,C,D,...);". The only known exception is with the
21524 // Windows ABI, where any variadic function is implicitly cdecl
21525 // regardless of its normal CC. Therefore we change the parameter
21526 // types to match the types of the arguments.
21527 //
21528 // This is a hack, but it is far superior to moving the
21529 // corresponding target-specific code from IR-gen to Sema/AST.
21530
21531 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21532 SmallVector<QualType, 8> ArgTypes;
21533 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21534 ArgTypes.reserve(E->getNumArgs());
21535 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21536 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21537 }
21538 ParamTypes = ArgTypes;
21539 }
21540 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21541 Proto->getExtProtoInfo());
21542 } else {
21543 DestType = S.Context.getFunctionNoProtoType(DestType,
21544 FnType->getExtInfo());
21545 }
21546
21547 // Rebuild the appropriate pointer-to-function type.
21548 switch (Kind) {
21549 case FK_MemberFunction:
21550 // Nothing to do.
21551 break;
21552
21553 case FK_FunctionPointer:
21554 DestType = S.Context.getPointerType(DestType);
21555 break;
21556
21557 case FK_BlockPointer:
21558 DestType = S.Context.getBlockPointerType(DestType);
21559 break;
21560 }
21561
21562 // Finally, we can recurse.
21563 ExprResult CalleeResult = Visit(CalleeExpr);
21564 if (!CalleeResult.isUsable()) return ExprError();
21565 E->setCallee(CalleeResult.get());
21566
21567 // Bind a temporary if necessary.
21568 return S.MaybeBindToTemporary(E);
21569}
21570
21571ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21572 // Verify that this is a legal result type of a call.
21573 if (DestType->isArrayType() || DestType->isFunctionType()) {
21574 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21575 << DestType->isFunctionType() << DestType;
21576 return ExprError();
21577 }
21578
21579 // Rewrite the method result type if available.
21580 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21581 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21582 Method->setReturnType(DestType);
21583 }
21584
21585 // Change the type of the message.
21586 E->setType(DestType.getNonReferenceType());
21588
21589 return S.MaybeBindToTemporary(E);
21590}
21591
21592ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21593 // The only case we should ever see here is a function-to-pointer decay.
21594 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21595 assert(E->isPRValue());
21596 assert(E->getObjectKind() == OK_Ordinary);
21597
21598 E->setType(DestType);
21599
21600 // Rebuild the sub-expression as the pointee (function) type.
21601 DestType = DestType->castAs<PointerType>()->getPointeeType();
21602
21603 ExprResult Result = Visit(E->getSubExpr());
21604 if (!Result.isUsable()) return ExprError();
21605
21606 E->setSubExpr(Result.get());
21607 return E;
21608 } else if (E->getCastKind() == CK_LValueToRValue) {
21609 assert(E->isPRValue());
21610 assert(E->getObjectKind() == OK_Ordinary);
21611
21612 assert(isa<BlockPointerType>(E->getType()));
21613
21614 E->setType(DestType);
21615
21616 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21617 DestType = S.Context.getLValueReferenceType(DestType);
21618
21619 ExprResult Result = Visit(E->getSubExpr());
21620 if (!Result.isUsable()) return ExprError();
21621
21622 E->setSubExpr(Result.get());
21623 return E;
21624 } else {
21625 llvm_unreachable("Unhandled cast type!");
21626 }
21627}
21628
21629ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21630 ExprValueKind ValueKind = VK_LValue;
21631 QualType Type = DestType;
21632
21633 // We know how to make this work for certain kinds of decls:
21634
21635 // - functions
21636 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21637 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21638 DestType = Ptr->getPointeeType();
21639 ExprResult Result = resolveDecl(E, VD);
21640 if (Result.isInvalid()) return ExprError();
21641 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21642 VK_PRValue);
21643 }
21644
21645 if (!Type->isFunctionType()) {
21646 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21647 << VD << E->getSourceRange();
21648 return ExprError();
21649 }
21650 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21651 // We must match the FunctionDecl's type to the hack introduced in
21652 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21653 // type. See the lengthy commentary in that routine.
21654 QualType FDT = FD->getType();
21655 const FunctionType *FnType = FDT->castAs<FunctionType>();
21656 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21657 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21658 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21659 SourceLocation Loc = FD->getLocation();
21660 FunctionDecl *NewFD = FunctionDecl::Create(
21661 S.Context, FD->getDeclContext(), Loc, Loc,
21662 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21664 false /*isInlineSpecified*/, FD->hasPrototype(),
21665 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21666
21667 if (FD->getQualifier())
21668 NewFD->setQualifierInfo(FD->getQualifierLoc());
21669
21670 SmallVector<ParmVarDecl*, 16> Params;
21671 for (const auto &AI : FT->param_types()) {
21672 ParmVarDecl *Param =
21673 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21674 Param->setScopeInfo(0, Params.size());
21675 Params.push_back(Param);
21676 }
21677 NewFD->setParams(Params);
21678 DRE->setDecl(NewFD);
21679 VD = DRE->getDecl();
21680 }
21681 }
21682
21683 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21684 if (MD->isInstance()) {
21685 ValueKind = VK_PRValue;
21687 }
21688
21689 // Function references aren't l-values in C.
21690 if (!S.getLangOpts().CPlusPlus)
21691 ValueKind = VK_PRValue;
21692
21693 // - variables
21694 } else if (isa<VarDecl>(VD)) {
21695 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21696 Type = RefTy->getPointeeType();
21697 } else if (Type->isFunctionType()) {
21698 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21699 << VD << E->getSourceRange();
21700 return ExprError();
21701 }
21702
21703 // - nothing else
21704 } else {
21705 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21706 << VD << E->getSourceRange();
21707 return ExprError();
21708 }
21709
21710 // Modifying the declaration like this is friendly to IR-gen but
21711 // also really dangerous.
21712 VD->setType(DestType);
21713 E->setType(Type);
21714 E->setValueKind(ValueKind);
21715 return E;
21716}
21717
21720 ExprValueKind &VK, CXXCastPath &Path) {
21721 // The type we're casting to must be either void or complete.
21722 if (!CastType->isVoidType() &&
21724 diag::err_typecheck_cast_to_incomplete))
21725 return ExprError();
21726
21727 // Rewrite the casted expression from scratch.
21728 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21729 if (!result.isUsable()) return ExprError();
21730
21731 CastExpr = result.get();
21733 CastKind = CK_NoOp;
21734
21735 return CastExpr;
21736}
21737
21739 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21740}
21741
21743 Expr *arg, QualType &paramType) {
21744 // If the syntactic form of the argument is not an explicit cast of
21745 // any sort, just do default argument promotion.
21746 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21747 if (!castArg) {
21749 if (result.isInvalid()) return ExprError();
21750 paramType = result.get()->getType();
21751 return result;
21752 }
21753
21754 // Otherwise, use the type that was written in the explicit cast.
21755 assert(!arg->hasPlaceholderType());
21756 paramType = castArg->getTypeAsWritten();
21757
21758 // Copy-initialize a parameter of that type.
21759 InitializedEntity entity =
21761 /*consumed*/ false);
21762 return PerformCopyInitialization(entity, callLoc, arg);
21763}
21764
21766 Expr *orig = E;
21767 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21768 while (true) {
21769 E = E->IgnoreParenImpCasts();
21770 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21771 E = call->getCallee();
21772 diagID = diag::err_uncasted_call_of_unknown_any;
21773 } else {
21774 break;
21775 }
21776 }
21777
21778 SourceLocation loc;
21779 NamedDecl *d;
21780 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21781 loc = ref->getLocation();
21782 d = ref->getDecl();
21783 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21784 loc = mem->getMemberLoc();
21785 d = mem->getMemberDecl();
21786 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21787 diagID = diag::err_uncasted_call_of_unknown_any;
21788 loc = msg->getSelectorStartLoc();
21789 d = msg->getMethodDecl();
21790 if (!d) {
21791 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21792 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21793 << orig->getSourceRange();
21794 return ExprError();
21795 }
21796 } else {
21797 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21798 << E->getSourceRange();
21799 return ExprError();
21800 }
21801
21802 S.Diag(loc, diagID) << d << orig->getSourceRange();
21803
21804 // Never recoverable.
21805 return ExprError();
21806}
21807
21809 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21810 if (!placeholderType) return E;
21811
21812 switch (placeholderType->getKind()) {
21813 case BuiltinType::UnresolvedTemplate: {
21814 auto *ULE = cast<UnresolvedLookupExpr>(E->IgnoreParens());
21815 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21816 // There's only one FoundDecl for UnresolvedTemplate type. See
21817 // BuildTemplateIdExpr.
21818 NamedDecl *Temp = *ULE->decls_begin();
21819 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21820
21821 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21822 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21823 // as it models only the unqualified-id case, where this case can clearly be
21824 // qualified. Thus we can't just qualify an assumed template.
21825 TemplateName TN;
21826 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21827 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21828 TemplateName(TD));
21829 else
21830 TN = Context.getAssumedTemplateName(NameInfo.getName());
21831
21832 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21833 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21834 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21835 << IsTypeAliasTemplateDecl;
21836
21837 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21838 bool HasAnyDependentTA = false;
21839 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21840 HasAnyDependentTA |= Arg.getArgument().isDependent();
21841 TAL.addArgument(Arg);
21842 }
21843
21844 QualType TST;
21845 {
21846 SFINAETrap Trap(*this);
21847 TST = CheckTemplateIdType(
21848 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
21849 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21850 }
21851 if (TST.isNull())
21852 TST = Context.getTemplateSpecializationType(
21853 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21854 /*CanonicalArgs=*/{},
21855 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21856 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21857 TST);
21858 }
21859
21860 // Overloaded expressions.
21861 case BuiltinType::Overload: {
21862 // Try to resolve a single function template specialization.
21863 // This is obligatory.
21864 ExprResult Result = E;
21866 return Result;
21867
21868 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21869 // leaves Result unchanged on failure.
21870 Result = E;
21872 return Result;
21873
21874 // If that failed, try to recover with a call.
21875 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21876 /*complain*/ true);
21877 return Result;
21878 }
21879
21880 // Bound member functions.
21881 case BuiltinType::BoundMember: {
21882 ExprResult result = E;
21883 const Expr *BME = E->IgnoreParens();
21884 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21885 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21887 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21888 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21889 if (ME->getMemberNameInfo().getName().getNameKind() ==
21891 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21892 }
21893 tryToRecoverWithCall(result, PD,
21894 /*complain*/ true);
21895 return result;
21896 }
21897
21898 // ARC unbridged casts.
21899 case BuiltinType::ARCUnbridgedCast: {
21900 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21901 ObjC().diagnoseARCUnbridgedCast(realCast);
21902 return realCast;
21903 }
21904
21905 // Expressions of unknown type.
21906 case BuiltinType::UnknownAny:
21907 return diagnoseUnknownAnyExpr(*this, E);
21908
21909 // Pseudo-objects.
21910 case BuiltinType::PseudoObject:
21911 return PseudoObject().checkRValue(E);
21912
21913 case BuiltinType::BuiltinFn: {
21914 // Accept __noop without parens by implicitly converting it to a call expr.
21915 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21916 if (DRE) {
21917 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21918 unsigned BuiltinID = FD->getBuiltinID();
21919 if (BuiltinID == Builtin::BI__noop) {
21920 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21921 CK_BuiltinFnToFnPtr)
21922 .get();
21923 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21926 }
21927
21928 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21929 // Any use of these other than a direct call is ill-formed as of C++20,
21930 // because they are not addressable functions. In earlier language
21931 // modes, warn and force an instantiation of the real body.
21932 Diag(E->getBeginLoc(),
21934 ? diag::err_use_of_unaddressable_function
21935 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21936 if (FD->isImplicitlyInstantiable()) {
21937 // Require a definition here because a normal attempt at
21938 // instantiation for a builtin will be ignored, and we won't try
21939 // again later. We assume that the definition of the template
21940 // precedes this use.
21942 /*Recursive=*/false,
21943 /*DefinitionRequired=*/true,
21944 /*AtEndOfTU=*/false);
21945 }
21946 // Produce a properly-typed reference to the function.
21947 CXXScopeSpec SS;
21948 SS.Adopt(DRE->getQualifierLoc());
21949 TemplateArgumentListInfo TemplateArgs;
21950 DRE->copyTemplateArgumentsInto(TemplateArgs);
21951 return BuildDeclRefExpr(
21952 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21953 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21954 DRE->getTemplateKeywordLoc(),
21955 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21956 }
21957 }
21958
21959 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21960 return ExprError();
21961 }
21962
21963 case BuiltinType::IncompleteMatrixIdx: {
21964 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
21965 // At this point, we know there was no second [] to complete the operator.
21966 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
21967 if (getLangOpts().HLSL) {
21969 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
21970 }
21971 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
21972 return ExprError();
21973 }
21974
21975 // Expressions of unknown type.
21976 case BuiltinType::ArraySection:
21977 // If we've already diagnosed something on the array section type, we
21978 // shouldn't need to do any further diagnostic here.
21979 if (!E->containsErrors())
21980 Diag(E->getBeginLoc(), diag::err_array_section_use)
21981 << cast<ArraySectionExpr>(E->IgnoreParens())->isOMPArraySection();
21982 return ExprError();
21983
21984 // Expressions of unknown type.
21985 case BuiltinType::OMPArrayShaping:
21986 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21987
21988 case BuiltinType::OMPIterator:
21989 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21990
21991 // Everything else should be impossible.
21992#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21993 case BuiltinType::Id:
21994#include "clang/Basic/OpenCLImageTypes.def"
21995#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21996 case BuiltinType::Id:
21997#include "clang/Basic/OpenCLExtensionTypes.def"
21998#define SVE_TYPE(Name, Id, SingletonId) \
21999 case BuiltinType::Id:
22000#include "clang/Basic/AArch64ACLETypes.def"
22001#define PPC_VECTOR_TYPE(Name, Id, Size) \
22002 case BuiltinType::Id:
22003#include "clang/Basic/PPCTypes.def"
22004#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22005#include "clang/Basic/RISCVVTypes.def"
22006#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22007#include "clang/Basic/WebAssemblyReferenceTypes.def"
22008#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22009#include "clang/Basic/AMDGPUTypes.def"
22010#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22011#include "clang/Basic/HLSLIntangibleTypes.def"
22012#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22013#define PLACEHOLDER_TYPE(Id, SingletonId)
22014#include "clang/AST/BuiltinTypes.def"
22015 break;
22016 }
22017
22018 llvm_unreachable("invalid placeholder type!");
22019}
22020
22022 if (E->isTypeDependent())
22023 return true;
22025 return E->getType()->isIntegralOrEnumerationType();
22026 return false;
22027}
22028
22030 ArrayRef<Expr *> SubExprs, QualType T) {
22031 if (!Context.getLangOpts().RecoveryAST)
22032 return ExprError();
22033
22034 if (isSFINAEContext())
22035 return ExprError();
22036
22037 if (T.isNull() || T->isUndeducedType() ||
22038 !Context.getLangOpts().RecoveryASTType)
22039 // We don't know the concrete type, fallback to dependent type.
22040 T = Context.DependentTy;
22041
22042 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
22043}
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:228
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:810
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:806
const LangOptions & getLangOpts() const
Definition ASTContext.h:960
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:928
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:925
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:1074
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:319
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:410
bool Contains(const Scope &rhs) const
Returns if rhs has a higher scope depth than this.
Definition Scope.h:619
bool isInCFunctionScope() const
isInObjcMethodScope - Return true if this scope is, or is contained, in an C function body.
Definition Scope.h:430
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:469
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)
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr)
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr)
const DeclContext * getCurObjCLexicalContext() const
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
void diagnoseARCUnbridgedCast(Expr *e)
Given that we saw an expression with the ARCUnbridgedCastTy placeholder type, complain bitterly.
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD, bool IsReinterpretCast=false)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod)
Build an ObjC subscript pseudo-object expression, given that that's supported by the runtime.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void CheckDeclReference(SourceLocation Loc, Expr *E, Decl *D)
ExprResult ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, Expr *Length, SourceLocation RBLoc)
Checks and creates an Array Section used in an OpenACC construct/clause.
ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig)
Given the potential call expression Call, determine if there is a specialization via the OpenMP decla...
void tryCaptureOpenMPLambdas(ValueDecl *V)
Function tries to capture lambda's captured variables in the OpenMP region before the original lambda...
OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const
Check if the specified variable is used in 'private' clause.
VarDecl * isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo=false, unsigned StopAt=0)
Check if the specified variable is used in one of the private clauses (private, firstprivate,...
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc)
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const
Return true if the provided declaration VD should be captured by reference.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified variable is captured by 'target' directive.
bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified global variable must be captured by outer capture regions.
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition SemaOpenMP.h:378
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
const ValueDecl * getOpenMPDeclareMapperVarName() const
ExprResult checkAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
ExprResult checkIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
ExprResult checkRValue(Expr *E)
void CheckDeviceUseOfDecl(NamedDecl *ND, SourceLocation Loc)
Issues a deferred diagnostic if use of the declaration designated by 'ND' is invalid in a device cont...
Definition SemaSYCL.cpp:224
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8534
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12549
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12593
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7803
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1448
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
ExprResult ActOnCXXParenListInitExpr(ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8287
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13686
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1141
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8337
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8255
bool isExternalWithNoLinkageType(const ValueDecl *VD) const
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
Definition Sema.cpp:955
bool isAttrContext() const
Definition Sema.h:7034
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression's result is syntactically ignored,...
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8330
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9417
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9456
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9425
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:416
ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx, SourceLocation RBLoc)
ExprResult ActOnConstantExpression(ExprResult Res)
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool areVectorTypesSameSize(QualType srcType, QualType destType)
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition Sema.h:1533
void ActOnStartStmtExpr()
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
void ActOnStmtExprError()
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt={})
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
bool BoundsSafetyCheckAssignmentToCountAttrPtr(QualType LHSTy, Expr *RHSExpr, AssignmentAction Action, SourceLocation Loc, const ValueDecl *Assignee, bool ShowFullyQualifiedAssigneeName)
Perform Bounds Safety Semantic checks for assigning to a __counted_by or __counted_by_or_null pointer...
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition Sema.h:1251
SemaCUDA & CUDA()
Definition Sema.h:1473
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7924
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7926
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7925
bool needsRebuildOfDefaultArgOrInit() const
Definition Sema.h:8275
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicCallType::DoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition Sema.h:8417
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1244
Preprocessor & getPreprocessor() const
Definition Sema.h:938
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7012
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2400
QualType GetSignedSizelessVectorType(QualType V)
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
llvm::SmallPtrSet< ConstantExpr *, 4 > FailedImmediateInvocations
Definition Sema.h:8406
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition Sema.h:8318
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
llvm::SmallSetVector< Expr *, 4 > MaybeODRUseExprSet
Store a set of either DeclRefExprs or MemberExprs that contain a reference to a variable (constant) t...
Definition Sema.h:6841
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit=nullptr)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal,...
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2077
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types?
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
SemaSYCL & SYCL()
Definition Sema.h:1558
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:7024
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1725
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc)
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:838
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Look for instances where it is likely the comma operator is confused with another operator.
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
ASTContext & Context
Definition Sema.h:1308
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition Sema.h:8242
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E)
Perform Bounds Safety semantic checks for uses of invalid uses counted_by or counted_by_or_null point...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool CheckCaseExpression(Expr *E)
SemaObjC & ObjC()
Definition Sema.h:1518
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition Sema.cpp:2910
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void CleanupVarDeclMarking()
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:759
bool isImmediateFunctionContext() const
Definition Sema.h:8267
ASTContext & getASTContext() const
Definition Sema.h:939
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1081
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:769
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
void PopExpressionEvaluationContext()
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition SemaExpr.cpp:888
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Sema.h:6159
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6161
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1730
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< TypeSourceInfo * > Types, ArrayRef< Expr * > Exprs)
ControllingExprOrType is either a TypeSourceInfo * or an Expr *.
AssumedTemplateKind
Definition Sema.h:11511
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
SourceRange getExprRange(Expr *E) const
Definition SemaExpr.cpp:511
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
std::optional< ExpressionEvaluationContextRecord::InitializationContext > OutermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8302
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition SemaStmt.cpp:405
FPOptions & getCurFPFeatures()
Definition Sema.h:934
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8400
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_Block
Block expression.
Definition Sema.h:14566
const LangOptions & getLangOpts() const
Definition Sema.h:932
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void DiagnoseInvalidJumps(Stmt *Body)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2531
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
SemaOpenACC & OpenACC()
Definition Sema.h:1523
ReuseLambdaContextDecl_t
Definition Sema.h:7103
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false)
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
Preprocessor & PP
Definition Sema.h:1307
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2209
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1306
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2646
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:957
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6585
SemaHLSL & HLSL()
Definition Sema.h:1483
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:15797
ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr)
Prepare SplattedExpr for a matrix splat operation, adding implicit casts if necessary.
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:215
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5321
ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc, TypeSourceInfo *TSI)
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:77
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Diagnose cases where a scalar was implicitly converted to a vector and diagnose the underlying types.
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7048
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6615
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
SmallVector< std::deque< PendingImplicitInstantiation >, 8 > SavedPendingInstantiations
Definition Sema.h:14108
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition Sema.cpp:869
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1341
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData, StringRef FileName)
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr)
DiagnoseAssignmentEnum - Warn if assignment to enum is a constant integer not in the range of enum va...
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:7045
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2383
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:644
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8271
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
ControllingExprOrType is either an opaque pointer coming out of a ParsedType or an Expr *.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8138
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2601
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition Sema.h:12620
SemaOpenCL & OpenCL()
Definition Sema.h:1528
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:14117
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8263
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1705
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr, bool ForTypeDeduction=false)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition Sema.h:6844
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
ExprResult TransformToPotentiallyEvaluated(Expr *E)
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14052
SourceManager & getSourceManager() const
Definition Sema.h:937
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
bool CheckVecStepExpr(Expr *E)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks, ObjCInterfaceDecl *ClassReceiver)
CallExpr::ADLCallKind ADLCallKind
Definition Sema.h:7557
@ NTCUK_Destruct
Definition Sema.h:4139
@ NTCUK_Copy
Definition Sema.h:4140
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8416
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
bool anyAltivecTypes(QualType srcType, QualType destType)
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition Sema.cpp:2431
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
MaybeODRUseExprSet MaybeODRUseExprs
Definition Sema.h:6842
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool isSFINAEContext() const
Definition Sema.h:13785
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15569
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2586
bool isConstantEvaluatedContext() const
Definition Sema.h:2639
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
ASTConsumer & Consumer
Definition Sema.h:1309
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4698
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:7052
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:125
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1346
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14100
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition Sema.h:6786
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6808
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6798
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6813
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6803
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6823
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6792
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6818
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6833
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Parse a __builtin_astype expression.
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1267
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition Sema.h:8253
void DiscardCleanupsInEvaluationContext()
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8403
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
SourceManager & SourceMgr
Definition Sema.h:1311
@ TemplateNameIsRequired
Definition Sema.h:11488
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:788
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1310
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:933
FPOptions CurFPFeatures
Definition Sema.h:1304
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:520
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types?
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc, bool IsExplicit)
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
friend class InitializationSequence
Definition Sema.h:1588
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void PopDeclContext()
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6619
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:631
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
ExprResult ActOnStmtExprResult(ExprResult E)
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2192
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
QualType PreferredConditionType(ConditionKind K) const
Definition Sema.h:8061
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9470
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9476
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9468
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9473
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9484
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9480
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6500
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:14096
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
static ConditionResult ConditionError()
Definition Sema.h:7910
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that's being passed to an __unknown_anytype parameter.
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
SemaPseudoObject & PseudoObject()
Definition Sema.h:1543
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2577
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
bool isCheckingDefaultArgumentOrInitializer() const
Definition Sema.h:8279
SemaARM & ARM()
Definition Sema.h:1453
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
SmallVector< std::pair< Scope *, SourceLocation >, 2 > CurrentDefer
Stack of '_Defer' statements that are currently being parsed, as well as the locations of their '_Def...
Definition Sema.h:11058
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8745
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition Expr.h:5020
SourceLocation getBeginLoc() const
Definition Expr.h:5065
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition Expr.h:5061
SourceLocation getEndLoc() const
Definition Expr.h:5066
SourceLocIdentKind getIdentKind() const
Definition Expr.h:5040
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4598
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
StmtClass getStmtClass() const
Definition Stmt.h:1503
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
unsigned getLength() const
Definition Expr.h:1912
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1193
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1885
StringRef getString() const
Definition Expr.h:1870
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3836
bool isUnion() const
Definition Decl.h:3946
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Exposes information about the current target.
Definition TargetInfo.h:227
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition TargetInfo.h:736
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:336
virtual bool useFP16ConversionIntrinsics() const
Check whether conversions to and from __fp16 should go through an integer bitcast with i16.
bool shouldUseMicrosoftCCforMangling() const
Should the Microsoft mangling scheme be used for C Calling Convention.
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
Location wrapper for a TemplateArgument.
Represents a template argument.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Represents a C++ template name within the type system.
A template parameter object.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
void setKind(tok::TokenKind K)
Definition Token.h:100
void startToken()
Reset all flags to cleared.
Definition Token.h:187
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
EnsureImmediateInvocationInDefaultArgs & getDerived()
Represents a declaration of a type.
Definition Decl.h:3531
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3565
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:160
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8416
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8427
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2545
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition TypeBase.h:9116
bool isBlockPointerType() const
Definition TypeBase.h:8702
bool isVoidType() const
Definition TypeBase.h:9048
bool isBooleanType() const
Definition TypeBase.h:9185
bool isObjCBuiltinType() const
Definition TypeBase.h:8912
bool isMFloat8Type() const
Definition TypeBase.h:9073
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition Type.cpp:2000
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9235
bool isIncompleteArrayType() const
Definition TypeBase.h:8789
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition TypeBase.h:9024
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2173
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9215
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition Type.cpp:2119
bool isVoidPointerType() const
Definition Type.cpp:749
const ComplexType * getAsComplexIntegerType() const
Definition Type.cpp:782
bool isArrayType() const
Definition TypeBase.h:8781
bool isCharType() const
Definition Type.cpp:2193
bool isFunctionPointerType() const
Definition TypeBase.h:8749
bool isArithmeticType() const
Definition Type.cpp:2422
bool isConstantMatrixType() const
Definition TypeBase.h:8849
bool isPointerType() const
Definition TypeBase.h:8682
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9092
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2667
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9342
bool isReferenceType() const
Definition TypeBase.h:8706
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9136
bool isEnumeralType() const
Definition TypeBase.h:8813
bool isScalarType() const
Definition TypeBase.h:9154
bool isVariableArrayType() const
Definition TypeBase.h:8793
bool isSizelessBuiltinType() const
Definition Type.cpp:2623
bool isClkEventT() const
Definition TypeBase.h:8934
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2701
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2156
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8882
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9170
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2376
bool isExtVectorType() const
Definition TypeBase.h:8825
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2229
bool isExtVectorBoolType() const
Definition TypeBase.h:8829
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2740
bool isImageType() const
Definition TypeBase.h:8946
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition TypeBase.h:9042
bool isPipeType() const
Definition TypeBase.h:8953
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2852
bool isBitIntType() const
Definition TypeBase.h:8957
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9017
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8805
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2844
bool isAnyComplexType() const
Definition TypeBase.h:8817
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9108
bool isHalfType() const
Definition TypeBase.h:9052
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9124
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2465
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2454
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9030
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2310
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2651
bool isQueueT() const
Definition TypeBase.h:8938
bool isMemberPointerType() const
Definition TypeBase.h:8763
bool isAtomicType() const
Definition TypeBase.h:8874
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9198
bool isObjCIdType() const
Definition TypeBase.h:8894
bool isMatrixType() const
Definition TypeBase.h:8845
bool isOverflowBehaviorType() const
Definition TypeBase.h:8853
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2862
bool isComplexIntegerType() const
Definition Type.cpp:767
bool isUnscopedEnumerationType() const
Definition Type.cpp:2186
bool isObjCObjectType() const
Definition TypeBase.h:8865
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition Type.cpp:5347
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9328
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5436
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9191
bool isHLSLResourceRecord() const
Definition Type.cpp:5496
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isDoubleType() const
Definition TypeBase.h:9065
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2527
bool isFunctionType() const
Definition TypeBase.h:8678
bool isObjCObjectPointerType() const
Definition TypeBase.h:8861
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2397
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9150
bool isVectorType() const
Definition TypeBase.h:8821
bool isObjCQualifiedClassType() const
Definition TypeBase.h:8888
bool isObjCClassType() const
Definition TypeBase.h:8900
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2688
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2983
@ STK_FloatingComplex
Definition TypeBase.h:2826
@ STK_ObjCObjectPointer
Definition TypeBase.h:2820
@ STK_IntegralComplex
Definition TypeBase.h:2825
@ STK_MemberPointer
Definition TypeBase.h:2821
bool isFloatingType() const
Definition Type.cpp:2389
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2332
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2990
bool isAnyPointerType() const
Definition TypeBase.h:8690
bool isRealType() const
Definition Type.cpp:2411
TypeClass getTypeClass() const
Definition TypeBase.h:2445
bool isSubscriptableVectorType() const
Definition TypeBase.h:8841
bool isSamplerT() const
Definition TypeBase.h:8926
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9275
bool isNullPtrType() const
Definition TypeBase.h:9085
bool isRecordType() const
Definition TypeBase.h:8809
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5500
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition Type.cpp:772
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5148
bool isUnicodeCharacterType() const
Definition Type.cpp:2249
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2444
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
std::string getAsString(const LangOptions &LO) const
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2628
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
void setSubExpr(Expr *E)
Definition Expr.h:2289
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition Expr.h:2292
Expr * getSubExpr() const
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2283
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1435
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2343
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5159
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4460
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1035
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1123
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1117
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1087
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:437
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4126
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition ExprCXX.cpp:1690
bool isImplicitAccess() const
True if this is an implicit access, i.e., one in which the member being accessed was not written in t...
Definition ExprCXX.cpp:1652
A set of unresolved declarations.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:644
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:4960
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5576
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3687
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:924
bool hasInit() const
Definition Decl.cpp:2377
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2236
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1591
bool isInternalLinkageFileVar() const
Returns true if this is a file-scope variable with internal linkage.
Definition Decl.h:1214
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1296
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1239
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition Decl.cpp:2465
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition Decl.cpp:2886
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1564
const Expr * getInit() const
Definition Decl.h:1381
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1230
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1182
@ TLS_None
Not a TLS variable.
Definition Decl.h:944
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1308
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2354
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2507
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2779
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1275
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2758
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2877
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4028
Expr * getSizeExpr() const
Definition TypeBase.h:4042
Represents a GCC generic vector type.
Definition TypeBase.h:4237
unsigned getNumElements() const
Definition TypeBase.h:4252
VectorKind getVectorKind() const
Definition TypeBase.h:4257
QualType getElementType() const
Definition TypeBase.h:4251
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:794
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition ScopeInfo.h:800
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition ScopeInfo.h:804
ValueDecl * getVariable() const
Definition ScopeInfo.h:679
bool isBlockCapture() const
Definition ScopeInfo.h:660
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:690
void markUsed(bool IsODRUse)
Definition ScopeInfo.h:672
bool isInvalid() const
Definition ScopeInfo.h:665
bool isThisCapture() const
Definition ScopeInfo.h:653
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition ScopeInfo.h:699
bool isCopyCapture() const
Definition ScopeInfo.h:658
bool isNested() const
Definition ScopeInfo.h:663
Retains information about a captured region.
Definition ScopeInfo.h:820
unsigned short CapRegionKind
The kind of captured region.
Definition ScopeInfo.h:835
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:749
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:736
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:732
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:725
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:712
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition ScopeInfo.h:722
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:762
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition ScopeInfo.h:718
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:759
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:741
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition ScopeInfo.h:775
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
void recordUseOfWeak(const ExprT *E, bool IsRead=true)
Record that a weak object was accessed.
Definition ScopeInfo.h:1094
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
void addBlock(const BlockDecl *BD)
Definition ScopeInfo.h:497
llvm::SmallVector< AddrLabelExpr *, 4 > AddrLabels
The set of GNU address of label extension "&&label".
Definition ScopeInfo.h:246
bool HasOMPDeclareReductionCombiner
True if current scope is for OpenMP declare reduction combiner.
Definition ScopeInfo.h:135
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:888
bool lambdaCaptureShouldBeConst() const
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas.
Definition ScopeInfo.h:996
void addPotentialThisCapture(SourceLocation Loc)
Definition ScopeInfo.h:1002
llvm::SmallPtrSet< VarDecl *, 4 > CUDAPotentialODRUsedVars
Variables that are potentially ODR-used in CUDA/HIP.
Definition ScopeInfo.h:957
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:875
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:896
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:883
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:878
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:35
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition TokenKinds.h:93
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:213
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus26
@ CPlusPlus17
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ GVA_StrongExternal
Definition Linkage.h:76
VariadicCallType
Definition Sema.h:513
bool isTargetAddressSpace(LangAS AS)
CUDAFunctionTarget
Definition Cuda.h:63
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
TryCaptureKind
Definition Sema.h:653
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition Sema.h:661
@ BitwiseOp
A bitwise operation.
Definition Sema.h:665
@ Arithmetic
An arithmetic operation.
Definition Sema.h:663
@ Conditional
A conditional (?:) operator.
Definition Sema.h:669
@ CompAssign
A compound assignment expression.
Definition Sema.h:671
@ Comparison
A comparison.
Definition Sema.h:667
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:349
@ Nullable
Values of this type can be null.
Definition Specifiers.h:353
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:358
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:150
@ OK_VectorComponent
A vector component is an element or range of elements of a vector.
Definition Specifiers.h:158
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:162
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition Specifiers.h:155
@ OK_MatrixComponent
A matrix component is a single element or range of elements of a matrix.
Definition Specifiers.h:170
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1029
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1027
@ AS_none
Definition Specifiers.h:128
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ CR_OpenMP
@ SC_Extern
Definition Specifiers.h:252
@ SC_Register
Definition Specifiers.h:258
@ SC_None
Definition Specifiers.h:251
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
unsigned toTargetAddressSpace(LangAS AS)
ExprResult ExprEmpty()
Definition Ownership.h:272
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:787
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:704
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:759
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:749
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:776
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:763
@ CompatibleOBTDiscards
CompatibleOBTDiscards - Assignment discards overflow behavior.
Definition Sema.h:783
@ IncompatibleOBTKinds
IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType kinds, e....
Definition Sema.h:780
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:696
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:738
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:772
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:723
@ IncompatiblePointerDiscardsOverflowBehavior
IncompatiblePointerDiscardsOverflowBehavior - The assignment discards overflow behavior annotations b...
Definition Sema.h:743
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:700
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:708
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:755
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:717
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:767
bool isFunctionLocalStringLiteralMacro(tok::TokenKind K, const LangOptions &LO)
Return true if the token corresponds to a function local predefined macro, which expands to a string ...
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:564
@ AR_Unavailable
Definition DeclBase.h:76
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AllowFoldKind
Definition Sema.h:655
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
VarArgKind
Definition Sema.h:676
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
AssignmentAction
Definition Sema.h:216
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Concept_template
The name refers to a concept.
BuiltinCountedByRefKind
Definition Sema.h:521
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:152
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
StringLiteralKind
Definition Expr.h:1766
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_X86VectorCall
Definition Specifiers.h:284
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4207
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4216
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4201
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4204
@ Neon
is ARM Neon vector
Definition TypeBase.h:4210
@ Generic
not a target-specific vector type
Definition TypeBase.h:4198
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4222
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4225
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4219
U cast(CodeGen::Address addr)
Definition Address.h:327
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
SourceLocIdentKind
Definition Expr.h:5007
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5989
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition OpenMPKinds.h:28
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1763
PredefinedIdentKind
Definition Expr.h:1992
@ Implicit
An implicit conversion.
Definition Sema.h:440
OptionalUnsigned< NullabilityKind > NullabilityKindOrNone
Definition Specifiers.h:365
CharacterLiteralKind
Definition Expr.h:1606
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:60
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition Specifiers.h:174
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition Specifiers.h:184
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:178
@ NOUR_None
This is an odr-use.
Definition Specifiers.h:176
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition Specifiers.h:181
#define false
Definition stdbool.h:26
ExprResult TransformSourceLocExpr(SourceLocExpr *E)
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
ExprResult TransformBlockExpr(BlockExpr *E)
ExprResult TransformLambdaExpr(LambdaExpr *E)
bool VisitSourceLocExpr(SourceLocExpr *E) override
bool VisitCXXConstructExpr(CXXConstructExpr *E) override
bool VisitCallExpr(CallExpr *E) override
const ASTContext & Context
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override
bool VisitLambdaExpr(LambdaExpr *E) override
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override
ImmediateCallVisitor(const ASTContext &Ctx)
Represents an element in a path from a derived class to a base class.
The class facilities generation and storage of conversion FixIts.
OverloadFixItKind Kind
The type of fix applied.
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
Stores data related to a single embed directive.
Definition Expr.h:5096
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:636
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition Expr.h:620
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
Extra information about a function prototype.
Definition TypeBase.h:5454
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13214
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6848
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6883
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6934
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6868
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6888
llvm::SmallPtrSet< DeclRefExpr *, 4 > ReferenceToConsteval
Set of DeclRefExprs referencing a consteval function when used in a context not already known to be i...
Definition Sema.h:6896
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6892
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6902
enum clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext
SmallVector< LambdaExpr *, 2 > Lambdas
The lambdas that are present within this context, if it is indeed an unevaluated context.
Definition Sema.h:6863
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6910
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6853
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6850
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6857
Abstract class used to diagnose incomplete types.
Definition Sema.h:8344
Location information for a TemplateArgument.
TemplateNameKind Kind
The kind of template that Template refers to.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
Describes an entity that is being assigned.