clang 22.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/Attrs.inc"
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"
33#include "clang/AST/Type.h"
34#include "clang/AST/TypeLoc.h"
45#include "clang/Sema/DeclSpec.h"
50#include "clang/Sema/Lookup.h"
51#include "clang/Sema/Overload.h"
53#include "clang/Sema/Scope.h"
55#include "clang/Sema/SemaARM.h"
56#include "clang/Sema/SemaCUDA.h"
58#include "clang/Sema/SemaHLSL.h"
59#include "clang/Sema/SemaObjC.h"
62#include "clang/Sema/Template.h"
63#include "llvm/ADT/STLExtras.h"
64#include "llvm/ADT/StringExtras.h"
65#include "llvm/Support/ConvertUTF.h"
66#include "llvm/Support/SaveAndRestore.h"
67#include "llvm/Support/TimeProfiler.h"
68#include "llvm/Support/TypeSize.h"
69#include <limits>
70#include <optional>
71
72using namespace clang;
73using namespace sema;
74
75bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
76 // See if this is an auto-typed variable whose initializer we are parsing.
77 if (ParsingInitForAutoVars.count(D))
78 return false;
79
80 // See if this is a deleted function.
81 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
82 if (FD->isDeleted())
83 return false;
84
85 // If the function has a deduced return type, and we can't deduce it,
86 // then we can't use it either.
87 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
88 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
89 return false;
90
91 // See if this is an aligned allocation/deallocation function that is
92 // unavailable.
93 if (TreatUnavailableAsInvalid &&
95 return false;
96 }
97
98 // See if this function is unavailable.
99 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
100 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
101 return false;
102
104 return false;
105
106 return true;
107}
108
110 // Warn if this is used but marked unused.
111 if (const auto *A = D->getAttr<UnusedAttr>()) {
112 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
113 // should diagnose them.
114 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
115 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
116 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
117 if (DC && !DC->hasAttr<UnusedAttr>())
118 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
119 }
120 }
121}
122
124 assert(Decl && Decl->isDeleted());
125
126 if (Decl->isDefaulted()) {
127 // If the method was explicitly defaulted, point at that declaration.
128 if (!Decl->isImplicit())
129 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
130
131 // Try to diagnose why this special member function was implicitly
132 // deleted. This might fail, if that reason no longer applies.
134 return;
135 }
136
137 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
138 if (Ctor && Ctor->isInheritingConstructor())
140
141 Diag(Decl->getLocation(), diag::note_availability_specified_here)
142 << Decl << 1;
143}
144
145/// Determine whether a FunctionDecl was ever declared with an
146/// explicit storage class.
148 for (auto *I : D->redecls()) {
149 if (I->getStorageClass() != SC_None)
150 return true;
151 }
152 return false;
153}
154
155/// Check whether we're in an extern inline function and referring to a
156/// variable or function with internal linkage (C11 6.7.4p3).
157///
158/// This is only a warning because we used to silently accept this code, but
159/// in many cases it will not behave correctly. This is not enabled in C++ mode
160/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
161/// and so while there may still be user mistakes, most of the time we can't
162/// prove that there are errors.
164 const NamedDecl *D,
165 SourceLocation Loc) {
166 // This is disabled under C++; there are too many ways for this to fire in
167 // contexts where the warning is a false positive, or where it is technically
168 // correct but benign.
169 if (S.getLangOpts().CPlusPlus)
170 return;
171
172 // Check if this is an inlined function or method.
173 FunctionDecl *Current = S.getCurFunctionDecl();
174 if (!Current)
175 return;
176 if (!Current->isInlined())
177 return;
178 if (!Current->isExternallyVisible())
179 return;
180
181 // Check if the decl has internal linkage.
183 return;
184
185 // Downgrade from ExtWarn to Extension if
186 // (1) the supposedly external inline function is in the main file,
187 // and probably won't be included anywhere else.
188 // (2) the thing we're referencing is a pure function.
189 // (3) the thing we're referencing is another inline function.
190 // This last can give us false negatives, but it's better than warning on
191 // wrappers for simple C library functions.
192 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
193 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
194 if (!DowngradeWarning && UsedFn)
195 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
196
197 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
198 : diag::ext_internal_in_extern_inline)
199 << /*IsVar=*/!UsedFn << D;
200
202
203 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
204 << D;
205}
206
208 const FunctionDecl *First = Cur->getFirstDecl();
209
210 // Suggest "static" on the function, if possible.
212 SourceLocation DeclBegin = First->getSourceRange().getBegin();
213 Diag(DeclBegin, diag::note_convert_inline_to_static)
214 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
215 }
216}
217
219 const ObjCInterfaceDecl *UnknownObjCClass,
220 bool ObjCPropertyAccess,
221 bool AvoidPartialAvailabilityChecks,
222 ObjCInterfaceDecl *ClassReceiver,
223 bool SkipTrailingRequiresClause) {
224 SourceLocation Loc = Locs.front();
226 // If there were any diagnostics suppressed by template argument deduction,
227 // emit them now.
228 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
229 if (Pos != SuppressedDiagnostics.end()) {
230 for (const auto &[DiagLoc, PD] : Pos->second) {
231 DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID()));
232 PD.Emit(Builder);
233 }
234 // Clear out the list of suppressed diagnostics, so that we don't emit
235 // them again for this specialization. However, we don't obsolete this
236 // entry from the table, because we want to avoid ever emitting these
237 // diagnostics again.
238 Pos->second.clear();
239 }
240
241 // C++ [basic.start.main]p3:
242 // The function 'main' shall not be used within a program.
243 if (cast<FunctionDecl>(D)->isMain())
244 Diag(Loc, diag::ext_main_used);
245
247 }
248
249 // See if this is an auto-typed variable whose initializer we are parsing.
250 if (ParsingInitForAutoVars.count(D)) {
251 if (isa<BindingDecl>(D)) {
252 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
253 << D->getDeclName();
254 } else {
255 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
256 << diag::ParsingInitFor::Var << D->getDeclName()
257 << cast<VarDecl>(D)->getType();
258 }
259 return true;
260 }
261
262 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
263 // See if this is a deleted function.
264 if (FD->isDeleted()) {
265 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
266 if (Ctor && Ctor->isInheritingConstructor())
267 Diag(Loc, diag::err_deleted_inherited_ctor_use)
268 << Ctor->getParent()
269 << Ctor->getInheritedConstructor().getConstructor()->getParent();
270 else {
271 StringLiteral *Msg = FD->getDeletedMessage();
272 Diag(Loc, diag::err_deleted_function_use)
273 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
274 }
276 return true;
277 }
278
279 // [expr.prim.id]p4
280 // A program that refers explicitly or implicitly to a function with a
281 // trailing requires-clause whose constraint-expression is not satisfied,
282 // other than to declare it, is ill-formed. [...]
283 //
284 // See if this is a function with constraints that need to be satisfied.
285 // Check this before deducing the return type, as it might instantiate the
286 // definition.
287 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
288 ConstraintSatisfaction Satisfaction;
289 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
290 /*ForOverloadResolution*/ true))
291 // A diagnostic will have already been generated (non-constant
292 // constraint expression, for example)
293 return true;
294 if (!Satisfaction.IsSatisfied) {
295 Diag(Loc,
296 diag::err_reference_to_function_with_unsatisfied_constraints)
297 << D;
298 DiagnoseUnsatisfiedConstraint(Satisfaction);
299 return true;
300 }
301 }
302
303 // If the function has a deduced return type, and we can't deduce it,
304 // then we can't use it either.
305 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
306 DeduceReturnType(FD, Loc))
307 return true;
308
309 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
310 return true;
311
312 }
313
314 if (auto *Concept = dyn_cast<ConceptDecl>(D);
316 return true;
317
318 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
319 // Lambdas are only default-constructible or assignable in C++2a onwards.
320 if (MD->getParent()->isLambda() &&
322 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
323 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
324 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
326 }
327 }
328
329 auto getReferencedObjCProp = [](const NamedDecl *D) ->
330 const ObjCPropertyDecl * {
331 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
332 return MD->findPropertyDecl();
333 return nullptr;
334 };
335 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
336 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
337 return true;
338 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
339 return true;
340 }
341
342 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
343 // Only the variables omp_in and omp_out are allowed in the combiner.
344 // Only the variables omp_priv and omp_orig are allowed in the
345 // initializer-clause.
346 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
347 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
348 isa<VarDecl>(D)) {
349 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
351 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
352 return true;
353 }
354
355 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
356 // List-items in map clauses on this construct may only refer to the declared
357 // variable var and entities that could be referenced by a procedure defined
358 // at the same location.
359 // [OpenMP 5.2] Also allow iterator declared variables.
360 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
361 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
362 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
364 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
365 return true;
366 }
367
368 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
369 Diag(Loc, diag::err_use_of_empty_using_if_exists);
370 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
371 return true;
372 }
373
374 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
375 AvoidPartialAvailabilityChecks, ClassReceiver);
376
377 DiagnoseUnusedOfDecl(*this, D, Loc);
378
380
381 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
382 if (getLangOpts().getFPEvalMethod() !=
384 PP.getLastFPEvalPragmaLocation().isValid() &&
385 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
386 Diag(D->getLocation(),
387 diag::err_type_available_only_in_default_eval_method)
388 << D->getName();
389 }
390
391 if (auto *VD = dyn_cast<ValueDecl>(D))
392 checkTypeSupport(VD->getType(), Loc, VD);
393
394 if (LangOpts.SYCLIsDevice ||
395 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
396 if (!Context.getTargetInfo().isTLSSupported())
397 if (const auto *VD = dyn_cast<VarDecl>(D))
398 if (VD->getTLSKind() != VarDecl::TLS_None)
399 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
400 }
401
402 return false;
403}
404
406 ArrayRef<Expr *> Args) {
407 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
408 if (!Attr)
409 return;
410
411 // The number of formal parameters of the declaration.
412 unsigned NumFormalParams;
413
414 // The kind of declaration. This is also an index into a %select in
415 // the diagnostic.
416 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
417
418 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
419 NumFormalParams = MD->param_size();
420 CalleeKind = CK_Method;
421 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
422 NumFormalParams = FD->param_size();
423 CalleeKind = CK_Function;
424 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
425 QualType Ty = VD->getType();
426 const FunctionType *Fn = nullptr;
427 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
428 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
429 if (!Fn)
430 return;
431 CalleeKind = CK_Function;
432 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
433 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
434 CalleeKind = CK_Block;
435 } else {
436 return;
437 }
438
439 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
440 NumFormalParams = proto->getNumParams();
441 else
442 NumFormalParams = 0;
443 } else {
444 return;
445 }
446
447 // "NullPos" is the number of formal parameters at the end which
448 // effectively count as part of the variadic arguments. This is
449 // useful if you would prefer to not have *any* formal parameters,
450 // but the language forces you to have at least one.
451 unsigned NullPos = Attr->getNullPos();
452 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
453 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
454
455 // The number of arguments which should follow the sentinel.
456 unsigned NumArgsAfterSentinel = Attr->getSentinel();
457
458 // If there aren't enough arguments for all the formal parameters,
459 // the sentinel, and the args after the sentinel, complain.
460 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
461 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
462 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
463 return;
464 }
465
466 // Otherwise, find the sentinel expression.
467 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
468 if (!SentinelExpr)
469 return;
470 if (SentinelExpr->isValueDependent())
471 return;
472 if (Context.isSentinelNullExpr(SentinelExpr))
473 return;
474
475 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
476 // or 'NULL' if those are actually defined in the context. Only use
477 // 'nil' for ObjC methods, where it's much more likely that the
478 // variadic arguments form a list of object pointers.
479 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
480 std::string NullValue;
481 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
482 NullValue = "nil";
483 else if (getLangOpts().CPlusPlus11)
484 NullValue = "nullptr";
485 else if (PP.isMacroDefined("NULL"))
486 NullValue = "NULL";
487 else
488 NullValue = "(void*) 0";
489
490 if (MissingNilLoc.isInvalid())
491 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
492 else
493 Diag(MissingNilLoc, diag::warn_missing_sentinel)
494 << int(CalleeKind)
495 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
496 Diag(D->getLocation(), diag::note_sentinel_here)
497 << int(CalleeKind) << Attr->getRange();
498}
499
501 return E ? E->getSourceRange() : SourceRange();
502}
503
504//===----------------------------------------------------------------------===//
505// Standard Promotions and Conversions
506//===----------------------------------------------------------------------===//
507
508/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
510 // Handle any placeholder expressions which made it here.
511 if (E->hasPlaceholderType()) {
513 if (result.isInvalid()) return ExprError();
514 E = result.get();
515 }
516
517 QualType Ty = E->getType();
518 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
519
520 if (Ty->isFunctionType()) {
521 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
522 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
524 return ExprError();
525
526 E = ImpCastExprToType(E, Context.getPointerType(Ty),
527 CK_FunctionToPointerDecay).get();
528 } else if (Ty->isArrayType()) {
529 // In C90 mode, arrays only promote to pointers if the array expression is
530 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
531 // type 'array of type' is converted to an expression that has type 'pointer
532 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
533 // that has type 'array of type' ...". The relevant change is "an lvalue"
534 // (C90) to "an expression" (C99).
535 //
536 // C++ 4.2p1:
537 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
538 // T" can be converted to an rvalue of type "pointer to T".
539 //
540 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
541 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
542 CK_ArrayToPointerDecay);
543 if (Res.isInvalid())
544 return ExprError();
545 E = Res.get();
546 }
547 }
548 return E;
549}
550
552 // Check to see if we are dereferencing a null pointer. If so,
553 // and if not volatile-qualified, this is undefined behavior that the
554 // optimizer will delete, so warn about it. People sometimes try to use this
555 // to get a deterministic trap and are surprised by clang's behavior. This
556 // only handles the pattern "*null", which is a very syntactic check.
557 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
558 if (UO && UO->getOpcode() == UO_Deref &&
559 UO->getSubExpr()->getType()->isPointerType()) {
560 const LangAS AS =
561 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
562 if ((!isTargetAddressSpace(AS) ||
563 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
564 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
566 !UO->getType().isVolatileQualified()) {
567 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
568 S.PDiag(diag::warn_indirection_through_null)
569 << UO->getSubExpr()->getSourceRange());
570 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
571 S.PDiag(diag::note_indirection_through_null));
572 }
573 }
574}
575
576static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
577 SourceLocation AssignLoc,
578 const Expr* RHS) {
579 const ObjCIvarDecl *IV = OIRE->getDecl();
580 if (!IV)
581 return;
582
583 DeclarationName MemberName = IV->getDeclName();
585 if (!Member || !Member->isStr("isa"))
586 return;
587
588 const Expr *Base = OIRE->getBase();
589 QualType BaseType = Base->getType();
590 if (OIRE->isArrow())
591 BaseType = BaseType->getPointeeType();
592 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
593 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
594 ObjCInterfaceDecl *ClassDeclared = nullptr;
595 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
596 if (!ClassDeclared->getSuperClass()
597 && (*ClassDeclared->ivar_begin()) == IV) {
598 if (RHS) {
599 NamedDecl *ObjectSetClass =
601 &S.Context.Idents.get("object_setClass"),
603 if (ObjectSetClass) {
604 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
605 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
607 "object_setClass(")
609 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
610 << FixItHint::CreateInsertion(RHSLocEnd, ")");
611 }
612 else
613 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
614 } else {
615 NamedDecl *ObjectGetClass =
617 &S.Context.Idents.get("object_getClass"),
619 if (ObjectGetClass)
620 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
622 "object_getClass(")
624 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
625 else
626 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
627 }
628 S.Diag(IV->getLocation(), diag::note_ivar_decl);
629 }
630 }
631}
632
634 // Handle any placeholder expressions which made it here.
635 if (E->hasPlaceholderType()) {
637 if (result.isInvalid()) return ExprError();
638 E = result.get();
639 }
640
641 // C++ [conv.lval]p1:
642 // A glvalue of a non-function, non-array type T can be
643 // converted to a prvalue.
644 if (!E->isGLValue()) return E;
645
646 QualType T = E->getType();
647 assert(!T.isNull() && "r-value conversion on typeless expression?");
648
649 // lvalue-to-rvalue conversion cannot be applied to types that decay to
650 // pointers (i.e. function or array types).
651 if (T->canDecayToPointerType())
652 return E;
653
654 // We don't want to throw lvalue-to-rvalue casts on top of
655 // expressions of certain types in C++.
656 if (getLangOpts().CPlusPlus) {
657 if (T == Context.OverloadTy || T->isRecordType() ||
658 (T->isDependentType() && !T->isAnyPointerType() &&
659 !T->isMemberPointerType()))
660 return E;
661 }
662
663 // The C standard is actually really unclear on this point, and
664 // DR106 tells us what the result should be but not why. It's
665 // generally best to say that void types just doesn't undergo
666 // lvalue-to-rvalue at all. Note that expressions of unqualified
667 // 'void' type are never l-values, but qualified void can be.
668 if (T->isVoidType())
669 return E;
670
671 // OpenCL usually rejects direct accesses to values of 'half' type.
672 if (getLangOpts().OpenCL &&
673 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
674 T->isHalfType()) {
675 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
676 << 0 << T;
677 return ExprError();
678 }
679
681 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
682 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
683 &Context.Idents.get("object_getClass"),
685 if (ObjectGetClass)
686 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
687 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
689 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
690 else
691 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
692 }
693 else if (const ObjCIvarRefExpr *OIRE =
694 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
695 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
696
697 // C++ [conv.lval]p1:
698 // [...] If T is a non-class type, the type of the prvalue is the
699 // cv-unqualified version of T. Otherwise, the type of the
700 // rvalue is T.
701 //
702 // C99 6.3.2.1p2:
703 // If the lvalue has qualified type, the value has the unqualified
704 // version of the type of the lvalue; otherwise, the value has the
705 // type of the lvalue.
706 if (T.hasQualifiers())
707 T = T.getUnqualifiedType();
708
709 // Under the MS ABI, lock down the inheritance model now.
710 if (T->isMemberPointerType() &&
711 Context.getTargetInfo().getCXXABI().isMicrosoft())
712 (void)isCompleteType(E->getExprLoc(), T);
713
715 if (Res.isInvalid())
716 return Res;
717 E = Res.get();
718
719 // Loading a __weak object implicitly retains the value, so we need a cleanup to
720 // balance that.
722 Cleanup.setExprNeedsCleanups(true);
723
725 Cleanup.setExprNeedsCleanups(true);
726
728 return ExprError();
729
730 // C++ [conv.lval]p3:
731 // If T is cv std::nullptr_t, the result is a null pointer constant.
732 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
733 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
735
736 // C11 6.3.2.1p2:
737 // ... if the lvalue has atomic type, the value has the non-atomic version
738 // of the type of the lvalue ...
739 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
740 T = Atomic->getValueType().getUnqualifiedType();
741 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
742 nullptr, VK_PRValue, FPOptionsOverride());
743 }
744
745 return Res;
746}
747
750 if (Res.isInvalid())
751 return ExprError();
752 Res = DefaultLvalueConversion(Res.get());
753 if (Res.isInvalid())
754 return ExprError();
755 return Res;
756}
757
759 QualType Ty = E->getType();
760 ExprResult Res = E;
761 // Only do implicit cast for a function type, but not for a pointer
762 // to function type.
763 if (Ty->isFunctionType()) {
764 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
765 CK_FunctionToPointerDecay);
766 if (Res.isInvalid())
767 return ExprError();
768 }
769 Res = DefaultLvalueConversion(Res.get());
770 if (Res.isInvalid())
771 return ExprError();
772 return Res.get();
773}
774
775/// UsualUnaryFPConversions - Promotes floating-point types according to the
776/// current language semantics.
778 QualType Ty = E->getType();
779 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
780
781 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
782 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
783 (getLangOpts().getFPEvalMethod() !=
785 PP.getLastFPEvalPragmaLocation().isValid())) {
786 switch (EvalMethod) {
787 default:
788 llvm_unreachable("Unrecognized float evaluation method");
789 break;
791 llvm_unreachable("Float evaluation method should be set by now");
792 break;
794 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
795 // Widen the expression to double.
796 return Ty->isComplexType()
798 Context.getComplexType(Context.DoubleTy),
799 CK_FloatingComplexCast)
800 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
801 break;
803 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
804 // Widen the expression to long double.
805 return Ty->isComplexType()
807 E, Context.getComplexType(Context.LongDoubleTy),
808 CK_FloatingComplexCast)
809 : ImpCastExprToType(E, Context.LongDoubleTy,
810 CK_FloatingCast);
811 break;
812 }
813 }
814
815 // Half FP have to be promoted to float unless it is natively supported
816 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
817 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
818
819 return E;
820}
821
822/// UsualUnaryConversions - Performs various conversions that are common to most
823/// operators (C99 6.3). The conversions of array and function types are
824/// sometimes suppressed. For example, the array->pointer conversion doesn't
825/// apply if the array is an argument to the sizeof or address (&) operators.
826/// In these instances, this routine should *not* be called.
828 // First, convert to an r-value.
830 if (Res.isInvalid())
831 return ExprError();
832
833 // Promote floating-point types.
834 Res = UsualUnaryFPConversions(Res.get());
835 if (Res.isInvalid())
836 return ExprError();
837 E = Res.get();
838
839 QualType Ty = E->getType();
840 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
841
842 // Try to perform integral promotions if the object has a theoretically
843 // promotable type.
845 // C99 6.3.1.1p2:
846 //
847 // The following may be used in an expression wherever an int or
848 // unsigned int may be used:
849 // - an object or expression with an integer type whose integer
850 // conversion rank is less than or equal to the rank of int
851 // and unsigned int.
852 // - A bit-field of type _Bool, int, signed int, or unsigned int.
853 //
854 // If an int can represent all values of the original type, the
855 // value is converted to an int; otherwise, it is converted to an
856 // unsigned int. These are called the integer promotions. All
857 // other types are unchanged by the integer promotions.
858
859 QualType PTy = Context.isPromotableBitField(E);
860 if (!PTy.isNull()) {
861 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
862 return E;
863 }
864 if (Context.isPromotableIntegerType(Ty)) {
865 QualType PT = Context.getPromotedIntegerType(Ty);
866 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
867 return E;
868 }
869 }
870 return E;
871}
872
873/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
874/// do not have a prototype. Arguments that have type float or __fp16
875/// are promoted to double. All other argument types are converted by
876/// UsualUnaryConversions().
878 QualType Ty = E->getType();
879 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
880
882 if (Res.isInvalid())
883 return ExprError();
884 E = Res.get();
885
886 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
887 // promote to double.
888 // Note that default argument promotion applies only to float (and
889 // half/fp16); it does not apply to _Float16.
890 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
891 if (BTy && (BTy->getKind() == BuiltinType::Half ||
892 BTy->getKind() == BuiltinType::Float)) {
893 if (getLangOpts().OpenCL &&
894 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
895 if (BTy->getKind() == BuiltinType::Half) {
896 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
897 }
898 } else {
899 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
900 }
901 }
902 if (BTy &&
903 getLangOpts().getExtendIntArgs() ==
905 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
906 Context.getTypeSizeInChars(BTy) <
907 Context.getTypeSizeInChars(Context.LongLongTy)) {
908 E = (Ty->isUnsignedIntegerType())
909 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
910 .get()
911 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
912 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
913 "Unexpected typesize for LongLongTy");
914 }
915
916 // C++ performs lvalue-to-rvalue conversion as a default argument
917 // promotion, even on class types, but note:
918 // C++11 [conv.lval]p2:
919 // When an lvalue-to-rvalue conversion occurs in an unevaluated
920 // operand or a subexpression thereof the value contained in the
921 // referenced object is not accessed. Otherwise, if the glvalue
922 // has a class type, the conversion copy-initializes a temporary
923 // of type T from the glvalue and the result of the conversion
924 // is a prvalue for the temporary.
925 // FIXME: add some way to gate this entire thing for correctness in
926 // potentially potentially evaluated contexts.
930 E->getExprLoc(), E);
931 if (Temp.isInvalid())
932 return ExprError();
933 E = Temp.get();
934 }
935
936 // C++ [expr.call]p7, per CWG722:
937 // An argument that has (possibly cv-qualified) type std::nullptr_t is
938 // converted to void* ([conv.ptr]).
939 // (This does not apply to C23 nullptr)
941 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
942
943 return E;
944}
945
947 if (Ty->isIncompleteType()) {
948 // C++11 [expr.call]p7:
949 // After these conversions, if the argument does not have arithmetic,
950 // enumeration, pointer, pointer to member, or class type, the program
951 // is ill-formed.
952 //
953 // Since we've already performed null pointer conversion, array-to-pointer
954 // decay and function-to-pointer decay, the only such type in C++ is cv
955 // void. This also handles initializer lists as variadic arguments.
956 if (Ty->isVoidType())
957 return VarArgKind::Invalid;
958
959 if (Ty->isObjCObjectType())
960 return VarArgKind::Invalid;
961 return VarArgKind::Valid;
962 }
963
965 return VarArgKind::Invalid;
966
967 if (Context.getTargetInfo().getTriple().isWasm() &&
969 return VarArgKind::Invalid;
970 }
971
972 if (Ty.isCXX98PODType(Context))
973 return VarArgKind::Valid;
974
975 // C++11 [expr.call]p7:
976 // Passing a potentially-evaluated argument of class type (Clause 9)
977 // having a non-trivial copy constructor, a non-trivial move constructor,
978 // or a non-trivial destructor, with no corresponding parameter,
979 // is conditionally-supported with implementation-defined semantics.
982 if (!Record->hasNonTrivialCopyConstructor() &&
983 !Record->hasNonTrivialMoveConstructor() &&
984 !Record->hasNonTrivialDestructor())
986
987 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
988 return VarArgKind::Valid;
989
990 if (Ty->isObjCObjectType())
991 return VarArgKind::Invalid;
992
993 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
994 return VarArgKind::Valid;
995
996 if (getLangOpts().MSVCCompat)
998
999 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1000 return VarArgKind::Valid;
1001
1002 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1003 // permitted to reject them. We should consider doing so.
1004 return VarArgKind::Undefined;
1005}
1006
1008 // Don't allow one to pass an Objective-C interface to a vararg.
1009 const QualType &Ty = E->getType();
1010 VarArgKind VAK = isValidVarArgType(Ty);
1011
1012 // Complain about passing non-POD types through varargs.
1013 switch (VAK) {
1016 E->getBeginLoc(), nullptr,
1017 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1018 [[fallthrough]];
1019 case VarArgKind::Valid:
1020 if (Ty->isRecordType()) {
1021 // This is unlikely to be what the user intended. If the class has a
1022 // 'c_str' member function, the user probably meant to call that.
1023 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1024 PDiag(diag::warn_pass_class_arg_to_vararg)
1025 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1026 }
1027 break;
1028
1031 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1032 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1033 << getLangOpts().CPlusPlus11 << Ty << CT);
1034 break;
1035
1038 Diag(E->getBeginLoc(),
1039 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1040 << Ty << CT;
1041 else if (Ty->isObjCObjectType())
1042 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1043 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1044 << Ty << CT);
1045 else
1046 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1047 << isa<InitListExpr>(E) << Ty << CT;
1048 break;
1049 }
1050}
1051
1053 FunctionDecl *FDecl) {
1054 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1055 // Strip the unbridged-cast placeholder expression off, if applicable.
1056 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1057 (CT == VariadicCallType::Method ||
1058 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1059 E = ObjC().stripARCUnbridgedCast(E);
1060
1061 // Otherwise, do normal placeholder checking.
1062 } else {
1063 ExprResult ExprRes = CheckPlaceholderExpr(E);
1064 if (ExprRes.isInvalid())
1065 return ExprError();
1066 E = ExprRes.get();
1067 }
1068 }
1069
1071 if (ExprRes.isInvalid())
1072 return ExprError();
1073
1074 // Copy blocks to the heap.
1075 if (ExprRes.get()->getType()->isBlockPointerType())
1076 maybeExtendBlockObject(ExprRes);
1077
1078 E = ExprRes.get();
1079
1080 // Diagnostics regarding non-POD argument types are
1081 // emitted along with format string checking in Sema::CheckFunctionCall().
1083 // Turn this into a trap.
1084 CXXScopeSpec SS;
1085 SourceLocation TemplateKWLoc;
1086 UnqualifiedId Name;
1087 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1088 E->getBeginLoc());
1089 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1090 /*HasTrailingLParen=*/true,
1091 /*IsAddressOfOperand=*/false);
1092 if (TrapFn.isInvalid())
1093 return ExprError();
1094
1095 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1096 E->getEndLoc());
1097 if (Call.isInvalid())
1098 return ExprError();
1099
1100 ExprResult Comma =
1101 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1102 if (Comma.isInvalid())
1103 return ExprError();
1104 return Comma.get();
1105 }
1106
1107 if (!getLangOpts().CPlusPlus &&
1109 diag::err_call_incomplete_argument))
1110 return ExprError();
1111
1112 return E;
1113}
1114
1115/// Convert complex integers to complex floats and real integers to
1116/// real floats as required for complex arithmetic. Helper function of
1117/// UsualArithmeticConversions()
1118///
1119/// \return false if the integer expression is an integer type and is
1120/// successfully converted to the (complex) float type.
1122 ExprResult &ComplexExpr,
1123 QualType IntTy,
1124 QualType ComplexTy,
1125 bool SkipCast) {
1126 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1127 if (SkipCast) return false;
1128 if (IntTy->isIntegerType()) {
1129 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1130 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1131 } else {
1132 assert(IntTy->isComplexIntegerType());
1133 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1134 CK_IntegralComplexToFloatingComplex);
1135 }
1136 return false;
1137}
1138
1139// This handles complex/complex, complex/float, or float/complex.
1140// When both operands are complex, the shorter operand is converted to the
1141// type of the longer, and that is the type of the result. This corresponds
1142// to what is done when combining two real floating-point operands.
1143// The fun begins when size promotion occur across type domains.
1144// From H&S 6.3.4: When one operand is complex and the other is a real
1145// floating-point type, the less precise type is converted, within it's
1146// real or complex domain, to the precision of the other type. For example,
1147// when combining a "long double" with a "double _Complex", the
1148// "double _Complex" is promoted to "long double _Complex".
1150 QualType ShorterType,
1151 QualType LongerType,
1152 bool PromotePrecision) {
1153 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1154 QualType Result =
1155 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1156
1157 if (PromotePrecision) {
1158 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1159 Shorter =
1160 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1161 } else {
1162 if (LongerIsComplex)
1163 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1164 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1165 }
1166 }
1167 return Result;
1168}
1169
1170/// Handle arithmetic conversion with complex types. Helper function of
1171/// UsualArithmeticConversions()
1173 ExprResult &RHS, QualType LHSType,
1174 QualType RHSType, bool IsCompAssign) {
1175 // Handle (complex) integer types.
1176 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1177 /*SkipCast=*/false))
1178 return LHSType;
1179 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1180 /*SkipCast=*/IsCompAssign))
1181 return RHSType;
1182
1183 // Compute the rank of the two types, regardless of whether they are complex.
1184 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1185 if (Order < 0)
1186 // Promote the precision of the LHS if not an assignment.
1187 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1188 /*PromotePrecision=*/!IsCompAssign);
1189 // Promote the precision of the RHS unless it is already the same as the LHS.
1190 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1191 /*PromotePrecision=*/Order > 0);
1192}
1193
1194/// Handle arithmetic conversion from integer to float. Helper function
1195/// of UsualArithmeticConversions()
1197 ExprResult &IntExpr,
1198 QualType FloatTy, QualType IntTy,
1199 bool ConvertFloat, bool ConvertInt) {
1200 if (IntTy->isIntegerType()) {
1201 if (ConvertInt)
1202 // Convert intExpr to the lhs floating point type.
1203 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1204 CK_IntegralToFloating);
1205 return FloatTy;
1206 }
1207
1208 // Convert both sides to the appropriate complex float.
1209 assert(IntTy->isComplexIntegerType());
1210 QualType result = S.Context.getComplexType(FloatTy);
1211
1212 // _Complex int -> _Complex float
1213 if (ConvertInt)
1214 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1215 CK_IntegralComplexToFloatingComplex);
1216
1217 // float -> _Complex float
1218 if (ConvertFloat)
1219 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1220 CK_FloatingRealToComplex);
1221
1222 return result;
1223}
1224
1225/// Handle arithmethic conversion with floating point types. Helper
1226/// function of UsualArithmeticConversions()
1228 ExprResult &RHS, QualType LHSType,
1229 QualType RHSType, bool IsCompAssign) {
1230 bool LHSFloat = LHSType->isRealFloatingType();
1231 bool RHSFloat = RHSType->isRealFloatingType();
1232
1233 // N1169 4.1.4: If one of the operands has a floating type and the other
1234 // operand has a fixed-point type, the fixed-point operand
1235 // is converted to the floating type [...]
1236 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1237 if (LHSFloat)
1238 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1239 else if (!IsCompAssign)
1240 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1241 return LHSFloat ? LHSType : RHSType;
1242 }
1243
1244 // If we have two real floating types, convert the smaller operand
1245 // to the bigger result.
1246 if (LHSFloat && RHSFloat) {
1247 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1248 if (order > 0) {
1249 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1250 return LHSType;
1251 }
1252
1253 assert(order < 0 && "illegal float comparison");
1254 if (!IsCompAssign)
1255 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1256 return RHSType;
1257 }
1258
1259 if (LHSFloat) {
1260 // Half FP has to be promoted to float unless it is natively supported
1261 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1262 LHSType = S.Context.FloatTy;
1263
1264 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1265 /*ConvertFloat=*/!IsCompAssign,
1266 /*ConvertInt=*/ true);
1267 }
1268 assert(RHSFloat);
1269 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1270 /*ConvertFloat=*/ true,
1271 /*ConvertInt=*/!IsCompAssign);
1272}
1273
1274/// Diagnose attempts to convert between __float128, __ibm128 and
1275/// long double if there is no support for such conversion.
1276/// Helper function of UsualArithmeticConversions().
1277static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1278 QualType RHSType) {
1279 // No issue if either is not a floating point type.
1280 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1281 return false;
1282
1283 // No issue if both have the same 128-bit float semantics.
1284 auto *LHSComplex = LHSType->getAs<ComplexType>();
1285 auto *RHSComplex = RHSType->getAs<ComplexType>();
1286
1287 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1288 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1289
1290 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1291 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1292
1293 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1294 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1295 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1296 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1297 return false;
1298
1299 return true;
1300}
1301
1302typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1303
1304namespace {
1305/// These helper callbacks are placed in an anonymous namespace to
1306/// permit their use as function template parameters.
1307ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1308 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1309}
1310
1311ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1312 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1313 CK_IntegralComplexCast);
1314}
1315}
1316
1317/// Handle integer arithmetic conversions. Helper function of
1318/// UsualArithmeticConversions()
1319template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1321 ExprResult &RHS, QualType LHSType,
1322 QualType RHSType, bool IsCompAssign) {
1323 // The rules for this case are in C99 6.3.1.8
1324 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1325 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1326 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1327 if (LHSSigned == RHSSigned) {
1328 // Same signedness; use the higher-ranked type
1329 if (order >= 0) {
1330 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1331 return LHSType;
1332 } else if (!IsCompAssign)
1333 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1334 return RHSType;
1335 } else if (order != (LHSSigned ? 1 : -1)) {
1336 // The unsigned type has greater than or equal rank to the
1337 // signed type, so use the unsigned type
1338 if (RHSSigned) {
1339 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1340 return LHSType;
1341 } else if (!IsCompAssign)
1342 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1343 return RHSType;
1344 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1345 // The two types are different widths; if we are here, that
1346 // means the signed type is larger than the unsigned type, so
1347 // use the signed type.
1348 if (LHSSigned) {
1349 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1350 return LHSType;
1351 } else if (!IsCompAssign)
1352 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1353 return RHSType;
1354 } else {
1355 // The signed type is higher-ranked than the unsigned type,
1356 // but isn't actually any bigger (like unsigned int and long
1357 // on most 32-bit systems). Use the unsigned type corresponding
1358 // to the signed type.
1359 QualType result =
1360 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1361 RHS = (*doRHSCast)(S, RHS.get(), result);
1362 if (!IsCompAssign)
1363 LHS = (*doLHSCast)(S, LHS.get(), result);
1364 return result;
1365 }
1366}
1367
1368/// Handle conversions with GCC complex int extension. Helper function
1369/// of UsualArithmeticConversions()
1371 ExprResult &RHS, QualType LHSType,
1372 QualType RHSType,
1373 bool IsCompAssign) {
1374 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1375 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1376
1377 if (LHSComplexInt && RHSComplexInt) {
1378 QualType LHSEltType = LHSComplexInt->getElementType();
1379 QualType RHSEltType = RHSComplexInt->getElementType();
1380 QualType ScalarType =
1382 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1383
1384 return S.Context.getComplexType(ScalarType);
1385 }
1386
1387 if (LHSComplexInt) {
1388 QualType LHSEltType = LHSComplexInt->getElementType();
1389 QualType ScalarType =
1391 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1393 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1394 CK_IntegralRealToComplex);
1395
1396 return ComplexType;
1397 }
1398
1399 assert(RHSComplexInt);
1400
1401 QualType RHSEltType = RHSComplexInt->getElementType();
1402 QualType ScalarType =
1404 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1406
1407 if (!IsCompAssign)
1408 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1409 CK_IntegralRealToComplex);
1410 return ComplexType;
1411}
1412
1413/// Return the rank of a given fixed point or integer type. The value itself
1414/// doesn't matter, but the values must be increasing with proper increasing
1415/// rank as described in N1169 4.1.1.
1416static unsigned GetFixedPointRank(QualType Ty) {
1417 const auto *BTy = Ty->getAs<BuiltinType>();
1418 assert(BTy && "Expected a builtin type.");
1419
1420 switch (BTy->getKind()) {
1421 case BuiltinType::ShortFract:
1422 case BuiltinType::UShortFract:
1423 case BuiltinType::SatShortFract:
1424 case BuiltinType::SatUShortFract:
1425 return 1;
1426 case BuiltinType::Fract:
1427 case BuiltinType::UFract:
1428 case BuiltinType::SatFract:
1429 case BuiltinType::SatUFract:
1430 return 2;
1431 case BuiltinType::LongFract:
1432 case BuiltinType::ULongFract:
1433 case BuiltinType::SatLongFract:
1434 case BuiltinType::SatULongFract:
1435 return 3;
1436 case BuiltinType::ShortAccum:
1437 case BuiltinType::UShortAccum:
1438 case BuiltinType::SatShortAccum:
1439 case BuiltinType::SatUShortAccum:
1440 return 4;
1441 case BuiltinType::Accum:
1442 case BuiltinType::UAccum:
1443 case BuiltinType::SatAccum:
1444 case BuiltinType::SatUAccum:
1445 return 5;
1446 case BuiltinType::LongAccum:
1447 case BuiltinType::ULongAccum:
1448 case BuiltinType::SatLongAccum:
1449 case BuiltinType::SatULongAccum:
1450 return 6;
1451 default:
1452 if (BTy->isInteger())
1453 return 0;
1454 llvm_unreachable("Unexpected fixed point or integer type");
1455 }
1456}
1457
1458/// handleFixedPointConversion - Fixed point operations between fixed
1459/// point types and integers or other fixed point types do not fall under
1460/// usual arithmetic conversion since these conversions could result in loss
1461/// of precsision (N1169 4.1.4). These operations should be calculated with
1462/// the full precision of their result type (N1169 4.1.6.2.1).
1464 QualType RHSTy) {
1465 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1466 "Expected at least one of the operands to be a fixed point type");
1467 assert((LHSTy->isFixedPointOrIntegerType() ||
1468 RHSTy->isFixedPointOrIntegerType()) &&
1469 "Special fixed point arithmetic operation conversions are only "
1470 "applied to ints or other fixed point types");
1471
1472 // If one operand has signed fixed-point type and the other operand has
1473 // unsigned fixed-point type, then the unsigned fixed-point operand is
1474 // converted to its corresponding signed fixed-point type and the resulting
1475 // type is the type of the converted operand.
1476 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1478 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1480
1481 // The result type is the type with the highest rank, whereby a fixed-point
1482 // conversion rank is always greater than an integer conversion rank; if the
1483 // type of either of the operands is a saturating fixedpoint type, the result
1484 // type shall be the saturating fixed-point type corresponding to the type
1485 // with the highest rank; the resulting value is converted (taking into
1486 // account rounding and overflow) to the precision of the resulting type.
1487 // Same ranks between signed and unsigned types are resolved earlier, so both
1488 // types are either signed or both unsigned at this point.
1489 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1490 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1491
1492 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1493
1495 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1496
1497 return ResultTy;
1498}
1499
1500/// Check that the usual arithmetic conversions can be performed on this pair of
1501/// expressions that might be of enumeration type.
1503 SourceLocation Loc,
1504 ArithConvKind ACK) {
1505 // C++2a [expr.arith.conv]p1:
1506 // If one operand is of enumeration type and the other operand is of a
1507 // different enumeration type or a floating-point type, this behavior is
1508 // deprecated ([depr.arith.conv.enum]).
1509 //
1510 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1511 // Eventually we will presumably reject these cases (in C++23 onwards?).
1513 R = RHS->getEnumCoercedType(Context);
1514 bool LEnum = L->isUnscopedEnumerationType(),
1515 REnum = R->isUnscopedEnumerationType();
1516 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1517 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1518 (REnum && L->isFloatingType())) {
1519 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1521 ? diag::warn_arith_conv_enum_float_cxx20
1522 : diag::warn_arith_conv_enum_float)
1523 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1524 << L << R;
1525 } else if (!IsCompAssign && LEnum && REnum &&
1526 !Context.hasSameUnqualifiedType(L, R)) {
1527 unsigned DiagID;
1528 // In C++ 26, usual arithmetic conversions between 2 different enum types
1529 // are ill-formed.
1531 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1532 else if (!L->castAsCanonical<EnumType>()
1533 ->getOriginalDecl()
1534 ->hasNameForLinkage() ||
1535 !R->castAsCanonical<EnumType>()
1536 ->getOriginalDecl()
1537 ->hasNameForLinkage()) {
1538 // If either enumeration type is unnamed, it's less likely that the
1539 // user cares about this, but this situation is still deprecated in
1540 // C++2a. Use a different warning group.
1541 DiagID = getLangOpts().CPlusPlus20
1542 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1543 : diag::warn_arith_conv_mixed_anon_enum_types;
1544 } else if (ACK == ArithConvKind::Conditional) {
1545 // Conditional expressions are separated out because they have
1546 // historically had a different warning flag.
1547 DiagID = getLangOpts().CPlusPlus20
1548 ? diag::warn_conditional_mixed_enum_types_cxx20
1549 : diag::warn_conditional_mixed_enum_types;
1550 } else if (ACK == ArithConvKind::Comparison) {
1551 // Comparison expressions are separated out because they have
1552 // historically had a different warning flag.
1553 DiagID = getLangOpts().CPlusPlus20
1554 ? diag::warn_comparison_mixed_enum_types_cxx20
1555 : diag::warn_comparison_mixed_enum_types;
1556 } else {
1557 DiagID = getLangOpts().CPlusPlus20
1558 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1559 : diag::warn_arith_conv_mixed_enum_types;
1560 }
1561 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1562 << (int)ACK << L << R;
1563 }
1564}
1565
1567 Expr *RHS, SourceLocation Loc,
1568 ArithConvKind ACK) {
1569 QualType LHSType = LHS->getType().getUnqualifiedType();
1570 QualType RHSType = RHS->getType().getUnqualifiedType();
1571
1572 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1573 !RHSType->isUnicodeCharacterType())
1574 return;
1575
1576 if (ACK == ArithConvKind::Comparison) {
1577 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1578 return;
1579
1580 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1581 if (T->isChar8Type())
1582 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1583 if (T->isChar16Type())
1584 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1585 assert(T->isChar32Type());
1586 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1587 };
1588
1589 Expr::EvalResult LHSRes, RHSRes;
1590 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1592 SemaRef.isConstantEvaluatedContext());
1593 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1595 SemaRef.isConstantEvaluatedContext());
1596
1597 // Don't warn if the one known value is a representable
1598 // in the type of both expressions.
1599 if (LHSSuccess != RHSuccess) {
1600 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1601 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1602 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1603 return;
1604 }
1605
1606 if (!LHSSuccess || !RHSuccess) {
1607 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1608 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1609 << RHSType;
1610 return;
1611 }
1612
1613 llvm::APSInt LHSValue(32);
1614 LHSValue = LHSRes.Val.getInt();
1615 llvm::APSInt RHSValue(32);
1616 RHSValue = RHSRes.Val.getInt();
1617
1618 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1619 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1620 if (LHSSafe && RHSSafe)
1621 return;
1622
1623 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1624 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1625 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1626 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1627 return;
1628 }
1629
1630 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1631 return;
1632
1633 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1634 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1635 << RHSType;
1636}
1637
1638/// UsualArithmeticConversions - Performs various conversions that are common to
1639/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1640/// routine returns the first non-arithmetic type found. The client is
1641/// responsible for emitting appropriate error diagnostics.
1643 SourceLocation Loc,
1644 ArithConvKind ACK) {
1645
1646 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1647
1648 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1649
1650 if (ACK != ArithConvKind::CompAssign) {
1651 LHS = UsualUnaryConversions(LHS.get());
1652 if (LHS.isInvalid())
1653 return QualType();
1654 }
1655
1656 RHS = UsualUnaryConversions(RHS.get());
1657 if (RHS.isInvalid())
1658 return QualType();
1659
1660 // For conversion purposes, we ignore any qualifiers.
1661 // For example, "const float" and "float" are equivalent.
1662 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1663 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1664
1665 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1666 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1667 LHSType = AtomicLHS->getValueType();
1668
1669 // If both types are identical, no conversion is needed.
1670 if (Context.hasSameType(LHSType, RHSType))
1671 return Context.getCommonSugaredType(LHSType, RHSType);
1672
1673 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1674 // The caller can deal with this (e.g. pointer + int).
1675 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1676 return QualType();
1677
1678 // Apply unary and bitfield promotions to the LHS's type.
1679 QualType LHSUnpromotedType = LHSType;
1680 if (Context.isPromotableIntegerType(LHSType))
1681 LHSType = Context.getPromotedIntegerType(LHSType);
1682 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1683 if (!LHSBitfieldPromoteTy.isNull())
1684 LHSType = LHSBitfieldPromoteTy;
1685 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1686 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1687
1688 // If both types are identical, no conversion is needed.
1689 if (Context.hasSameType(LHSType, RHSType))
1690 return Context.getCommonSugaredType(LHSType, RHSType);
1691
1692 // At this point, we have two different arithmetic types.
1693
1694 // Diagnose attempts to convert between __ibm128, __float128 and long double
1695 // where such conversions currently can't be handled.
1696 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1697 return QualType();
1698
1699 // Handle complex types first (C99 6.3.1.8p1).
1700 if (LHSType->isComplexType() || RHSType->isComplexType())
1701 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1703
1704 // Now handle "real" floating types (i.e. float, double, long double).
1705 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1706 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1708
1709 // Handle GCC complex int extension.
1710 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1711 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1713
1714 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1715 return handleFixedPointConversion(*this, LHSType, RHSType);
1716
1717 // Finally, we have two differing integer types.
1719 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1720}
1721
1722//===----------------------------------------------------------------------===//
1723// Semantic Analysis for various Expression Types
1724//===----------------------------------------------------------------------===//
1725
1726
1728 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1729 bool PredicateIsExpr, void *ControllingExprOrType,
1730 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1731 unsigned NumAssocs = ArgTypes.size();
1732 assert(NumAssocs == ArgExprs.size());
1733
1734 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1735 for (unsigned i = 0; i < NumAssocs; ++i) {
1736 if (ArgTypes[i])
1737 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1738 else
1739 Types[i] = nullptr;
1740 }
1741
1742 // If we have a controlling type, we need to convert it from a parsed type
1743 // into a semantic type and then pass that along.
1744 if (!PredicateIsExpr) {
1745 TypeSourceInfo *ControllingType;
1746 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1747 &ControllingType);
1748 assert(ControllingType && "couldn't get the type out of the parser");
1749 ControllingExprOrType = ControllingType;
1750 }
1751
1753 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1754 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1755 delete [] Types;
1756 return ER;
1757}
1758
1760 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1761 bool PredicateIsExpr, void *ControllingExprOrType,
1763 unsigned NumAssocs = Types.size();
1764 assert(NumAssocs == Exprs.size());
1765 assert(ControllingExprOrType &&
1766 "Must have either a controlling expression or a controlling type");
1767
1768 Expr *ControllingExpr = nullptr;
1769 TypeSourceInfo *ControllingType = nullptr;
1770 if (PredicateIsExpr) {
1771 // Decay and strip qualifiers for the controlling expression type, and
1772 // handle placeholder type replacement. See committee discussion from WG14
1773 // DR423.
1777 reinterpret_cast<Expr *>(ControllingExprOrType));
1778 if (R.isInvalid())
1779 return ExprError();
1780 ControllingExpr = R.get();
1781 } else {
1782 // The extension form uses the type directly rather than converting it.
1783 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1784 if (!ControllingType)
1785 return ExprError();
1786 }
1787
1788 bool TypeErrorFound = false,
1789 IsResultDependent = ControllingExpr
1790 ? ControllingExpr->isTypeDependent()
1791 : ControllingType->getType()->isDependentType(),
1792 ContainsUnexpandedParameterPack =
1793 ControllingExpr
1794 ? ControllingExpr->containsUnexpandedParameterPack()
1795 : ControllingType->getType()->containsUnexpandedParameterPack();
1796
1797 // The controlling expression is an unevaluated operand, so side effects are
1798 // likely unintended.
1799 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1800 ControllingExpr->HasSideEffects(Context, false))
1801 Diag(ControllingExpr->getExprLoc(),
1802 diag::warn_side_effects_unevaluated_context);
1803
1804 for (unsigned i = 0; i < NumAssocs; ++i) {
1805 if (Exprs[i]->containsUnexpandedParameterPack())
1806 ContainsUnexpandedParameterPack = true;
1807
1808 if (Types[i]) {
1809 if (Types[i]->getType()->containsUnexpandedParameterPack())
1810 ContainsUnexpandedParameterPack = true;
1811
1812 if (Types[i]->getType()->isDependentType()) {
1813 IsResultDependent = true;
1814 } else {
1815 // We relax the restriction on use of incomplete types and non-object
1816 // types with the type-based extension of _Generic. Allowing incomplete
1817 // objects means those can be used as "tags" for a type-safe way to map
1818 // to a value. Similarly, matching on function types rather than
1819 // function pointer types can be useful. However, the restriction on VM
1820 // types makes sense to retain as there are open questions about how
1821 // the selection can be made at compile time.
1822 //
1823 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1824 // complete object type other than a variably modified type."
1825 // C2y removed the requirement that an expression form must
1826 // use a complete type, though it's still as-if the type has undergone
1827 // lvalue conversion. We support this as an extension in C23 and
1828 // earlier because GCC does so.
1829 unsigned D = 0;
1830 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1831 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1832 : diag::ext_assoc_type_incomplete;
1833 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1834 D = diag::err_assoc_type_nonobject;
1835 else if (Types[i]->getType()->isVariablyModifiedType())
1836 D = diag::err_assoc_type_variably_modified;
1837 else if (ControllingExpr) {
1838 // Because the controlling expression undergoes lvalue conversion,
1839 // array conversion, and function conversion, an association which is
1840 // of array type, function type, or is qualified can never be
1841 // reached. We will warn about this so users are less surprised by
1842 // the unreachable association. However, we don't have to handle
1843 // function types; that's not an object type, so it's handled above.
1844 //
1845 // The logic is somewhat different for C++ because C++ has different
1846 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1847 // If T is a non-class type, the type of the prvalue is the cv-
1848 // unqualified version of T. Otherwise, the type of the prvalue is T.
1849 // The result of these rules is that all qualified types in an
1850 // association in C are unreachable, and in C++, only qualified non-
1851 // class types are unreachable.
1852 //
1853 // NB: this does not apply when the first operand is a type rather
1854 // than an expression, because the type form does not undergo
1855 // conversion.
1856 unsigned Reason = 0;
1857 QualType QT = Types[i]->getType();
1858 if (QT->isArrayType())
1859 Reason = 1;
1860 else if (QT.hasQualifiers() &&
1861 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1862 Reason = 2;
1863
1864 if (Reason)
1865 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1866 diag::warn_unreachable_association)
1867 << QT << (Reason - 1);
1868 }
1869
1870 if (D != 0) {
1871 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1872 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1873 if (getDiagnostics().getDiagnosticLevel(
1874 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1876 TypeErrorFound = true;
1877 }
1878
1879 // C11 6.5.1.1p2 "No two generic associations in the same generic
1880 // selection shall specify compatible types."
1881 for (unsigned j = i+1; j < NumAssocs; ++j)
1882 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1883 Context.typesAreCompatible(Types[i]->getType(),
1884 Types[j]->getType())) {
1885 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1886 diag::err_assoc_compatible_types)
1887 << Types[j]->getTypeLoc().getSourceRange()
1888 << Types[j]->getType()
1889 << Types[i]->getType();
1890 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1891 diag::note_compat_assoc)
1892 << Types[i]->getTypeLoc().getSourceRange()
1893 << Types[i]->getType();
1894 TypeErrorFound = true;
1895 }
1896 }
1897 }
1898 }
1899 if (TypeErrorFound)
1900 return ExprError();
1901
1902 // If we determined that the generic selection is result-dependent, don't
1903 // try to compute the result expression.
1904 if (IsResultDependent) {
1905 if (ControllingExpr)
1906 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1907 Types, Exprs, DefaultLoc, RParenLoc,
1908 ContainsUnexpandedParameterPack);
1909 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1910 Exprs, DefaultLoc, RParenLoc,
1911 ContainsUnexpandedParameterPack);
1912 }
1913
1914 SmallVector<unsigned, 1> CompatIndices;
1915 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
1916 // Look at the canonical type of the controlling expression in case it was a
1917 // deduced type like __auto_type. However, when issuing diagnostics, use the
1918 // type the user wrote in source rather than the canonical one.
1919 for (unsigned i = 0; i < NumAssocs; ++i) {
1920 if (!Types[i])
1921 DefaultIndex = i;
1922 else if (ControllingExpr &&
1923 Context.typesAreCompatible(
1924 ControllingExpr->getType().getCanonicalType(),
1925 Types[i]->getType()))
1926 CompatIndices.push_back(i);
1927 else if (ControllingType &&
1928 Context.typesAreCompatible(
1929 ControllingType->getType().getCanonicalType(),
1930 Types[i]->getType()))
1931 CompatIndices.push_back(i);
1932 }
1933
1934 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1935 TypeSourceInfo *ControllingType) {
1936 // We strip parens here because the controlling expression is typically
1937 // parenthesized in macro definitions.
1938 if (ControllingExpr)
1939 ControllingExpr = ControllingExpr->IgnoreParens();
1940
1941 SourceRange SR = ControllingExpr
1942 ? ControllingExpr->getSourceRange()
1943 : ControllingType->getTypeLoc().getSourceRange();
1944 QualType QT = ControllingExpr ? ControllingExpr->getType()
1945 : ControllingType->getType();
1946
1947 return std::make_pair(SR, QT);
1948 };
1949
1950 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1951 // type compatible with at most one of the types named in its generic
1952 // association list."
1953 if (CompatIndices.size() > 1) {
1954 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1955 SourceRange SR = P.first;
1956 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1957 << SR << P.second << (unsigned)CompatIndices.size();
1958 for (unsigned I : CompatIndices) {
1959 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1960 diag::note_compat_assoc)
1961 << Types[I]->getTypeLoc().getSourceRange()
1962 << Types[I]->getType();
1963 }
1964 return ExprError();
1965 }
1966
1967 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1968 // its controlling expression shall have type compatible with exactly one of
1969 // the types named in its generic association list."
1970 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
1971 CompatIndices.size() == 0) {
1972 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1973 SourceRange SR = P.first;
1974 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1975 return ExprError();
1976 }
1977
1978 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1979 // type name that is compatible with the type of the controlling expression,
1980 // then the result expression of the generic selection is the expression
1981 // in that generic association. Otherwise, the result expression of the
1982 // generic selection is the expression in the default generic association."
1983 unsigned ResultIndex =
1984 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1985
1986 if (ControllingExpr) {
1988 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1989 ContainsUnexpandedParameterPack, ResultIndex);
1990 }
1992 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1993 ContainsUnexpandedParameterPack, ResultIndex);
1994}
1995
1997 switch (Kind) {
1998 default:
1999 llvm_unreachable("unexpected TokenKind");
2000 case tok::kw___func__:
2001 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2002 case tok::kw___FUNCTION__:
2004 case tok::kw___FUNCDNAME__:
2005 return PredefinedIdentKind::FuncDName; // [MS]
2006 case tok::kw___FUNCSIG__:
2007 return PredefinedIdentKind::FuncSig; // [MS]
2008 case tok::kw_L__FUNCTION__:
2009 return PredefinedIdentKind::LFunction; // [MS]
2010 case tok::kw_L__FUNCSIG__:
2011 return PredefinedIdentKind::LFuncSig; // [MS]
2012 case tok::kw___PRETTY_FUNCTION__:
2014 }
2015}
2016
2017/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2018/// to determine the value of a PredefinedExpr. This can be either a
2019/// block, lambda, captured statement, function, otherwise a nullptr.
2022 DC = DC->getParent();
2023 return cast_or_null<Decl>(DC);
2024}
2025
2026/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2027/// location of the token and the offset of the ud-suffix within it.
2029 unsigned Offset) {
2030 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2031 S.getLangOpts());
2032}
2033
2034/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2035/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2037 IdentifierInfo *UDSuffix,
2038 SourceLocation UDSuffixLoc,
2039 ArrayRef<Expr*> Args,
2040 SourceLocation LitEndLoc) {
2041 assert(Args.size() <= 2 && "too many arguments for literal operator");
2042
2043 QualType ArgTy[2];
2044 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2045 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2046 if (ArgTy[ArgIdx]->isArrayType())
2047 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2048 }
2049
2050 DeclarationName OpName =
2052 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2053 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2054
2055 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2056 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2057 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2058 /*AllowStringTemplatePack*/ false,
2059 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2060 return ExprError();
2061
2062 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2063}
2064
2066 // StringToks needs backing storage as it doesn't hold array elements itself
2067 std::vector<Token> ExpandedToks;
2068 if (getLangOpts().MicrosoftExt)
2069 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2070
2071 StringLiteralParser Literal(StringToks, PP,
2073 if (Literal.hadError)
2074 return ExprError();
2075
2076 SmallVector<SourceLocation, 4> StringTokLocs;
2077 for (const Token &Tok : StringToks)
2078 StringTokLocs.push_back(Tok.getLocation());
2079
2080 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2082 false, {}, StringTokLocs);
2083
2084 if (!Literal.getUDSuffix().empty()) {
2085 SourceLocation UDSuffixLoc =
2086 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2087 Literal.getUDSuffixOffset());
2088 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2089 }
2090
2091 return Lit;
2092}
2093
2094std::vector<Token>
2096 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2097 // local macros that expand to string literals that may be concatenated.
2098 // These macros are expanded here (in Sema), because StringLiteralParser
2099 // (in Lex) doesn't know the enclosing function (because it hasn't been
2100 // parsed yet).
2101 assert(getLangOpts().MicrosoftExt);
2102
2103 // Note: Although function local macros are defined only inside functions,
2104 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2105 // expansion of macros into empty string literals without additional checks.
2106 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2107 if (!CurrentDecl)
2108 CurrentDecl = Context.getTranslationUnitDecl();
2109
2110 std::vector<Token> ExpandedToks;
2111 ExpandedToks.reserve(Toks.size());
2112 for (const Token &Tok : Toks) {
2114 assert(tok::isStringLiteral(Tok.getKind()));
2115 ExpandedToks.emplace_back(Tok);
2116 continue;
2117 }
2118 if (isa<TranslationUnitDecl>(CurrentDecl))
2119 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2120 // Stringify predefined expression
2121 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2122 << Tok.getKind();
2123 SmallString<64> Str;
2124 llvm::raw_svector_ostream OS(Str);
2125 Token &Exp = ExpandedToks.emplace_back();
2126 Exp.startToken();
2127 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2128 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2129 OS << 'L';
2130 Exp.setKind(tok::wide_string_literal);
2131 } else {
2132 Exp.setKind(tok::string_literal);
2133 }
2134 OS << '"'
2136 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2137 << '"';
2138 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2139 }
2140 return ExpandedToks;
2141}
2142
2145 assert(!StringToks.empty() && "Must have at least one string!");
2146
2147 // StringToks needs backing storage as it doesn't hold array elements itself
2148 std::vector<Token> ExpandedToks;
2149 if (getLangOpts().MicrosoftExt)
2150 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2151
2152 StringLiteralParser Literal(StringToks, PP);
2153 if (Literal.hadError)
2154 return ExprError();
2155
2156 SmallVector<SourceLocation, 4> StringTokLocs;
2157 for (const Token &Tok : StringToks)
2158 StringTokLocs.push_back(Tok.getLocation());
2159
2160 QualType CharTy = Context.CharTy;
2162 if (Literal.isWide()) {
2163 CharTy = Context.getWideCharType();
2165 } else if (Literal.isUTF8()) {
2166 if (getLangOpts().Char8)
2167 CharTy = Context.Char8Ty;
2168 else if (getLangOpts().C23)
2169 CharTy = Context.UnsignedCharTy;
2171 } else if (Literal.isUTF16()) {
2172 CharTy = Context.Char16Ty;
2174 } else if (Literal.isUTF32()) {
2175 CharTy = Context.Char32Ty;
2177 } else if (Literal.isPascal()) {
2178 CharTy = Context.UnsignedCharTy;
2179 }
2180
2181 // Warn on u8 string literals before C++20 and C23, whose type
2182 // was an array of char before but becomes an array of char8_t.
2183 // In C++20, it cannot be used where a pointer to char is expected.
2184 // In C23, it might have an unexpected value if char was signed.
2185 if (Kind == StringLiteralKind::UTF8 &&
2187 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2188 : !getLangOpts().C23)) {
2189 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2190 ? diag::warn_cxx20_compat_utf8_string
2191 : diag::warn_c23_compat_utf8_string);
2192
2193 // Create removals for all 'u8' prefixes in the string literal(s). This
2194 // ensures C++20/C23 compatibility (but may change the program behavior when
2195 // built by non-Clang compilers for which the execution character set is
2196 // not always UTF-8).
2197 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2198 SourceLocation RemovalDiagLoc;
2199 for (const Token &Tok : StringToks) {
2200 if (Tok.getKind() == tok::utf8_string_literal) {
2201 if (RemovalDiagLoc.isInvalid())
2202 RemovalDiagLoc = Tok.getLocation();
2204 Tok.getLocation(),
2205 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2207 }
2208 }
2209 Diag(RemovalDiagLoc, RemovalDiag);
2210 }
2211
2212 QualType StrTy =
2213 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2214
2215 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2217 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2218 if (Literal.getUDSuffix().empty())
2219 return Lit;
2220
2221 // We're building a user-defined literal.
2222 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2223 SourceLocation UDSuffixLoc =
2224 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2225 Literal.getUDSuffixOffset());
2226
2227 // Make sure we're allowed user-defined literals here.
2228 if (!UDLScope)
2229 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2230
2231 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2232 // operator "" X (str, len)
2233 QualType SizeType = Context.getSizeType();
2234
2235 DeclarationName OpName =
2236 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2237 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2238 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2239
2240 QualType ArgTy[] = {
2241 Context.getArrayDecayedType(StrTy), SizeType
2242 };
2243
2244 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2245 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2246 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2247 /*AllowStringTemplatePack*/ true,
2248 /*DiagnoseMissing*/ true, Lit)) {
2249
2250 case LOLR_Cooked: {
2251 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2252 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2253 StringTokLocs[0]);
2254 Expr *Args[] = { Lit, LenArg };
2255
2256 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2257 }
2258
2259 case LOLR_Template: {
2260 TemplateArgumentListInfo ExplicitArgs;
2261 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2262 TemplateArgumentLocInfo ArgInfo(Lit);
2263 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2264 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2265 &ExplicitArgs);
2266 }
2267
2269 TemplateArgumentListInfo ExplicitArgs;
2270
2271 unsigned CharBits = Context.getIntWidth(CharTy);
2272 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2273 llvm::APSInt Value(CharBits, CharIsUnsigned);
2274
2275 TemplateArgument TypeArg(CharTy);
2276 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2277 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2278
2279 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2280 Value = Lit->getCodeUnit(I);
2281 TemplateArgument Arg(Context, Value, CharTy);
2283 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2284 }
2285 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2286 &ExplicitArgs);
2287 }
2288 case LOLR_Raw:
2290 llvm_unreachable("unexpected literal operator lookup result");
2291 case LOLR_Error:
2292 return ExprError();
2293 }
2294 llvm_unreachable("unexpected literal operator lookup result");
2295}
2296
2299 SourceLocation Loc,
2300 const CXXScopeSpec *SS) {
2301 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2302 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2303}
2304
2307 const DeclarationNameInfo &NameInfo,
2308 const CXXScopeSpec *SS, NamedDecl *FoundD,
2309 SourceLocation TemplateKWLoc,
2310 const TemplateArgumentListInfo *TemplateArgs) {
2313 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2314 TemplateArgs);
2315}
2316
2317// CUDA/HIP: Check whether a captured reference variable is referencing a
2318// host variable in a device or host device lambda.
2320 VarDecl *VD) {
2321 if (!S.getLangOpts().CUDA || !VD->hasInit())
2322 return false;
2323 assert(VD->getType()->isReferenceType());
2324
2325 // Check whether the reference variable is referencing a host variable.
2326 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2327 if (!DRE)
2328 return false;
2329 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2330 if (!Referee || !Referee->hasGlobalStorage() ||
2331 Referee->hasAttr<CUDADeviceAttr>())
2332 return false;
2333
2334 // Check whether the current function is a device or host device lambda.
2335 // Check whether the reference variable is a capture by getDeclContext()
2336 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2337 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2338 if (MD && MD->getParent()->isLambda() &&
2339 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2340 VD->getDeclContext() != MD)
2341 return true;
2342
2343 return false;
2344}
2345
2347 // A declaration named in an unevaluated operand never constitutes an odr-use.
2349 return NOUR_Unevaluated;
2350
2351 // C++2a [basic.def.odr]p4:
2352 // A variable x whose name appears as a potentially-evaluated expression e
2353 // is odr-used by e unless [...] x is a reference that is usable in
2354 // constant expressions.
2355 // CUDA/HIP:
2356 // If a reference variable referencing a host variable is captured in a
2357 // device or host device lambda, the value of the referee must be copied
2358 // to the capture and the reference variable must be treated as odr-use
2359 // since the value of the referee is not known at compile time and must
2360 // be loaded from the captured.
2361 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2362 if (VD->getType()->isReferenceType() &&
2363 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2365 VD->isUsableInConstantExpressions(Context))
2366 return NOUR_Constant;
2367 }
2368
2369 // All remaining non-variable cases constitute an odr-use. For variables, we
2370 // need to wait and see how the expression is used.
2371 return NOUR_None;
2372}
2373
2376 const DeclarationNameInfo &NameInfo,
2377 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2378 SourceLocation TemplateKWLoc,
2379 const TemplateArgumentListInfo *TemplateArgs) {
2380 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2381 NeedToCaptureVariable(D, NameInfo.getLoc());
2382
2384 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2385 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2387
2388 // C++ [except.spec]p17:
2389 // An exception-specification is considered to be needed when:
2390 // - in an expression, the function is the unique lookup result or
2391 // the selected member of a set of overloaded functions.
2392 //
2393 // We delay doing this until after we've built the function reference and
2394 // marked it as used so that:
2395 // a) if the function is defaulted, we get errors from defining it before /
2396 // instead of errors from computing its exception specification, and
2397 // b) if the function is a defaulted comparison, we can use the body we
2398 // build when defining it as input to the exception specification
2399 // computation rather than computing a new body.
2400 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2401 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2402 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2403 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2404 }
2405 }
2406
2407 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2409 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2411
2412 const auto *FD = dyn_cast<FieldDecl>(D);
2413 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2414 FD = IFD->getAnonField();
2415 if (FD) {
2416 UnusedPrivateFields.remove(FD);
2417 // Just in case we're building an illegal pointer-to-member.
2418 if (FD->isBitField())
2420 }
2421
2422 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2423 // designates a bit-field.
2424 if (const auto *BD = dyn_cast<BindingDecl>(D))
2425 if (const auto *BE = BD->getBinding())
2426 E->setObjectKind(BE->getObjectKind());
2427
2428 return E;
2429}
2430
2431void
2434 DeclarationNameInfo &NameInfo,
2435 const TemplateArgumentListInfo *&TemplateArgs) {
2437 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2438 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2439
2440 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2441 Id.TemplateId->NumArgs);
2442 translateTemplateArguments(TemplateArgsPtr, Buffer);
2443
2444 TemplateName TName = Id.TemplateId->Template.get();
2446 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2447 TemplateArgs = &Buffer;
2448 } else {
2449 NameInfo = GetNameFromUnqualifiedId(Id);
2450 TemplateArgs = nullptr;
2451 }
2452}
2453
2455 // During a default argument instantiation the CurContext points
2456 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2457 // function parameter list, hence add an explicit check.
2458 bool isDefaultArgument =
2459 !CodeSynthesisContexts.empty() &&
2460 CodeSynthesisContexts.back().Kind ==
2462 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2463 bool isInstance = CurMethod && CurMethod->isInstance() &&
2464 R.getNamingClass() == CurMethod->getParent() &&
2465 !isDefaultArgument;
2466
2467 // There are two ways we can find a class-scope declaration during template
2468 // instantiation that we did not find in the template definition: if it is a
2469 // member of a dependent base class, or if it is declared after the point of
2470 // use in the same class. Distinguish these by comparing the class in which
2471 // the member was found to the naming class of the lookup.
2472 unsigned DiagID = diag::err_found_in_dependent_base;
2473 unsigned NoteID = diag::note_member_declared_at;
2475 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2476 : diag::err_found_later_in_class;
2477 } else if (getLangOpts().MSVCCompat) {
2478 DiagID = diag::ext_found_in_dependent_base;
2479 NoteID = diag::note_dependent_member_use;
2480 }
2481
2482 if (isInstance) {
2483 // Give a code modification hint to insert 'this->'.
2484 Diag(R.getNameLoc(), DiagID)
2485 << R.getLookupName()
2486 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2488 } else {
2489 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2490 // they're not shadowed).
2491 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2492 }
2493
2494 for (const NamedDecl *D : R)
2495 Diag(D->getLocation(), NoteID);
2496
2497 // Return true if we are inside a default argument instantiation
2498 // and the found name refers to an instance member function, otherwise
2499 // the caller will try to create an implicit member call and this is wrong
2500 // for default arguments.
2501 //
2502 // FIXME: Is this special case necessary? We could allow the caller to
2503 // diagnose this.
2504 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2505 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2506 return true;
2507 }
2508
2509 // Tell the callee to try to recover.
2510 return false;
2511}
2512
2515 TemplateArgumentListInfo *ExplicitTemplateArgs,
2516 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2517 DeclarationName Name = R.getLookupName();
2519
2520 unsigned diagnostic = diag::err_undeclared_var_use;
2521 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2525 diagnostic = diag::err_undeclared_use;
2526 diagnostic_suggest = diag::err_undeclared_use_suggest;
2527 }
2528
2529 // If the original lookup was an unqualified lookup, fake an
2530 // unqualified lookup. This is useful when (for example) the
2531 // original lookup would not have found something because it was a
2532 // dependent name.
2533 DeclContext *DC =
2534 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2535 while (DC) {
2536 if (isa<CXXRecordDecl>(DC)) {
2537 if (ExplicitTemplateArgs) {
2539 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2540 /*EnteringContext*/ false, TemplateNameIsRequired,
2541 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2542 return true;
2543 } else {
2544 LookupQualifiedName(R, DC);
2545 }
2546
2547 if (!R.empty()) {
2548 // Don't give errors about ambiguities in this lookup.
2550
2551 // If there's a best viable function among the results, only mention
2552 // that one in the notes.
2553 OverloadCandidateSet Candidates(R.getNameLoc(),
2555 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2557 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2558 OR_Success) {
2559 R.clear();
2560 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2561 R.resolveKind();
2562 }
2563
2565 }
2566
2567 R.clear();
2568 }
2569
2570 DC = DC->getLookupParent();
2571 }
2572
2573 // We didn't find anything, so try to correct for a typo.
2574 TypoCorrection Corrected;
2575 if (S && (Corrected =
2577 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2578 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2579 bool DroppedSpecifier =
2580 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2581 R.setLookupName(Corrected.getCorrection());
2582
2583 bool AcceptableWithRecovery = false;
2584 bool AcceptableWithoutRecovery = false;
2585 NamedDecl *ND = Corrected.getFoundDecl();
2586 if (ND) {
2587 if (Corrected.isOverloaded()) {
2591 for (NamedDecl *CD : Corrected) {
2592 if (FunctionTemplateDecl *FTD =
2593 dyn_cast<FunctionTemplateDecl>(CD))
2595 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2596 Args, OCS);
2597 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2598 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2600 Args, OCS);
2601 }
2602 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2603 case OR_Success:
2604 ND = Best->FoundDecl;
2605 Corrected.setCorrectionDecl(ND);
2606 break;
2607 default:
2608 // FIXME: Arbitrarily pick the first declaration for the note.
2609 Corrected.setCorrectionDecl(ND);
2610 break;
2611 }
2612 }
2613 R.addDecl(ND);
2614 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2617 if (!Record)
2621 }
2622
2623 auto *UnderlyingND = ND->getUnderlyingDecl();
2624 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2625 isa<FunctionTemplateDecl>(UnderlyingND);
2626 // FIXME: If we ended up with a typo for a type name or
2627 // Objective-C class name, we're in trouble because the parser
2628 // is in the wrong place to recover. Suggest the typo
2629 // correction, but don't make it a fix-it since we're not going
2630 // to recover well anyway.
2631 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2632 getAsTypeTemplateDecl(UnderlyingND) ||
2633 isa<ObjCInterfaceDecl>(UnderlyingND);
2634 } else {
2635 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2636 // because we aren't able to recover.
2637 AcceptableWithoutRecovery = true;
2638 }
2639
2640 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2641 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2642 ? diag::note_implicit_param_decl
2643 : diag::note_previous_decl;
2644 if (SS.isEmpty())
2645 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2646 PDiag(NoteID), AcceptableWithRecovery);
2647 else
2648 diagnoseTypo(Corrected,
2649 PDiag(diag::err_no_member_suggest)
2650 << Name << computeDeclContext(SS, false)
2651 << DroppedSpecifier << NameRange,
2652 PDiag(NoteID), AcceptableWithRecovery);
2653
2654 // Tell the callee whether to try to recover.
2655 return !AcceptableWithRecovery;
2656 }
2657 }
2658 R.clear();
2659
2660 // Emit a special diagnostic for failed member lookups.
2661 // FIXME: computing the declaration context might fail here (?)
2662 if (!SS.isEmpty()) {
2663 Diag(R.getNameLoc(), diag::err_no_member)
2664 << Name << computeDeclContext(SS, false) << NameRange;
2665 return true;
2666 }
2667
2668 // Give up, we can't recover.
2669 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2670 return true;
2671}
2672
2673/// In Microsoft mode, if we are inside a template class whose parent class has
2674/// dependent base classes, and we can't resolve an unqualified identifier, then
2675/// assume the identifier is a member of a dependent base class. We can only
2676/// recover successfully in static methods, instance methods, and other contexts
2677/// where 'this' is available. This doesn't precisely match MSVC's
2678/// instantiation model, but it's close enough.
2679static Expr *
2681 DeclarationNameInfo &NameInfo,
2682 SourceLocation TemplateKWLoc,
2683 const TemplateArgumentListInfo *TemplateArgs) {
2684 // Only try to recover from lookup into dependent bases in static methods or
2685 // contexts where 'this' is available.
2686 QualType ThisType = S.getCurrentThisType();
2687 const CXXRecordDecl *RD = nullptr;
2688 if (!ThisType.isNull())
2689 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2690 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2691 RD = MD->getParent();
2692 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2693 return nullptr;
2694
2695 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2696 // is available, suggest inserting 'this->' as a fixit.
2697 SourceLocation Loc = NameInfo.getLoc();
2698 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2699 DB << NameInfo.getName() << RD;
2700
2701 if (!ThisType.isNull()) {
2702 DB << FixItHint::CreateInsertion(Loc, "this->");
2704 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2705 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2706 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2707 }
2708
2709 // Synthesize a fake NNS that points to the derived class. This will
2710 // perform name lookup during template instantiation.
2711 CXXScopeSpec SS;
2712 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2713 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2715 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2716 TemplateArgs);
2717}
2718
2721 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2722 bool HasTrailingLParen, bool IsAddressOfOperand,
2724 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2725 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2726 "cannot be direct & operand and have a trailing lparen");
2727 if (SS.isInvalid())
2728 return ExprError();
2729
2730 TemplateArgumentListInfo TemplateArgsBuffer;
2731
2732 // Decompose the UnqualifiedId into the following data.
2733 DeclarationNameInfo NameInfo;
2734 const TemplateArgumentListInfo *TemplateArgs;
2735 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2736
2737 DeclarationName Name = NameInfo.getName();
2739 SourceLocation NameLoc = NameInfo.getLoc();
2740
2741 if (II && II->isEditorPlaceholder()) {
2742 // FIXME: When typed placeholders are supported we can create a typed
2743 // placeholder expression node.
2744 return ExprError();
2745 }
2746
2747 // This specially handles arguments of attributes appertains to a type of C
2748 // struct field such that the name lookup within a struct finds the member
2749 // name, which is not the case for other contexts in C.
2750 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2751 // See if this is reference to a field of struct.
2752 LookupResult R(*this, NameInfo, LookupMemberName);
2753 // LookupName handles a name lookup from within anonymous struct.
2754 if (LookupName(R, S)) {
2755 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2756 QualType type = VD->getType().getNonReferenceType();
2757 // This will eventually be translated into MemberExpr upon
2758 // the use of instantiated struct fields.
2759 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2760 }
2761 }
2762 }
2763
2764 // Perform the required lookup.
2765 LookupResult R(*this, NameInfo,
2769 if (TemplateKWLoc.isValid() || TemplateArgs) {
2770 // Lookup the template name again to correctly establish the context in
2771 // which it was found. This is really unfortunate as we already did the
2772 // lookup to determine that it was a template name in the first place. If
2773 // this becomes a performance hit, we can work harder to preserve those
2774 // results until we get here but it's likely not worth it.
2775 AssumedTemplateKind AssumedTemplate;
2776 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2777 /*EnteringContext=*/false, TemplateKWLoc,
2778 &AssumedTemplate))
2779 return ExprError();
2780
2782 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2783 IsAddressOfOperand, TemplateArgs);
2784 } else {
2785 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2786 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2787 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2788
2789 // If the result might be in a dependent base class, this is a dependent
2790 // id-expression.
2792 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2793 IsAddressOfOperand, TemplateArgs);
2794
2795 // If this reference is in an Objective-C method, then we need to do
2796 // some special Objective-C lookup, too.
2797 if (IvarLookupFollowUp) {
2798 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2799 if (E.isInvalid())
2800 return ExprError();
2801
2802 if (Expr *Ex = E.getAs<Expr>())
2803 return Ex;
2804 }
2805 }
2806
2807 if (R.isAmbiguous())
2808 return ExprError();
2809
2810 // This could be an implicitly declared function reference if the language
2811 // mode allows it as a feature.
2812 if (R.empty() && HasTrailingLParen && II &&
2813 getLangOpts().implicitFunctionsAllowed()) {
2814 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2815 if (D) R.addDecl(D);
2816 }
2817
2818 // Determine whether this name might be a candidate for
2819 // argument-dependent lookup.
2820 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2821
2822 if (R.empty() && !ADL) {
2823 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2824 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2825 TemplateKWLoc, TemplateArgs))
2826 return E;
2827 }
2828
2829 // Don't diagnose an empty lookup for inline assembly.
2830 if (IsInlineAsmIdentifier)
2831 return ExprError();
2832
2833 // If this name wasn't predeclared and if this is not a function
2834 // call, diagnose the problem.
2835 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2836 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2837 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2838 "Typo correction callback misconfigured");
2839 if (CCC) {
2840 // Make sure the callback knows what the typo being diagnosed is.
2841 CCC->setTypoName(II);
2842 if (SS.isValid())
2843 CCC->setTypoNNS(SS.getScopeRep());
2844 }
2845 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2846 // a template name, but we happen to have always already looked up the name
2847 // before we get here if it must be a template name.
2848 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2849 {}, nullptr))
2850 return ExprError();
2851
2852 assert(!R.empty() &&
2853 "DiagnoseEmptyLookup returned false but added no results");
2854
2855 // If we found an Objective-C instance variable, let
2856 // LookupInObjCMethod build the appropriate expression to
2857 // reference the ivar.
2858 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2859 R.clear();
2860 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2861 // In a hopelessly buggy code, Objective-C instance variable
2862 // lookup fails and no expression will be built to reference it.
2863 if (!E.isInvalid() && !E.get())
2864 return ExprError();
2865 return E;
2866 }
2867 }
2868
2869 // This is guaranteed from this point on.
2870 assert(!R.empty() || ADL);
2871
2872 // Check whether this might be a C++ implicit instance member access.
2873 // C++ [class.mfct.non-static]p3:
2874 // When an id-expression that is not part of a class member access
2875 // syntax and not used to form a pointer to member is used in the
2876 // body of a non-static member function of class X, if name lookup
2877 // resolves the name in the id-expression to a non-static non-type
2878 // member of some class C, the id-expression is transformed into a
2879 // class member access expression using (*this) as the
2880 // postfix-expression to the left of the . operator.
2881 //
2882 // But we don't actually need to do this for '&' operands if R
2883 // resolved to a function or overloaded function set, because the
2884 // expression is ill-formed if it actually works out to be a
2885 // non-static member function:
2886 //
2887 // C++ [expr.ref]p4:
2888 // Otherwise, if E1.E2 refers to a non-static member function. . .
2889 // [t]he expression can be used only as the left-hand operand of a
2890 // member function call.
2891 //
2892 // There are other safeguards against such uses, but it's important
2893 // to get this right here so that we don't end up making a
2894 // spuriously dependent expression if we're inside a dependent
2895 // instance method.
2896 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2897 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2898 S);
2899
2900 if (TemplateArgs || TemplateKWLoc.isValid()) {
2901
2902 // In C++1y, if this is a variable template id, then check it
2903 // in BuildTemplateIdExpr().
2904 // The single lookup result must be a variable template declaration.
2908 assert(R.getAsSingle<TemplateDecl>() &&
2909 "There should only be one declaration found.");
2910 }
2911
2912 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2913 }
2914
2915 return BuildDeclarationNameExpr(SS, R, ADL);
2916}
2917
2919 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2920 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2921 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2922 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2923
2924 if (R.isAmbiguous())
2925 return ExprError();
2926
2928 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2929 NameInfo, /*TemplateArgs=*/nullptr);
2930
2931 if (R.empty()) {
2932 // Don't diagnose problems with invalid record decl, the secondary no_member
2933 // diagnostic during template instantiation is likely bogus, e.g. if a class
2934 // is invalid because it's derived from an invalid base class, then missing
2935 // members were likely supposed to be inherited.
2937 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2938 if (CD->isInvalidDecl())
2939 return ExprError();
2940 Diag(NameInfo.getLoc(), diag::err_no_member)
2941 << NameInfo.getName() << DC << SS.getRange();
2942 return ExprError();
2943 }
2944
2945 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2946 QualType ET;
2947 TypeLocBuilder TLB;
2948 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
2949 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
2950 SS.getScopeRep(), TagD,
2951 /*OwnsTag=*/false);
2952 auto TL = TLB.push<TagTypeLoc>(ET);
2954 TL.setQualifierLoc(SS.getWithLocInContext(Context));
2955 TL.setNameLoc(NameInfo.getLoc());
2956 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
2957 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
2958 SS.getScopeRep(), TypedefD);
2959 TLB.push<TypedefTypeLoc>(ET).set(
2960 /*ElaboratedKeywordLoc=*/SourceLocation(),
2961 SS.getWithLocInContext(Context), NameInfo.getLoc());
2962 } else {
2963 // FIXME: What else can appear here?
2964 ET = SemaRef.Context.getTypeDeclType(TD);
2965 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
2966 assert(SS.isEmpty());
2967 }
2968
2969 // Diagnose a missing typename if this resolved unambiguously to a type in
2970 // a dependent context. If we can recover with a type, downgrade this to
2971 // a warning in Microsoft compatibility mode.
2972 unsigned DiagID = diag::err_typename_missing;
2973 if (RecoveryTSI && getLangOpts().MSVCCompat)
2974 DiagID = diag::ext_typename_missing;
2975 SourceLocation Loc = SS.getBeginLoc();
2976 auto D = Diag(Loc, DiagID);
2977 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
2978
2979 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2980 // context.
2981 if (!RecoveryTSI)
2982 return ExprError();
2983
2984 // Only issue the fixit if we're prepared to recover.
2985 D << FixItHint::CreateInsertion(Loc, "typename ");
2986
2987 // Recover by pretending this was an elaborated type.
2988 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2989
2990 return ExprEmpty();
2991 }
2992
2993 // If necessary, build an implicit class member access.
2994 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2996 /*TemplateKWLoc=*/SourceLocation(),
2997 R, /*TemplateArgs=*/nullptr,
2998 /*S=*/nullptr);
2999
3000 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3001}
3002
3004 NestedNameSpecifier Qualifier,
3005 NamedDecl *FoundDecl,
3006 NamedDecl *Member) {
3007 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3008 if (!RD)
3009 return From;
3010
3011 QualType DestRecordType;
3012 QualType DestType;
3013 QualType FromRecordType;
3014 QualType FromType = From->getType();
3015 bool PointerConversions = false;
3016 if (isa<FieldDecl>(Member)) {
3017 DestRecordType = Context.getCanonicalTagType(RD);
3018 auto FromPtrType = FromType->getAs<PointerType>();
3019 DestRecordType = Context.getAddrSpaceQualType(
3020 DestRecordType, FromPtrType
3021 ? FromType->getPointeeType().getAddressSpace()
3022 : FromType.getAddressSpace());
3023
3024 if (FromPtrType) {
3025 DestType = Context.getPointerType(DestRecordType);
3026 FromRecordType = FromPtrType->getPointeeType();
3027 PointerConversions = true;
3028 } else {
3029 DestType = DestRecordType;
3030 FromRecordType = FromType;
3031 }
3032 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3033 if (!Method->isImplicitObjectMemberFunction())
3034 return From;
3035
3036 DestType = Method->getThisType().getNonReferenceType();
3037 DestRecordType = Method->getFunctionObjectParameterType();
3038
3039 if (FromType->getAs<PointerType>()) {
3040 FromRecordType = FromType->getPointeeType();
3041 PointerConversions = true;
3042 } else {
3043 FromRecordType = FromType;
3044 DestType = DestRecordType;
3045 }
3046
3047 LangAS FromAS = FromRecordType.getAddressSpace();
3048 LangAS DestAS = DestRecordType.getAddressSpace();
3049 if (FromAS != DestAS) {
3050 QualType FromRecordTypeWithoutAS =
3051 Context.removeAddrSpaceQualType(FromRecordType);
3052 QualType FromTypeWithDestAS =
3053 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3054 if (PointerConversions)
3055 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3056 From = ImpCastExprToType(From, FromTypeWithDestAS,
3057 CK_AddressSpaceConversion, From->getValueKind())
3058 .get();
3059 }
3060 } else {
3061 // No conversion necessary.
3062 return From;
3063 }
3064
3065 if (DestType->isDependentType() || FromType->isDependentType())
3066 return From;
3067
3068 // If the unqualified types are the same, no conversion is necessary.
3069 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3070 return From;
3071
3072 SourceRange FromRange = From->getSourceRange();
3073 SourceLocation FromLoc = FromRange.getBegin();
3074
3075 ExprValueKind VK = From->getValueKind();
3076
3077 // C++ [class.member.lookup]p8:
3078 // [...] Ambiguities can often be resolved by qualifying a name with its
3079 // class name.
3080 //
3081 // If the member was a qualified name and the qualified referred to a
3082 // specific base subobject type, we'll cast to that intermediate type
3083 // first and then to the object in which the member is declared. That allows
3084 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3085 //
3086 // class Base { public: int x; };
3087 // class Derived1 : public Base { };
3088 // class Derived2 : public Base { };
3089 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3090 //
3091 // void VeryDerived::f() {
3092 // x = 17; // error: ambiguous base subobjects
3093 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3094 // }
3095 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3096 QualType QType = QualType(Qualifier.getAsType(), 0);
3097 assert(QType->isRecordType() && "lookup done with non-record type");
3098
3099 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3100
3101 // In C++98, the qualifier type doesn't actually have to be a base
3102 // type of the object type, in which case we just ignore it.
3103 // Otherwise build the appropriate casts.
3104 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3105 CXXCastPath BasePath;
3106 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3107 FromLoc, FromRange, &BasePath))
3108 return ExprError();
3109
3110 if (PointerConversions)
3111 QType = Context.getPointerType(QType);
3112 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3113 VK, &BasePath).get();
3114
3115 FromType = QType;
3116 FromRecordType = QRecordType;
3117
3118 // If the qualifier type was the same as the destination type,
3119 // we're done.
3120 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3121 return From;
3122 }
3123 }
3124
3125 CXXCastPath BasePath;
3126 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3127 FromLoc, FromRange, &BasePath,
3128 /*IgnoreAccess=*/true))
3129 return ExprError();
3130
3131 // Propagate qualifiers to base subobjects as per:
3132 // C++ [basic.type.qualifier]p1.2:
3133 // A volatile object is [...] a subobject of a volatile object.
3134 Qualifiers FromTypeQuals = FromType.getQualifiers();
3135 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3136 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3137
3138 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3139 &BasePath);
3140}
3141
3143 const LookupResult &R,
3144 bool HasTrailingLParen) {
3145 // Only when used directly as the postfix-expression of a call.
3146 if (!HasTrailingLParen)
3147 return false;
3148
3149 // Never if a scope specifier was provided.
3150 if (SS.isNotEmpty())
3151 return false;
3152
3153 // Only in C++ or ObjC++.
3154 if (!getLangOpts().CPlusPlus)
3155 return false;
3156
3157 // Turn off ADL when we find certain kinds of declarations during
3158 // normal lookup:
3159 for (const NamedDecl *D : R) {
3160 // C++0x [basic.lookup.argdep]p3:
3161 // -- a declaration of a class member
3162 // Since using decls preserve this property, we check this on the
3163 // original decl.
3164 if (D->isCXXClassMember())
3165 return false;
3166
3167 // C++0x [basic.lookup.argdep]p3:
3168 // -- a block-scope function declaration that is not a
3169 // using-declaration
3170 // NOTE: we also trigger this for function templates (in fact, we
3171 // don't check the decl type at all, since all other decl types
3172 // turn off ADL anyway).
3173 if (isa<UsingShadowDecl>(D))
3174 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3175 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3176 return false;
3177
3178 // C++0x [basic.lookup.argdep]p3:
3179 // -- a declaration that is neither a function or a function
3180 // template
3181 // And also for builtin functions.
3182 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3183 // But also builtin functions.
3184 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3185 return false;
3186 } else if (!isa<FunctionTemplateDecl>(D))
3187 return false;
3188 }
3189
3190 return true;
3191}
3192
3193
3194/// Diagnoses obvious problems with the use of the given declaration
3195/// as an expression. This is only actually called for lookups that
3196/// were not overloaded, and it doesn't promise that the declaration
3197/// will in fact be used.
3199 bool AcceptInvalid) {
3200 if (D->isInvalidDecl() && !AcceptInvalid)
3201 return true;
3202
3203 if (isa<TypedefNameDecl>(D)) {
3204 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3205 return true;
3206 }
3207
3208 if (isa<ObjCInterfaceDecl>(D)) {
3209 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3210 return true;
3211 }
3212
3213 if (isa<NamespaceDecl>(D)) {
3214 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3215 return true;
3216 }
3217
3218 return false;
3219}
3220
3221// Certain multiversion types should be treated as overloaded even when there is
3222// only one result.
3224 assert(R.isSingleResult() && "Expected only a single result");
3225 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3226 return FD &&
3227 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3228}
3229
3231 LookupResult &R, bool NeedsADL,
3232 bool AcceptInvalidDecl) {
3233 // If this is a single, fully-resolved result and we don't need ADL,
3234 // just build an ordinary singleton decl ref.
3235 if (!NeedsADL && R.isSingleResult() &&
3239 R.getRepresentativeDecl(), nullptr,
3240 AcceptInvalidDecl);
3241
3242 // We only need to check the declaration if there's exactly one
3243 // result, because in the overloaded case the results can only be
3244 // functions and function templates.
3246 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3247 AcceptInvalidDecl))
3248 return ExprError();
3249
3250 // Otherwise, just build an unresolved lookup expression. Suppress
3251 // any lookup-related diagnostics; we'll hash these out later, when
3252 // we've picked a target.
3254
3257 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3258 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3259
3260 return ULE;
3261}
3262
3264 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3265 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3266 bool AcceptInvalidDecl) {
3267 assert(D && "Cannot refer to a NULL declaration");
3268 assert(!isa<FunctionTemplateDecl>(D) &&
3269 "Cannot refer unambiguously to a function template");
3270
3271 SourceLocation Loc = NameInfo.getLoc();
3272 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3273 // Recovery from invalid cases (e.g. D is an invalid Decl).
3274 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3275 // diagnostics, as invalid decls use int as a fallback type.
3276 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3277 }
3278
3279 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3280 // Specifically diagnose references to class templates that are missing
3281 // a template argument list.
3282 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3283 return ExprError();
3284 }
3285
3286 // Make sure that we're referring to a value.
3288 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3289 Diag(D->getLocation(), diag::note_declared_at);
3290 return ExprError();
3291 }
3292
3293 // Check whether this declaration can be used. Note that we suppress
3294 // this check when we're going to perform argument-dependent lookup
3295 // on this function name, because this might not be the function
3296 // that overload resolution actually selects.
3297 if (DiagnoseUseOfDecl(D, Loc))
3298 return ExprError();
3299
3300 auto *VD = cast<ValueDecl>(D);
3301
3302 // Only create DeclRefExpr's for valid Decl's.
3303 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3304 return ExprError();
3305
3306 // Handle members of anonymous structs and unions. If we got here,
3307 // and the reference is to a class member indirect field, then this
3308 // must be the subject of a pointer-to-member expression.
3309 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3310 IndirectField && !IndirectField->isCXXClassMember())
3312 IndirectField);
3313
3314 QualType type = VD->getType();
3315 if (type.isNull())
3316 return ExprError();
3317 ExprValueKind valueKind = VK_PRValue;
3318
3319 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3320 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3321 // is expanded by some outer '...' in the context of the use.
3322 type = type.getNonPackExpansionType();
3323
3324 switch (D->getKind()) {
3325 // Ignore all the non-ValueDecl kinds.
3326#define ABSTRACT_DECL(kind)
3327#define VALUE(type, base)
3328#define DECL(type, base) case Decl::type:
3329#include "clang/AST/DeclNodes.inc"
3330 llvm_unreachable("invalid value decl kind");
3331
3332 // These shouldn't make it here.
3333 case Decl::ObjCAtDefsField:
3334 llvm_unreachable("forming non-member reference to ivar?");
3335
3336 // Enum constants are always r-values and never references.
3337 // Unresolved using declarations are dependent.
3338 case Decl::EnumConstant:
3339 case Decl::UnresolvedUsingValue:
3340 case Decl::OMPDeclareReduction:
3341 case Decl::OMPDeclareMapper:
3342 valueKind = VK_PRValue;
3343 break;
3344
3345 // Fields and indirect fields that got here must be for
3346 // pointer-to-member expressions; we just call them l-values for
3347 // internal consistency, because this subexpression doesn't really
3348 // exist in the high-level semantics.
3349 case Decl::Field:
3350 case Decl::IndirectField:
3351 case Decl::ObjCIvar:
3352 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3353 "building reference to field in C?");
3354
3355 // These can't have reference type in well-formed programs, but
3356 // for internal consistency we do this anyway.
3357 type = type.getNonReferenceType();
3358 valueKind = VK_LValue;
3359 break;
3360
3361 // Non-type template parameters are either l-values or r-values
3362 // depending on the type.
3363 case Decl::NonTypeTemplateParm: {
3364 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3365 type = reftype->getPointeeType();
3366 valueKind = VK_LValue; // even if the parameter is an r-value reference
3367 break;
3368 }
3369
3370 // [expr.prim.id.unqual]p2:
3371 // If the entity is a template parameter object for a template
3372 // parameter of type T, the type of the expression is const T.
3373 // [...] The expression is an lvalue if the entity is a [...] template
3374 // parameter object.
3375 if (type->isRecordType()) {
3376 type = type.getUnqualifiedType().withConst();
3377 valueKind = VK_LValue;
3378 break;
3379 }
3380
3381 // For non-references, we need to strip qualifiers just in case
3382 // the template parameter was declared as 'const int' or whatever.
3383 valueKind = VK_PRValue;
3384 type = type.getUnqualifiedType();
3385 break;
3386 }
3387
3388 case Decl::Var:
3389 case Decl::VarTemplateSpecialization:
3390 case Decl::VarTemplatePartialSpecialization:
3391 case Decl::Decomposition:
3392 case Decl::Binding:
3393 case Decl::OMPCapturedExpr:
3394 // In C, "extern void blah;" is valid and is an r-value.
3395 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3396 type->isVoidType()) {
3397 valueKind = VK_PRValue;
3398 break;
3399 }
3400 [[fallthrough]];
3401
3402 case Decl::ImplicitParam:
3403 case Decl::ParmVar: {
3404 // These are always l-values.
3405 valueKind = VK_LValue;
3406 type = type.getNonReferenceType();
3407
3408 // FIXME: Does the addition of const really only apply in
3409 // potentially-evaluated contexts? Since the variable isn't actually
3410 // captured in an unevaluated context, it seems that the answer is no.
3411 if (!isUnevaluatedContext()) {
3412 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3413 if (!CapturedType.isNull())
3414 type = CapturedType;
3415 }
3416 break;
3417 }
3418
3419 case Decl::Function: {
3420 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3421 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3422 type = Context.BuiltinFnTy;
3423 valueKind = VK_PRValue;
3424 break;
3425 }
3426 }
3427
3428 const FunctionType *fty = type->castAs<FunctionType>();
3429
3430 // If we're referring to a function with an __unknown_anytype
3431 // result type, make the entire expression __unknown_anytype.
3432 if (fty->getReturnType() == Context.UnknownAnyTy) {
3433 type = Context.UnknownAnyTy;
3434 valueKind = VK_PRValue;
3435 break;
3436 }
3437
3438 // Functions are l-values in C++.
3439 if (getLangOpts().CPlusPlus) {
3440 valueKind = VK_LValue;
3441 break;
3442 }
3443
3444 // C99 DR 316 says that, if a function type comes from a
3445 // function definition (without a prototype), that type is only
3446 // used for checking compatibility. Therefore, when referencing
3447 // the function, we pretend that we don't have the full function
3448 // type.
3449 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3450 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3451 fty->getExtInfo());
3452
3453 // Functions are r-values in C.
3454 valueKind = VK_PRValue;
3455 break;
3456 }
3457
3458 case Decl::CXXDeductionGuide:
3459 llvm_unreachable("building reference to deduction guide");
3460
3461 case Decl::MSProperty:
3462 case Decl::MSGuid:
3463 case Decl::TemplateParamObject:
3464 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3465 // capture in OpenMP, or duplicated between host and device?
3466 valueKind = VK_LValue;
3467 break;
3468
3469 case Decl::UnnamedGlobalConstant:
3470 valueKind = VK_LValue;
3471 break;
3472
3473 case Decl::CXXMethod:
3474 // If we're referring to a method with an __unknown_anytype
3475 // result type, make the entire expression __unknown_anytype.
3476 // This should only be possible with a type written directly.
3477 if (const FunctionProtoType *proto =
3478 dyn_cast<FunctionProtoType>(VD->getType()))
3479 if (proto->getReturnType() == Context.UnknownAnyTy) {
3480 type = Context.UnknownAnyTy;
3481 valueKind = VK_PRValue;
3482 break;
3483 }
3484
3485 // C++ methods are l-values if static, r-values if non-static.
3486 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3487 valueKind = VK_LValue;
3488 break;
3489 }
3490 [[fallthrough]];
3491
3492 case Decl::CXXConversion:
3493 case Decl::CXXDestructor:
3494 case Decl::CXXConstructor:
3495 valueKind = VK_PRValue;
3496 break;
3497 }
3498
3499 auto *E =
3500 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3501 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3502 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3503 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3504 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3505 // diagnostics).
3506 if (VD->isInvalidDecl() && E)
3507 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3508 return E;
3509}
3510
3511static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3513 Target.resize(CharByteWidth * (Source.size() + 1));
3514 char *ResultPtr = &Target[0];
3515 const llvm::UTF8 *ErrorPtr;
3516 bool success =
3517 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3518 (void)success;
3519 assert(success);
3520 Target.resize(ResultPtr - &Target[0]);
3521}
3522
3525 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3526 if (!currentDecl) {
3527 Diag(Loc, diag::ext_predef_outside_function);
3528 currentDecl = Context.getTranslationUnitDecl();
3529 }
3530
3531 QualType ResTy;
3532 StringLiteral *SL = nullptr;
3533 if (cast<DeclContext>(currentDecl)->isDependentContext())
3534 ResTy = Context.DependentTy;
3535 else {
3536 // Pre-defined identifiers are of type char[x], where x is the length of
3537 // the string.
3538 bool ForceElaboratedPrinting =
3539 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3540 auto Str =
3541 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3542 unsigned Length = Str.length();
3543
3544 llvm::APInt LengthI(32, Length + 1);
3547 ResTy =
3548 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3549 SmallString<32> RawChars;
3550 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3551 Str, RawChars);
3552 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3554 /*IndexTypeQuals*/ 0);
3556 /*Pascal*/ false, ResTy, Loc);
3557 } else {
3558 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3559 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3561 /*IndexTypeQuals*/ 0);
3563 /*Pascal*/ false, ResTy, Loc);
3564 }
3565 }
3566
3567 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3568 SL);
3569}
3570
3574
3576 SmallString<16> CharBuffer;
3577 bool Invalid = false;
3578 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3579 if (Invalid)
3580 return ExprError();
3581
3582 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3583 PP, Tok.getKind());
3584 if (Literal.hadError())
3585 return ExprError();
3586
3587 QualType Ty;
3588 if (Literal.isWide())
3589 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3590 else if (Literal.isUTF8() && getLangOpts().C23)
3591 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3592 else if (Literal.isUTF8() && getLangOpts().Char8)
3593 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3594 else if (Literal.isUTF16())
3595 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3596 else if (Literal.isUTF32())
3597 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3598 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3599 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3600 else
3601 Ty = Context.CharTy; // 'x' -> char in C++;
3602 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3603
3605 if (Literal.isWide())
3607 else if (Literal.isUTF16())
3609 else if (Literal.isUTF32())
3611 else if (Literal.isUTF8())
3613
3614 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3615 Tok.getLocation());
3616
3617 if (Literal.getUDSuffix().empty())
3618 return Lit;
3619
3620 // We're building a user-defined literal.
3621 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3622 SourceLocation UDSuffixLoc =
3623 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3624
3625 // Make sure we're allowed user-defined literals here.
3626 if (!UDLScope)
3627 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3628
3629 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3630 // operator "" X (ch)
3631 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3632 Lit, Tok.getLocation());
3633}
3634
3636 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3638 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3639 Context.IntTy, Loc);
3640}
3641
3643 QualType Ty, SourceLocation Loc) {
3644 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3645
3646 using llvm::APFloat;
3647 APFloat Val(Format);
3648
3649 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3650 if (RM == llvm::RoundingMode::Dynamic)
3651 RM = llvm::RoundingMode::NearestTiesToEven;
3652 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3653
3654 // Overflow is always an error, but underflow is only an error if
3655 // we underflowed to zero (APFloat reports denormals as underflow).
3656 if ((result & APFloat::opOverflow) ||
3657 ((result & APFloat::opUnderflow) && Val.isZero())) {
3658 unsigned diagnostic;
3659 SmallString<20> buffer;
3660 if (result & APFloat::opOverflow) {
3661 diagnostic = diag::warn_float_overflow;
3662 APFloat::getLargest(Format).toString(buffer);
3663 } else {
3664 diagnostic = diag::warn_float_underflow;
3665 APFloat::getSmallest(Format).toString(buffer);
3666 }
3667
3668 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3669 }
3670
3671 bool isExact = (result == APFloat::opOK);
3672 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3673}
3674
3675bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3676 assert(E && "Invalid expression");
3677
3678 if (E->isValueDependent())
3679 return false;
3680
3681 QualType QT = E->getType();
3682 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3683 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3684 return true;
3685 }
3686
3687 llvm::APSInt ValueAPS;
3689
3690 if (R.isInvalid())
3691 return true;
3692
3693 // GCC allows the value of unroll count to be 0.
3694 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3695 // "The values of 0 and 1 block any unrolling of the loop."
3696 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3697 // '#pragma unroll' cases.
3698 bool ValueIsPositive =
3699 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3700 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3701 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3702 << toString(ValueAPS, 10) << ValueIsPositive;
3703 return true;
3704 }
3705
3706 return false;
3707}
3708
3710 // Fast path for a single digit (which is quite common). A single digit
3711 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3712 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3713 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3714 return ActOnIntegerConstant(Tok.getLocation(), Val);
3715 }
3716
3717 SmallString<128> SpellingBuffer;
3718 // NumericLiteralParser wants to overread by one character. Add padding to
3719 // the buffer in case the token is copied to the buffer. If getSpelling()
3720 // returns a StringRef to the memory buffer, it should have a null char at
3721 // the EOF, so it is also safe.
3722 SpellingBuffer.resize(Tok.getLength() + 1);
3723
3724 // Get the spelling of the token, which eliminates trigraphs, etc.
3725 bool Invalid = false;
3726 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3727 if (Invalid)
3728 return ExprError();
3729
3730 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3731 PP.getSourceManager(), PP.getLangOpts(),
3732 PP.getTargetInfo(), PP.getDiagnostics());
3733 if (Literal.hadError)
3734 return ExprError();
3735
3736 if (Literal.hasUDSuffix()) {
3737 // We're building a user-defined literal.
3738 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3739 SourceLocation UDSuffixLoc =
3740 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3741
3742 // Make sure we're allowed user-defined literals here.
3743 if (!UDLScope)
3744 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3745
3746 QualType CookedTy;
3747 if (Literal.isFloatingLiteral()) {
3748 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3749 // long double, the literal is treated as a call of the form
3750 // operator "" X (f L)
3751 CookedTy = Context.LongDoubleTy;
3752 } else {
3753 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3754 // unsigned long long, the literal is treated as a call of the form
3755 // operator "" X (n ULL)
3756 CookedTy = Context.UnsignedLongLongTy;
3757 }
3758
3759 DeclarationName OpName =
3760 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3761 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3762 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3763
3764 SourceLocation TokLoc = Tok.getLocation();
3765
3766 // Perform literal operator lookup to determine if we're building a raw
3767 // literal or a cooked one.
3768 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3769 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3770 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3771 /*AllowStringTemplatePack*/ false,
3772 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3774 // Lookup failure for imaginary constants isn't fatal, there's still the
3775 // GNU extension producing _Complex types.
3776 break;
3777 case LOLR_Error:
3778 return ExprError();
3779 case LOLR_Cooked: {
3780 Expr *Lit;
3781 if (Literal.isFloatingLiteral()) {
3782 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3783 } else {
3784 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3785 if (Literal.GetIntegerValue(ResultVal))
3786 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3787 << /* Unsigned */ 1;
3788 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3789 Tok.getLocation());
3790 }
3791 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3792 }
3793
3794 case LOLR_Raw: {
3795 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3796 // literal is treated as a call of the form
3797 // operator "" X ("n")
3798 unsigned Length = Literal.getUDSuffixOffset();
3799 QualType StrTy = Context.getConstantArrayType(
3800 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3801 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3802 Expr *Lit =
3803 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3805 /*Pascal*/ false, StrTy, TokLoc);
3806 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3807 }
3808
3809 case LOLR_Template: {
3810 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3811 // template), L is treated as a call fo the form
3812 // operator "" X <'c1', 'c2', ... 'ck'>()
3813 // where n is the source character sequence c1 c2 ... ck.
3814 TemplateArgumentListInfo ExplicitArgs;
3815 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3816 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3817 llvm::APSInt Value(CharBits, CharIsUnsigned);
3818 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3819 Value = TokSpelling[I];
3820 TemplateArgument Arg(Context, Value, Context.CharTy);
3822 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3823 }
3824 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3825 }
3827 llvm_unreachable("unexpected literal operator lookup result");
3828 }
3829 }
3830
3831 Expr *Res;
3832
3833 if (Literal.isFixedPointLiteral()) {
3834 QualType Ty;
3835
3836 if (Literal.isAccum) {
3837 if (Literal.isHalf) {
3838 Ty = Context.ShortAccumTy;
3839 } else if (Literal.isLong) {
3840 Ty = Context.LongAccumTy;
3841 } else {
3842 Ty = Context.AccumTy;
3843 }
3844 } else if (Literal.isFract) {
3845 if (Literal.isHalf) {
3846 Ty = Context.ShortFractTy;
3847 } else if (Literal.isLong) {
3848 Ty = Context.LongFractTy;
3849 } else {
3850 Ty = Context.FractTy;
3851 }
3852 }
3853
3854 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3855
3856 bool isSigned = !Literal.isUnsigned;
3857 unsigned scale = Context.getFixedPointScale(Ty);
3858 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3859
3860 llvm::APInt Val(bit_width, 0, isSigned);
3861 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3862 bool ValIsZero = Val.isZero() && !Overflowed;
3863
3864 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3865 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3866 // Clause 6.4.4 - The value of a constant shall be in the range of
3867 // representable values for its type, with exception for constants of a
3868 // fract type with a value of exactly 1; such a constant shall denote
3869 // the maximal value for the type.
3870 --Val;
3871 else if (Val.ugt(MaxVal) || Overflowed)
3872 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3873
3875 Tok.getLocation(), scale);
3876 } else if (Literal.isFloatingLiteral()) {
3877 QualType Ty;
3878 if (Literal.isHalf){
3879 if (getLangOpts().HLSL ||
3880 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3881 Ty = Context.HalfTy;
3882 else {
3883 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3884 return ExprError();
3885 }
3886 } else if (Literal.isFloat)
3887 Ty = Context.FloatTy;
3888 else if (Literal.isLong)
3889 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3890 else if (Literal.isFloat16)
3891 Ty = Context.Float16Ty;
3892 else if (Literal.isFloat128)
3893 Ty = Context.Float128Ty;
3894 else if (getLangOpts().HLSL)
3895 Ty = Context.FloatTy;
3896 else
3897 Ty = Context.DoubleTy;
3898
3899 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3900
3901 if (Ty == Context.DoubleTy) {
3902 if (getLangOpts().SinglePrecisionConstants) {
3903 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3904 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3905 }
3906 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3907 "cl_khr_fp64", getLangOpts())) {
3908 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3909 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3911 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3912 }
3913 }
3914 } else if (!Literal.isIntegerLiteral()) {
3915 return ExprError();
3916 } else {
3917 QualType Ty;
3918
3919 // 'z/uz' literals are a C++23 feature.
3920 if (Literal.isSizeT)
3921 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3923 ? diag::warn_cxx20_compat_size_t_suffix
3924 : diag::ext_cxx23_size_t_suffix
3925 : diag::err_cxx23_size_t_suffix);
3926
3927 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3928 // but we do not currently support the suffix in C++ mode because it's not
3929 // entirely clear whether WG21 will prefer this suffix to return a library
3930 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3931 // literals are a C++ extension.
3932 if (Literal.isBitInt)
3933 PP.Diag(Tok.getLocation(),
3934 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3935 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3936 : diag::ext_c23_bitint_suffix);
3937
3938 // Get the value in the widest-possible width. What is "widest" depends on
3939 // whether the literal is a bit-precise integer or not. For a bit-precise
3940 // integer type, try to scan the source to determine how many bits are
3941 // needed to represent the value. This may seem a bit expensive, but trying
3942 // to get the integer value from an overly-wide APInt is *extremely*
3943 // expensive, so the naive approach of assuming
3944 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3945 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
3946 if (Literal.isBitInt)
3947 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
3948 Literal.getLiteralDigits(), Literal.getRadix());
3949 if (Literal.MicrosoftInteger) {
3950 if (Literal.MicrosoftInteger == 128 &&
3951 !Context.getTargetInfo().hasInt128Type())
3952 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3953 << Literal.isUnsigned;
3954 BitsNeeded = Literal.MicrosoftInteger;
3955 }
3956
3957 llvm::APInt ResultVal(BitsNeeded, 0);
3958
3959 if (Literal.GetIntegerValue(ResultVal)) {
3960 // If this value didn't fit into uintmax_t, error and force to ull.
3961 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3962 << /* Unsigned */ 1;
3963 Ty = Context.UnsignedLongLongTy;
3964 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3965 "long long is not intmax_t?");
3966 } else {
3967 // If this value fits into a ULL, try to figure out what else it fits into
3968 // according to the rules of C99 6.4.4.1p5.
3969
3970 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3971 // be an unsigned int.
3972 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3973
3974 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3975 // suffix for portability of code with C++, but both `l` and `ll` are
3976 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3977 // same.
3978 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3979 Literal.isLong = true;
3980 Literal.isLongLong = false;
3981 }
3982
3983 // Check from smallest to largest, picking the smallest type we can.
3984 unsigned Width = 0;
3985
3986 // Microsoft specific integer suffixes are explicitly sized.
3987 if (Literal.MicrosoftInteger) {
3988 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3989 Width = 8;
3990 Ty = Context.CharTy;
3991 } else {
3992 Width = Literal.MicrosoftInteger;
3993 Ty = Context.getIntTypeForBitwidth(Width,
3994 /*Signed=*/!Literal.isUnsigned);
3995 }
3996 }
3997
3998 // Bit-precise integer literals are automagically-sized based on the
3999 // width required by the literal.
4000 if (Literal.isBitInt) {
4001 // The signed version has one more bit for the sign value. There are no
4002 // zero-width bit-precise integers, even if the literal value is 0.
4003 Width = std::max(ResultVal.getActiveBits(), 1u) +
4004 (Literal.isUnsigned ? 0u : 1u);
4005
4006 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4007 // and reset the type to the largest supported width.
4008 unsigned int MaxBitIntWidth =
4009 Context.getTargetInfo().getMaxBitIntWidth();
4010 if (Width > MaxBitIntWidth) {
4011 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4012 << Literal.isUnsigned;
4013 Width = MaxBitIntWidth;
4014 }
4015
4016 // Reset the result value to the smaller APInt and select the correct
4017 // type to be used. Note, we zext even for signed values because the
4018 // literal itself is always an unsigned value (a preceeding - is a
4019 // unary operator, not part of the literal).
4020 ResultVal = ResultVal.zextOrTrunc(Width);
4021 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4022 }
4023
4024 // Check C++23 size_t literals.
4025 if (Literal.isSizeT) {
4026 assert(!Literal.MicrosoftInteger &&
4027 "size_t literals can't be Microsoft literals");
4028 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4029 Context.getTargetInfo().getSizeType());
4030
4031 // Does it fit in size_t?
4032 if (ResultVal.isIntN(SizeTSize)) {
4033 // Does it fit in ssize_t?
4034 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4035 Ty = Context.getSignedSizeType();
4036 else if (AllowUnsigned)
4037 Ty = Context.getSizeType();
4038 Width = SizeTSize;
4039 }
4040 }
4041
4042 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4043 !Literal.isSizeT) {
4044 // Are int/unsigned possibilities?
4045 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4046
4047 // Does it fit in a unsigned int?
4048 if (ResultVal.isIntN(IntSize)) {
4049 // Does it fit in a signed int?
4050 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4051 Ty = Context.IntTy;
4052 else if (AllowUnsigned)
4053 Ty = Context.UnsignedIntTy;
4054 Width = IntSize;
4055 }
4056 }
4057
4058 // Are long/unsigned long possibilities?
4059 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4060 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4061
4062 // Does it fit in a unsigned long?
4063 if (ResultVal.isIntN(LongSize)) {
4064 // Does it fit in a signed long?
4065 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4066 Ty = Context.LongTy;
4067 else if (AllowUnsigned)
4068 Ty = Context.UnsignedLongTy;
4069 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4070 // is compatible.
4071 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4072 const unsigned LongLongSize =
4073 Context.getTargetInfo().getLongLongWidth();
4074 Diag(Tok.getLocation(),
4076 ? Literal.isLong
4077 ? diag::warn_old_implicitly_unsigned_long_cxx
4078 : /*C++98 UB*/ diag::
4079 ext_old_implicitly_unsigned_long_cxx
4080 : diag::warn_old_implicitly_unsigned_long)
4081 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4082 : /*will be ill-formed*/ 1);
4083 Ty = Context.UnsignedLongTy;
4084 }
4085 Width = LongSize;
4086 }
4087 }
4088
4089 // Check long long if needed.
4090 if (Ty.isNull() && !Literal.isSizeT) {
4091 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4092
4093 // Does it fit in a unsigned long long?
4094 if (ResultVal.isIntN(LongLongSize)) {
4095 // Does it fit in a signed long long?
4096 // To be compatible with MSVC, hex integer literals ending with the
4097 // LL or i64 suffix are always signed in Microsoft mode.
4098 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4099 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4100 Ty = Context.LongLongTy;
4101 else if (AllowUnsigned)
4102 Ty = Context.UnsignedLongLongTy;
4103 Width = LongLongSize;
4104
4105 // 'long long' is a C99 or C++11 feature, whether the literal
4106 // explicitly specified 'long long' or we needed the extra width.
4107 if (getLangOpts().CPlusPlus)
4108 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4109 ? diag::warn_cxx98_compat_longlong
4110 : diag::ext_cxx11_longlong);
4111 else if (!getLangOpts().C99)
4112 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4113 }
4114 }
4115
4116 // If we still couldn't decide a type, we either have 'size_t' literal
4117 // that is out of range, or a decimal literal that does not fit in a
4118 // signed long long and has no U suffix.
4119 if (Ty.isNull()) {
4120 if (Literal.isSizeT)
4121 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4122 << Literal.isUnsigned;
4123 else
4124 Diag(Tok.getLocation(),
4125 diag::ext_integer_literal_too_large_for_signed);
4126 Ty = Context.UnsignedLongLongTy;
4127 Width = Context.getTargetInfo().getLongLongWidth();
4128 }
4129
4130 if (ResultVal.getBitWidth() != Width)
4131 ResultVal = ResultVal.trunc(Width);
4132 }
4133 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4134 }
4135
4136 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4137 if (Literal.isImaginary) {
4138 Res = new (Context) ImaginaryLiteral(Res,
4139 Context.getComplexType(Res->getType()));
4140
4141 // In C++, this is a GNU extension. In C, it's a C2y extension.
4142 unsigned DiagId;
4143 if (getLangOpts().CPlusPlus)
4144 DiagId = diag::ext_gnu_imaginary_constant;
4145 else if (getLangOpts().C2y)
4146 DiagId = diag::warn_c23_compat_imaginary_constant;
4147 else
4148 DiagId = diag::ext_c2y_imaginary_constant;
4149 Diag(Tok.getLocation(), DiagId);
4150 }
4151 return Res;
4152}
4153
4155 assert(E && "ActOnParenExpr() missing expr");
4156 QualType ExprTy = E->getType();
4157 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4158 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4159 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4160 return new (Context) ParenExpr(L, R, E);
4161}
4162
4164 SourceLocation Loc,
4165 SourceRange ArgRange) {
4166 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4167 // scalar or vector data type argument..."
4168 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4169 // type (C99 6.2.5p18) or void.
4170 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4171 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4172 << T << ArgRange;
4173 return true;
4174 }
4175
4176 assert((T->isVoidType() || !T->isIncompleteType()) &&
4177 "Scalar types should always be complete");
4178 return false;
4179}
4180
4182 SourceLocation Loc,
4183 SourceRange ArgRange) {
4184 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4185 if (!T->isVectorType() && !T->isSizelessVectorType())
4186 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4187 << ""
4188 << "__builtin_vectorelements" << T << ArgRange;
4189
4190 return false;
4191}
4192
4194 SourceLocation Loc,
4195 SourceRange ArgRange) {
4196 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4197 return true;
4198
4199 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4200 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4201 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4202 return true;
4203 }
4204
4205 return false;
4206}
4207
4209 SourceLocation Loc,
4210 SourceRange ArgRange,
4211 UnaryExprOrTypeTrait TraitKind) {
4212 // Invalid types must be hard errors for SFINAE in C++.
4213 if (S.LangOpts.CPlusPlus)
4214 return true;
4215
4216 // C99 6.5.3.4p1:
4217 if (T->isFunctionType() &&
4218 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4219 TraitKind == UETT_PreferredAlignOf)) {
4220 // sizeof(function)/alignof(function) is allowed as an extension.
4221 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4222 << getTraitSpelling(TraitKind) << ArgRange;
4223 return false;
4224 }
4225
4226 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4227 // this is an error (OpenCL v1.1 s6.3.k)
4228 if (T->isVoidType()) {
4229 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4230 : diag::ext_sizeof_alignof_void_type;
4231 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4232 return false;
4233 }
4234
4235 return true;
4236}
4237
4239 SourceLocation Loc,
4240 SourceRange ArgRange,
4241 UnaryExprOrTypeTrait TraitKind) {
4242 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4243 // runtime doesn't allow it.
4244 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4245 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4246 << T << (TraitKind == UETT_SizeOf)
4247 << ArgRange;
4248 return true;
4249 }
4250
4251 return false;
4252}
4253
4254/// Check whether E is a pointer from a decayed array type (the decayed
4255/// pointer type is equal to T) and emit a warning if it is.
4257 const Expr *E) {
4258 // Don't warn if the operation changed the type.
4259 if (T != E->getType())
4260 return;
4261
4262 // Now look for array decays.
4263 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4264 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4265 return;
4266
4267 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4268 << ICE->getType()
4269 << ICE->getSubExpr()->getType();
4270}
4271
4273 UnaryExprOrTypeTrait ExprKind) {
4274 QualType ExprTy = E->getType();
4275 assert(!ExprTy->isReferenceType());
4276
4277 bool IsUnevaluatedOperand =
4278 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4279 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4280 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4281 if (IsUnevaluatedOperand) {
4283 if (Result.isInvalid())
4284 return true;
4285 E = Result.get();
4286 }
4287
4288 // The operand for sizeof and alignof is in an unevaluated expression context,
4289 // so side effects could result in unintended consequences.
4290 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4291 // used to build SFINAE gadgets.
4292 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4293 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4295 !E->getType()->isVariableArrayType() &&
4296 E->HasSideEffects(Context, false))
4297 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4298
4299 if (ExprKind == UETT_VecStep)
4300 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4301 E->getSourceRange());
4302
4303 if (ExprKind == UETT_VectorElements)
4304 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4305 E->getSourceRange());
4306
4307 // Explicitly list some types as extensions.
4308 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4309 E->getSourceRange(), ExprKind))
4310 return false;
4311
4312 // WebAssembly tables are always illegal operands to unary expressions and
4313 // type traits.
4314 if (Context.getTargetInfo().getTriple().isWasm() &&
4316 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4317 << getTraitSpelling(ExprKind);
4318 return true;
4319 }
4320
4321 // 'alignof' applied to an expression only requires the base element type of
4322 // the expression to be complete. 'sizeof' requires the expression's type to
4323 // be complete (and will attempt to complete it if it's an array of unknown
4324 // bound).
4325 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4327 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4328 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4329 getTraitSpelling(ExprKind), E->getSourceRange()))
4330 return true;
4331 } else {
4333 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4334 getTraitSpelling(ExprKind), E->getSourceRange()))
4335 return true;
4336 }
4337
4338 // Completing the expression's type may have changed it.
4339 ExprTy = E->getType();
4340 assert(!ExprTy->isReferenceType());
4341
4342 if (ExprTy->isFunctionType()) {
4343 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4344 << getTraitSpelling(ExprKind) << E->getSourceRange();
4345 return true;
4346 }
4347
4348 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4349 E->getSourceRange(), ExprKind))
4350 return true;
4351
4352 if (ExprKind == UETT_CountOf) {
4353 // The type has to be an array type. We already checked for incomplete
4354 // types above.
4355 QualType ExprType = E->IgnoreParens()->getType();
4356 if (!ExprType->isArrayType()) {
4357 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4358 return true;
4359 }
4360 // FIXME: warn on _Countof on an array parameter. Not warning on it
4361 // currently because there are papers in WG14 about array types which do
4362 // not decay that could impact this behavior, so we want to see if anything
4363 // changes here before coming up with a warning group for _Countof-related
4364 // diagnostics.
4365 }
4366
4367 if (ExprKind == UETT_SizeOf) {
4368 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4369 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4370 QualType OType = PVD->getOriginalType();
4371 QualType Type = PVD->getType();
4372 if (Type->isPointerType() && OType->isArrayType()) {
4373 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4374 << Type << OType;
4375 Diag(PVD->getLocation(), diag::note_declared_at);
4376 }
4377 }
4378 }
4379
4380 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4381 // decays into a pointer and returns an unintended result. This is most
4382 // likely a typo for "sizeof(array) op x".
4383 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4384 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4385 BO->getLHS());
4386 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4387 BO->getRHS());
4388 }
4389 }
4390
4391 return false;
4392}
4393
4394static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4395 // Cannot know anything else if the expression is dependent.
4396 if (E->isTypeDependent())
4397 return false;
4398
4399 if (E->getObjectKind() == OK_BitField) {
4400 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4401 << 1 << E->getSourceRange();
4402 return true;
4403 }
4404
4405 ValueDecl *D = nullptr;
4406 Expr *Inner = E->IgnoreParens();
4407 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4408 D = DRE->getDecl();
4409 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4410 D = ME->getMemberDecl();
4411 }
4412
4413 // If it's a field, require the containing struct to have a
4414 // complete definition so that we can compute the layout.
4415 //
4416 // This can happen in C++11 onwards, either by naming the member
4417 // in a way that is not transformed into a member access expression
4418 // (in an unevaluated operand, for instance), or by naming the member
4419 // in a trailing-return-type.
4420 //
4421 // For the record, since __alignof__ on expressions is a GCC
4422 // extension, GCC seems to permit this but always gives the
4423 // nonsensical answer 0.
4424 //
4425 // We don't really need the layout here --- we could instead just
4426 // directly check for all the appropriate alignment-lowing
4427 // attributes --- but that would require duplicating a lot of
4428 // logic that just isn't worth duplicating for such a marginal
4429 // use-case.
4430 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4431 // Fast path this check, since we at least know the record has a
4432 // definition if we can find a member of it.
4433 if (!FD->getParent()->isCompleteDefinition()) {
4434 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4435 << E->getSourceRange();
4436 return true;
4437 }
4438
4439 // Otherwise, if it's a field, and the field doesn't have
4440 // reference type, then it must have a complete type (or be a
4441 // flexible array member, which we explicitly want to
4442 // white-list anyway), which makes the following checks trivial.
4443 if (!FD->getType()->isReferenceType())
4444 return false;
4445 }
4446
4447 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4448}
4449
4451 E = E->IgnoreParens();
4452
4453 // Cannot know anything else if the expression is dependent.
4454 if (E->isTypeDependent())
4455 return false;
4456
4457 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4458}
4459
4461 CapturingScopeInfo *CSI) {
4462 assert(T->isVariablyModifiedType());
4463 assert(CSI != nullptr);
4464
4465 // We're going to walk down into the type and look for VLA expressions.
4466 do {
4467 const Type *Ty = T.getTypePtr();
4468 switch (Ty->getTypeClass()) {
4469#define TYPE(Class, Base)
4470#define ABSTRACT_TYPE(Class, Base)
4471#define NON_CANONICAL_TYPE(Class, Base)
4472#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4473#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4474#include "clang/AST/TypeNodes.inc"
4475 T = QualType();
4476 break;
4477 // These types are never variably-modified.
4478 case Type::Builtin:
4479 case Type::Complex:
4480 case Type::Vector:
4481 case Type::ExtVector:
4482 case Type::ConstantMatrix:
4483 case Type::Record:
4484 case Type::Enum:
4485 case Type::TemplateSpecialization:
4486 case Type::ObjCObject:
4487 case Type::ObjCInterface:
4488 case Type::ObjCObjectPointer:
4489 case Type::ObjCTypeParam:
4490 case Type::Pipe:
4491 case Type::BitInt:
4492 case Type::HLSLInlineSpirv:
4493 llvm_unreachable("type class is never variably-modified!");
4494 case Type::Adjusted:
4495 T = cast<AdjustedType>(Ty)->getOriginalType();
4496 break;
4497 case Type::Decayed:
4498 T = cast<DecayedType>(Ty)->getPointeeType();
4499 break;
4500 case Type::ArrayParameter:
4501 T = cast<ArrayParameterType>(Ty)->getElementType();
4502 break;
4503 case Type::Pointer:
4504 T = cast<PointerType>(Ty)->getPointeeType();
4505 break;
4506 case Type::BlockPointer:
4507 T = cast<BlockPointerType>(Ty)->getPointeeType();
4508 break;
4509 case Type::LValueReference:
4510 case Type::RValueReference:
4511 T = cast<ReferenceType>(Ty)->getPointeeType();
4512 break;
4513 case Type::MemberPointer:
4514 T = cast<MemberPointerType>(Ty)->getPointeeType();
4515 break;
4516 case Type::ConstantArray:
4517 case Type::IncompleteArray:
4518 // Losing element qualification here is fine.
4519 T = cast<ArrayType>(Ty)->getElementType();
4520 break;
4521 case Type::VariableArray: {
4522 // Losing element qualification here is fine.
4524
4525 // Unknown size indication requires no size computation.
4526 // Otherwise, evaluate and record it.
4527 auto Size = VAT->getSizeExpr();
4528 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4530 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4531
4532 T = VAT->getElementType();
4533 break;
4534 }
4535 case Type::FunctionProto:
4536 case Type::FunctionNoProto:
4537 T = cast<FunctionType>(Ty)->getReturnType();
4538 break;
4539 case Type::Paren:
4540 case Type::TypeOf:
4541 case Type::UnaryTransform:
4542 case Type::Attributed:
4543 case Type::BTFTagAttributed:
4544 case Type::HLSLAttributedResource:
4545 case Type::SubstTemplateTypeParm:
4546 case Type::MacroQualified:
4547 case Type::CountAttributed:
4548 // Keep walking after single level desugaring.
4549 T = T.getSingleStepDesugaredType(Context);
4550 break;
4551 case Type::Typedef:
4552 T = cast<TypedefType>(Ty)->desugar();
4553 break;
4554 case Type::Decltype:
4555 T = cast<DecltypeType>(Ty)->desugar();
4556 break;
4557 case Type::PackIndexing:
4558 T = cast<PackIndexingType>(Ty)->desugar();
4559 break;
4560 case Type::Using:
4561 T = cast<UsingType>(Ty)->desugar();
4562 break;
4563 case Type::Auto:
4564 case Type::DeducedTemplateSpecialization:
4565 T = cast<DeducedType>(Ty)->getDeducedType();
4566 break;
4567 case Type::TypeOfExpr:
4568 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4569 break;
4570 case Type::Atomic:
4571 T = cast<AtomicType>(Ty)->getValueType();
4572 break;
4573 case Type::PredefinedSugar:
4574 T = cast<PredefinedSugarType>(Ty)->desugar();
4575 break;
4576 }
4577 } while (!T.isNull() && T->isVariablyModifiedType());
4578}
4579
4581 SourceLocation OpLoc,
4582 SourceRange ExprRange,
4583 UnaryExprOrTypeTrait ExprKind,
4584 StringRef KWName) {
4585 if (ExprType->isDependentType())
4586 return false;
4587
4588 // C++ [expr.sizeof]p2:
4589 // When applied to a reference or a reference type, the result
4590 // is the size of the referenced type.
4591 // C++11 [expr.alignof]p3:
4592 // When alignof is applied to a reference type, the result
4593 // shall be the alignment of the referenced type.
4594 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4595 ExprType = Ref->getPointeeType();
4596
4597 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4598 // When alignof or _Alignof is applied to an array type, the result
4599 // is the alignment of the element type.
4600 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4601 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4602 // If the trait is 'alignof' in C before C2y, the ability to apply the
4603 // trait to an incomplete array is an extension.
4604 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4605 ExprType->isIncompleteArrayType())
4606 Diag(OpLoc, getLangOpts().C2y
4607 ? diag::warn_c2y_compat_alignof_incomplete_array
4608 : diag::ext_c2y_alignof_incomplete_array);
4609 ExprType = Context.getBaseElementType(ExprType);
4610 }
4611
4612 if (ExprKind == UETT_VecStep)
4613 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4614
4615 if (ExprKind == UETT_VectorElements)
4616 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4617 ExprRange);
4618
4619 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4620 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4621 ExprRange);
4622
4623 // Explicitly list some types as extensions.
4624 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4625 ExprKind))
4626 return false;
4627
4629 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4630 KWName, ExprRange))
4631 return true;
4632
4633 if (ExprType->isFunctionType()) {
4634 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4635 return true;
4636 }
4637
4638 if (ExprKind == UETT_CountOf) {
4639 // The type has to be an array type. We already checked for incomplete
4640 // types above.
4641 if (!ExprType->isArrayType()) {
4642 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4643 return true;
4644 }
4645 }
4646
4647 // WebAssembly tables are always illegal operands to unary expressions and
4648 // type traits.
4649 if (Context.getTargetInfo().getTriple().isWasm() &&
4650 ExprType->isWebAssemblyTableType()) {
4651 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4652 << getTraitSpelling(ExprKind);
4653 return true;
4654 }
4655
4656 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4657 ExprKind))
4658 return true;
4659
4660 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4661 if (auto *TT = ExprType->getAs<TypedefType>()) {
4662 for (auto I = FunctionScopes.rbegin(),
4663 E = std::prev(FunctionScopes.rend());
4664 I != E; ++I) {
4665 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4666 if (CSI == nullptr)
4667 break;
4668 DeclContext *DC = nullptr;
4669 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4670 DC = LSI->CallOperator;
4671 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4672 DC = CRSI->TheCapturedDecl;
4673 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4674 DC = BSI->TheDecl;
4675 if (DC) {
4676 if (DC->containsDecl(TT->getDecl()))
4677 break;
4678 captureVariablyModifiedType(Context, ExprType, CSI);
4679 }
4680 }
4681 }
4682 }
4683
4684 return false;
4685}
4686
4688 SourceLocation OpLoc,
4689 UnaryExprOrTypeTrait ExprKind,
4690 SourceRange R) {
4691 if (!TInfo)
4692 return ExprError();
4693
4694 QualType T = TInfo->getType();
4695
4696 if (!T->isDependentType() &&
4697 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4698 getTraitSpelling(ExprKind)))
4699 return ExprError();
4700
4701 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4702 // properly deal with VLAs in nested calls of sizeof and typeof.
4703 if (currentEvaluationContext().isUnevaluated() &&
4704 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4705 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4706 TInfo->getType()->isVariablyModifiedType())
4707 TInfo = TransformToPotentiallyEvaluated(TInfo);
4708
4709 // It's possible that the transformation above failed.
4710 if (!TInfo)
4711 return ExprError();
4712
4713 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4714 return new (Context) UnaryExprOrTypeTraitExpr(
4715 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4716}
4717
4720 UnaryExprOrTypeTrait ExprKind) {
4722 if (PE.isInvalid())
4723 return ExprError();
4724
4725 E = PE.get();
4726
4727 // Verify that the operand is valid.
4728 bool isInvalid = false;
4729 if (E->isTypeDependent()) {
4730 // Delay type-checking for type-dependent expressions.
4731 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4732 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4733 } else if (ExprKind == UETT_VecStep) {
4735 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4736 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4737 isInvalid = true;
4738 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4739 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4740 isInvalid = true;
4741 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4742 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4744 }
4745
4746 if (isInvalid)
4747 return ExprError();
4748
4749 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4750 E->getType()->isVariableArrayType()) {
4752 if (PE.isInvalid()) return ExprError();
4753 E = PE.get();
4754 }
4755
4756 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4757 return new (Context) UnaryExprOrTypeTraitExpr(
4758 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4759}
4760
4763 UnaryExprOrTypeTrait ExprKind, bool IsType,
4764 void *TyOrEx, SourceRange ArgRange) {
4765 // If error parsing type, ignore.
4766 if (!TyOrEx) return ExprError();
4767
4768 if (IsType) {
4769 TypeSourceInfo *TInfo;
4770 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4771 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4772 }
4773
4774 Expr *ArgEx = (Expr *)TyOrEx;
4775 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4776 return Result;
4777}
4778
4780 SourceLocation OpLoc, SourceRange R) {
4781 if (!TInfo)
4782 return true;
4783 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4784 UETT_AlignOf, KWName);
4785}
4786
4788 SourceLocation OpLoc, SourceRange R) {
4789 TypeSourceInfo *TInfo;
4791 &TInfo);
4792 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4793}
4794
4796 bool IsReal) {
4797 if (V.get()->isTypeDependent())
4798 return S.Context.DependentTy;
4799
4800 // _Real and _Imag are only l-values for normal l-values.
4801 if (V.get()->getObjectKind() != OK_Ordinary) {
4802 V = S.DefaultLvalueConversion(V.get());
4803 if (V.isInvalid())
4804 return QualType();
4805 }
4806
4807 // These operators return the element type of a complex type.
4808 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4809 return CT->getElementType();
4810
4811 // Otherwise they pass through real integer and floating point types here.
4812 if (V.get()->getType()->isArithmeticType())
4813 return V.get()->getType();
4814
4815 // Test for placeholders.
4816 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4817 if (PR.isInvalid()) return QualType();
4818 if (PR.get() != V.get()) {
4819 V = PR;
4820 return CheckRealImagOperand(S, V, Loc, IsReal);
4821 }
4822
4823 // Reject anything else.
4824 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4825 << (IsReal ? "__real" : "__imag");
4826 return QualType();
4827}
4828
4829
4830
4833 tok::TokenKind Kind, Expr *Input) {
4835 switch (Kind) {
4836 default: llvm_unreachable("Unknown unary op!");
4837 case tok::plusplus: Opc = UO_PostInc; break;
4838 case tok::minusminus: Opc = UO_PostDec; break;
4839 }
4840
4841 // Since this might is a postfix expression, get rid of ParenListExprs.
4843 if (Result.isInvalid()) return ExprError();
4844 Input = Result.get();
4845
4846 return BuildUnaryOp(S, OpLoc, Opc, Input);
4847}
4848
4849/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4850///
4851/// \return true on error
4853 SourceLocation opLoc,
4854 Expr *op) {
4855 assert(op->getType()->isObjCObjectPointerType());
4857 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4858 return false;
4859
4860 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4862 << op->getSourceRange();
4863 return true;
4864}
4865
4867 auto *BaseNoParens = Base->IgnoreParens();
4868 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4869 return MSProp->getPropertyDecl()->getType()->isArrayType();
4870 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4871}
4872
4873// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4874// Typically this is DependentTy, but can sometimes be more precise.
4875//
4876// There are cases when we could determine a non-dependent type:
4877// - LHS and RHS may have non-dependent types despite being type-dependent
4878// (e.g. unbounded array static members of the current instantiation)
4879// - one may be a dependent-sized array with known element type
4880// - one may be a dependent-typed valid index (enum in current instantiation)
4881//
4882// We *always* return a dependent type, in such cases it is DependentTy.
4883// This avoids creating type-dependent expressions with non-dependent types.
4884// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4886 const ASTContext &Ctx) {
4887 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4888 QualType LTy = LHS->getType(), RTy = RHS->getType();
4889 QualType Result = Ctx.DependentTy;
4890 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4891 if (const PointerType *PT = LTy->getAs<PointerType>())
4892 Result = PT->getPointeeType();
4893 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4894 Result = AT->getElementType();
4895 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4896 if (const PointerType *PT = RTy->getAs<PointerType>())
4897 Result = PT->getPointeeType();
4898 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4899 Result = AT->getElementType();
4900 }
4901 // Ensure we return a dependent type.
4902 return Result->isDependentType() ? Result : Ctx.DependentTy;
4903}
4904
4906 SourceLocation lbLoc,
4907 MultiExprArg ArgExprs,
4908 SourceLocation rbLoc) {
4909
4910 if (base && !base->getType().isNull() &&
4911 base->hasPlaceholderType(BuiltinType::ArraySection)) {
4912 auto *AS = cast<ArraySectionExpr>(base);
4913 if (AS->isOMPArraySection())
4915 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4916 /*Length*/ nullptr,
4917 /*Stride=*/nullptr, rbLoc);
4918
4919 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4920 SourceLocation(), /*Length*/ nullptr,
4921 rbLoc);
4922 }
4923
4924 // Since this might be a postfix expression, get rid of ParenListExprs.
4925 if (isa<ParenListExpr>(base)) {
4927 if (result.isInvalid())
4928 return ExprError();
4929 base = result.get();
4930 }
4931
4932 // Check if base and idx form a MatrixSubscriptExpr.
4933 //
4934 // Helper to check for comma expressions, which are not allowed as indices for
4935 // matrix subscript expressions.
4936 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4937 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4938 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4939 << SourceRange(base->getBeginLoc(), rbLoc);
4940 return true;
4941 }
4942 return false;
4943 };
4944 // The matrix subscript operator ([][])is considered a single operator.
4945 // Separating the index expressions by parenthesis is not allowed.
4946 if (base && !base->getType().isNull() &&
4947 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4948 !isa<MatrixSubscriptExpr>(base)) {
4949 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4950 << SourceRange(base->getBeginLoc(), rbLoc);
4951 return ExprError();
4952 }
4953 // If the base is a MatrixSubscriptExpr, try to create a new
4954 // MatrixSubscriptExpr.
4955 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4956 if (matSubscriptE) {
4957 assert(ArgExprs.size() == 1);
4958 if (CheckAndReportCommaError(ArgExprs.front()))
4959 return ExprError();
4960
4961 assert(matSubscriptE->isIncomplete() &&
4962 "base has to be an incomplete matrix subscript");
4963 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4964 matSubscriptE->getRowIdx(),
4965 ArgExprs.front(), rbLoc);
4966 }
4967 if (base->getType()->isWebAssemblyTableType()) {
4968 Diag(base->getExprLoc(), diag::err_wasm_table_art)
4969 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4970 return ExprError();
4971 }
4972
4973 CheckInvalidBuiltinCountedByRef(base,
4975
4976 // Handle any non-overload placeholder types in the base and index
4977 // expressions. We can't handle overloads here because the other
4978 // operand might be an overloadable type, in which case the overload
4979 // resolution for the operator overload should get the first crack
4980 // at the overload.
4981 bool IsMSPropertySubscript = false;
4982 if (base->getType()->isNonOverloadPlaceholderType()) {
4983 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4984 if (!IsMSPropertySubscript) {
4985 ExprResult result = CheckPlaceholderExpr(base);
4986 if (result.isInvalid())
4987 return ExprError();
4988 base = result.get();
4989 }
4990 }
4991
4992 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4993 if (base->getType()->isMatrixType()) {
4994 assert(ArgExprs.size() == 1);
4995 if (CheckAndReportCommaError(ArgExprs.front()))
4996 return ExprError();
4997
4998 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4999 rbLoc);
5000 }
5001
5002 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5003 Expr *idx = ArgExprs[0];
5004 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5006 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5007 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5008 << SourceRange(base->getBeginLoc(), rbLoc);
5009 }
5010 }
5011
5012 if (ArgExprs.size() == 1 &&
5013 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5014 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5015 if (result.isInvalid())
5016 return ExprError();
5017 ArgExprs[0] = result.get();
5018 } else {
5019 if (CheckArgsForPlaceholders(ArgExprs))
5020 return ExprError();
5021 }
5022
5023 // Build an unanalyzed expression if either operand is type-dependent.
5024 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5025 (base->isTypeDependent() ||
5027 !isa<PackExpansionExpr>(ArgExprs[0])) {
5028 return new (Context) ArraySubscriptExpr(
5029 base, ArgExprs.front(),
5030 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5031 VK_LValue, OK_Ordinary, rbLoc);
5032 }
5033
5034 // MSDN, property (C++)
5035 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5036 // This attribute can also be used in the declaration of an empty array in a
5037 // class or structure definition. For example:
5038 // __declspec(property(get=GetX, put=PutX)) int x[];
5039 // The above statement indicates that x[] can be used with one or more array
5040 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5041 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5042 if (IsMSPropertySubscript) {
5043 assert(ArgExprs.size() == 1);
5044 // Build MS property subscript expression if base is MS property reference
5045 // or MS property subscript.
5046 return new (Context)
5047 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5048 VK_LValue, OK_Ordinary, rbLoc);
5049 }
5050
5051 // Use C++ overloaded-operator rules if either operand has record
5052 // type. The spec says to do this if either type is *overloadable*,
5053 // but enum types can't declare subscript operators or conversion
5054 // operators, so there's nothing interesting for overload resolution
5055 // to do if there aren't any record types involved.
5056 //
5057 // ObjC pointers have their own subscripting logic that is not tied
5058 // to overload resolution and so should not take this path.
5060 ((base->getType()->isRecordType() ||
5061 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5062 ArgExprs[0]->getType()->isRecordType())))) {
5063 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5064 }
5065
5066 ExprResult Res =
5067 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5068
5069 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5070 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5071
5072 return Res;
5073}
5074
5077 InitializationKind Kind =
5079 InitializationSequence InitSeq(*this, Entity, Kind, E);
5080 return InitSeq.Perform(*this, Entity, Kind, E);
5081}
5082
5084 Expr *ColumnIdx,
5085 SourceLocation RBLoc) {
5087 if (BaseR.isInvalid())
5088 return BaseR;
5089 Base = BaseR.get();
5090
5091 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5092 if (RowR.isInvalid())
5093 return RowR;
5094 RowIdx = RowR.get();
5095
5096 if (!ColumnIdx)
5097 return new (Context) MatrixSubscriptExpr(
5098 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5099
5100 // Build an unanalyzed expression if any of the operands is type-dependent.
5101 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5102 ColumnIdx->isTypeDependent())
5103 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5104 Context.DependentTy, RBLoc);
5105
5106 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5107 if (ColumnR.isInvalid())
5108 return ColumnR;
5109 ColumnIdx = ColumnR.get();
5110
5111 // Check that IndexExpr is an integer expression. If it is a constant
5112 // expression, check that it is less than Dim (= the number of elements in the
5113 // corresponding dimension).
5114 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5115 bool IsColumnIdx) -> Expr * {
5116 if (!IndexExpr->getType()->isIntegerType() &&
5117 !IndexExpr->isTypeDependent()) {
5118 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5119 << IsColumnIdx;
5120 return nullptr;
5121 }
5122
5123 if (std::optional<llvm::APSInt> Idx =
5124 IndexExpr->getIntegerConstantExpr(Context)) {
5125 if ((*Idx < 0 || *Idx >= Dim)) {
5126 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5127 << IsColumnIdx << Dim;
5128 return nullptr;
5129 }
5130 }
5131
5132 ExprResult ConvExpr = IndexExpr;
5133 assert(!ConvExpr.isInvalid() &&
5134 "should be able to convert any integer type to size type");
5135 return ConvExpr.get();
5136 };
5137
5138 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5139 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5140 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5141 if (!RowIdx || !ColumnIdx)
5142 return ExprError();
5143
5144 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5145 MTy->getElementType(), RBLoc);
5146}
5147
5148void Sema::CheckAddressOfNoDeref(const Expr *E) {
5149 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5150 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5151
5152 // For expressions like `&(*s).b`, the base is recorded and what should be
5153 // checked.
5154 const MemberExpr *Member = nullptr;
5155 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5156 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5157
5158 LastRecord.PossibleDerefs.erase(StrippedExpr);
5159}
5160
5161void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5163 return;
5164
5165 QualType ResultTy = E->getType();
5166 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5167
5168 // Bail if the element is an array since it is not memory access.
5169 if (isa<ArrayType>(ResultTy))
5170 return;
5171
5172 if (ResultTy->hasAttr(attr::NoDeref)) {
5173 LastRecord.PossibleDerefs.insert(E);
5174 return;
5175 }
5176
5177 // Check if the base type is a pointer to a member access of a struct
5178 // marked with noderef.
5179 const Expr *Base = E->getBase();
5180 QualType BaseTy = Base->getType();
5181 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5182 // Not a pointer access
5183 return;
5184
5185 const MemberExpr *Member = nullptr;
5186 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5187 Member->isArrow())
5188 Base = Member->getBase();
5189
5190 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5191 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5192 LastRecord.PossibleDerefs.insert(E);
5193 }
5194}
5195
5198 Expr *Idx, SourceLocation RLoc) {
5199 Expr *LHSExp = Base;
5200 Expr *RHSExp = Idx;
5201
5204
5205 // Per C++ core issue 1213, the result is an xvalue if either operand is
5206 // a non-lvalue array, and an lvalue otherwise.
5207 if (getLangOpts().CPlusPlus11) {
5208 for (auto *Op : {LHSExp, RHSExp}) {
5209 Op = Op->IgnoreImplicit();
5210 if (Op->getType()->isArrayType() && !Op->isLValue())
5211 VK = VK_XValue;
5212 }
5213 }
5214
5215 // Perform default conversions.
5216 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5218 if (Result.isInvalid())
5219 return ExprError();
5220 LHSExp = Result.get();
5221 }
5223 if (Result.isInvalid())
5224 return ExprError();
5225 RHSExp = Result.get();
5226
5227 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5228
5229 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5230 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5231 // in the subscript position. As a result, we need to derive the array base
5232 // and index from the expression types.
5233 Expr *BaseExpr, *IndexExpr;
5234 QualType ResultType;
5235 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5236 BaseExpr = LHSExp;
5237 IndexExpr = RHSExp;
5238 ResultType =
5240 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5241 BaseExpr = LHSExp;
5242 IndexExpr = RHSExp;
5243 ResultType = PTy->getPointeeType();
5244 } else if (const ObjCObjectPointerType *PTy =
5245 LHSTy->getAs<ObjCObjectPointerType>()) {
5246 BaseExpr = LHSExp;
5247 IndexExpr = RHSExp;
5248
5249 // Use custom logic if this should be the pseudo-object subscript
5250 // expression.
5251 if (!LangOpts.isSubscriptPointerArithmetic())
5252 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5253 nullptr, nullptr);
5254
5255 ResultType = PTy->getPointeeType();
5256 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5257 // Handle the uncommon case of "123[Ptr]".
5258 BaseExpr = RHSExp;
5259 IndexExpr = LHSExp;
5260 ResultType = PTy->getPointeeType();
5261 } else if (const ObjCObjectPointerType *PTy =
5262 RHSTy->getAs<ObjCObjectPointerType>()) {
5263 // Handle the uncommon case of "123[Ptr]".
5264 BaseExpr = RHSExp;
5265 IndexExpr = LHSExp;
5266 ResultType = PTy->getPointeeType();
5267 if (!LangOpts.isSubscriptPointerArithmetic()) {
5268 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5269 << ResultType << BaseExpr->getSourceRange();
5270 return ExprError();
5271 }
5272 } else if (LHSTy->isSubscriptableVectorType()) {
5273 if (LHSTy->isBuiltinType() &&
5274 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5275 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5276 if (BTy->isSVEBool())
5277 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5278 << LHSExp->getSourceRange()
5279 << RHSExp->getSourceRange());
5280 ResultType = BTy->getSveEltType(Context);
5281 } else {
5282 const VectorType *VTy = LHSTy->getAs<VectorType>();
5283 ResultType = VTy->getElementType();
5284 }
5285 BaseExpr = LHSExp; // vectors: V[123]
5286 IndexExpr = RHSExp;
5287 // We apply C++ DR1213 to vector subscripting too.
5288 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5289 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5290 if (Materialized.isInvalid())
5291 return ExprError();
5292 LHSExp = Materialized.get();
5293 }
5294 VK = LHSExp->getValueKind();
5295 if (VK != VK_PRValue)
5296 OK = OK_VectorComponent;
5297
5298 QualType BaseType = BaseExpr->getType();
5299 Qualifiers BaseQuals = BaseType.getQualifiers();
5300 Qualifiers MemberQuals = ResultType.getQualifiers();
5301 Qualifiers Combined = BaseQuals + MemberQuals;
5302 if (Combined != MemberQuals)
5303 ResultType = Context.getQualifiedType(ResultType, Combined);
5304 } else if (LHSTy->isArrayType()) {
5305 // If we see an array that wasn't promoted by
5306 // DefaultFunctionArrayLvalueConversion, it must be an array that
5307 // wasn't promoted because of the C90 rule that doesn't
5308 // allow promoting non-lvalue arrays. Warn, then
5309 // force the promotion here.
5310 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5311 << LHSExp->getSourceRange();
5312 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5313 CK_ArrayToPointerDecay).get();
5314 LHSTy = LHSExp->getType();
5315
5316 BaseExpr = LHSExp;
5317 IndexExpr = RHSExp;
5318 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5319 } else if (RHSTy->isArrayType()) {
5320 // Same as previous, except for 123[f().a] case
5321 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5322 << RHSExp->getSourceRange();
5323 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5324 CK_ArrayToPointerDecay).get();
5325 RHSTy = RHSExp->getType();
5326
5327 BaseExpr = RHSExp;
5328 IndexExpr = LHSExp;
5329 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5330 } else {
5331 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5332 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5333 }
5334 // C99 6.5.2.1p1
5335 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5336 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5337 << IndexExpr->getSourceRange());
5338
5339 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5340 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5341 !IndexExpr->isTypeDependent()) {
5342 std::optional<llvm::APSInt> IntegerContantExpr =
5344 if (!IntegerContantExpr.has_value() ||
5345 IntegerContantExpr.value().isNegative())
5346 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5347 }
5348
5349 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5350 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5351 // type. Note that Functions are not objects, and that (in C99 parlance)
5352 // incomplete types are not object types.
5353 if (ResultType->isFunctionType()) {
5354 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5355 << ResultType << BaseExpr->getSourceRange();
5356 return ExprError();
5357 }
5358
5359 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5360 // GNU extension: subscripting on pointer to void
5361 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5362 << BaseExpr->getSourceRange();
5363
5364 // C forbids expressions of unqualified void type from being l-values.
5365 // See IsCForbiddenLValueType.
5366 if (!ResultType.hasQualifiers())
5367 VK = VK_PRValue;
5368 } else if (!ResultType->isDependentType() &&
5369 !ResultType.isWebAssemblyReferenceType() &&
5371 LLoc, ResultType,
5372 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5373 return ExprError();
5374
5375 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5376 !ResultType.isCForbiddenLValueType());
5377
5379 FunctionScopes.size() > 1) {
5380 if (auto *TT =
5381 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5382 for (auto I = FunctionScopes.rbegin(),
5383 E = std::prev(FunctionScopes.rend());
5384 I != E; ++I) {
5385 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5386 if (CSI == nullptr)
5387 break;
5388 DeclContext *DC = nullptr;
5389 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5390 DC = LSI->CallOperator;
5391 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5392 DC = CRSI->TheCapturedDecl;
5393 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5394 DC = BSI->TheDecl;
5395 if (DC) {
5396 if (DC->containsDecl(TT->getDecl()))
5397 break;
5399 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5400 }
5401 }
5402 }
5403 }
5404
5405 return new (Context)
5406 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5407}
5408
5410 ParmVarDecl *Param, Expr *RewrittenInit,
5411 bool SkipImmediateInvocations) {
5412 if (Param->hasUnparsedDefaultArg()) {
5413 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5414 // If we've already cleared out the location for the default argument,
5415 // that means we're parsing it right now.
5416 if (!UnparsedDefaultArgLocs.count(Param)) {
5417 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5418 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5419 Param->setInvalidDecl();
5420 return true;
5421 }
5422
5423 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5424 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5426 diag::note_default_argument_declared_here);
5427 return true;
5428 }
5429
5430 if (Param->hasUninstantiatedDefaultArg()) {
5431 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5432 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5433 return true;
5434 }
5435
5436 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5437 assert(Init && "default argument but no initializer?");
5438
5439 // If the default expression creates temporaries, we need to
5440 // push them to the current stack of expression temporaries so they'll
5441 // be properly destroyed.
5442 // FIXME: We should really be rebuilding the default argument with new
5443 // bound temporaries; see the comment in PR5810.
5444 // We don't need to do that with block decls, though, because
5445 // blocks in default argument expression can never capture anything.
5446 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5447 // Set the "needs cleanups" bit regardless of whether there are
5448 // any explicit objects.
5449 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5450 // Append all the objects to the cleanup list. Right now, this
5451 // should always be a no-op, because blocks in default argument
5452 // expressions should never be able to capture anything.
5453 assert(!InitWithCleanup->getNumObjects() &&
5454 "default argument expression has capturing blocks?");
5455 }
5456 // C++ [expr.const]p15.1:
5457 // An expression or conversion is in an immediate function context if it is
5458 // potentially evaluated and [...] its innermost enclosing non-block scope
5459 // is a function parameter scope of an immediate function.
5461 *this,
5465 Param);
5466 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5467 SkipImmediateInvocations;
5468 runWithSufficientStackSpace(CallLoc, [&] {
5469 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5470 });
5471 return false;
5472}
5473
5478 }
5479
5480 bool HasImmediateCalls = false;
5481
5482 bool VisitCallExpr(CallExpr *E) override {
5483 if (const FunctionDecl *FD = E->getDirectCallee())
5484 HasImmediateCalls |= FD->isImmediateFunction();
5486 }
5487
5489 if (const FunctionDecl *FD = E->getConstructor())
5490 HasImmediateCalls |= FD->isImmediateFunction();
5492 }
5493
5494 // SourceLocExpr are not immediate invocations
5495 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5496 // need to be rebuilt so that they refer to the correct SourceLocation and
5497 // DeclContext.
5499 HasImmediateCalls = true;
5501 }
5502
5503 // A nested lambda might have parameters with immediate invocations
5504 // in their default arguments.
5505 // The compound statement is not visited (as it does not constitute a
5506 // subexpression).
5507 // FIXME: We should consider visiting and transforming captures
5508 // with init expressions.
5509 bool VisitLambdaExpr(LambdaExpr *E) override {
5510 return VisitCXXMethodDecl(E->getCallOperator());
5511 }
5512
5514 return TraverseStmt(E->getExpr());
5515 }
5516
5518 return TraverseStmt(E->getExpr());
5519 }
5520};
5521
5523 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5526
5527 bool AlwaysRebuild() { return true; }
5528
5529 // Lambda can only have immediate invocations in the default
5530 // args of their parameters, which is transformed upon calling the closure.
5531 // The body is not a subexpression, so we have nothing to do.
5532 // FIXME: Immediate calls in capture initializers should be transformed.
5535
5536 // Make sure we don't rebuild the this pointer as it would
5537 // cause it to incorrectly point it to the outermost class
5538 // in the case of nested struct initialization.
5540
5541 // Rewrite to source location to refer to the context in which they are used.
5543 DeclContext *DC = E->getParentContext();
5544 if (DC == SemaRef.CurContext)
5545 return E;
5546
5547 // FIXME: During instantiation, because the rebuild of defaults arguments
5548 // is not always done in the context of the template instantiator,
5549 // we run the risk of producing a dependent source location
5550 // that would never be rebuilt.
5551 // This usually happens during overload resolution, or in contexts
5552 // where the value of the source location does not matter.
5553 // However, we should find a better way to deal with source location
5554 // of function templates.
5555 if (!SemaRef.CurrentInstantiationScope ||
5556 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5557 DC = SemaRef.CurContext;
5558
5559 return getDerived().RebuildSourceLocExpr(
5560 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5561 }
5562};
5563
5565 FunctionDecl *FD, ParmVarDecl *Param,
5566 Expr *Init) {
5567 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5568
5569 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5570 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5571 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5572 InitializationContext =
5574 if (!InitializationContext.has_value())
5575 InitializationContext.emplace(CallLoc, Param, CurContext);
5576
5577 if (!Init && !Param->hasUnparsedDefaultArg()) {
5578 // Mark that we are replacing a default argument first.
5579 // If we are instantiating a template we won't have to
5580 // retransform immediate calls.
5581 // C++ [expr.const]p15.1:
5582 // An expression or conversion is in an immediate function context if it
5583 // is potentially evaluated and [...] its innermost enclosing non-block
5584 // scope is a function parameter scope of an immediate function.
5586 *this,
5590 Param);
5591
5592 if (Param->hasUninstantiatedDefaultArg()) {
5593 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5594 return ExprError();
5595 }
5596 // CWG2631
5597 // An immediate invocation that is not evaluated where it appears is
5598 // evaluated and checked for whether it is a constant expression at the
5599 // point where the enclosing initializer is used in a function call.
5601 if (!NestedDefaultChecking)
5602 V.TraverseDecl(Param);
5603
5604 // Rewrite the call argument that was created from the corresponding
5605 // parameter's default argument.
5606 if (V.HasImmediateCalls ||
5607 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5608 if (V.HasImmediateCalls)
5609 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5610 CallLoc, Param, CurContext};
5611 // Pass down lifetime extending flag, and collect temporaries in
5612 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5616 ExprResult Res;
5617 runWithSufficientStackSpace(CallLoc, [&] {
5618 Res = Immediate.TransformInitializer(Param->getInit(),
5619 /*NotCopy=*/false);
5620 });
5621 if (Res.isInvalid())
5622 return ExprError();
5623 Res = ConvertParamDefaultArgument(Param, Res.get(),
5624 Res.get()->getBeginLoc());
5625 if (Res.isInvalid())
5626 return ExprError();
5627 Init = Res.get();
5628 }
5629 }
5630
5632 CallLoc, FD, Param, Init,
5633 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5634 return ExprError();
5635
5636 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5637 Init, InitializationContext->Context);
5638}
5639
5641 FieldDecl *Field) {
5642 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5643 return Pattern;
5644 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5645 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5647 ClassPattern->lookup(Field->getDeclName());
5648 auto Rng = llvm::make_filter_range(
5649 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5650 if (Rng.empty())
5651 return nullptr;
5652 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5653 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5654 // && "Duplicated instantiation pattern for field decl");
5655 return cast<FieldDecl>(*Rng.begin());
5656}
5657
5659 assert(Field->hasInClassInitializer());
5660
5661 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5662
5663 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5664
5665 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5666 InitializationContext =
5668 if (!InitializationContext.has_value())
5669 InitializationContext.emplace(Loc, Field, CurContext);
5670
5671 Expr *Init = nullptr;
5672
5673 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5674 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5677
5678 if (!Field->getInClassInitializer()) {
5679 // Maybe we haven't instantiated the in-class initializer. Go check the
5680 // pattern FieldDecl to see if it has one.
5681 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5682 FieldDecl *Pattern =
5684 assert(Pattern && "We must have set the Pattern!");
5685 if (!Pattern->hasInClassInitializer() ||
5686 InstantiateInClassInitializer(Loc, Field, Pattern,
5688 Field->setInvalidDecl();
5689 return ExprError();
5690 }
5691 }
5692 }
5693
5694 // CWG2631
5695 // An immediate invocation that is not evaluated where it appears is
5696 // evaluated and checked for whether it is a constant expression at the
5697 // point where the enclosing initializer is used in a [...] a constructor
5698 // definition, or an aggregate initialization.
5700 if (!NestedDefaultChecking)
5701 V.TraverseDecl(Field);
5702
5703 // CWG1815
5704 // Support lifetime extension of temporary created by aggregate
5705 // initialization using a default member initializer. We should rebuild
5706 // the initializer in a lifetime extension context if the initializer
5707 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5708 // extension code recurses into the default initializer and does lifetime
5709 // extension when warranted.
5710 bool ContainsAnyTemporaries =
5711 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5712 if (Field->getInClassInitializer() &&
5713 !Field->getInClassInitializer()->containsErrors() &&
5714 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5715 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5716 CurContext};
5717 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5718 NestedDefaultChecking;
5719 // Pass down lifetime extending flag, and collect temporaries in
5720 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5724 ExprResult Res;
5726 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5727 /*CXXDirectInit=*/false);
5728 });
5729 if (!Res.isInvalid())
5730 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5731 if (Res.isInvalid()) {
5732 Field->setInvalidDecl();
5733 return ExprError();
5734 }
5735 Init = Res.get();
5736 }
5737
5738 if (Field->getInClassInitializer()) {
5739 Expr *E = Init ? Init : Field->getInClassInitializer();
5740 if (!NestedDefaultChecking)
5742 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5743 });
5746 // C++11 [class.base.init]p7:
5747 // The initialization of each base and member constitutes a
5748 // full-expression.
5749 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5750 if (Res.isInvalid()) {
5751 Field->setInvalidDecl();
5752 return ExprError();
5753 }
5754 Init = Res.get();
5755
5756 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5757 Field, InitializationContext->Context,
5758 Init);
5759 }
5760
5761 // DR1351:
5762 // If the brace-or-equal-initializer of a non-static data member
5763 // invokes a defaulted default constructor of its class or of an
5764 // enclosing class in a potentially evaluated subexpression, the
5765 // program is ill-formed.
5766 //
5767 // This resolution is unworkable: the exception specification of the
5768 // default constructor can be needed in an unevaluated context, in
5769 // particular, in the operand of a noexcept-expression, and we can be
5770 // unable to compute an exception specification for an enclosed class.
5771 //
5772 // Any attempt to resolve the exception specification of a defaulted default
5773 // constructor before the initializer is lexically complete will ultimately
5774 // come here at which point we can diagnose it.
5775 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5776 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5777 << OutermostClass << Field;
5778 Diag(Field->getEndLoc(),
5779 diag::note_default_member_initializer_not_yet_parsed);
5780 // Recover by marking the field invalid, unless we're in a SFINAE context.
5781 if (!isSFINAEContext())
5782 Field->setInvalidDecl();
5783 return ExprError();
5784}
5785
5787 const FunctionProtoType *Proto,
5788 Expr *Fn) {
5789 if (Proto && Proto->isVariadic()) {
5790 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5792 else if (Fn && Fn->getType()->isBlockPointerType())
5794 else if (FDecl) {
5795 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5796 if (Method->isInstance())
5798 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5801 }
5803}
5804
5805namespace {
5806class FunctionCallCCC final : public FunctionCallFilterCCC {
5807public:
5808 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5809 unsigned NumArgs, MemberExpr *ME)
5810 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5811 FunctionName(FuncName) {}
5812
5813 bool ValidateCandidate(const TypoCorrection &candidate) override {
5814 if (!candidate.getCorrectionSpecifier() ||
5815 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5816 return false;
5817 }
5818
5820 }
5821
5822 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5823 return std::make_unique<FunctionCallCCC>(*this);
5824 }
5825
5826private:
5827 const IdentifierInfo *const FunctionName;
5828};
5829}
5830
5832 FunctionDecl *FDecl,
5833 ArrayRef<Expr *> Args) {
5834 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5835 DeclarationName FuncName = FDecl->getDeclName();
5836 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5837
5838 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5839 if (TypoCorrection Corrected = S.CorrectTypo(
5841 S.getScopeForContext(S.CurContext), nullptr, CCC,
5843 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5844 if (Corrected.isOverloaded()) {
5847 for (NamedDecl *CD : Corrected) {
5848 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5850 OCS);
5851 }
5852 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5853 case OR_Success:
5854 ND = Best->FoundDecl;
5855 Corrected.setCorrectionDecl(ND);
5856 break;
5857 default:
5858 break;
5859 }
5860 }
5861 ND = ND->getUnderlyingDecl();
5863 return Corrected;
5864 }
5865 }
5866 return TypoCorrection();
5867}
5868
5869// [C++26][[expr.unary.op]/p4
5870// A pointer to member is only formed when an explicit &
5871// is used and its operand is a qualified-id not enclosed in parentheses.
5873 if (!isa<ParenExpr>(Fn))
5874 return false;
5875
5876 Fn = Fn->IgnoreParens();
5877
5878 auto *UO = dyn_cast<UnaryOperator>(Fn);
5879 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5880 return false;
5881 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5882 return DRE->hasQualifier();
5883 }
5884 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5885 return bool(OVL->getQualifier());
5886 return false;
5887}
5888
5889bool
5891 FunctionDecl *FDecl,
5892 const FunctionProtoType *Proto,
5893 ArrayRef<Expr *> Args,
5894 SourceLocation RParenLoc,
5895 bool IsExecConfig) {
5896 // Bail out early if calling a builtin with custom typechecking.
5897 if (FDecl)
5898 if (unsigned ID = FDecl->getBuiltinID())
5899 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5900 return false;
5901
5902 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5903 // assignment, to the types of the corresponding parameter, ...
5904
5905 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5906 bool HasExplicitObjectParameter =
5907 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5908 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5909 unsigned NumParams = Proto->getNumParams();
5910 bool Invalid = false;
5911 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5912 unsigned FnKind = Fn->getType()->isBlockPointerType()
5913 ? 1 /* block */
5914 : (IsExecConfig ? 3 /* kernel function (exec config) */
5915 : 0 /* function */);
5916
5917 // If too few arguments are available (and we don't have default
5918 // arguments for the remaining parameters), don't make the call.
5919 if (Args.size() < NumParams) {
5920 if (Args.size() < MinArgs) {
5921 TypoCorrection TC;
5922 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5923 unsigned diag_id =
5924 MinArgs == NumParams && !Proto->isVariadic()
5925 ? diag::err_typecheck_call_too_few_args_suggest
5926 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5928 TC, PDiag(diag_id)
5929 << FnKind << MinArgs - ExplicitObjectParameterOffset
5930 << static_cast<unsigned>(Args.size()) -
5931 ExplicitObjectParameterOffset
5932 << HasExplicitObjectParameter << TC.getCorrectionRange());
5933 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5934 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5935 ->getDeclName())
5936 Diag(RParenLoc,
5937 MinArgs == NumParams && !Proto->isVariadic()
5938 ? diag::err_typecheck_call_too_few_args_one
5939 : diag::err_typecheck_call_too_few_args_at_least_one)
5940 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5941 << HasExplicitObjectParameter << Fn->getSourceRange();
5942 else
5943 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5944 ? diag::err_typecheck_call_too_few_args
5945 : diag::err_typecheck_call_too_few_args_at_least)
5946 << FnKind << MinArgs - ExplicitObjectParameterOffset
5947 << static_cast<unsigned>(Args.size()) -
5948 ExplicitObjectParameterOffset
5949 << HasExplicitObjectParameter << Fn->getSourceRange();
5950
5951 // Emit the location of the prototype.
5952 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5953 Diag(FDecl->getLocation(), diag::note_callee_decl)
5954 << FDecl << FDecl->getParametersSourceRange();
5955
5956 return true;
5957 }
5958 // We reserve space for the default arguments when we create
5959 // the call expression, before calling ConvertArgumentsForCall.
5960 assert((Call->getNumArgs() == NumParams) &&
5961 "We should have reserved space for the default arguments before!");
5962 }
5963
5964 // If too many are passed and not variadic, error on the extras and drop
5965 // them.
5966 if (Args.size() > NumParams) {
5967 if (!Proto->isVariadic()) {
5968 TypoCorrection TC;
5969 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5970 unsigned diag_id =
5971 MinArgs == NumParams && !Proto->isVariadic()
5972 ? diag::err_typecheck_call_too_many_args_suggest
5973 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5975 TC, PDiag(diag_id)
5976 << FnKind << NumParams - ExplicitObjectParameterOffset
5977 << static_cast<unsigned>(Args.size()) -
5978 ExplicitObjectParameterOffset
5979 << HasExplicitObjectParameter << TC.getCorrectionRange());
5980 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5981 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5982 ->getDeclName())
5983 Diag(Args[NumParams]->getBeginLoc(),
5984 MinArgs == NumParams
5985 ? diag::err_typecheck_call_too_many_args_one
5986 : diag::err_typecheck_call_too_many_args_at_most_one)
5987 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5988 << static_cast<unsigned>(Args.size()) -
5989 ExplicitObjectParameterOffset
5990 << HasExplicitObjectParameter << Fn->getSourceRange()
5991 << SourceRange(Args[NumParams]->getBeginLoc(),
5992 Args.back()->getEndLoc());
5993 else
5994 Diag(Args[NumParams]->getBeginLoc(),
5995 MinArgs == NumParams
5996 ? diag::err_typecheck_call_too_many_args
5997 : diag::err_typecheck_call_too_many_args_at_most)
5998 << FnKind << NumParams - ExplicitObjectParameterOffset
5999 << static_cast<unsigned>(Args.size()) -
6000 ExplicitObjectParameterOffset
6001 << HasExplicitObjectParameter << Fn->getSourceRange()
6002 << SourceRange(Args[NumParams]->getBeginLoc(),
6003 Args.back()->getEndLoc());
6004
6005 // Emit the location of the prototype.
6006 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6007 Diag(FDecl->getLocation(), diag::note_callee_decl)
6008 << FDecl << FDecl->getParametersSourceRange();
6009
6010 // This deletes the extra arguments.
6011 Call->shrinkNumArgs(NumParams);
6012 return true;
6013 }
6014 }
6015 SmallVector<Expr *, 8> AllArgs;
6016 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6017
6018 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6019 AllArgs, CallType);
6020 if (Invalid)
6021 return true;
6022 unsigned TotalNumArgs = AllArgs.size();
6023 for (unsigned i = 0; i < TotalNumArgs; ++i)
6024 Call->setArg(i, AllArgs[i]);
6025
6026 Call->computeDependence();
6027 return false;
6028}
6029
6031 const FunctionProtoType *Proto,
6032 unsigned FirstParam, ArrayRef<Expr *> Args,
6033 SmallVectorImpl<Expr *> &AllArgs,
6034 VariadicCallType CallType, bool AllowExplicit,
6035 bool IsListInitialization) {
6036 unsigned NumParams = Proto->getNumParams();
6037 bool Invalid = false;
6038 size_t ArgIx = 0;
6039 // Continue to check argument types (even if we have too few/many args).
6040 for (unsigned i = FirstParam; i < NumParams; i++) {
6041 QualType ProtoArgType = Proto->getParamType(i);
6042
6043 Expr *Arg;
6044 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6045 if (ArgIx < Args.size()) {
6046 Arg = Args[ArgIx++];
6047
6048 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6049 diag::err_call_incomplete_argument, Arg))
6050 return true;
6051
6052 // Strip the unbridged-cast placeholder expression off, if applicable.
6053 bool CFAudited = false;
6054 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6055 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6056 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6057 Arg = ObjC().stripARCUnbridgedCast(Arg);
6058 else if (getLangOpts().ObjCAutoRefCount &&
6059 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6060 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6061 CFAudited = true;
6062
6063 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6064 ProtoArgType->isBlockPointerType())
6065 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6066 BE->getBlockDecl()->setDoesNotEscape();
6067 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6069 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6070 if (ArgExpr.isInvalid())
6071 return true;
6072 Arg = ArgExpr.getAs<Expr>();
6073 }
6074
6075 InitializedEntity Entity =
6077 ProtoArgType)
6079 Context, ProtoArgType, Proto->isParamConsumed(i));
6080
6081 // Remember that parameter belongs to a CF audited API.
6082 if (CFAudited)
6083 Entity.setParameterCFAudited();
6084
6086 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6087 if (ArgE.isInvalid())
6088 return true;
6089
6090 Arg = ArgE.getAs<Expr>();
6091 } else {
6092 assert(Param && "can't use default arguments without a known callee");
6093
6094 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6095 if (ArgExpr.isInvalid())
6096 return true;
6097
6098 Arg = ArgExpr.getAs<Expr>();
6099 }
6100
6101 // Check for array bounds violations for each argument to the call. This
6102 // check only triggers warnings when the argument isn't a more complex Expr
6103 // with its own checking, such as a BinaryOperator.
6104 CheckArrayAccess(Arg);
6105
6106 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6107 CheckStaticArrayArgument(CallLoc, Param, Arg);
6108
6109 AllArgs.push_back(Arg);
6110 }
6111
6112 // If this is a variadic call, handle args passed through "...".
6113 if (CallType != VariadicCallType::DoesNotApply) {
6114 // Assume that extern "C" functions with variadic arguments that
6115 // return __unknown_anytype aren't *really* variadic.
6116 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6117 FDecl->isExternC()) {
6118 for (Expr *A : Args.slice(ArgIx)) {
6119 QualType paramType; // ignored
6120 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6121 Invalid |= arg.isInvalid();
6122 AllArgs.push_back(arg.get());
6123 }
6124
6125 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6126 } else {
6127 for (Expr *A : Args.slice(ArgIx)) {
6128 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6129 Invalid |= Arg.isInvalid();
6130 AllArgs.push_back(Arg.get());
6131 }
6132 }
6133
6134 // Check for array bounds violations.
6135 for (Expr *A : Args.slice(ArgIx))
6136 CheckArrayAccess(A);
6137 }
6138 return Invalid;
6139}
6140
6142 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6143 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6144 TL = DTL.getOriginalLoc();
6145 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6146 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6147 << ATL.getLocalSourceRange();
6148}
6149
6150void
6152 ParmVarDecl *Param,
6153 const Expr *ArgExpr) {
6154 // Static array parameters are not supported in C++.
6155 if (!Param || getLangOpts().CPlusPlus)
6156 return;
6157
6158 QualType OrigTy = Param->getOriginalType();
6159
6160 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6161 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6162 return;
6163
6164 if (ArgExpr->isNullPointerConstant(Context,
6166 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6167 DiagnoseCalleeStaticArrayParam(*this, Param);
6168 return;
6169 }
6170
6171 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6172 if (!CAT)
6173 return;
6174
6175 const ConstantArrayType *ArgCAT =
6176 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6177 if (!ArgCAT)
6178 return;
6179
6180 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6181 ArgCAT->getElementType())) {
6182 if (ArgCAT->getSize().ult(CAT->getSize())) {
6183 Diag(CallLoc, diag::warn_static_array_too_small)
6184 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6185 << (unsigned)CAT->getZExtSize() << 0;
6186 DiagnoseCalleeStaticArrayParam(*this, Param);
6187 }
6188 return;
6189 }
6190
6191 std::optional<CharUnits> ArgSize =
6193 std::optional<CharUnits> ParmSize =
6195 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6196 Diag(CallLoc, diag::warn_static_array_too_small)
6197 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6198 << (unsigned)ParmSize->getQuantity() << 1;
6199 DiagnoseCalleeStaticArrayParam(*this, Param);
6200 }
6201}
6202
6203/// Given a function expression of unknown-any type, try to rebuild it
6204/// to have a function type.
6206
6207/// Is the given type a placeholder that we need to lower out
6208/// immediately during argument processing?
6210 // Placeholders are never sugared.
6211 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6212 if (!placeholder) return false;
6213
6214 switch (placeholder->getKind()) {
6215 // Ignore all the non-placeholder types.
6216#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6217 case BuiltinType::Id:
6218#include "clang/Basic/OpenCLImageTypes.def"
6219#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6220 case BuiltinType::Id:
6221#include "clang/Basic/OpenCLExtensionTypes.def"
6222 // In practice we'll never use this, since all SVE types are sugared
6223 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6224#define SVE_TYPE(Name, Id, SingletonId) \
6225 case BuiltinType::Id:
6226#include "clang/Basic/AArch64ACLETypes.def"
6227#define PPC_VECTOR_TYPE(Name, Id, Size) \
6228 case BuiltinType::Id:
6229#include "clang/Basic/PPCTypes.def"
6230#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6231#include "clang/Basic/RISCVVTypes.def"
6232#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6233#include "clang/Basic/WebAssemblyReferenceTypes.def"
6234#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6235#include "clang/Basic/AMDGPUTypes.def"
6236#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6237#include "clang/Basic/HLSLIntangibleTypes.def"
6238#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6239#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6240#include "clang/AST/BuiltinTypes.def"
6241 return false;
6242
6243 case BuiltinType::UnresolvedTemplate:
6244 // We cannot lower out overload sets; they might validly be resolved
6245 // by the call machinery.
6246 case BuiltinType::Overload:
6247 return false;
6248
6249 // Unbridged casts in ARC can be handled in some call positions and
6250 // should be left in place.
6251 case BuiltinType::ARCUnbridgedCast:
6252 return false;
6253
6254 // Pseudo-objects should be converted as soon as possible.
6255 case BuiltinType::PseudoObject:
6256 return true;
6257
6258 // The debugger mode could theoretically but currently does not try
6259 // to resolve unknown-typed arguments based on known parameter types.
6260 case BuiltinType::UnknownAny:
6261 return true;
6262
6263 // These are always invalid as call arguments and should be reported.
6264 case BuiltinType::BoundMember:
6265 case BuiltinType::BuiltinFn:
6266 case BuiltinType::IncompleteMatrixIdx:
6267 case BuiltinType::ArraySection:
6268 case BuiltinType::OMPArrayShaping:
6269 case BuiltinType::OMPIterator:
6270 return true;
6271
6272 }
6273 llvm_unreachable("bad builtin type kind");
6274}
6275
6277 // Apply this processing to all the arguments at once instead of
6278 // dying at the first failure.
6279 bool hasInvalid = false;
6280 for (size_t i = 0, e = args.size(); i != e; i++) {
6281 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6282 ExprResult result = CheckPlaceholderExpr(args[i]);
6283 if (result.isInvalid()) hasInvalid = true;
6284 else args[i] = result.get();
6285 }
6286 }
6287 return hasInvalid;
6288}
6289
6290/// If a builtin function has a pointer argument with no explicit address
6291/// space, then it should be able to accept a pointer to any address
6292/// space as input. In order to do this, we need to replace the
6293/// standard builtin declaration with one that uses the same address space
6294/// as the call.
6295///
6296/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6297/// it does not contain any pointer arguments without
6298/// an address space qualifer. Otherwise the rewritten
6299/// FunctionDecl is returned.
6300/// TODO: Handle pointer return types.
6302 FunctionDecl *FDecl,
6303 MultiExprArg ArgExprs) {
6304
6305 QualType DeclType = FDecl->getType();
6306 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6307
6308 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6309 ArgExprs.size() < FT->getNumParams())
6310 return nullptr;
6311
6312 bool NeedsNewDecl = false;
6313 unsigned i = 0;
6314 SmallVector<QualType, 8> OverloadParams;
6315
6316 {
6317 // The lvalue conversions in this loop are only for type resolution and
6318 // don't actually occur.
6321 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6322
6323 for (QualType ParamType : FT->param_types()) {
6324
6325 // Convert array arguments to pointer to simplify type lookup.
6326 ExprResult ArgRes =
6328 if (ArgRes.isInvalid())
6329 return nullptr;
6330 Expr *Arg = ArgRes.get();
6331 QualType ArgType = Arg->getType();
6332 if (!ParamType->isPointerType() ||
6333 ParamType->getPointeeType().hasAddressSpace() ||
6334 !ArgType->isPointerType() ||
6335 !ArgType->getPointeeType().hasAddressSpace() ||
6336 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6337 OverloadParams.push_back(ParamType);
6338 continue;
6339 }
6340
6341 QualType PointeeType = ParamType->getPointeeType();
6342 NeedsNewDecl = true;
6343 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6344
6345 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6346 OverloadParams.push_back(Context.getPointerType(PointeeType));
6347 }
6348 }
6349
6350 if (!NeedsNewDecl)
6351 return nullptr;
6352
6354 EPI.Variadic = FT->isVariadic();
6355 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6356 OverloadParams, EPI);
6357 DeclContext *Parent = FDecl->getParent();
6358 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6359 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6360 FDecl->getIdentifier(), OverloadTy,
6361 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6362 false,
6363 /*hasPrototype=*/true);
6365 FT = cast<FunctionProtoType>(OverloadTy);
6366 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6367 QualType ParamType = FT->getParamType(i);
6368 ParmVarDecl *Parm =
6369 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6370 SourceLocation(), nullptr, ParamType,
6371 /*TInfo=*/nullptr, SC_None, nullptr);
6372 Parm->setScopeInfo(0, i);
6373 Params.push_back(Parm);
6374 }
6375 OverloadDecl->setParams(Params);
6376 // We cannot merge host/device attributes of redeclarations. They have to
6377 // be consistent when created.
6378 if (Sema->LangOpts.CUDA) {
6379 if (FDecl->hasAttr<CUDAHostAttr>())
6380 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6381 if (FDecl->hasAttr<CUDADeviceAttr>())
6382 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6383 }
6384 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6385 return OverloadDecl;
6386}
6387
6388static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6389 FunctionDecl *Callee,
6390 MultiExprArg ArgExprs) {
6391 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6392 // similar attributes) really don't like it when functions are called with an
6393 // invalid number of args.
6394 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6395 /*PartialOverloading=*/false) &&
6396 !Callee->isVariadic())
6397 return;
6398 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6399 return;
6400
6401 if (const EnableIfAttr *Attr =
6402 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6403 S.Diag(Fn->getBeginLoc(),
6404 isa<CXXMethodDecl>(Callee)
6405 ? diag::err_ovl_no_viable_member_function_in_call
6406 : diag::err_ovl_no_viable_function_in_call)
6407 << Callee << Callee->getSourceRange();
6408 S.Diag(Callee->getLocation(),
6409 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6410 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6411 return;
6412 }
6413}
6414
6416 const UnresolvedMemberExpr *const UME, Sema &S) {
6417
6418 const auto GetFunctionLevelDCIfCXXClass =
6419 [](Sema &S) -> const CXXRecordDecl * {
6420 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6421 if (!DC || !DC->getParent())
6422 return nullptr;
6423
6424 // If the call to some member function was made from within a member
6425 // function body 'M' return return 'M's parent.
6426 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6427 return MD->getParent()->getCanonicalDecl();
6428 // else the call was made from within a default member initializer of a
6429 // class, so return the class.
6430 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6431 return RD->getCanonicalDecl();
6432 return nullptr;
6433 };
6434 // If our DeclContext is neither a member function nor a class (in the
6435 // case of a lambda in a default member initializer), we can't have an
6436 // enclosing 'this'.
6437
6438 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6439 if (!CurParentClass)
6440 return false;
6441
6442 // The naming class for implicit member functions call is the class in which
6443 // name lookup starts.
6444 const CXXRecordDecl *const NamingClass =
6446 assert(NamingClass && "Must have naming class even for implicit access");
6447
6448 // If the unresolved member functions were found in a 'naming class' that is
6449 // related (either the same or derived from) to the class that contains the
6450 // member function that itself contained the implicit member access.
6451
6452 return CurParentClass == NamingClass ||
6453 CurParentClass->isDerivedFrom(NamingClass);
6454}
6455
6456static void
6458 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6459
6460 if (!UME)
6461 return;
6462
6463 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6464 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6465 // already been captured, or if this is an implicit member function call (if
6466 // it isn't, an attempt to capture 'this' should already have been made).
6467 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6468 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6469 return;
6470
6471 // Check if the naming class in which the unresolved members were found is
6472 // related (same as or is a base of) to the enclosing class.
6473
6475 return;
6476
6477
6478 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6479 // If the enclosing function is not dependent, then this lambda is
6480 // capture ready, so if we can capture this, do so.
6481 if (!EnclosingFunctionCtx->isDependentContext()) {
6482 // If the current lambda and all enclosing lambdas can capture 'this' -
6483 // then go ahead and capture 'this' (since our unresolved overload set
6484 // contains at least one non-static member function).
6485 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6486 S.CheckCXXThisCapture(CallLoc);
6487 } else if (S.CurContext->isDependentContext()) {
6488 // ... since this is an implicit member reference, that might potentially
6489 // involve a 'this' capture, mark 'this' for potential capture in
6490 // enclosing lambdas.
6491 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6492 CurLSI->addPotentialThisCapture(CallLoc);
6493 }
6494}
6495
6496// Once a call is fully resolved, warn for unqualified calls to specific
6497// C++ standard functions, like move and forward.
6499 const CallExpr *Call) {
6500 // We are only checking unary move and forward so exit early here.
6501 if (Call->getNumArgs() != 1)
6502 return;
6503
6504 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6505 if (!E || isa<UnresolvedLookupExpr>(E))
6506 return;
6507 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6508 if (!DRE || !DRE->getLocation().isValid())
6509 return;
6510
6511 if (DRE->getQualifier())
6512 return;
6513
6514 const FunctionDecl *FD = Call->getDirectCallee();
6515 if (!FD)
6516 return;
6517
6518 // Only warn for some functions deemed more frequent or problematic.
6519 unsigned BuiltinID = FD->getBuiltinID();
6520 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6521 return;
6522
6523 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6525 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6526}
6527
6529 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6530 Expr *ExecConfig) {
6532 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6533 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6534 if (Call.isInvalid())
6535 return Call;
6536
6537 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6538 // language modes.
6539 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6540 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6541 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6542 << ULE->getName();
6543 }
6544
6545 if (LangOpts.OpenMP)
6546 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6547 ExecConfig);
6548 if (LangOpts.CPlusPlus) {
6549 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6551
6552 // If we previously found that the id-expression of this call refers to a
6553 // consteval function but the call is dependent, we should not treat is an
6554 // an invalid immediate call.
6555 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6556 DRE && Call.get()->isValueDependent()) {
6558 }
6559 }
6560 return Call;
6561}
6562
6563// Any type that could be used to form a callable expression
6564static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6565 QualType T = E->getType();
6566 if (T->isDependentType())
6567 return true;
6568
6569 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6570 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6571 T->isFunctionType() || T->isFunctionReferenceType() ||
6572 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6573 T->isBlockPointerType() || T->isRecordType())
6574 return true;
6575
6578}
6579
6581 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6582 Expr *ExecConfig, bool IsExecConfig,
6583 bool AllowRecovery) {
6584 // Since this might be a postfix expression, get rid of ParenListExprs.
6586 if (Result.isInvalid()) return ExprError();
6587 Fn = Result.get();
6588
6589 if (CheckArgsForPlaceholders(ArgExprs))
6590 return ExprError();
6591
6592 // The result of __builtin_counted_by_ref cannot be used as a function
6593 // argument. It allows leaking and modification of bounds safety information.
6594 for (const Expr *Arg : ArgExprs)
6595 if (CheckInvalidBuiltinCountedByRef(Arg,
6597 return ExprError();
6598
6599 if (getLangOpts().CPlusPlus) {
6600 // If this is a pseudo-destructor expression, build the call immediately.
6602 if (!ArgExprs.empty()) {
6603 // Pseudo-destructor calls should not have any arguments.
6604 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6606 SourceRange(ArgExprs.front()->getBeginLoc(),
6607 ArgExprs.back()->getEndLoc()));
6608 }
6609
6610 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6611 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6612 }
6613 if (Fn->getType() == Context.PseudoObjectTy) {
6614 ExprResult result = CheckPlaceholderExpr(Fn);
6615 if (result.isInvalid()) return ExprError();
6616 Fn = result.get();
6617 }
6618
6619 // Determine whether this is a dependent call inside a C++ template,
6620 // in which case we won't do any semantic analysis now.
6621 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6622 if (ExecConfig) {
6624 cast<CallExpr>(ExecConfig), ArgExprs,
6625 Context.DependentTy, VK_PRValue,
6626 RParenLoc, CurFPFeatureOverrides());
6627 } else {
6628
6630 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6631 Fn->getBeginLoc());
6632
6633 // If the type of the function itself is not dependent
6634 // check that it is a reasonable as a function, as type deduction
6635 // later assume the CallExpr has a sensible TYPE.
6636 if (!MayBeFunctionType(Context, Fn))
6637 return ExprError(
6638 Diag(LParenLoc, diag::err_typecheck_call_not_function)
6639 << Fn->getType() << Fn->getSourceRange());
6640
6641 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6642 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6643 }
6644 }
6645
6646 // Determine whether this is a call to an object (C++ [over.call.object]).
6647 if (Fn->getType()->isRecordType())
6648 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6649 RParenLoc);
6650
6651 if (Fn->getType() == Context.UnknownAnyTy) {
6652 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6653 if (result.isInvalid()) return ExprError();
6654 Fn = result.get();
6655 }
6656
6657 if (Fn->getType() == Context.BoundMemberTy) {
6658 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6659 RParenLoc, ExecConfig, IsExecConfig,
6660 AllowRecovery);
6661 }
6662 }
6663
6664 // Check for overloaded calls. This can happen even in C due to extensions.
6665 if (Fn->getType() == Context.OverloadTy) {
6667
6668 // We aren't supposed to apply this logic if there's an '&' involved.
6671 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6672 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6673 OverloadExpr *ovl = find.Expression;
6674 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6676 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6677 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6678 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6679 RParenLoc, ExecConfig, IsExecConfig,
6680 AllowRecovery);
6681 }
6682 }
6683
6684 // If we're directly calling a function, get the appropriate declaration.
6685 if (Fn->getType() == Context.UnknownAnyTy) {
6686 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6687 if (result.isInvalid()) return ExprError();
6688 Fn = result.get();
6689 }
6690
6691 Expr *NakedFn = Fn->IgnoreParens();
6692
6693 bool CallingNDeclIndirectly = false;
6694 NamedDecl *NDecl = nullptr;
6695 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6696 if (UnOp->getOpcode() == UO_AddrOf) {
6697 CallingNDeclIndirectly = true;
6698 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6699 }
6700 }
6701
6702 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6703 NDecl = DRE->getDecl();
6704
6705 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6706 if (FDecl && FDecl->getBuiltinID()) {
6707 // Rewrite the function decl for this builtin by replacing parameters
6708 // with no explicit address space with the address space of the arguments
6709 // in ArgExprs.
6710 if ((FDecl =
6711 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6712 NDecl = FDecl;
6714 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6715 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6716 nullptr, DRE->isNonOdrUse());
6717 }
6718 }
6719 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6720 NDecl = ME->getMemberDecl();
6721
6722 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6723 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6724 FD, /*Complain=*/true, Fn->getBeginLoc()))
6725 return ExprError();
6726
6727 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6728
6729 // If this expression is a call to a builtin function in HIP device
6730 // compilation, allow a pointer-type argument to default address space to be
6731 // passed as a pointer-type parameter to a non-default address space.
6732 // If Arg is declared in the default address space and Param is declared
6733 // in a non-default address space, perform an implicit address space cast to
6734 // the parameter type.
6735 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6736 FD->getBuiltinID()) {
6737 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6738 ++Idx) {
6739 ParmVarDecl *Param = FD->getParamDecl(Idx);
6740 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6741 !ArgExprs[Idx]->getType()->isPointerType())
6742 continue;
6743
6744 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6745 auto ArgTy = ArgExprs[Idx]->getType();
6746 auto ArgPtTy = ArgTy->getPointeeType();
6747 auto ArgAS = ArgPtTy.getAddressSpace();
6748
6749 // Add address space cast if target address spaces are different
6750 bool NeedImplicitASC =
6751 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6752 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6753 // or from specific AS which has target AS matching that of Param.
6755 if (!NeedImplicitASC)
6756 continue;
6757
6758 // First, ensure that the Arg is an RValue.
6759 if (ArgExprs[Idx]->isGLValue()) {
6760 ArgExprs[Idx] = ImplicitCastExpr::Create(
6761 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6762 nullptr, VK_PRValue, FPOptionsOverride());
6763 }
6764
6765 // Construct a new arg type with address space of Param
6766 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6767 ArgPtQuals.setAddressSpace(ParamAS);
6768 auto NewArgPtTy =
6769 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6770 auto NewArgTy =
6771 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6772 ArgTy.getQualifiers());
6773
6774 // Finally perform an implicit address space cast
6775 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6776 CK_AddressSpaceConversion)
6777 .get();
6778 }
6779 }
6780 }
6781
6782 if (Context.isDependenceAllowed() &&
6783 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6784 assert(!getLangOpts().CPlusPlus);
6785 assert((Fn->containsErrors() ||
6786 llvm::any_of(ArgExprs,
6787 [](clang::Expr *E) { return E->containsErrors(); })) &&
6788 "should only occur in error-recovery path.");
6789 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6790 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6791 }
6792 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6793 ExecConfig, IsExecConfig);
6794}
6795
6797 MultiExprArg CallArgs) {
6798 std::string Name = Context.BuiltinInfo.getName(Id);
6799 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6801 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6802
6803 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6804 assert(BuiltInDecl && "failed to find builtin declaration");
6805
6806 ExprResult DeclRef =
6807 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6808 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6809
6811 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6812
6813 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6814 return Call.get();
6815}
6816
6818 SourceLocation BuiltinLoc,
6819 SourceLocation RParenLoc) {
6820 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6821 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6822}
6823
6825 SourceLocation BuiltinLoc,
6826 SourceLocation RParenLoc) {
6829 QualType SrcTy = E->getType();
6830 if (!SrcTy->isDependentType() &&
6831 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6832 return ExprError(
6833 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6834 << DestTy << SrcTy << E->getSourceRange());
6835 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6836}
6837
6839 SourceLocation BuiltinLoc,
6840 SourceLocation RParenLoc) {
6841 TypeSourceInfo *TInfo;
6842 GetTypeFromParser(ParsedDestTy, &TInfo);
6843 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6844}
6845
6847 SourceLocation LParenLoc,
6848 ArrayRef<Expr *> Args,
6849 SourceLocation RParenLoc, Expr *Config,
6850 bool IsExecConfig, ADLCallKind UsesADL) {
6851 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6852 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6853
6854 // Functions with 'interrupt' attribute cannot be called directly.
6855 if (FDecl) {
6856 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6857 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6858 return ExprError();
6859 }
6860 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6861 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6862 return ExprError();
6863 }
6864 }
6865
6866 // X86 interrupt handlers may only call routines with attribute
6867 // no_caller_saved_registers since there is no efficient way to
6868 // save and restore the non-GPR state.
6869 if (auto *Caller = getCurFunctionDecl()) {
6870 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6871 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6872 const TargetInfo &TI = Context.getTargetInfo();
6873 bool HasNonGPRRegisters =
6874 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6875 if (HasNonGPRRegisters &&
6876 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6877 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6878 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6879 if (FDecl)
6880 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6881 }
6882 }
6883 }
6884
6885 // Promote the function operand.
6886 // We special-case function promotion here because we only allow promoting
6887 // builtin functions to function pointers in the callee of a call.
6889 QualType ResultTy;
6890 if (BuiltinID &&
6891 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6892 // Extract the return type from the (builtin) function pointer type.
6893 // FIXME Several builtins still have setType in
6894 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6895 // Builtins.td to ensure they are correct before removing setType calls.
6896 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6897 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6898 ResultTy = FDecl->getCallResultType();
6899 } else {
6901 ResultTy = Context.BoolTy;
6902 }
6903 if (Result.isInvalid())
6904 return ExprError();
6905 Fn = Result.get();
6906
6907 // Check for a valid function type, but only if it is not a builtin which
6908 // requires custom type checking. These will be handled by
6909 // CheckBuiltinFunctionCall below just after creation of the call expression.
6910 const FunctionType *FuncT = nullptr;
6911 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6912 retry:
6913 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6914 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6915 // have type pointer to function".
6916 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6917 if (!FuncT)
6918 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6919 << Fn->getType() << Fn->getSourceRange());
6920 } else if (const BlockPointerType *BPT =
6921 Fn->getType()->getAs<BlockPointerType>()) {
6922 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6923 } else {
6924 // Handle calls to expressions of unknown-any type.
6925 if (Fn->getType() == Context.UnknownAnyTy) {
6926 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6927 if (rewrite.isInvalid())
6928 return ExprError();
6929 Fn = rewrite.get();
6930 goto retry;
6931 }
6932
6933 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6934 << Fn->getType() << Fn->getSourceRange());
6935 }
6936 }
6937
6938 // Get the number of parameters in the function prototype, if any.
6939 // We will allocate space for max(Args.size(), NumParams) arguments
6940 // in the call expression.
6941 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6942 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6943
6944 CallExpr *TheCall;
6945 if (Config) {
6946 assert(UsesADL == ADLCallKind::NotADL &&
6947 "CUDAKernelCallExpr should not use ADL");
6948 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6949 Args, ResultTy, VK_PRValue, RParenLoc,
6950 CurFPFeatureOverrides(), NumParams);
6951 } else {
6952 TheCall =
6953 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6954 CurFPFeatureOverrides(), NumParams, UsesADL);
6955 }
6956
6957 // Bail out early if calling a builtin with custom type checking.
6958 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6959 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6960 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
6961 E = CheckForImmediateInvocation(E, FDecl);
6962 return E;
6963 }
6964
6965 if (getLangOpts().CUDA) {
6966 if (Config) {
6967 // CUDA: Kernel calls must be to global functions
6968 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6969 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6970 << FDecl << Fn->getSourceRange());
6971
6972 // CUDA: Kernel function must have 'void' return type
6973 if (!FuncT->getReturnType()->isVoidType() &&
6974 !FuncT->getReturnType()->getAs<AutoType>() &&
6976 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6977 << Fn->getType() << Fn->getSourceRange());
6978 } else {
6979 // CUDA: Calls to global functions must be configured
6980 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6981 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6982 << FDecl << Fn->getSourceRange());
6983 }
6984 }
6985
6986 // Check for a valid return type
6987 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6988 FDecl))
6989 return ExprError();
6990
6991 // We know the result type of the call, set it.
6992 TheCall->setType(FuncT->getCallResultType(Context));
6994
6995 // WebAssembly tables can't be used as arguments.
6996 if (Context.getTargetInfo().getTriple().isWasm()) {
6997 for (const Expr *Arg : Args) {
6998 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
6999 return ExprError(Diag(Arg->getExprLoc(),
7000 diag::err_wasm_table_as_function_parameter));
7001 }
7002 }
7003 }
7004
7005 if (Proto) {
7006 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7007 IsExecConfig))
7008 return ExprError();
7009 } else {
7010 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7011
7012 if (FDecl) {
7013 // Check if we have too few/too many template arguments, based
7014 // on our knowledge of the function definition.
7015 const FunctionDecl *Def = nullptr;
7016 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7017 Proto = Def->getType()->getAs<FunctionProtoType>();
7018 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7019 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7020 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7021 }
7022
7023 // If the function we're calling isn't a function prototype, but we have
7024 // a function prototype from a prior declaratiom, use that prototype.
7025 if (!FDecl->hasPrototype())
7026 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7027 }
7028
7029 // If we still haven't found a prototype to use but there are arguments to
7030 // the call, diagnose this as calling a function without a prototype.
7031 // However, if we found a function declaration, check to see if
7032 // -Wdeprecated-non-prototype was disabled where the function was declared.
7033 // If so, we will silence the diagnostic here on the assumption that this
7034 // interface is intentional and the user knows what they're doing. We will
7035 // also silence the diagnostic if there is a function declaration but it
7036 // was implicitly defined (the user already gets diagnostics about the
7037 // creation of the implicit function declaration, so the additional warning
7038 // is not helpful).
7039 if (!Proto && !Args.empty() &&
7040 (!FDecl || (!FDecl->isImplicit() &&
7041 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7042 FDecl->getLocation()))))
7043 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7044 << (FDecl != nullptr) << FDecl;
7045
7046 // Promote the arguments (C99 6.5.2.2p6).
7047 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7048 Expr *Arg = Args[i];
7049
7050 if (Proto && i < Proto->getNumParams()) {
7052 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7053 ExprResult ArgE =
7055 if (ArgE.isInvalid())
7056 return true;
7057
7058 Arg = ArgE.getAs<Expr>();
7059
7060 } else {
7062
7063 if (ArgE.isInvalid())
7064 return true;
7065
7066 Arg = ArgE.getAs<Expr>();
7067 }
7068
7069 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7070 diag::err_call_incomplete_argument, Arg))
7071 return ExprError();
7072
7073 TheCall->setArg(i, Arg);
7074 }
7075 TheCall->computeDependence();
7076 }
7077
7078 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7079 if (Method->isImplicitObjectMemberFunction())
7080 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7081 << Fn->getSourceRange() << 0);
7082
7083 // Check for sentinels
7084 if (NDecl)
7085 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7086
7087 // Warn for unions passing across security boundary (CMSE).
7088 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7089 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7090 if (const auto *RT =
7091 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7092 if (RT->getOriginalDecl()->isOrContainsUnion())
7093 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7094 << 0 << i;
7095 }
7096 }
7097 }
7098
7099 // Do special checking on direct calls to functions.
7100 if (FDecl) {
7101 if (CheckFunctionCall(FDecl, TheCall, Proto))
7102 return ExprError();
7103
7104 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7105
7106 if (BuiltinID)
7107 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7108 } else if (NDecl) {
7109 if (CheckPointerCall(NDecl, TheCall, Proto))
7110 return ExprError();
7111 } else {
7112 if (CheckOtherCall(TheCall, Proto))
7113 return ExprError();
7114 }
7115
7116 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7117}
7118
7121 SourceLocation RParenLoc, Expr *InitExpr) {
7122 assert(Ty && "ActOnCompoundLiteral(): missing type");
7123 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7124
7125 TypeSourceInfo *TInfo;
7126 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7127 if (!TInfo)
7128 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7129
7130 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7131}
7132
7135 SourceLocation RParenLoc, Expr *LiteralExpr) {
7136 QualType literalType = TInfo->getType();
7137
7138 if (literalType->isArrayType()) {
7140 LParenLoc, Context.getBaseElementType(literalType),
7141 diag::err_array_incomplete_or_sizeless_type,
7142 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7143 return ExprError();
7144 if (literalType->isVariableArrayType()) {
7145 // C23 6.7.10p4: An entity of variable length array type shall not be
7146 // initialized except by an empty initializer.
7147 //
7148 // The C extension warnings are issued from ParseBraceInitializer() and
7149 // do not need to be issued here. However, we continue to issue an error
7150 // in the case there are initializers or we are compiling C++. We allow
7151 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7152 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7153 // FIXME: should we allow this construct in C++ when it makes sense to do
7154 // so?
7155 //
7156 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7157 // shall specify an object type or an array of unknown size, but not a
7158 // variable length array type. This seems odd, as it allows 'int a[size] =
7159 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7160 // says, this is what's implemented here for C (except for the extension
7161 // that permits constant foldable size arrays)
7162
7163 auto diagID = LangOpts.CPlusPlus
7164 ? diag::err_variable_object_no_init
7165 : diag::err_compound_literal_with_vla_type;
7166 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7167 diagID))
7168 return ExprError();
7169 }
7170 } else if (!literalType->isDependentType() &&
7171 RequireCompleteType(LParenLoc, literalType,
7172 diag::err_typecheck_decl_incomplete_type,
7173 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7174 return ExprError();
7175
7176 InitializedEntity Entity
7180 SourceRange(LParenLoc, RParenLoc),
7181 /*InitList=*/true);
7182 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7183 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7184 &literalType);
7185 if (Result.isInvalid())
7186 return ExprError();
7187 LiteralExpr = Result.get();
7188
7189 // We treat the compound literal as being at file scope if it's not in a
7190 // function or method body, or within the function's prototype scope. This
7191 // means the following compound literal is not at file scope:
7192 // void func(char *para[(int [1]){ 0 }[0]);
7193 const Scope *S = getCurScope();
7194 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7195 !S->isInCFunctionScope() &&
7196 (!S || !S->isFunctionPrototypeScope());
7197
7198 // In C, compound literals are l-values for some reason.
7199 // For GCC compatibility, in C++, file-scope array compound literals with
7200 // constant initializers are also l-values, and compound literals are
7201 // otherwise prvalues.
7202 //
7203 // (GCC also treats C++ list-initialized file-scope array prvalues with
7204 // constant initializers as l-values, but that's non-conforming, so we don't
7205 // follow it there.)
7206 //
7207 // FIXME: It would be better to handle the lvalue cases as materializing and
7208 // lifetime-extending a temporary object, but our materialized temporaries
7209 // representation only supports lifetime extension from a variable, not "out
7210 // of thin air".
7211 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7212 // is bound to the result of applying array-to-pointer decay to the compound
7213 // literal.
7214 // FIXME: GCC supports compound literals of reference type, which should
7215 // obviously have a value kind derived from the kind of reference involved.
7217 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7218 ? VK_PRValue
7219 : VK_LValue;
7220
7221 // C99 6.5.2.5
7222 // "If the compound literal occurs outside the body of a function, the
7223 // initializer list shall consist of constant expressions."
7224 if (IsFileScope)
7225 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7226 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7227 Expr *Init = ILE->getInit(i);
7228 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7229 !Init->isConstantInitializer(Context, /*IsForRef=*/false)) {
7230 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7231 << Init->getSourceBitField();
7232 return ExprError();
7233 }
7234
7235 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7236 }
7237
7238 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7239 LiteralExpr, IsFileScope);
7240 if (IsFileScope) {
7241 if (!LiteralExpr->isTypeDependent() &&
7242 !LiteralExpr->isValueDependent() &&
7243 !literalType->isDependentType()) // C99 6.5.2.5p3
7244 if (CheckForConstantInitializer(LiteralExpr))
7245 return ExprError();
7246 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7247 literalType.getAddressSpace() != LangAS::Default) {
7248 // Embedded-C extensions to C99 6.5.2.5:
7249 // "If the compound literal occurs inside the body of a function, the
7250 // type name shall not be qualified by an address-space qualifier."
7251 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7252 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7253 return ExprError();
7254 }
7255
7256 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7257 // Compound literals that have automatic storage duration are destroyed at
7258 // the end of the scope in C; in C++, they're just temporaries.
7259
7260 // Emit diagnostics if it is or contains a C union type that is non-trivial
7261 // to destruct.
7266
7267 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7268 if (literalType.isDestructedType()) {
7269 Cleanup.setExprNeedsCleanups(true);
7270 ExprCleanupObjects.push_back(E);
7272 }
7273 }
7274
7277 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7278 E->getInitializer()->getExprLoc());
7279
7280 return MaybeBindToTemporary(E);
7281}
7282
7285 SourceLocation RBraceLoc) {
7286 // Only produce each kind of designated initialization diagnostic once.
7287 SourceLocation FirstDesignator;
7288 bool DiagnosedArrayDesignator = false;
7289 bool DiagnosedNestedDesignator = false;
7290 bool DiagnosedMixedDesignator = false;
7291
7292 // Check that any designated initializers are syntactically valid in the
7293 // current language mode.
7294 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7295 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7296 if (FirstDesignator.isInvalid())
7297 FirstDesignator = DIE->getBeginLoc();
7298
7299 if (!getLangOpts().CPlusPlus)
7300 break;
7301
7302 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7303 DiagnosedNestedDesignator = true;
7304 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7305 << DIE->getDesignatorsSourceRange();
7306 }
7307
7308 for (auto &Desig : DIE->designators()) {
7309 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7310 DiagnosedArrayDesignator = true;
7311 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7312 << Desig.getSourceRange();
7313 }
7314 }
7315
7316 if (!DiagnosedMixedDesignator &&
7317 !isa<DesignatedInitExpr>(InitArgList[0])) {
7318 DiagnosedMixedDesignator = true;
7319 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7320 << DIE->getSourceRange();
7321 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7322 << InitArgList[0]->getSourceRange();
7323 }
7324 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7325 isa<DesignatedInitExpr>(InitArgList[0])) {
7326 DiagnosedMixedDesignator = true;
7327 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7328 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7329 << DIE->getSourceRange();
7330 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7331 << InitArgList[I]->getSourceRange();
7332 }
7333 }
7334
7335 if (FirstDesignator.isValid()) {
7336 // Only diagnose designated initiaization as a C++20 extension if we didn't
7337 // already diagnose use of (non-C++20) C99 designator syntax.
7338 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7339 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7340 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7341 ? diag::warn_cxx17_compat_designated_init
7342 : diag::ext_cxx_designated_init);
7343 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7344 Diag(FirstDesignator, diag::ext_designated_init);
7345 }
7346 }
7347
7348 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7349}
7350
7353 SourceLocation RBraceLoc) {
7354 // Semantic analysis for initializers is done by ActOnDeclarator() and
7355 // CheckInitializer() - it requires knowledge of the object being initialized.
7356
7357 // Immediately handle non-overload placeholders. Overloads can be
7358 // resolved contextually, but everything else here can't.
7359 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7360 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7361 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7362
7363 // Ignore failures; dropping the entire initializer list because
7364 // of one failure would be terrible for indexing/etc.
7365 if (result.isInvalid()) continue;
7366
7367 InitArgList[I] = result.get();
7368 }
7369 }
7370
7371 InitListExpr *E =
7372 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7373 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7374 return E;
7375}
7376
7378 assert(E.get()->getType()->isBlockPointerType());
7379 assert(E.get()->isPRValue());
7380
7381 // Only do this in an r-value context.
7382 if (!getLangOpts().ObjCAutoRefCount) return;
7383
7385 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7386 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7387 Cleanup.setExprNeedsCleanups(true);
7388}
7389
7391 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7392 // Also, callers should have filtered out the invalid cases with
7393 // pointers. Everything else should be possible.
7394
7395 QualType SrcTy = Src.get()->getType();
7396 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7397 return CK_NoOp;
7398
7399 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7401 llvm_unreachable("member pointer type in C");
7402
7403 case Type::STK_CPointer:
7406 switch (DestTy->getScalarTypeKind()) {
7407 case Type::STK_CPointer: {
7408 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7409 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7410 if (SrcAS != DestAS)
7411 return CK_AddressSpaceConversion;
7412 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7413 return CK_NoOp;
7414 return CK_BitCast;
7415 }
7417 return (SrcKind == Type::STK_BlockPointer
7418 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7420 if (SrcKind == Type::STK_ObjCObjectPointer)
7421 return CK_BitCast;
7422 if (SrcKind == Type::STK_CPointer)
7423 return CK_CPointerToObjCPointerCast;
7425 return CK_BlockPointerToObjCPointerCast;
7426 case Type::STK_Bool:
7427 return CK_PointerToBoolean;
7428 case Type::STK_Integral:
7429 return CK_PointerToIntegral;
7430 case Type::STK_Floating:
7435 llvm_unreachable("illegal cast from pointer");
7436 }
7437 llvm_unreachable("Should have returned before this");
7438
7440 switch (DestTy->getScalarTypeKind()) {
7442 return CK_FixedPointCast;
7443 case Type::STK_Bool:
7444 return CK_FixedPointToBoolean;
7445 case Type::STK_Integral:
7446 return CK_FixedPointToIntegral;
7447 case Type::STK_Floating:
7448 return CK_FixedPointToFloating;
7451 Diag(Src.get()->getExprLoc(),
7452 diag::err_unimplemented_conversion_with_fixed_point_type)
7453 << DestTy;
7454 return CK_IntegralCast;
7455 case Type::STK_CPointer:
7459 llvm_unreachable("illegal cast to pointer type");
7460 }
7461 llvm_unreachable("Should have returned before this");
7462
7463 case Type::STK_Bool: // casting from bool is like casting from an integer
7464 case Type::STK_Integral:
7465 switch (DestTy->getScalarTypeKind()) {
7466 case Type::STK_CPointer:
7471 return CK_NullToPointer;
7472 return CK_IntegralToPointer;
7473 case Type::STK_Bool:
7474 return CK_IntegralToBoolean;
7475 case Type::STK_Integral:
7476 return CK_IntegralCast;
7477 case Type::STK_Floating:
7478 return CK_IntegralToFloating;
7480 Src = ImpCastExprToType(Src.get(),
7481 DestTy->castAs<ComplexType>()->getElementType(),
7482 CK_IntegralCast);
7483 return CK_IntegralRealToComplex;
7485 Src = ImpCastExprToType(Src.get(),
7486 DestTy->castAs<ComplexType>()->getElementType(),
7487 CK_IntegralToFloating);
7488 return CK_FloatingRealToComplex;
7490 llvm_unreachable("member pointer type in C");
7492 return CK_IntegralToFixedPoint;
7493 }
7494 llvm_unreachable("Should have returned before this");
7495
7496 case Type::STK_Floating:
7497 switch (DestTy->getScalarTypeKind()) {
7498 case Type::STK_Floating:
7499 return CK_FloatingCast;
7500 case Type::STK_Bool:
7501 return CK_FloatingToBoolean;
7502 case Type::STK_Integral:
7503 return CK_FloatingToIntegral;
7505 Src = ImpCastExprToType(Src.get(),
7506 DestTy->castAs<ComplexType>()->getElementType(),
7507 CK_FloatingCast);
7508 return CK_FloatingRealToComplex;
7510 Src = ImpCastExprToType(Src.get(),
7511 DestTy->castAs<ComplexType>()->getElementType(),
7512 CK_FloatingToIntegral);
7513 return CK_IntegralRealToComplex;
7514 case Type::STK_CPointer:
7517 llvm_unreachable("valid float->pointer cast?");
7519 llvm_unreachable("member pointer type in C");
7521 return CK_FloatingToFixedPoint;
7522 }
7523 llvm_unreachable("Should have returned before this");
7524
7526 switch (DestTy->getScalarTypeKind()) {
7528 return CK_FloatingComplexCast;
7530 return CK_FloatingComplexToIntegralComplex;
7531 case Type::STK_Floating: {
7532 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7533 if (Context.hasSameType(ET, DestTy))
7534 return CK_FloatingComplexToReal;
7535 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7536 return CK_FloatingCast;
7537 }
7538 case Type::STK_Bool:
7539 return CK_FloatingComplexToBoolean;
7540 case Type::STK_Integral:
7541 Src = ImpCastExprToType(Src.get(),
7542 SrcTy->castAs<ComplexType>()->getElementType(),
7543 CK_FloatingComplexToReal);
7544 return CK_FloatingToIntegral;
7545 case Type::STK_CPointer:
7548 llvm_unreachable("valid complex float->pointer cast?");
7550 llvm_unreachable("member pointer type in C");
7552 Diag(Src.get()->getExprLoc(),
7553 diag::err_unimplemented_conversion_with_fixed_point_type)
7554 << SrcTy;
7555 return CK_IntegralCast;
7556 }
7557 llvm_unreachable("Should have returned before this");
7558
7560 switch (DestTy->getScalarTypeKind()) {
7562 return CK_IntegralComplexToFloatingComplex;
7564 return CK_IntegralComplexCast;
7565 case Type::STK_Integral: {
7566 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7567 if (Context.hasSameType(ET, DestTy))
7568 return CK_IntegralComplexToReal;
7569 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7570 return CK_IntegralCast;
7571 }
7572 case Type::STK_Bool:
7573 return CK_IntegralComplexToBoolean;
7574 case Type::STK_Floating:
7575 Src = ImpCastExprToType(Src.get(),
7576 SrcTy->castAs<ComplexType>()->getElementType(),
7577 CK_IntegralComplexToReal);
7578 return CK_IntegralToFloating;
7579 case Type::STK_CPointer:
7582 llvm_unreachable("valid complex int->pointer cast?");
7584 llvm_unreachable("member pointer type in C");
7586 Diag(Src.get()->getExprLoc(),
7587 diag::err_unimplemented_conversion_with_fixed_point_type)
7588 << SrcTy;
7589 return CK_IntegralCast;
7590 }
7591 llvm_unreachable("Should have returned before this");
7592 }
7593
7594 llvm_unreachable("Unhandled scalar cast");
7595}
7596
7597static bool breakDownVectorType(QualType type, uint64_t &len,
7598 QualType &eltType) {
7599 // Vectors are simple.
7600 if (const VectorType *vecType = type->getAs<VectorType>()) {
7601 len = vecType->getNumElements();
7602 eltType = vecType->getElementType();
7603 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7604 return true;
7605 }
7606
7607 // We allow lax conversion to and from non-vector types, but only if
7608 // they're real types (i.e. non-complex, non-pointer scalar types).
7609 if (!type->isRealType()) return false;
7610
7611 len = 1;
7612 eltType = type;
7613 return true;
7614}
7615
7617 assert(srcTy->isVectorType() || destTy->isVectorType());
7618
7619 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7620 if (!FirstType->isSVESizelessBuiltinType())
7621 return false;
7622
7623 const auto *VecTy = SecondType->getAs<VectorType>();
7624 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7625 };
7626
7627 return ValidScalableConversion(srcTy, destTy) ||
7628 ValidScalableConversion(destTy, srcTy);
7629}
7630
7632 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7633 return false;
7634
7635 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7636 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7637
7638 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7639 matSrcType->getNumColumns() == matDestType->getNumColumns();
7640}
7641
7643 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7644
7645 uint64_t SrcLen, DestLen;
7646 QualType SrcEltTy, DestEltTy;
7647 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7648 return false;
7649 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7650 return false;
7651
7652 // ASTContext::getTypeSize will return the size rounded up to a
7653 // power of 2, so instead of using that, we need to use the raw
7654 // element size multiplied by the element count.
7655 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7656 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7657
7658 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7659}
7660
7662 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7663 "expected at least one type to be a vector here");
7664
7665 bool IsSrcTyAltivec =
7666 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7668 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7670 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7672
7673 bool IsDestTyAltivec = DestTy->isVectorType() &&
7674 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7676 (DestTy->castAs<VectorType>()->getVectorKind() ==
7678 (DestTy->castAs<VectorType>()->getVectorKind() ==
7680
7681 return (IsSrcTyAltivec || IsDestTyAltivec);
7682}
7683
7685 assert(destTy->isVectorType() || srcTy->isVectorType());
7686
7687 // Disallow lax conversions between scalars and ExtVectors (these
7688 // conversions are allowed for other vector types because common headers
7689 // depend on them). Most scalar OP ExtVector cases are handled by the
7690 // splat path anyway, which does what we want (convert, not bitcast).
7691 // What this rules out for ExtVectors is crazy things like char4*float.
7692 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7693 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7694
7695 return areVectorTypesSameSize(srcTy, destTy);
7696}
7697
7699 assert(destTy->isVectorType() || srcTy->isVectorType());
7700
7701 switch (Context.getLangOpts().getLaxVectorConversions()) {
7703 return false;
7704
7706 if (!srcTy->isIntegralOrEnumerationType()) {
7707 auto *Vec = srcTy->getAs<VectorType>();
7708 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7709 return false;
7710 }
7711 if (!destTy->isIntegralOrEnumerationType()) {
7712 auto *Vec = destTy->getAs<VectorType>();
7713 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7714 return false;
7715 }
7716 // OK, integer (vector) -> integer (vector) bitcast.
7717 break;
7718
7720 break;
7721 }
7722
7723 return areLaxCompatibleVectorTypes(srcTy, destTy);
7724}
7725
7727 CastKind &Kind) {
7728 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7729 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7730 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7731 << DestTy << SrcTy << R;
7732 }
7733 } else if (SrcTy->isMatrixType()) {
7734 return Diag(R.getBegin(),
7735 diag::err_invalid_conversion_between_matrix_and_type)
7736 << SrcTy << DestTy << R;
7737 } else if (DestTy->isMatrixType()) {
7738 return Diag(R.getBegin(),
7739 diag::err_invalid_conversion_between_matrix_and_type)
7740 << DestTy << SrcTy << R;
7741 }
7742
7743 Kind = CK_MatrixCast;
7744 return false;
7745}
7746
7748 CastKind &Kind) {
7749 assert(VectorTy->isVectorType() && "Not a vector type!");
7750
7751 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7752 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7753 return Diag(R.getBegin(),
7754 Ty->isVectorType() ?
7755 diag::err_invalid_conversion_between_vectors :
7756 diag::err_invalid_conversion_between_vector_and_integer)
7757 << VectorTy << Ty << R;
7758 } else
7759 return Diag(R.getBegin(),
7760 diag::err_invalid_conversion_between_vector_and_scalar)
7761 << VectorTy << Ty << R;
7762
7763 Kind = CK_BitCast;
7764 return false;
7765}
7766
7768 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7769
7770 if (DestElemTy == SplattedExpr->getType())
7771 return SplattedExpr;
7772
7773 assert(DestElemTy->isFloatingType() ||
7774 DestElemTy->isIntegralOrEnumerationType());
7775
7776 CastKind CK;
7777 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7778 // OpenCL requires that we convert `true` boolean expressions to -1, but
7779 // only when splatting vectors.
7780 if (DestElemTy->isFloatingType()) {
7781 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7782 // in two steps: boolean to signed integral, then to floating.
7783 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7784 CK_BooleanToSignedIntegral);
7785 SplattedExpr = CastExprRes.get();
7786 CK = CK_IntegralToFloating;
7787 } else {
7788 CK = CK_BooleanToSignedIntegral;
7789 }
7790 } else {
7791 ExprResult CastExprRes = SplattedExpr;
7792 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7793 if (CastExprRes.isInvalid())
7794 return ExprError();
7795 SplattedExpr = CastExprRes.get();
7796 }
7797 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7798}
7799
7801 Expr *CastExpr, CastKind &Kind) {
7802 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7803
7804 QualType SrcTy = CastExpr->getType();
7805
7806 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7807 // an ExtVectorType.
7808 // In OpenCL, casts between vectors of different types are not allowed.
7809 // (See OpenCL 6.2).
7810 if (SrcTy->isVectorType()) {
7811 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7812 (getLangOpts().OpenCL &&
7813 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7814 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7815 << DestTy << SrcTy << R;
7816 return ExprError();
7817 }
7818 Kind = CK_BitCast;
7819 return CastExpr;
7820 }
7821
7822 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7823 // conversion will take place first from scalar to elt type, and then
7824 // splat from elt type to vector.
7825 if (SrcTy->isPointerType())
7826 return Diag(R.getBegin(),
7827 diag::err_invalid_conversion_between_vector_and_scalar)
7828 << DestTy << SrcTy << R;
7829
7830 Kind = CK_VectorSplat;
7831 return prepareVectorSplat(DestTy, CastExpr);
7832}
7833
7834/// Check that a call to alloc_size function specifies sufficient space for the
7835/// destination type.
7836static void CheckSufficientAllocSize(Sema &S, QualType DestType,
7837 const Expr *E) {
7838 QualType SourceType = E->getType();
7839 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
7840 DestType == SourceType)
7841 return;
7842
7843 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
7844 if (!CE)
7845 return;
7846
7847 // Find the total size allocated by the function call.
7848 if (!CE->getCalleeAllocSizeAttr())
7849 return;
7850 std::optional<llvm::APInt> AllocSize =
7851 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
7852 // Allocations of size zero are permitted as a special case. They are usually
7853 // done intentionally.
7854 if (!AllocSize || AllocSize->isZero())
7855 return;
7856 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
7857
7858 QualType TargetType = DestType->getPointeeType();
7859 // Find the destination size. As a special case function types have size of
7860 // one byte to match the sizeof operator behavior.
7861 auto LhsSize = TargetType->isFunctionType()
7862 ? CharUnits::One()
7863 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
7864 if (LhsSize && Size < LhsSize)
7865 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
7866 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
7867}
7868
7871 Declarator &D, ParsedType &Ty,
7872 SourceLocation RParenLoc, Expr *CastExpr) {
7873 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7874 "ActOnCastExpr(): missing type or expr");
7875
7877 if (D.isInvalidType())
7878 return ExprError();
7879
7880 if (getLangOpts().CPlusPlus) {
7881 // Check that there are no default arguments (C++ only).
7883 }
7884
7886
7887 QualType castType = castTInfo->getType();
7888 Ty = CreateParsedType(castType, castTInfo);
7889
7890 bool isVectorLiteral = false;
7891
7892 // Check for an altivec or OpenCL literal,
7893 // i.e. all the elements are integer constants.
7894 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7895 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7896 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7897 && castType->isVectorType() && (PE || PLE)) {
7898 if (PLE && PLE->getNumExprs() == 0) {
7899 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7900 return ExprError();
7901 }
7902 if (PE || PLE->getNumExprs() == 1) {
7903 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7904 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7905 isVectorLiteral = true;
7906 }
7907 else
7908 isVectorLiteral = true;
7909 }
7910
7911 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7912 // then handle it as such.
7913 if (isVectorLiteral)
7914 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7915
7916 // If the Expr being casted is a ParenListExpr, handle it specially.
7917 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7918 // sequence of BinOp comma operators.
7921 if (Result.isInvalid()) return ExprError();
7922 CastExpr = Result.get();
7923 }
7924
7925 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7926 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7927
7929
7931
7933
7934 CheckSufficientAllocSize(*this, castType, CastExpr);
7935
7936 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7937}
7938
7940 SourceLocation RParenLoc, Expr *E,
7941 TypeSourceInfo *TInfo) {
7942 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7943 "Expected paren or paren list expression");
7944
7945 Expr **exprs;
7946 unsigned numExprs;
7947 Expr *subExpr;
7948 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7949 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7950 LiteralLParenLoc = PE->getLParenLoc();
7951 LiteralRParenLoc = PE->getRParenLoc();
7952 exprs = PE->getExprs();
7953 numExprs = PE->getNumExprs();
7954 } else { // isa<ParenExpr> by assertion at function entrance
7955 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7956 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7957 subExpr = cast<ParenExpr>(E)->getSubExpr();
7958 exprs = &subExpr;
7959 numExprs = 1;
7960 }
7961
7962 QualType Ty = TInfo->getType();
7963 assert(Ty->isVectorType() && "Expected vector type");
7964
7965 SmallVector<Expr *, 8> initExprs;
7966 const VectorType *VTy = Ty->castAs<VectorType>();
7967 unsigned numElems = VTy->getNumElements();
7968
7969 // '(...)' form of vector initialization in AltiVec: the number of
7970 // initializers must be one or must match the size of the vector.
7971 // If a single value is specified in the initializer then it will be
7972 // replicated to all the components of the vector
7974 VTy->getElementType()))
7975 return ExprError();
7977 // The number of initializers must be one or must match the size of the
7978 // vector. If a single value is specified in the initializer then it will
7979 // be replicated to all the components of the vector
7980 if (numExprs == 1) {
7981 QualType ElemTy = VTy->getElementType();
7982 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7983 if (Literal.isInvalid())
7984 return ExprError();
7985 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7986 PrepareScalarCast(Literal, ElemTy));
7987 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7988 }
7989 else if (numExprs < numElems) {
7990 Diag(E->getExprLoc(),
7991 diag::err_incorrect_number_of_vector_initializers);
7992 return ExprError();
7993 }
7994 else
7995 initExprs.append(exprs, exprs + numExprs);
7996 }
7997 else {
7998 // For OpenCL, when the number of initializers is a single value,
7999 // it will be replicated to all components of the vector.
8001 numExprs == 1) {
8002 QualType ElemTy = VTy->getElementType();
8003 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8004 if (Literal.isInvalid())
8005 return ExprError();
8006 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8007 PrepareScalarCast(Literal, ElemTy));
8008 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8009 }
8010
8011 initExprs.append(exprs, exprs + numExprs);
8012 }
8013 // FIXME: This means that pretty-printing the final AST will produce curly
8014 // braces instead of the original commas.
8015 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8016 initExprs, LiteralRParenLoc);
8017 initE->setType(Ty);
8018 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8019}
8020
8023 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8024 if (!E)
8025 return OrigExpr;
8026
8027 ExprResult Result(E->getExpr(0));
8028
8029 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8030 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8031 E->getExpr(i));
8032
8033 if (Result.isInvalid()) return ExprError();
8034
8035 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8036}
8037
8043
8045 unsigned NumUserSpecifiedExprs,
8046 SourceLocation InitLoc,
8047 SourceLocation LParenLoc,
8048 SourceLocation RParenLoc) {
8049 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8050 InitLoc, LParenLoc, RParenLoc);
8051}
8052
8053bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8054 SourceLocation QuestionLoc) {
8055 const Expr *NullExpr = LHSExpr;
8056 const Expr *NonPointerExpr = RHSExpr;
8060
8061 if (NullKind == Expr::NPCK_NotNull) {
8062 NullExpr = RHSExpr;
8063 NonPointerExpr = LHSExpr;
8064 NullKind =
8067 }
8068
8069 if (NullKind == Expr::NPCK_NotNull)
8070 return false;
8071
8072 if (NullKind == Expr::NPCK_ZeroExpression)
8073 return false;
8074
8075 if (NullKind == Expr::NPCK_ZeroLiteral) {
8076 // In this case, check to make sure that we got here from a "NULL"
8077 // string in the source code.
8078 NullExpr = NullExpr->IgnoreParenImpCasts();
8079 SourceLocation loc = NullExpr->getExprLoc();
8080 if (!findMacroSpelling(loc, "NULL"))
8081 return false;
8082 }
8083
8084 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8085 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8086 << NonPointerExpr->getType() << DiagType
8087 << NonPointerExpr->getSourceRange();
8088 return true;
8089}
8090
8091/// Return false if the condition expression is valid, true otherwise.
8092static bool checkCondition(Sema &S, const Expr *Cond,
8093 SourceLocation QuestionLoc) {
8094 QualType CondTy = Cond->getType();
8095
8096 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8097 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8098 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8099 << CondTy << Cond->getSourceRange();
8100 return true;
8101 }
8102
8103 // C99 6.5.15p2
8104 if (CondTy->isScalarType()) return false;
8105
8106 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8107 << CondTy << Cond->getSourceRange();
8108 return true;
8109}
8110
8111/// Return false if the NullExpr can be promoted to PointerTy,
8112/// true otherwise.
8114 QualType PointerTy) {
8115 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8116 !NullExpr.get()->isNullPointerConstant(S.Context,
8118 return true;
8119
8120 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8121 return false;
8122}
8123
8124/// Checks compatibility between two pointers and return the resulting
8125/// type.
8127 ExprResult &RHS,
8128 SourceLocation Loc) {
8129 QualType LHSTy = LHS.get()->getType();
8130 QualType RHSTy = RHS.get()->getType();
8131
8132 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8133 // Two identical pointers types are always compatible.
8134 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8135 }
8136
8137 QualType lhptee, rhptee;
8138
8139 // Get the pointee types.
8140 bool IsBlockPointer = false;
8141 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8142 lhptee = LHSBTy->getPointeeType();
8143 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8144 IsBlockPointer = true;
8145 } else {
8146 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8147 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8148 }
8149
8150 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8151 // differently qualified versions of compatible types, the result type is
8152 // a pointer to an appropriately qualified version of the composite
8153 // type.
8154
8155 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8156 // clause doesn't make sense for our extensions. E.g. address space 2 should
8157 // be incompatible with address space 3: they may live on different devices or
8158 // anything.
8159 Qualifiers lhQual = lhptee.getQualifiers();
8160 Qualifiers rhQual = rhptee.getQualifiers();
8161
8162 LangAS ResultAddrSpace = LangAS::Default;
8163 LangAS LAddrSpace = lhQual.getAddressSpace();
8164 LangAS RAddrSpace = rhQual.getAddressSpace();
8165
8166 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8167 // spaces is disallowed.
8168 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8169 ResultAddrSpace = LAddrSpace;
8170 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8171 ResultAddrSpace = RAddrSpace;
8172 else {
8173 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8174 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8175 << RHS.get()->getSourceRange();
8176 return QualType();
8177 }
8178
8179 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8180 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8181 lhQual.removeCVRQualifiers();
8182 rhQual.removeCVRQualifiers();
8183
8184 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8185 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8186 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8187 << RHS.get()->getSourceRange();
8188 return QualType();
8189 }
8190
8191 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8192 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8193 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8194 // qual types are compatible iff
8195 // * corresponded types are compatible
8196 // * CVR qualifiers are equal
8197 // * address spaces are equal
8198 // Thus for conditional operator we merge CVR and address space unqualified
8199 // pointees and if there is a composite type we return a pointer to it with
8200 // merged qualifiers.
8201 LHSCastKind =
8202 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8203 RHSCastKind =
8204 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8205 lhQual.removeAddressSpace();
8206 rhQual.removeAddressSpace();
8207
8208 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8209 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8210
8211 QualType CompositeTy = S.Context.mergeTypes(
8212 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8213 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8214
8215 if (CompositeTy.isNull()) {
8216 // In this situation, we assume void* type. No especially good
8217 // reason, but this is what gcc does, and we do have to pick
8218 // to get a consistent AST.
8219 QualType incompatTy;
8220 incompatTy = S.Context.getPointerType(
8221 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8222 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8223 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8224
8225 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8226 // for casts between types with incompatible address space qualifiers.
8227 // For the following code the compiler produces casts between global and
8228 // local address spaces of the corresponded innermost pointees:
8229 // local int *global *a;
8230 // global int *global *b;
8231 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8232 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8233 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8234 << RHS.get()->getSourceRange();
8235
8236 return incompatTy;
8237 }
8238
8239 // The pointer types are compatible.
8240 // In case of OpenCL ResultTy should have the address space qualifier
8241 // which is a superset of address spaces of both the 2nd and the 3rd
8242 // operands of the conditional operator.
8243 QualType ResultTy = [&, ResultAddrSpace]() {
8244 if (S.getLangOpts().OpenCL) {
8245 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8246 CompositeQuals.setAddressSpace(ResultAddrSpace);
8247 return S.Context
8248 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8249 .withCVRQualifiers(MergedCVRQual);
8250 }
8251 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8252 }();
8253 if (IsBlockPointer)
8254 ResultTy = S.Context.getBlockPointerType(ResultTy);
8255 else
8256 ResultTy = S.Context.getPointerType(ResultTy);
8257
8258 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8259 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8260 return ResultTy;
8261}
8262
8263/// Return the resulting type when the operands are both block pointers.
8265 ExprResult &LHS,
8266 ExprResult &RHS,
8267 SourceLocation Loc) {
8268 QualType LHSTy = LHS.get()->getType();
8269 QualType RHSTy = RHS.get()->getType();
8270
8271 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8272 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8274 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8275 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8276 return destType;
8277 }
8278 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8279 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8280 << RHS.get()->getSourceRange();
8281 return QualType();
8282 }
8283
8284 // We have 2 block pointer types.
8285 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8286}
8287
8288/// Return the resulting type when the operands are both pointers.
8289static QualType
8291 ExprResult &RHS,
8292 SourceLocation Loc) {
8293 // get the pointer types
8294 QualType LHSTy = LHS.get()->getType();
8295 QualType RHSTy = RHS.get()->getType();
8296
8297 // get the "pointed to" types
8298 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8299 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8300
8301 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8302 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8303 // Figure out necessary qualifiers (C99 6.5.15p6)
8304 QualType destPointee
8305 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8306 QualType destType = S.Context.getPointerType(destPointee);
8307 // Add qualifiers if necessary.
8308 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8309 // Promote to void*.
8310 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8311 return destType;
8312 }
8313 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8314 QualType destPointee
8315 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8316 QualType destType = S.Context.getPointerType(destPointee);
8317 // Add qualifiers if necessary.
8318 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8319 // Promote to void*.
8320 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8321 return destType;
8322 }
8323
8324 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8325}
8326
8327/// Return false if the first expression is not an integer and the second
8328/// expression is not a pointer, true otherwise.
8330 Expr* PointerExpr, SourceLocation Loc,
8331 bool IsIntFirstExpr) {
8332 if (!PointerExpr->getType()->isPointerType() ||
8333 !Int.get()->getType()->isIntegerType())
8334 return false;
8335
8336 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8337 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8338
8339 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8340 << Expr1->getType() << Expr2->getType()
8341 << Expr1->getSourceRange() << Expr2->getSourceRange();
8342 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8343 CK_IntegralToPointer);
8344 return true;
8345}
8346
8347/// Simple conversion between integer and floating point types.
8348///
8349/// Used when handling the OpenCL conditional operator where the
8350/// condition is a vector while the other operands are scalar.
8351///
8352/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8353/// types are either integer or floating type. Between the two
8354/// operands, the type with the higher rank is defined as the "result
8355/// type". The other operand needs to be promoted to the same type. No
8356/// other type promotion is allowed. We cannot use
8357/// UsualArithmeticConversions() for this purpose, since it always
8358/// promotes promotable types.
8360 ExprResult &RHS,
8361 SourceLocation QuestionLoc) {
8363 if (LHS.isInvalid())
8364 return QualType();
8366 if (RHS.isInvalid())
8367 return QualType();
8368
8369 // For conversion purposes, we ignore any qualifiers.
8370 // For example, "const float" and "float" are equivalent.
8371 QualType LHSType =
8373 QualType RHSType =
8375
8376 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8377 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8378 << LHSType << LHS.get()->getSourceRange();
8379 return QualType();
8380 }
8381
8382 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8383 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8384 << RHSType << RHS.get()->getSourceRange();
8385 return QualType();
8386 }
8387
8388 // If both types are identical, no conversion is needed.
8389 if (LHSType == RHSType)
8390 return LHSType;
8391
8392 // Now handle "real" floating types (i.e. float, double, long double).
8393 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8394 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8395 /*IsCompAssign = */ false);
8396
8397 // Finally, we have two differing integer types.
8399 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8400}
8401
8402/// Convert scalar operands to a vector that matches the
8403/// condition in length.
8404///
8405/// Used when handling the OpenCL conditional operator where the
8406/// condition is a vector while the other operands are scalar.
8407///
8408/// We first compute the "result type" for the scalar operands
8409/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8410/// into a vector of that type where the length matches the condition
8411/// vector type. s6.11.6 requires that the element types of the result
8412/// and the condition must have the same number of bits.
8413static QualType
8415 QualType CondTy, SourceLocation QuestionLoc) {
8416 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8417 if (ResTy.isNull()) return QualType();
8418
8419 const VectorType *CV = CondTy->getAs<VectorType>();
8420 assert(CV);
8421
8422 // Determine the vector result type
8423 unsigned NumElements = CV->getNumElements();
8424 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8425
8426 // Ensure that all types have the same number of bits
8428 != S.Context.getTypeSize(ResTy)) {
8429 // Since VectorTy is created internally, it does not pretty print
8430 // with an OpenCL name. Instead, we just print a description.
8431 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8432 SmallString<64> Str;
8433 llvm::raw_svector_ostream OS(Str);
8434 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8435 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8436 << CondTy << OS.str();
8437 return QualType();
8438 }
8439
8440 // Convert operands to the vector result type
8441 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8442 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8443
8444 return VectorTy;
8445}
8446
8447/// Return false if this is a valid OpenCL condition vector
8449 SourceLocation QuestionLoc) {
8450 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8451 // integral type.
8452 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8453 assert(CondTy);
8454 QualType EleTy = CondTy->getElementType();
8455 if (EleTy->isIntegerType()) return false;
8456
8457 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8458 << Cond->getType() << Cond->getSourceRange();
8459 return true;
8460}
8461
8462/// Return false if the vector condition type and the vector
8463/// result type are compatible.
8464///
8465/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8466/// number of elements, and their element types have the same number
8467/// of bits.
8468static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8469 SourceLocation QuestionLoc) {
8470 const VectorType *CV = CondTy->getAs<VectorType>();
8471 const VectorType *RV = VecResTy->getAs<VectorType>();
8472 assert(CV && RV);
8473
8474 if (CV->getNumElements() != RV->getNumElements()) {
8475 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8476 << CondTy << VecResTy;
8477 return true;
8478 }
8479
8480 QualType CVE = CV->getElementType();
8481 QualType RVE = RV->getElementType();
8482
8483 // Boolean vectors are permitted outside of OpenCL mode.
8484 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8485 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8486 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8487 << CondTy << VecResTy;
8488 return true;
8489 }
8490
8491 return false;
8492}
8493
8494/// Return the resulting type for the conditional operator in
8495/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8496/// s6.3.i) when the condition is a vector type.
8497static QualType
8499 ExprResult &LHS, ExprResult &RHS,
8500 SourceLocation QuestionLoc) {
8502 if (Cond.isInvalid())
8503 return QualType();
8504 QualType CondTy = Cond.get()->getType();
8505
8506 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8507 return QualType();
8508
8509 // If either operand is a vector then find the vector type of the
8510 // result as specified in OpenCL v1.1 s6.3.i.
8511 if (LHS.get()->getType()->isVectorType() ||
8512 RHS.get()->getType()->isVectorType()) {
8513 bool IsBoolVecLang =
8514 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8515 QualType VecResTy =
8516 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8517 /*isCompAssign*/ false,
8518 /*AllowBothBool*/ true,
8519 /*AllowBoolConversions*/ false,
8520 /*AllowBooleanOperation*/ IsBoolVecLang,
8521 /*ReportInvalid*/ true);
8522 if (VecResTy.isNull())
8523 return QualType();
8524 // The result type must match the condition type as specified in
8525 // OpenCL v1.1 s6.11.6.
8526 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8527 return QualType();
8528 return VecResTy;
8529 }
8530
8531 // Both operands are scalar.
8532 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8533}
8534
8535/// Return true if the Expr is block type
8536static bool checkBlockType(Sema &S, const Expr *E) {
8537 if (E->getType()->isBlockPointerType()) {
8538 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8539 return true;
8540 }
8541
8542 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8543 QualType Ty = CE->getCallee()->getType();
8544 if (Ty->isBlockPointerType()) {
8545 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8546 return true;
8547 }
8548 }
8549 return false;
8550}
8551
8552/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8553/// In that case, LHS = cond.
8554/// C99 6.5.15
8557 ExprObjectKind &OK,
8558 SourceLocation QuestionLoc) {
8559
8560 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8561 if (!LHSResult.isUsable()) return QualType();
8562 LHS = LHSResult;
8563
8564 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8565 if (!RHSResult.isUsable()) return QualType();
8566 RHS = RHSResult;
8567
8568 // C++ is sufficiently different to merit its own checker.
8569 if (getLangOpts().CPlusPlus)
8570 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8571
8572 VK = VK_PRValue;
8573 OK = OK_Ordinary;
8574
8575 if (Context.isDependenceAllowed() &&
8576 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8577 RHS.get()->isTypeDependent())) {
8578 assert(!getLangOpts().CPlusPlus);
8579 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8580 RHS.get()->containsErrors()) &&
8581 "should only occur in error-recovery path.");
8582 return Context.DependentTy;
8583 }
8584
8585 // The OpenCL operator with a vector condition is sufficiently
8586 // different to merit its own checker.
8587 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8588 Cond.get()->getType()->isExtVectorType())
8589 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8590
8591 // First, check the condition.
8593 if (Cond.isInvalid())
8594 return QualType();
8595 if (checkCondition(*this, Cond.get(), QuestionLoc))
8596 return QualType();
8597
8598 // Handle vectors.
8599 if (LHS.get()->getType()->isVectorType() ||
8600 RHS.get()->getType()->isVectorType())
8601 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8602 /*AllowBothBool*/ true,
8603 /*AllowBoolConversions*/ false,
8604 /*AllowBooleanOperation*/ false,
8605 /*ReportInvalid*/ true);
8606
8607 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
8609 if (LHS.isInvalid() || RHS.isInvalid())
8610 return QualType();
8611
8612 // WebAssembly tables are not allowed as conditional LHS or RHS.
8613 QualType LHSTy = LHS.get()->getType();
8614 QualType RHSTy = RHS.get()->getType();
8615 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8616 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8617 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8618 return QualType();
8619 }
8620
8621 // Diagnose attempts to convert between __ibm128, __float128 and long double
8622 // where such conversions currently can't be handled.
8623 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8624 Diag(QuestionLoc,
8625 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8626 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8627 return QualType();
8628 }
8629
8630 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8631 // selection operator (?:).
8632 if (getLangOpts().OpenCL &&
8633 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8634 return QualType();
8635 }
8636
8637 // If both operands have arithmetic type, do the usual arithmetic conversions
8638 // to find a common type: C99 6.5.15p3,5.
8639 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8640 // Disallow invalid arithmetic conversions, such as those between bit-
8641 // precise integers types of different sizes, or between a bit-precise
8642 // integer and another type.
8643 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8644 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8645 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8646 << RHS.get()->getSourceRange();
8647 return QualType();
8648 }
8649
8650 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8651 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8652
8653 return ResTy;
8654 }
8655
8656 // If both operands are the same structure or union type, the result is that
8657 // type.
8658 // FIXME: Type of conditional expression must be complete in C mode.
8659 if (LHSTy->isRecordType() &&
8660 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
8661 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
8662 RHSTy.getUnqualifiedType());
8663
8664 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8665 // The following || allows only one side to be void (a GCC-ism).
8666 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8667 QualType ResTy;
8668 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8669 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8670 } else if (RHSTy->isVoidType()) {
8671 ResTy = RHSTy;
8672 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8673 << RHS.get()->getSourceRange();
8674 } else {
8675 ResTy = LHSTy;
8676 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8677 << LHS.get()->getSourceRange();
8678 }
8679 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8680 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8681 return ResTy;
8682 }
8683
8684 // C23 6.5.15p7:
8685 // ... if both the second and third operands have nullptr_t type, the
8686 // result also has that type.
8687 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8688 return ResTy;
8689
8690 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8691 // the type of the other operand."
8692 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8693 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8694
8695 // All objective-c pointer type analysis is done here.
8696 QualType compositeType =
8697 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8698 if (LHS.isInvalid() || RHS.isInvalid())
8699 return QualType();
8700 if (!compositeType.isNull())
8701 return compositeType;
8702
8703
8704 // Handle block pointer types.
8705 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8706 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8707 QuestionLoc);
8708
8709 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8710 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8711 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8712 QuestionLoc);
8713
8714 // GCC compatibility: soften pointer/integer mismatch. Note that
8715 // null pointers have been filtered out by this point.
8716 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8717 /*IsIntFirstExpr=*/true))
8718 return RHSTy;
8719 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8720 /*IsIntFirstExpr=*/false))
8721 return LHSTy;
8722
8723 // Emit a better diagnostic if one of the expressions is a null pointer
8724 // constant and the other is not a pointer type. In this case, the user most
8725 // likely forgot to take the address of the other expression.
8726 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8727 return QualType();
8728
8729 // Finally, if the LHS and RHS types are canonically the same type, we can
8730 // use the common sugared type.
8731 if (Context.hasSameType(LHSTy, RHSTy))
8732 return Context.getCommonSugaredType(LHSTy, RHSTy);
8733
8734 // Otherwise, the operands are not compatible.
8735 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8736 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8737 << RHS.get()->getSourceRange();
8738 return QualType();
8739}
8740
8741/// SuggestParentheses - Emit a note with a fixit hint that wraps
8742/// ParenRange in parentheses.
8744 const PartialDiagnostic &Note,
8745 SourceRange ParenRange) {
8746 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8747 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8748 EndLoc.isValid()) {
8749 Self.Diag(Loc, Note)
8750 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8751 << FixItHint::CreateInsertion(EndLoc, ")");
8752 } else {
8753 // We can't display the parentheses, so just show the bare note.
8754 Self.Diag(Loc, Note) << ParenRange;
8755 }
8756}
8757
8759 return BinaryOperator::isAdditiveOp(Opc) ||
8761 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8762 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8763 // not any of the logical operators. Bitwise-xor is commonly used as a
8764 // logical-xor because there is no logical-xor operator. The logical
8765 // operators, including uses of xor, have a high false positive rate for
8766 // precedence warnings.
8767}
8768
8769/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8770/// expression, either using a built-in or overloaded operator,
8771/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8772/// expression.
8773static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
8774 const Expr **RHSExprs) {
8775 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8776 E = E->IgnoreImpCasts();
8778 E = E->IgnoreImpCasts();
8779 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8780 E = MTE->getSubExpr();
8781 E = E->IgnoreImpCasts();
8782 }
8783
8784 // Built-in binary operator.
8785 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8786 OP && IsArithmeticOp(OP->getOpcode())) {
8787 *Opcode = OP->getOpcode();
8788 *RHSExprs = OP->getRHS();
8789 return true;
8790 }
8791
8792 // Overloaded operator.
8793 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8794 if (Call->getNumArgs() != 2)
8795 return false;
8796
8797 // Make sure this is really a binary operator that is safe to pass into
8798 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8799 OverloadedOperatorKind OO = Call->getOperator();
8800 if (OO < OO_Plus || OO > OO_Arrow ||
8801 OO == OO_PlusPlus || OO == OO_MinusMinus)
8802 return false;
8803
8805 if (IsArithmeticOp(OpKind)) {
8806 *Opcode = OpKind;
8807 *RHSExprs = Call->getArg(1);
8808 return true;
8809 }
8810 }
8811
8812 return false;
8813}
8814
8815/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8816/// or is a logical expression such as (x==y) which has int type, but is
8817/// commonly interpreted as boolean.
8818static bool ExprLooksBoolean(const Expr *E) {
8819 E = E->IgnoreParenImpCasts();
8820
8821 if (E->getType()->isBooleanType())
8822 return true;
8823 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8824 return OP->isComparisonOp() || OP->isLogicalOp();
8825 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8826 return OP->getOpcode() == UO_LNot;
8827 if (E->getType()->isPointerType())
8828 return true;
8829 // FIXME: What about overloaded operator calls returning "unspecified boolean
8830 // type"s (commonly pointer-to-members)?
8831
8832 return false;
8833}
8834
8835/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8836/// and binary operator are mixed in a way that suggests the programmer assumed
8837/// the conditional operator has higher precedence, for example:
8838/// "int x = a + someBinaryCondition ? 1 : 2".
8840 Expr *Condition, const Expr *LHSExpr,
8841 const Expr *RHSExpr) {
8842 BinaryOperatorKind CondOpcode;
8843 const Expr *CondRHS;
8844
8845 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8846 return;
8847 if (!ExprLooksBoolean(CondRHS))
8848 return;
8849
8850 // The condition is an arithmetic binary expression, with a right-
8851 // hand side that looks boolean, so warn.
8852
8853 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8854 ? diag::warn_precedence_bitwise_conditional
8855 : diag::warn_precedence_conditional;
8856
8857 Self.Diag(OpLoc, DiagID)
8858 << Condition->getSourceRange()
8859 << BinaryOperator::getOpcodeStr(CondOpcode);
8860
8862 Self, OpLoc,
8863 Self.PDiag(diag::note_precedence_silence)
8864 << BinaryOperator::getOpcodeStr(CondOpcode),
8865 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8866
8867 SuggestParentheses(Self, OpLoc,
8868 Self.PDiag(diag::note_precedence_conditional_first),
8869 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8870}
8871
8872/// Compute the nullability of a conditional expression.
8874 QualType LHSTy, QualType RHSTy,
8875 ASTContext &Ctx) {
8876 if (!ResTy->isAnyPointerType())
8877 return ResTy;
8878
8879 auto GetNullability = [](QualType Ty) {
8880 std::optional<NullabilityKind> Kind = Ty->getNullability();
8881 if (Kind) {
8882 // For our purposes, treat _Nullable_result as _Nullable.
8885 return *Kind;
8886 }
8888 };
8889
8890 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8891 NullabilityKind MergedKind;
8892
8893 // Compute nullability of a binary conditional expression.
8894 if (IsBin) {
8895 if (LHSKind == NullabilityKind::NonNull)
8896 MergedKind = NullabilityKind::NonNull;
8897 else
8898 MergedKind = RHSKind;
8899 // Compute nullability of a normal conditional expression.
8900 } else {
8901 if (LHSKind == NullabilityKind::Nullable ||
8902 RHSKind == NullabilityKind::Nullable)
8903 MergedKind = NullabilityKind::Nullable;
8904 else if (LHSKind == NullabilityKind::NonNull)
8905 MergedKind = RHSKind;
8906 else if (RHSKind == NullabilityKind::NonNull)
8907 MergedKind = LHSKind;
8908 else
8909 MergedKind = NullabilityKind::Unspecified;
8910 }
8911
8912 // Return if ResTy already has the correct nullability.
8913 if (GetNullability(ResTy) == MergedKind)
8914 return ResTy;
8915
8916 // Strip all nullability from ResTy.
8917 while (ResTy->getNullability())
8918 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8919
8920 // Create a new AttributedType with the new nullability kind.
8921 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
8922}
8923
8925 SourceLocation ColonLoc,
8926 Expr *CondExpr, Expr *LHSExpr,
8927 Expr *RHSExpr) {
8928 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8929 // was the condition.
8930 OpaqueValueExpr *opaqueValue = nullptr;
8931 Expr *commonExpr = nullptr;
8932 if (!LHSExpr) {
8933 commonExpr = CondExpr;
8934 // Lower out placeholder types first. This is important so that we don't
8935 // try to capture a placeholder. This happens in few cases in C++; such
8936 // as Objective-C++'s dictionary subscripting syntax.
8937 if (commonExpr->hasPlaceholderType()) {
8938 ExprResult result = CheckPlaceholderExpr(commonExpr);
8939 if (!result.isUsable()) return ExprError();
8940 commonExpr = result.get();
8941 }
8942 // We usually want to apply unary conversions *before* saving, except
8943 // in the special case of a C++ l-value conditional.
8944 if (!(getLangOpts().CPlusPlus
8945 && !commonExpr->isTypeDependent()
8946 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8947 && commonExpr->isGLValue()
8948 && commonExpr->isOrdinaryOrBitFieldObject()
8949 && RHSExpr->isOrdinaryOrBitFieldObject()
8950 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8951 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8952 if (commonRes.isInvalid())
8953 return ExprError();
8954 commonExpr = commonRes.get();
8955 }
8956
8957 // If the common expression is a class or array prvalue, materialize it
8958 // so that we can safely refer to it multiple times.
8959 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8960 commonExpr->getType()->isArrayType())) {
8961 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8962 if (MatExpr.isInvalid())
8963 return ExprError();
8964 commonExpr = MatExpr.get();
8965 }
8966
8967 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8968 commonExpr->getType(),
8969 commonExpr->getValueKind(),
8970 commonExpr->getObjectKind(),
8971 commonExpr);
8972 LHSExpr = CondExpr = opaqueValue;
8973 }
8974
8975 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8978 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8979 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8980 VK, OK, QuestionLoc);
8981 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8982 RHS.isInvalid())
8983 return ExprError();
8984
8985 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8986 RHS.get());
8987
8988 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8989
8990 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8991 Context);
8992
8993 if (!commonExpr)
8994 return new (Context)
8995 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8996 RHS.get(), result, VK, OK);
8997
8999 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9000 ColonLoc, result, VK, OK);
9001}
9002
9004 unsigned FromAttributes = 0, ToAttributes = 0;
9005 if (const auto *FromFn =
9006 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9007 FromAttributes =
9008 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9009 if (const auto *ToFn =
9010 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9011 ToAttributes =
9012 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9013
9014 return FromAttributes != ToAttributes;
9015}
9016
9017// Check if we have a conversion between incompatible cmse function pointer
9018// types, that is, a conversion between a function pointer with the
9019// cmse_nonsecure_call attribute and one without.
9021 QualType ToType) {
9022 if (const auto *ToFn =
9023 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9024 if (const auto *FromFn =
9025 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9026 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9027 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9028
9029 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9030 }
9031 }
9032 return false;
9033}
9034
9035// checkPointerTypesForAssignment - This is a very tricky routine (despite
9036// being closely modeled after the C99 spec:-). The odd characteristic of this
9037// routine is it effectively iqnores the qualifiers on the top level pointee.
9038// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9039// FIXME: add a couple examples in this comment.
9041 QualType LHSType,
9042 QualType RHSType,
9043 SourceLocation Loc) {
9044 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9045 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9046
9047 // get the "pointed to" type (ignoring qualifiers at the top level)
9048 const Type *lhptee, *rhptee;
9049 Qualifiers lhq, rhq;
9050 std::tie(lhptee, lhq) =
9051 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9052 std::tie(rhptee, rhq) =
9053 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9054
9056
9057 // C99 6.5.16.1p1: This following citation is common to constraints
9058 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9059 // qualifiers of the type *pointed to* by the right;
9060
9061 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9062 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9064 // Ignore lifetime for further calculation.
9065 lhq.removeObjCLifetime();
9066 rhq.removeObjCLifetime();
9067 }
9068
9069 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9070 // Treat address-space mismatches as fatal.
9071 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9073
9074 // It's okay to add or remove GC or lifetime qualifiers when converting to
9075 // and from void*.
9078 S.getASTContext()) &&
9079 (lhptee->isVoidType() || rhptee->isVoidType()))
9080 ; // keep old
9081
9082 // Treat lifetime mismatches as fatal.
9083 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9085
9086 // Treat pointer-auth mismatches as fatal.
9087 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9089
9090 // For GCC/MS compatibility, other qualifier mismatches are treated
9091 // as still compatible in C.
9092 else
9094 }
9095
9096 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9097 // incomplete type and the other is a pointer to a qualified or unqualified
9098 // version of void...
9099 if (lhptee->isVoidType()) {
9100 if (rhptee->isIncompleteOrObjectType())
9101 return ConvTy;
9102
9103 // As an extension, we allow cast to/from void* to function pointer.
9104 assert(rhptee->isFunctionType());
9106 }
9107
9108 if (rhptee->isVoidType()) {
9109 // In C, void * to another pointer type is compatible, but we want to note
9110 // that there will be an implicit conversion happening here.
9111 if (lhptee->isIncompleteOrObjectType())
9112 return ConvTy == AssignConvertType::Compatible &&
9113 !S.getLangOpts().CPlusPlus
9115 : ConvTy;
9116
9117 // As an extension, we allow cast to/from void* to function pointer.
9118 assert(lhptee->isFunctionType());
9120 }
9121
9122 if (!S.Diags.isIgnored(
9123 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9124 Loc) &&
9125 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9126 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9128
9129 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9130 // unqualified versions of compatible types, ...
9131 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9132 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9133 // Check if the pointee types are compatible ignoring the sign.
9134 // We explicitly check for char so that we catch "char" vs
9135 // "unsigned char" on systems where "char" is unsigned.
9136 if (lhptee->isCharType())
9137 ltrans = S.Context.UnsignedCharTy;
9138 else if (lhptee->hasSignedIntegerRepresentation())
9139 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9140
9141 if (rhptee->isCharType())
9142 rtrans = S.Context.UnsignedCharTy;
9143 else if (rhptee->hasSignedIntegerRepresentation())
9144 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9145
9146 if (ltrans == rtrans) {
9147 // Types are compatible ignoring the sign. Qualifier incompatibility
9148 // takes priority over sign incompatibility because the sign
9149 // warning can be disabled.
9150 if (!S.IsAssignConvertCompatible(ConvTy))
9151 return ConvTy;
9152
9154 }
9155
9156 // If we are a multi-level pointer, it's possible that our issue is simply
9157 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9158 // the eventual target type is the same and the pointers have the same
9159 // level of indirection, this must be the issue.
9160 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9161 do {
9162 std::tie(lhptee, lhq) =
9163 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9164 std::tie(rhptee, rhq) =
9165 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9166
9167 // Inconsistent address spaces at this point is invalid, even if the
9168 // address spaces would be compatible.
9169 // FIXME: This doesn't catch address space mismatches for pointers of
9170 // different nesting levels, like:
9171 // __local int *** a;
9172 // int ** b = a;
9173 // It's not clear how to actually determine when such pointers are
9174 // invalidly incompatible.
9175 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9176 return AssignConvertType::
9177 IncompatibleNestedPointerAddressSpaceMismatch;
9178
9179 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9180
9181 if (lhptee == rhptee)
9183 }
9184
9185 // General pointer incompatibility takes priority over qualifiers.
9186 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9189 }
9190 bool DiscardingCFIUncheckedCallee, AddingCFIUncheckedCallee;
9191 if (!S.getLangOpts().CPlusPlus &&
9192 S.IsFunctionConversion(ltrans, rtrans, &DiscardingCFIUncheckedCallee,
9193 &AddingCFIUncheckedCallee)) {
9194 // Allow conversions between CFIUncheckedCallee-ness.
9195 if (!DiscardingCFIUncheckedCallee && !AddingCFIUncheckedCallee)
9197 }
9198 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9200 if (S.IsInvalidSMECallConversion(rtrans, ltrans))
9202 return ConvTy;
9203}
9204
9205/// checkBlockPointerTypesForAssignment - This routine determines whether two
9206/// block pointer types are compatible or whether a block and normal pointer
9207/// are compatible. It is more restrict than comparing two function pointer
9208// types.
9210 QualType LHSType,
9211 QualType RHSType) {
9212 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9213 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9214
9215 QualType lhptee, rhptee;
9216
9217 // get the "pointed to" type (ignoring qualifiers at the top level)
9218 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9219 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9220
9221 // In C++, the types have to match exactly.
9222 if (S.getLangOpts().CPlusPlus)
9224
9226
9227 // For blocks we enforce that qualifiers are identical.
9228 Qualifiers LQuals = lhptee.getLocalQualifiers();
9229 Qualifiers RQuals = rhptee.getLocalQualifiers();
9230 if (S.getLangOpts().OpenCL) {
9231 LQuals.removeAddressSpace();
9232 RQuals.removeAddressSpace();
9233 }
9234 if (LQuals != RQuals)
9236
9237 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9238 // assignment.
9239 // The current behavior is similar to C++ lambdas. A block might be
9240 // assigned to a variable iff its return type and parameters are compatible
9241 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9242 // an assignment. Presumably it should behave in way that a function pointer
9243 // assignment does in C, so for each parameter and return type:
9244 // * CVR and address space of LHS should be a superset of CVR and address
9245 // space of RHS.
9246 // * unqualified types should be compatible.
9247 if (S.getLangOpts().OpenCL) {
9249 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9250 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9252 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9254
9255 return ConvTy;
9256}
9257
9258/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9259/// for assignment compatibility.
9261 QualType LHSType,
9262 QualType RHSType) {
9263 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9264 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9265
9266 if (LHSType->isObjCBuiltinType()) {
9267 // Class is not compatible with ObjC object pointers.
9268 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9269 !RHSType->isObjCQualifiedClassType())
9272 }
9273 if (RHSType->isObjCBuiltinType()) {
9274 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9275 !LHSType->isObjCQualifiedClassType())
9278 }
9279 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9280 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9281
9282 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9283 // make an exception for id<P>
9284 !LHSType->isObjCQualifiedIdType())
9286
9287 if (S.Context.typesAreCompatible(LHSType, RHSType))
9289 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9292}
9293
9295 QualType LHSType,
9296 QualType RHSType) {
9297 // Fake up an opaque expression. We don't actually care about what
9298 // cast operations are required, so if CheckAssignmentConstraints
9299 // adds casts to this they'll be wasted, but fortunately that doesn't
9300 // usually happen on valid code.
9301 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9302 ExprResult RHSPtr = &RHSExpr;
9303 CastKind K;
9304
9305 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9306}
9307
9308/// This helper function returns true if QT is a vector type that has element
9309/// type ElementType.
9310static bool isVector(QualType QT, QualType ElementType) {
9311 if (const VectorType *VT = QT->getAs<VectorType>())
9312 return VT->getElementType().getCanonicalType() == ElementType;
9313 return false;
9314}
9315
9316/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9317/// has code to accommodate several GCC extensions when type checking
9318/// pointers. Here are some objectionable examples that GCC considers warnings:
9319///
9320/// int a, *pint;
9321/// short *pshort;
9322/// struct foo *pfoo;
9323///
9324/// pint = pshort; // warning: assignment from incompatible pointer type
9325/// a = pint; // warning: assignment makes integer from pointer without a cast
9326/// pint = a; // warning: assignment makes pointer from integer without a cast
9327/// pint = pfoo; // warning: assignment from incompatible pointer type
9328///
9329/// As a result, the code for dealing with pointers is more complex than the
9330/// C99 spec dictates.
9331///
9332/// Sets 'Kind' for any result kind except Incompatible.
9334 ExprResult &RHS,
9335 CastKind &Kind,
9336 bool ConvertRHS) {
9337 QualType RHSType = RHS.get()->getType();
9338 QualType OrigLHSType = LHSType;
9339
9340 // Get canonical types. We're not formatting these types, just comparing
9341 // them.
9342 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9343 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9344
9345 // Common case: no conversion required.
9346 if (LHSType == RHSType) {
9347 Kind = CK_NoOp;
9349 }
9350
9351 // If the LHS has an __auto_type, there are no additional type constraints
9352 // to be worried about.
9353 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9354 if (AT->isGNUAutoType()) {
9355 Kind = CK_NoOp;
9357 }
9358 }
9359
9360 // If we have an atomic type, try a non-atomic assignment, then just add an
9361 // atomic qualification step.
9362 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9364 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9366 return Result;
9367 if (Kind != CK_NoOp && ConvertRHS)
9368 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9369 Kind = CK_NonAtomicToAtomic;
9370 return Result;
9371 }
9372
9373 // If the left-hand side is a reference type, then we are in a
9374 // (rare!) case where we've allowed the use of references in C,
9375 // e.g., as a parameter type in a built-in function. In this case,
9376 // just make sure that the type referenced is compatible with the
9377 // right-hand side type. The caller is responsible for adjusting
9378 // LHSType so that the resulting expression does not have reference
9379 // type.
9380 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9381 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9382 Kind = CK_LValueBitCast;
9384 }
9386 }
9387
9388 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9389 // of an ExtVector type to the same ExtVector type.
9390 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9391 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9392 // Implicit conversions require the same number of elements.
9393 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9395
9396 if (LHSType->isExtVectorBoolType() &&
9397 RHSExtType->getElementType()->isIntegerType()) {
9398 Kind = CK_IntegralToBoolean;
9400 }
9402 }
9403 if (RHSType->isArithmeticType()) {
9404 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9405 if (ConvertRHS)
9406 RHS = prepareVectorSplat(LHSType, RHS.get());
9407 Kind = CK_VectorSplat;
9409 }
9410 }
9411
9412 // Conversions to or from vector type.
9413 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9414 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9415 // Allow assignments of an AltiVec vector type to an equivalent GCC
9416 // vector type and vice versa
9417 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9418 Kind = CK_BitCast;
9420 }
9421
9422 // If we are allowing lax vector conversions, and LHS and RHS are both
9423 // vectors, the total size only needs to be the same. This is a bitcast;
9424 // no bits are changed but the result type is different.
9425 if (isLaxVectorConversion(RHSType, LHSType)) {
9426 // The default for lax vector conversions with Altivec vectors will
9427 // change, so if we are converting between vector types where
9428 // at least one is an Altivec vector, emit a warning.
9429 if (Context.getTargetInfo().getTriple().isPPC() &&
9430 anyAltivecTypes(RHSType, LHSType) &&
9431 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9432 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9433 << RHSType << LHSType;
9434 Kind = CK_BitCast;
9436 }
9437 }
9438
9439 // When the RHS comes from another lax conversion (e.g. binops between
9440 // scalars and vectors) the result is canonicalized as a vector. When the
9441 // LHS is also a vector, the lax is allowed by the condition above. Handle
9442 // the case where LHS is a scalar.
9443 if (LHSType->isScalarType()) {
9444 const VectorType *VecType = RHSType->getAs<VectorType>();
9445 if (VecType && VecType->getNumElements() == 1 &&
9446 isLaxVectorConversion(RHSType, LHSType)) {
9447 if (Context.getTargetInfo().getTriple().isPPC() &&
9449 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9451 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9452 << RHSType << LHSType;
9453 ExprResult *VecExpr = &RHS;
9454 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9455 Kind = CK_BitCast;
9457 }
9458 }
9459
9460 // Allow assignments between fixed-length and sizeless SVE vectors.
9461 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9462 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9463 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9464 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9465 Kind = CK_BitCast;
9467 }
9468
9469 // Allow assignments between fixed-length and sizeless RVV vectors.
9470 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9471 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9472 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9473 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9474 Kind = CK_BitCast;
9476 }
9477 }
9478
9480 }
9481
9482 // Diagnose attempts to convert between __ibm128, __float128 and long double
9483 // where such conversions currently can't be handled.
9484 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9486
9487 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9488 // discards the imaginary part.
9489 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9490 !LHSType->getAs<ComplexType>())
9492
9493 // Arithmetic conversions.
9494 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9495 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9496 if (ConvertRHS)
9497 Kind = PrepareScalarCast(RHS, LHSType);
9499 }
9500
9501 // Conversions to normal pointers.
9502 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9503 // U* -> T*
9504 if (isa<PointerType>(RHSType)) {
9505 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9506 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9507 if (AddrSpaceL != AddrSpaceR)
9508 Kind = CK_AddressSpaceConversion;
9509 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9510 Kind = CK_NoOp;
9511 else
9512 Kind = CK_BitCast;
9513 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9514 RHS.get()->getBeginLoc());
9515 }
9516
9517 // int -> T*
9518 if (RHSType->isIntegerType()) {
9519 Kind = CK_IntegralToPointer; // FIXME: null?
9521 }
9522
9523 // C pointers are not compatible with ObjC object pointers,
9524 // with two exceptions:
9525 if (isa<ObjCObjectPointerType>(RHSType)) {
9526 // - conversions to void*
9527 if (LHSPointer->getPointeeType()->isVoidType()) {
9528 Kind = CK_BitCast;
9530 }
9531
9532 // - conversions from 'Class' to the redefinition type
9533 if (RHSType->isObjCClassType() &&
9534 Context.hasSameType(LHSType,
9535 Context.getObjCClassRedefinitionType())) {
9536 Kind = CK_BitCast;
9538 }
9539
9540 Kind = CK_BitCast;
9542 }
9543
9544 // U^ -> void*
9545 if (RHSType->getAs<BlockPointerType>()) {
9546 if (LHSPointer->getPointeeType()->isVoidType()) {
9547 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9548 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9549 ->getPointeeType()
9550 .getAddressSpace();
9551 Kind =
9552 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9554 }
9555 }
9556
9558 }
9559
9560 // Conversions to block pointers.
9561 if (isa<BlockPointerType>(LHSType)) {
9562 // U^ -> T^
9563 if (RHSType->isBlockPointerType()) {
9564 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9565 ->getPointeeType()
9566 .getAddressSpace();
9567 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9568 ->getPointeeType()
9569 .getAddressSpace();
9570 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9571 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9572 }
9573
9574 // int or null -> T^
9575 if (RHSType->isIntegerType()) {
9576 Kind = CK_IntegralToPointer; // FIXME: null
9578 }
9579
9580 // id -> T^
9581 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9582 Kind = CK_AnyPointerToBlockPointerCast;
9584 }
9585
9586 // void* -> T^
9587 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9588 if (RHSPT->getPointeeType()->isVoidType()) {
9589 Kind = CK_AnyPointerToBlockPointerCast;
9591 }
9592
9594 }
9595
9596 // Conversions to Objective-C pointers.
9597 if (isa<ObjCObjectPointerType>(LHSType)) {
9598 // A* -> B*
9599 if (RHSType->isObjCObjectPointerType()) {
9600 Kind = CK_BitCast;
9601 AssignConvertType result =
9602 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9603 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9605 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9607 return result;
9608 }
9609
9610 // int or null -> A*
9611 if (RHSType->isIntegerType()) {
9612 Kind = CK_IntegralToPointer; // FIXME: null
9614 }
9615
9616 // In general, C pointers are not compatible with ObjC object pointers,
9617 // with two exceptions:
9618 if (isa<PointerType>(RHSType)) {
9619 Kind = CK_CPointerToObjCPointerCast;
9620
9621 // - conversions from 'void*'
9622 if (RHSType->isVoidPointerType()) {
9624 }
9625
9626 // - conversions to 'Class' from its redefinition type
9627 if (LHSType->isObjCClassType() &&
9628 Context.hasSameType(RHSType,
9629 Context.getObjCClassRedefinitionType())) {
9631 }
9632
9634 }
9635
9636 // Only under strict condition T^ is compatible with an Objective-C pointer.
9637 if (RHSType->isBlockPointerType() &&
9639 if (ConvertRHS)
9641 Kind = CK_BlockPointerToObjCPointerCast;
9643 }
9644
9646 }
9647
9648 // Conversion to nullptr_t (C23 only)
9649 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9652 // null -> nullptr_t
9653 Kind = CK_NullToPointer;
9655 }
9656
9657 // Conversions from pointers that are not covered by the above.
9658 if (isa<PointerType>(RHSType)) {
9659 // T* -> _Bool
9660 if (LHSType == Context.BoolTy) {
9661 Kind = CK_PointerToBoolean;
9663 }
9664
9665 // T* -> int
9666 if (LHSType->isIntegerType()) {
9667 Kind = CK_PointerToIntegral;
9669 }
9670
9672 }
9673
9674 // Conversions from Objective-C pointers that are not covered by the above.
9675 if (isa<ObjCObjectPointerType>(RHSType)) {
9676 // T* -> _Bool
9677 if (LHSType == Context.BoolTy) {
9678 Kind = CK_PointerToBoolean;
9680 }
9681
9682 // T* -> int
9683 if (LHSType->isIntegerType()) {
9684 Kind = CK_PointerToIntegral;
9686 }
9687
9689 }
9690
9691 // struct A -> struct B
9692 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9693 if (Context.typesAreCompatible(LHSType, RHSType)) {
9694 Kind = CK_NoOp;
9696 }
9697 }
9698
9699 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9700 Kind = CK_IntToOCLSampler;
9702 }
9703
9705}
9706
9707/// Constructs a transparent union from an expression that is
9708/// used to initialize the transparent union.
9710 ExprResult &EResult, QualType UnionType,
9711 FieldDecl *Field) {
9712 // Build an initializer list that designates the appropriate member
9713 // of the transparent union.
9714 Expr *E = EResult.get();
9716 E, SourceLocation());
9717 Initializer->setType(UnionType);
9718 Initializer->setInitializedFieldInUnion(Field);
9719
9720 // Build a compound literal constructing a value of the transparent
9721 // union type from this initializer list.
9722 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9723 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9724 VK_PRValue, Initializer, false);
9725}
9726
9729 ExprResult &RHS) {
9730 QualType RHSType = RHS.get()->getType();
9731
9732 // If the ArgType is a Union type, we want to handle a potential
9733 // transparent_union GCC extension.
9734 const RecordType *UT = ArgType->getAsUnionType();
9735 if (!UT)
9737
9738 RecordDecl *UD = UT->getOriginalDecl()->getDefinitionOrSelf();
9739 if (!UD->hasAttr<TransparentUnionAttr>())
9741
9742 // The field to initialize within the transparent union.
9743 FieldDecl *InitField = nullptr;
9744 // It's compatible if the expression matches any of the fields.
9745 for (auto *it : UD->fields()) {
9746 if (it->getType()->isPointerType()) {
9747 // If the transparent union contains a pointer type, we allow:
9748 // 1) void pointer
9749 // 2) null pointer constant
9750 if (RHSType->isPointerType())
9751 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9752 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9753 InitField = it;
9754 break;
9755 }
9756
9759 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9760 CK_NullToPointer);
9761 InitField = it;
9762 break;
9763 }
9764 }
9765
9766 CastKind Kind;
9767 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
9769 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9770 InitField = it;
9771 break;
9772 }
9773 }
9774
9775 if (!InitField)
9777
9778 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9780}
9781
9783 ExprResult &CallerRHS,
9784 bool Diagnose,
9785 bool DiagnoseCFAudited,
9786 bool ConvertRHS) {
9787 // We need to be able to tell the caller whether we diagnosed a problem, if
9788 // they ask us to issue diagnostics.
9789 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9790
9791 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9792 // we can't avoid *all* modifications at the moment, so we need some somewhere
9793 // to put the updated value.
9794 ExprResult LocalRHS = CallerRHS;
9795 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9796
9797 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9798 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9799 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9800 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9801 Diag(RHS.get()->getExprLoc(),
9802 diag::warn_noderef_to_dereferenceable_pointer)
9803 << RHS.get()->getSourceRange();
9804 }
9805 }
9806 }
9807
9808 if (getLangOpts().CPlusPlus) {
9809 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9810 // C++ 5.17p3: If the left operand is not of class type, the
9811 // expression is implicitly converted (C++ 4) to the
9812 // cv-unqualified type of the left operand.
9813 QualType RHSType = RHS.get()->getType();
9814 if (Diagnose) {
9815 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9817 } else {
9820 /*SuppressUserConversions=*/false,
9821 AllowedExplicit::None,
9822 /*InOverloadResolution=*/false,
9823 /*CStyle=*/false,
9824 /*AllowObjCWritebackConversion=*/false);
9825 if (ICS.isFailure())
9827 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9829 }
9830 if (RHS.isInvalid())
9833 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9834 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9836 return result;
9837 }
9838
9839 // FIXME: Currently, we fall through and treat C++ classes like C
9840 // structures.
9841 // FIXME: We also fall through for atomics; not sure what should
9842 // happen there, though.
9843 } else if (RHS.get()->getType() == Context.OverloadTy) {
9844 // As a set of extensions to C, we support overloading on functions. These
9845 // functions need to be resolved here.
9846 DeclAccessPair DAP;
9848 RHS.get(), LHSType, /*Complain=*/false, DAP))
9849 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9850 else
9852 }
9853
9854 // This check seems unnatural, however it is necessary to ensure the proper
9855 // conversion of functions/arrays. If the conversion were done for all
9856 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9857 // expressions that suppress this implicit conversion (&, sizeof). This needs
9858 // to happen before we check for null pointer conversions because C does not
9859 // undergo the same implicit conversions as C++ does above (by the calls to
9860 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9861 // lvalue to rvalue cast before checking for null pointer constraints. This
9862 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9863 //
9864 // Suppress this for references: C++ 8.5.3p5.
9865 if (!LHSType->isReferenceType()) {
9866 // FIXME: We potentially allocate here even if ConvertRHS is false.
9868 if (RHS.isInvalid())
9870 }
9871
9872 // The constraints are expressed in terms of the atomic, qualified, or
9873 // unqualified type of the LHS.
9874 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9875
9876 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9877 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9878 if ((LHSTypeAfterConversion->isPointerType() ||
9879 LHSTypeAfterConversion->isObjCObjectPointerType() ||
9880 LHSTypeAfterConversion->isBlockPointerType()) &&
9881 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9885 if (Diagnose || ConvertRHS) {
9886 CastKind Kind;
9887 CXXCastPath Path;
9888 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9889 /*IgnoreBaseAccess=*/false, Diagnose);
9890
9891 // If there is a conversion of some kind, check to see what kind of
9892 // pointer conversion happened so we can diagnose a C++ compatibility
9893 // diagnostic if the conversion is invalid. This only matters if the RHS
9894 // is some kind of void pointer. We have a carve-out when the RHS is from
9895 // a macro expansion because the use of a macro may indicate different
9896 // code between C and C++. Consider: char *s = NULL; where NULL is
9897 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
9898 // C++, which is valid in C++.
9899 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
9900 !RHS.get()->getBeginLoc().isMacroID()) {
9901 QualType CanRHS =
9903 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
9904 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
9905 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
9906 RHS.get()->getExprLoc());
9907 // Anything that's not considered perfectly compatible would be
9908 // incompatible in C++.
9911 }
9912 }
9913
9914 if (ConvertRHS)
9915 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9916 }
9917 return Ret;
9918 }
9919 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9920 // unqualified bool, and the right operand is a pointer or its type is
9921 // nullptr_t.
9922 if (getLangOpts().C23 && LHSType->isBooleanType() &&
9923 RHS.get()->getType()->isNullPtrType()) {
9924 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9925 // only handles nullptr -> _Bool due to needing an extra conversion
9926 // step.
9927 // We model this by converting from nullptr -> void * and then let the
9928 // conversion from void * -> _Bool happen naturally.
9929 if (Diagnose || ConvertRHS) {
9930 CastKind Kind;
9931 CXXCastPath Path;
9932 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
9933 /*IgnoreBaseAccess=*/false, Diagnose);
9934 if (ConvertRHS)
9935 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9936 &Path);
9937 }
9938 }
9939
9940 // OpenCL queue_t type assignment.
9941 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9943 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9945 }
9946
9947 CastKind Kind;
9948 AssignConvertType result =
9949 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9950
9951 // If assigning a void * created by an allocation function call to some other
9952 // type, check that the allocated size is sufficient for that type.
9953 if (result != AssignConvertType::Incompatible &&
9954 RHS.get()->getType()->isVoidPointerType())
9955 CheckSufficientAllocSize(*this, LHSType, RHS.get());
9956
9957 // C99 6.5.16.1p2: The value of the right operand is converted to the
9958 // type of the assignment expression.
9959 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9960 // so that we can use references in built-in functions even in C.
9961 // The getNonReferenceType() call makes sure that the resulting expression
9962 // does not have reference type.
9963 if (result != AssignConvertType::Incompatible &&
9964 RHS.get()->getType() != LHSType) {
9966 Expr *E = RHS.get();
9967
9968 // Check for various Objective-C errors. If we are not reporting
9969 // diagnostics and just checking for errors, e.g., during overload
9970 // resolution, return Incompatible to indicate the failure.
9971 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9972 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9974 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9975 if (!Diagnose)
9977 }
9978 if (getLangOpts().ObjC &&
9979 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9980 E->getType(), E, Diagnose) ||
9981 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9982 if (!Diagnose)
9984 // Replace the expression with a corrected version and continue so we
9985 // can find further errors.
9986 RHS = E;
9988 }
9989
9990 if (ConvertRHS)
9991 RHS = ImpCastExprToType(E, Ty, Kind);
9992 }
9993
9994 return result;
9995}
9996
9997namespace {
9998/// The original operand to an operator, prior to the application of the usual
9999/// arithmetic conversions and converting the arguments of a builtin operator
10000/// candidate.
10001struct OriginalOperand {
10002 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10003 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10004 Op = MTE->getSubExpr();
10005 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10006 Op = BTE->getSubExpr();
10007 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10008 Orig = ICE->getSubExprAsWritten();
10009 Conversion = ICE->getConversionFunction();
10010 }
10011 }
10012
10013 QualType getType() const { return Orig->getType(); }
10014
10015 Expr *Orig;
10016 NamedDecl *Conversion;
10017};
10018}
10019
10021 ExprResult &RHS) {
10022 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10023
10024 Diag(Loc, diag::err_typecheck_invalid_operands)
10025 << OrigLHS.getType() << OrigRHS.getType()
10026 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10027
10028 // If a user-defined conversion was applied to either of the operands prior
10029 // to applying the built-in operator rules, tell the user about it.
10030 if (OrigLHS.Conversion) {
10031 Diag(OrigLHS.Conversion->getLocation(),
10032 diag::note_typecheck_invalid_operands_converted)
10033 << 0 << LHS.get()->getType();
10034 }
10035 if (OrigRHS.Conversion) {
10036 Diag(OrigRHS.Conversion->getLocation(),
10037 diag::note_typecheck_invalid_operands_converted)
10038 << 1 << RHS.get()->getType();
10039 }
10040
10041 return QualType();
10042}
10043
10045 ExprResult &RHS) {
10046 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10047 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10048
10049 bool LHSNatVec = LHSType->isVectorType();
10050 bool RHSNatVec = RHSType->isVectorType();
10051
10052 if (!(LHSNatVec && RHSNatVec)) {
10053 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10054 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10055 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10056 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10057 << Vector->getSourceRange();
10058 return QualType();
10059 }
10060
10061 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10062 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10063 << RHS.get()->getSourceRange();
10064
10065 return QualType();
10066}
10067
10068/// Try to convert a value of non-vector type to a vector type by converting
10069/// the type to the element type of the vector and then performing a splat.
10070/// If the language is OpenCL, we only use conversions that promote scalar
10071/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10072/// for float->int.
10073///
10074/// OpenCL V2.0 6.2.6.p2:
10075/// An error shall occur if any scalar operand type has greater rank
10076/// than the type of the vector element.
10077///
10078/// \param scalar - if non-null, actually perform the conversions
10079/// \return true if the operation fails (but without diagnosing the failure)
10081 QualType scalarTy,
10082 QualType vectorEltTy,
10083 QualType vectorTy,
10084 unsigned &DiagID) {
10085 // The conversion to apply to the scalar before splatting it,
10086 // if necessary.
10087 CastKind scalarCast = CK_NoOp;
10088
10089 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10090 scalarCast = CK_IntegralToBoolean;
10091 } else if (vectorEltTy->isIntegralType(S.Context)) {
10092 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10093 (scalarTy->isIntegerType() &&
10094 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10095 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10096 return true;
10097 }
10098 if (!scalarTy->isIntegralType(S.Context))
10099 return true;
10100 scalarCast = CK_IntegralCast;
10101 } else if (vectorEltTy->isRealFloatingType()) {
10102 if (scalarTy->isRealFloatingType()) {
10103 if (S.getLangOpts().OpenCL &&
10104 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10105 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10106 return true;
10107 }
10108 scalarCast = CK_FloatingCast;
10109 }
10110 else if (scalarTy->isIntegralType(S.Context))
10111 scalarCast = CK_IntegralToFloating;
10112 else
10113 return true;
10114 } else {
10115 return true;
10116 }
10117
10118 // Adjust scalar if desired.
10119 if (scalar) {
10120 if (scalarCast != CK_NoOp)
10121 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10122 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10123 }
10124 return false;
10125}
10126
10127/// Convert vector E to a vector with the same number of elements but different
10128/// element type.
10129static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10130 const auto *VecTy = E->getType()->getAs<VectorType>();
10131 assert(VecTy && "Expression E must be a vector");
10132 QualType NewVecTy =
10133 VecTy->isExtVectorType()
10134 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10135 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10136 VecTy->getVectorKind());
10137
10138 // Look through the implicit cast. Return the subexpression if its type is
10139 // NewVecTy.
10140 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10141 if (ICE->getSubExpr()->getType() == NewVecTy)
10142 return ICE->getSubExpr();
10143
10144 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10145 return S.ImpCastExprToType(E, NewVecTy, Cast);
10146}
10147
10148/// Test if a (constant) integer Int can be casted to another integer type
10149/// IntTy without losing precision.
10151 QualType OtherIntTy) {
10152 if (Int->get()->containsErrors())
10153 return false;
10154
10155 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10156
10157 // Reject cases where the value of the Int is unknown as that would
10158 // possibly cause truncation, but accept cases where the scalar can be
10159 // demoted without loss of precision.
10160 Expr::EvalResult EVResult;
10161 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10162 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10163 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10164 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10165
10166 if (CstInt) {
10167 // If the scalar is constant and is of a higher order and has more active
10168 // bits that the vector element type, reject it.
10169 llvm::APSInt Result = EVResult.Val.getInt();
10170 unsigned NumBits = IntSigned
10171 ? (Result.isNegative() ? Result.getSignificantBits()
10172 : Result.getActiveBits())
10173 : Result.getActiveBits();
10174 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10175 return true;
10176
10177 // If the signedness of the scalar type and the vector element type
10178 // differs and the number of bits is greater than that of the vector
10179 // element reject it.
10180 return (IntSigned != OtherIntSigned &&
10181 NumBits > S.Context.getIntWidth(OtherIntTy));
10182 }
10183
10184 // Reject cases where the value of the scalar is not constant and it's
10185 // order is greater than that of the vector element type.
10186 return (Order < 0);
10187}
10188
10189/// Test if a (constant) integer Int can be casted to floating point type
10190/// FloatTy without losing precision.
10192 QualType FloatTy) {
10193 if (Int->get()->containsErrors())
10194 return false;
10195
10196 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10197
10198 // Determine if the integer constant can be expressed as a floating point
10199 // number of the appropriate type.
10200 Expr::EvalResult EVResult;
10201 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10202
10203 uint64_t Bits = 0;
10204 if (CstInt) {
10205 // Reject constants that would be truncated if they were converted to
10206 // the floating point type. Test by simple to/from conversion.
10207 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10208 // could be avoided if there was a convertFromAPInt method
10209 // which could signal back if implicit truncation occurred.
10210 llvm::APSInt Result = EVResult.Val.getInt();
10211 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10212 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10213 llvm::APFloat::rmTowardZero);
10214 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10216 bool Ignored = false;
10217 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10218 &Ignored);
10219 if (Result != ConvertBack)
10220 return true;
10221 } else {
10222 // Reject types that cannot be fully encoded into the mantissa of
10223 // the float.
10224 Bits = S.Context.getTypeSize(IntTy);
10225 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10226 S.Context.getFloatTypeSemantics(FloatTy));
10227 if (Bits > FloatPrec)
10228 return true;
10229 }
10230
10231 return false;
10232}
10233
10234/// Attempt to convert and splat Scalar into a vector whose types matches
10235/// Vector following GCC conversion rules. The rule is that implicit
10236/// conversion can occur when Scalar can be casted to match Vector's element
10237/// type without causing truncation of Scalar.
10239 ExprResult *Vector) {
10240 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10241 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10242 QualType VectorEltTy;
10243
10244 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10245 assert(!isa<ExtVectorType>(VT) &&
10246 "ExtVectorTypes should not be handled here!");
10247 VectorEltTy = VT->getElementType();
10248 } else if (VectorTy->isSveVLSBuiltinType()) {
10249 VectorEltTy =
10250 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10251 } else {
10252 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10253 }
10254
10255 // Reject cases where the vector element type or the scalar element type are
10256 // not integral or floating point types.
10257 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10258 return true;
10259
10260 // The conversion to apply to the scalar before splatting it,
10261 // if necessary.
10262 CastKind ScalarCast = CK_NoOp;
10263
10264 // Accept cases where the vector elements are integers and the scalar is
10265 // an integer.
10266 // FIXME: Notionally if the scalar was a floating point value with a precise
10267 // integral representation, we could cast it to an appropriate integer
10268 // type and then perform the rest of the checks here. GCC will perform
10269 // this conversion in some cases as determined by the input language.
10270 // We should accept it on a language independent basis.
10271 if (VectorEltTy->isIntegralType(S.Context) &&
10272 ScalarTy->isIntegralType(S.Context) &&
10273 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10274
10275 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10276 return true;
10277
10278 ScalarCast = CK_IntegralCast;
10279 } else if (VectorEltTy->isIntegralType(S.Context) &&
10280 ScalarTy->isRealFloatingType()) {
10281 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10282 ScalarCast = CK_FloatingToIntegral;
10283 else
10284 return true;
10285 } else if (VectorEltTy->isRealFloatingType()) {
10286 if (ScalarTy->isRealFloatingType()) {
10287
10288 // Reject cases where the scalar type is not a constant and has a higher
10289 // Order than the vector element type.
10290 llvm::APFloat Result(0.0);
10291
10292 // Determine whether this is a constant scalar. In the event that the
10293 // value is dependent (and thus cannot be evaluated by the constant
10294 // evaluator), skip the evaluation. This will then diagnose once the
10295 // expression is instantiated.
10296 bool CstScalar = Scalar->get()->isValueDependent() ||
10297 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10298 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10299 if (!CstScalar && Order < 0)
10300 return true;
10301
10302 // If the scalar cannot be safely casted to the vector element type,
10303 // reject it.
10304 if (CstScalar) {
10305 bool Truncated = false;
10306 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10307 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10308 if (Truncated)
10309 return true;
10310 }
10311
10312 ScalarCast = CK_FloatingCast;
10313 } else if (ScalarTy->isIntegralType(S.Context)) {
10314 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10315 return true;
10316
10317 ScalarCast = CK_IntegralToFloating;
10318 } else
10319 return true;
10320 } else if (ScalarTy->isEnumeralType())
10321 return true;
10322
10323 // Adjust scalar if desired.
10324 if (ScalarCast != CK_NoOp)
10325 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10326 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10327 return false;
10328}
10329
10331 SourceLocation Loc, bool IsCompAssign,
10332 bool AllowBothBool,
10333 bool AllowBoolConversions,
10334 bool AllowBoolOperation,
10335 bool ReportInvalid) {
10336 if (!IsCompAssign) {
10338 if (LHS.isInvalid())
10339 return QualType();
10340 }
10342 if (RHS.isInvalid())
10343 return QualType();
10344
10345 // For conversion purposes, we ignore any qualifiers.
10346 // For example, "const float" and "float" are equivalent.
10347 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10348 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10349
10350 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10351 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10352 assert(LHSVecType || RHSVecType);
10353
10354 if (getLangOpts().HLSL)
10355 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10356 IsCompAssign);
10357
10358 // Any operation with MFloat8 type is only possible with C intrinsics
10359 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10360 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10361 return InvalidOperands(Loc, LHS, RHS);
10362
10363 // AltiVec-style "vector bool op vector bool" combinations are allowed
10364 // for some operators but not others.
10365 if (!AllowBothBool && LHSVecType &&
10366 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10367 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10368 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10369
10370 // This operation may not be performed on boolean vectors.
10371 if (!AllowBoolOperation &&
10372 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10373 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10374
10375 // If the vector types are identical, return.
10376 if (Context.hasSameType(LHSType, RHSType))
10377 return Context.getCommonSugaredType(LHSType, RHSType);
10378
10379 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10380 if (LHSVecType && RHSVecType &&
10381 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10382 if (isa<ExtVectorType>(LHSVecType)) {
10383 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10384 return LHSType;
10385 }
10386
10387 if (!IsCompAssign)
10388 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10389 return RHSType;
10390 }
10391
10392 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10393 // can be mixed, with the result being the non-bool type. The non-bool
10394 // operand must have integer element type.
10395 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10396 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10397 (Context.getTypeSize(LHSVecType->getElementType()) ==
10398 Context.getTypeSize(RHSVecType->getElementType()))) {
10399 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10400 LHSVecType->getElementType()->isIntegerType() &&
10401 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10402 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10403 return LHSType;
10404 }
10405 if (!IsCompAssign &&
10406 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10407 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10408 RHSVecType->getElementType()->isIntegerType()) {
10409 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10410 return RHSType;
10411 }
10412 }
10413
10414 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10415 // invalid since the ambiguity can affect the ABI.
10416 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10417 unsigned &SVEorRVV) {
10418 const VectorType *VecType = SecondType->getAs<VectorType>();
10419 SVEorRVV = 0;
10420 if (FirstType->isSizelessBuiltinType() && VecType) {
10423 return true;
10429 SVEorRVV = 1;
10430 return true;
10431 }
10432 }
10433
10434 return false;
10435 };
10436
10437 unsigned SVEorRVV;
10438 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10439 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10440 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10441 << SVEorRVV << LHSType << RHSType;
10442 return QualType();
10443 }
10444
10445 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10446 // invalid since the ambiguity can affect the ABI.
10447 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10448 unsigned &SVEorRVV) {
10449 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10450 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10451
10452 SVEorRVV = 0;
10453 if (FirstVecType && SecondVecType) {
10454 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10455 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10456 SecondVecType->getVectorKind() ==
10458 return true;
10459 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10460 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10461 SecondVecType->getVectorKind() ==
10463 SecondVecType->getVectorKind() ==
10465 SecondVecType->getVectorKind() ==
10467 SVEorRVV = 1;
10468 return true;
10469 }
10470 }
10471 return false;
10472 }
10473
10474 if (SecondVecType &&
10475 SecondVecType->getVectorKind() == VectorKind::Generic) {
10476 if (FirstType->isSVESizelessBuiltinType())
10477 return true;
10478 if (FirstType->isRVVSizelessBuiltinType()) {
10479 SVEorRVV = 1;
10480 return true;
10481 }
10482 }
10483
10484 return false;
10485 };
10486
10487 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10488 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10489 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10490 << SVEorRVV << LHSType << RHSType;
10491 return QualType();
10492 }
10493
10494 // If there's a vector type and a scalar, try to convert the scalar to
10495 // the vector element type and splat.
10496 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10497 if (!RHSVecType) {
10498 if (isa<ExtVectorType>(LHSVecType)) {
10499 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10500 LHSVecType->getElementType(), LHSType,
10501 DiagID))
10502 return LHSType;
10503 } else {
10504 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10505 return LHSType;
10506 }
10507 }
10508 if (!LHSVecType) {
10509 if (isa<ExtVectorType>(RHSVecType)) {
10510 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10511 LHSType, RHSVecType->getElementType(),
10512 RHSType, DiagID))
10513 return RHSType;
10514 } else {
10515 if (LHS.get()->isLValue() ||
10516 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10517 return RHSType;
10518 }
10519 }
10520
10521 // FIXME: The code below also handles conversion between vectors and
10522 // non-scalars, we should break this down into fine grained specific checks
10523 // and emit proper diagnostics.
10524 QualType VecType = LHSVecType ? LHSType : RHSType;
10525 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10526 QualType OtherType = LHSVecType ? RHSType : LHSType;
10527 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10528 if (isLaxVectorConversion(OtherType, VecType)) {
10529 if (Context.getTargetInfo().getTriple().isPPC() &&
10530 anyAltivecTypes(RHSType, LHSType) &&
10531 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10532 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10533 // If we're allowing lax vector conversions, only the total (data) size
10534 // needs to be the same. For non compound assignment, if one of the types is
10535 // scalar, the result is always the vector type.
10536 if (!IsCompAssign) {
10537 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10538 return VecType;
10539 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10540 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10541 // type. Note that this is already done by non-compound assignments in
10542 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10543 // <1 x T> -> T. The result is also a vector type.
10544 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10545 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10546 ExprResult *RHSExpr = &RHS;
10547 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10548 return VecType;
10549 }
10550 }
10551
10552 // Okay, the expression is invalid.
10553
10554 // If there's a non-vector, non-real operand, diagnose that.
10555 if ((!RHSVecType && !RHSType->isRealType()) ||
10556 (!LHSVecType && !LHSType->isRealType())) {
10557 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10558 << LHSType << RHSType
10559 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10560 return QualType();
10561 }
10562
10563 // OpenCL V1.1 6.2.6.p1:
10564 // If the operands are of more than one vector type, then an error shall
10565 // occur. Implicit conversions between vector types are not permitted, per
10566 // section 6.2.1.
10567 if (getLangOpts().OpenCL &&
10568 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10569 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10570 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10571 << RHSType;
10572 return QualType();
10573 }
10574
10575
10576 // If there is a vector type that is not a ExtVector and a scalar, we reach
10577 // this point if scalar could not be converted to the vector's element type
10578 // without truncation.
10579 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10580 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10581 QualType Scalar = LHSVecType ? RHSType : LHSType;
10582 QualType Vector = LHSVecType ? LHSType : RHSType;
10583 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10584 Diag(Loc,
10585 diag::err_typecheck_vector_not_convertable_implict_truncation)
10586 << ScalarOrVector << Scalar << Vector;
10587
10588 return QualType();
10589 }
10590
10591 // Otherwise, use the generic diagnostic.
10592 Diag(Loc, DiagID)
10593 << LHSType << RHSType
10594 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10595 return QualType();
10596}
10597
10599 SourceLocation Loc,
10600 bool IsCompAssign,
10601 ArithConvKind OperationKind) {
10602 if (!IsCompAssign) {
10604 if (LHS.isInvalid())
10605 return QualType();
10606 }
10608 if (RHS.isInvalid())
10609 return QualType();
10610
10611 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10612 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10613
10614 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10615 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10616
10617 unsigned DiagID = diag::err_typecheck_invalid_operands;
10618 if ((OperationKind == ArithConvKind::Arithmetic) &&
10619 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10620 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10621 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10622 << RHS.get()->getSourceRange();
10623 return QualType();
10624 }
10625
10626 if (Context.hasSameType(LHSType, RHSType))
10627 return LHSType;
10628
10629 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10630 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10631 return LHSType;
10632 }
10633 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10634 if (LHS.get()->isLValue() ||
10635 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10636 return RHSType;
10637 }
10638
10639 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10640 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10641 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10642 << LHSType << RHSType << LHS.get()->getSourceRange()
10643 << RHS.get()->getSourceRange();
10644 return QualType();
10645 }
10646
10647 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10648 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10649 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10650 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10651 << LHSType << RHSType << LHS.get()->getSourceRange()
10652 << RHS.get()->getSourceRange();
10653 return QualType();
10654 }
10655
10656 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10657 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10658 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10659 bool ScalarOrVector =
10660 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10661
10662 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10663 << ScalarOrVector << Scalar << Vector;
10664
10665 return QualType();
10666 }
10667
10668 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10669 << RHS.get()->getSourceRange();
10670 return QualType();
10671}
10672
10673// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10674// expression. These are mainly cases where the null pointer is used as an
10675// integer instead of a pointer.
10677 SourceLocation Loc, bool IsCompare) {
10678 // The canonical way to check for a GNU null is with isNullPointerConstant,
10679 // but we use a bit of a hack here for speed; this is a relatively
10680 // hot path, and isNullPointerConstant is slow.
10681 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10682 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10683
10684 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10685
10686 // Avoid analyzing cases where the result will either be invalid (and
10687 // diagnosed as such) or entirely valid and not something to warn about.
10688 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10689 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10690 return;
10691
10692 // Comparison operations would not make sense with a null pointer no matter
10693 // what the other expression is.
10694 if (!IsCompare) {
10695 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10696 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10697 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10698 return;
10699 }
10700
10701 // The rest of the operations only make sense with a null pointer
10702 // if the other expression is a pointer.
10703 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10704 NonNullType->canDecayToPointerType())
10705 return;
10706
10707 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10708 << LHSNull /* LHS is NULL */ << NonNullType
10709 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10710}
10711
10713 SourceLocation OpLoc) {
10714 // If the divisor is real, then this is real/real or complex/real division.
10715 // Either way there can be no precision loss.
10716 auto *CT = DivisorTy->getAs<ComplexType>();
10717 if (!CT)
10718 return;
10719
10720 QualType ElementType = CT->getElementType();
10721 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
10723 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
10724 return;
10725
10726 ASTContext &Ctx = S.getASTContext();
10727 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
10728 const llvm::fltSemantics &ElementTypeSemantics =
10729 Ctx.getFloatTypeSemantics(ElementType);
10730 const llvm::fltSemantics &HigherElementTypeSemantics =
10731 Ctx.getFloatTypeSemantics(HigherElementType);
10732
10733 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
10734 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
10735 (HigherElementType == Ctx.LongDoubleTy &&
10736 !Ctx.getTargetInfo().hasLongDoubleType())) {
10737 // Retain the location of the first use of higher precision type.
10740 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
10741 if (Type == HigherElementType) {
10742 Num++;
10743 return;
10744 }
10745 }
10746 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
10747 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
10748 }
10749}
10750
10752 SourceLocation Loc) {
10753 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10754 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10755 if (!LUE || !RUE)
10756 return;
10757 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10758 RUE->getKind() != UETT_SizeOf)
10759 return;
10760
10761 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10762 QualType LHSTy = LHSArg->getType();
10763 QualType RHSTy;
10764
10765 if (RUE->isArgumentType())
10766 RHSTy = RUE->getArgumentType().getNonReferenceType();
10767 else
10768 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10769
10770 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10771 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10772 return;
10773
10774 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10775 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10776 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10777 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10778 << LHSArgDecl;
10779 }
10780 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10781 QualType ArrayElemTy = ArrayTy->getElementType();
10782 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10783 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10784 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10785 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10786 return;
10787 S.Diag(Loc, diag::warn_division_sizeof_array)
10788 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10789 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10790 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10791 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10792 << LHSArgDecl;
10793 }
10794
10795 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10796 }
10797}
10798
10800 ExprResult &RHS,
10801 SourceLocation Loc, bool IsDiv) {
10802 // Check for division/remainder by zero.
10803 Expr::EvalResult RHSValue;
10804 if (!RHS.get()->isValueDependent() &&
10805 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10806 RHSValue.Val.getInt() == 0)
10807 S.DiagRuntimeBehavior(Loc, RHS.get(),
10808 S.PDiag(diag::warn_remainder_division_by_zero)
10809 << IsDiv << RHS.get()->getSourceRange());
10810}
10811
10812static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
10813 const ExprResult &LHS, const ExprResult &RHS,
10814 BinaryOperatorKind Opc) {
10815 if (!LHS.isUsable() || !RHS.isUsable())
10816 return;
10817 const Expr *LHSExpr = LHS.get();
10818 const Expr *RHSExpr = RHS.get();
10819 const QualType LHSType = LHSExpr->getType();
10820 const QualType RHSType = RHSExpr->getType();
10821 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
10822 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
10823 if (!LHSIsScoped && !RHSIsScoped)
10824 return;
10825 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
10826 return;
10827 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
10828 return;
10829 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
10830 return;
10831 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
10832 SourceLocation BeginLoc = expr->getBeginLoc();
10833 QualType IntType = type->castAs<EnumType>()
10834 ->getOriginalDecl()
10835 ->getDefinitionOrSelf()
10836 ->getIntegerType();
10837 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
10838 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
10839 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
10840 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
10841 };
10842 if (LHSIsScoped) {
10843 DiagnosticHelper(LHSExpr, LHSType);
10844 }
10845 if (RHSIsScoped) {
10846 DiagnosticHelper(RHSExpr, RHSType);
10847 }
10848}
10849
10851 SourceLocation Loc,
10852 BinaryOperatorKind Opc) {
10853 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
10854 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
10855
10856 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10857
10858 QualType LHSTy = LHS.get()->getType();
10859 QualType RHSTy = RHS.get()->getType();
10860 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10861 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10862 /*AllowBothBool*/ getLangOpts().AltiVec,
10863 /*AllowBoolConversions*/ false,
10864 /*AllowBooleanOperation*/ false,
10865 /*ReportInvalid*/ true);
10866 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10867 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10869 if (!IsDiv &&
10870 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10871 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10872 // For division, only matrix-by-scalar is supported. Other combinations with
10873 // matrix types are invalid.
10874 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10875 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10876
10878 LHS, RHS, Loc,
10880 if (LHS.isInvalid() || RHS.isInvalid())
10881 return QualType();
10882
10883 if (compType.isNull() || !compType->isArithmeticType()) {
10884 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
10885 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
10886 return ResultTy;
10887 }
10888 if (IsDiv) {
10889 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
10890 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10891 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10892 }
10893 return compType;
10894}
10895
10897 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10898 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10899
10900 // Note: This check is here to simplify the double exclusions of
10901 // scalar and vector HLSL checks. No getLangOpts().HLSL
10902 // is needed since all languages exlcude doubles.
10903 if (LHS.get()->getType()->isDoubleType() ||
10904 RHS.get()->getType()->isDoubleType() ||
10905 (LHS.get()->getType()->isVectorType() && LHS.get()
10906 ->getType()
10907 ->getAs<VectorType>()
10908 ->getElementType()
10909 ->isDoubleType()) ||
10910 (RHS.get()->getType()->isVectorType() && RHS.get()
10911 ->getType()
10912 ->getAs<VectorType>()
10913 ->getElementType()
10914 ->isDoubleType()))
10915 return InvalidOperands(Loc, LHS, RHS);
10916
10917 if (LHS.get()->getType()->isVectorType() ||
10918 RHS.get()->getType()->isVectorType()) {
10919 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
10920 RHS.get()->getType()->hasIntegerRepresentation()) ||
10921 (getLangOpts().HLSL &&
10922 (LHS.get()->getType()->hasFloatingRepresentation() ||
10924 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10925 /*AllowBothBool*/ getLangOpts().AltiVec,
10926 /*AllowBoolConversions*/ false,
10927 /*AllowBooleanOperation*/ false,
10928 /*ReportInvalid*/ true);
10929 return InvalidOperands(Loc, LHS, RHS);
10930 }
10931
10932 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10933 RHS.get()->getType()->isSveVLSBuiltinType()) {
10934 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10936 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10938
10939 return InvalidOperands(Loc, LHS, RHS);
10940 }
10941
10943 LHS, RHS, Loc,
10945 if (LHS.isInvalid() || RHS.isInvalid())
10946 return QualType();
10947
10948 if (compType.isNull() ||
10949 (!compType->isIntegerType() &&
10950 !(getLangOpts().HLSL && compType->isFloatingType()))) {
10951 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
10952 diagnoseScopedEnums(*this, Loc, LHS, RHS,
10953 IsCompAssign ? BO_RemAssign : BO_Rem);
10954 return ResultTy;
10955 }
10956 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10957 return compType;
10958}
10959
10960/// Diagnose invalid arithmetic on two void pointers.
10962 Expr *LHSExpr, Expr *RHSExpr) {
10963 S.Diag(Loc, S.getLangOpts().CPlusPlus
10964 ? diag::err_typecheck_pointer_arith_void_type
10965 : diag::ext_gnu_void_ptr)
10966 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10967 << RHSExpr->getSourceRange();
10968}
10969
10970/// Diagnose invalid arithmetic on a void pointer.
10972 Expr *Pointer) {
10973 S.Diag(Loc, S.getLangOpts().CPlusPlus
10974 ? diag::err_typecheck_pointer_arith_void_type
10975 : diag::ext_gnu_void_ptr)
10976 << 0 /* one pointer */ << Pointer->getSourceRange();
10977}
10978
10979/// Diagnose invalid arithmetic on a null pointer.
10980///
10981/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10982/// idiom, which we recognize as a GNU extension.
10983///
10985 Expr *Pointer, bool IsGNUIdiom) {
10986 if (IsGNUIdiom)
10987 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10988 << Pointer->getSourceRange();
10989 else
10990 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10991 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10992}
10993
10994/// Diagnose invalid subraction on a null pointer.
10995///
10997 Expr *Pointer, bool BothNull) {
10998 // Null - null is valid in C++ [expr.add]p7
10999 if (BothNull && S.getLangOpts().CPlusPlus)
11000 return;
11001
11002 // Is this s a macro from a system header?
11004 return;
11005
11007 S.PDiag(diag::warn_pointer_sub_null_ptr)
11008 << S.getLangOpts().CPlusPlus
11009 << Pointer->getSourceRange());
11010}
11011
11012/// Diagnose invalid arithmetic on two function pointers.
11014 Expr *LHS, Expr *RHS) {
11015 assert(LHS->getType()->isAnyPointerType());
11016 assert(RHS->getType()->isAnyPointerType());
11017 S.Diag(Loc, S.getLangOpts().CPlusPlus
11018 ? diag::err_typecheck_pointer_arith_function_type
11019 : diag::ext_gnu_ptr_func_arith)
11020 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11021 // We only show the second type if it differs from the first.
11023 RHS->getType())
11024 << RHS->getType()->getPointeeType()
11025 << LHS->getSourceRange() << RHS->getSourceRange();
11026}
11027
11028/// Diagnose invalid arithmetic on a function pointer.
11030 Expr *Pointer) {
11031 assert(Pointer->getType()->isAnyPointerType());
11032 S.Diag(Loc, S.getLangOpts().CPlusPlus
11033 ? diag::err_typecheck_pointer_arith_function_type
11034 : diag::ext_gnu_ptr_func_arith)
11035 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11036 << 0 /* one pointer, so only one type */
11037 << Pointer->getSourceRange();
11038}
11039
11040/// Emit error if Operand is incomplete pointer type
11041///
11042/// \returns True if pointer has incomplete type
11044 Expr *Operand) {
11045 QualType ResType = Operand->getType();
11046 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11047 ResType = ResAtomicType->getValueType();
11048
11049 assert(ResType->isAnyPointerType());
11050 QualType PointeeTy = ResType->getPointeeType();
11051 return S.RequireCompleteSizedType(
11052 Loc, PointeeTy,
11053 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11054 Operand->getSourceRange());
11055}
11056
11057/// Check the validity of an arithmetic pointer operand.
11058///
11059/// If the operand has pointer type, this code will check for pointer types
11060/// which are invalid in arithmetic operations. These will be diagnosed
11061/// appropriately, including whether or not the use is supported as an
11062/// extension.
11063///
11064/// \returns True when the operand is valid to use (even if as an extension).
11066 Expr *Operand) {
11067 QualType ResType = Operand->getType();
11068 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11069 ResType = ResAtomicType->getValueType();
11070
11071 if (!ResType->isAnyPointerType()) return true;
11072
11073 QualType PointeeTy = ResType->getPointeeType();
11074 if (PointeeTy->isVoidType()) {
11075 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11076 return !S.getLangOpts().CPlusPlus;
11077 }
11078 if (PointeeTy->isFunctionType()) {
11079 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11080 return !S.getLangOpts().CPlusPlus;
11081 }
11082
11083 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11084
11085 return true;
11086}
11087
11088/// Check the validity of a binary arithmetic operation w.r.t. pointer
11089/// operands.
11090///
11091/// This routine will diagnose any invalid arithmetic on pointer operands much
11092/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11093/// for emitting a single diagnostic even for operations where both LHS and RHS
11094/// are (potentially problematic) pointers.
11095///
11096/// \returns True when the operand is valid to use (even if as an extension).
11098 Expr *LHSExpr, Expr *RHSExpr) {
11099 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11100 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11101 if (!isLHSPointer && !isRHSPointer) return true;
11102
11103 QualType LHSPointeeTy, RHSPointeeTy;
11104 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11105 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11106
11107 // if both are pointers check if operation is valid wrt address spaces
11108 if (isLHSPointer && isRHSPointer) {
11109 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11110 S.getASTContext())) {
11111 S.Diag(Loc,
11112 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11113 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11114 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11115 return false;
11116 }
11117 }
11118
11119 // Check for arithmetic on pointers to incomplete types.
11120 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11121 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11122 if (isLHSVoidPtr || isRHSVoidPtr) {
11123 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11124 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11125 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11126
11127 return !S.getLangOpts().CPlusPlus;
11128 }
11129
11130 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11131 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11132 if (isLHSFuncPtr || isRHSFuncPtr) {
11133 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11134 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11135 RHSExpr);
11136 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11137
11138 return !S.getLangOpts().CPlusPlus;
11139 }
11140
11141 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11142 return false;
11143 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11144 return false;
11145
11146 return true;
11147}
11148
11149/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11150/// literal.
11152 Expr *LHSExpr, Expr *RHSExpr) {
11153 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11154 Expr* IndexExpr = RHSExpr;
11155 if (!StrExpr) {
11156 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11157 IndexExpr = LHSExpr;
11158 }
11159
11160 bool IsStringPlusInt = StrExpr &&
11162 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11163 return;
11164
11165 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11166 Self.Diag(OpLoc, diag::warn_string_plus_int)
11167 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11168
11169 // Only print a fixit for "str" + int, not for int + "str".
11170 if (IndexExpr == RHSExpr) {
11171 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11172 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11173 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11175 << FixItHint::CreateInsertion(EndLoc, "]");
11176 } else
11177 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11178}
11179
11180/// Emit a warning when adding a char literal to a string.
11182 Expr *LHSExpr, Expr *RHSExpr) {
11183 const Expr *StringRefExpr = LHSExpr;
11184 const CharacterLiteral *CharExpr =
11185 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11186
11187 if (!CharExpr) {
11188 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11189 StringRefExpr = RHSExpr;
11190 }
11191
11192 if (!CharExpr || !StringRefExpr)
11193 return;
11194
11195 const QualType StringType = StringRefExpr->getType();
11196
11197 // Return if not a PointerType.
11198 if (!StringType->isAnyPointerType())
11199 return;
11200
11201 // Return if not a CharacterType.
11202 if (!StringType->getPointeeType()->isAnyCharacterType())
11203 return;
11204
11205 ASTContext &Ctx = Self.getASTContext();
11206 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11207
11208 const QualType CharType = CharExpr->getType();
11209 if (!CharType->isAnyCharacterType() &&
11210 CharType->isIntegerType() &&
11211 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11212 Self.Diag(OpLoc, diag::warn_string_plus_char)
11213 << DiagRange << Ctx.CharTy;
11214 } else {
11215 Self.Diag(OpLoc, diag::warn_string_plus_char)
11216 << DiagRange << CharExpr->getType();
11217 }
11218
11219 // Only print a fixit for str + char, not for char + str.
11220 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11221 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11222 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11223 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11225 << FixItHint::CreateInsertion(EndLoc, "]");
11226 } else {
11227 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11228 }
11229}
11230
11231/// Emit error when two pointers are incompatible.
11233 Expr *LHSExpr, Expr *RHSExpr) {
11234 assert(LHSExpr->getType()->isAnyPointerType());
11235 assert(RHSExpr->getType()->isAnyPointerType());
11236 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11237 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11238 << RHSExpr->getSourceRange();
11239}
11240
11241// C99 6.5.6
11244 QualType* CompLHSTy) {
11245 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11246
11247 if (LHS.get()->getType()->isVectorType() ||
11248 RHS.get()->getType()->isVectorType()) {
11249 QualType compType =
11250 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11251 /*AllowBothBool*/ getLangOpts().AltiVec,
11252 /*AllowBoolConversions*/ getLangOpts().ZVector,
11253 /*AllowBooleanOperation*/ false,
11254 /*ReportInvalid*/ true);
11255 if (CompLHSTy) *CompLHSTy = compType;
11256 return compType;
11257 }
11258
11259 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11260 RHS.get()->getType()->isSveVLSBuiltinType()) {
11261 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11263 if (CompLHSTy)
11264 *CompLHSTy = compType;
11265 return compType;
11266 }
11267
11268 if (LHS.get()->getType()->isConstantMatrixType() ||
11269 RHS.get()->getType()->isConstantMatrixType()) {
11270 QualType compType =
11271 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11272 if (CompLHSTy)
11273 *CompLHSTy = compType;
11274 return compType;
11275 }
11276
11278 LHS, RHS, Loc,
11280 if (LHS.isInvalid() || RHS.isInvalid())
11281 return QualType();
11282
11283 // Diagnose "string literal" '+' int and string '+' "char literal".
11284 if (Opc == BO_Add) {
11285 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11286 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11287 }
11288
11289 // handle the common case first (both operands are arithmetic).
11290 if (!compType.isNull() && compType->isArithmeticType()) {
11291 if (CompLHSTy) *CompLHSTy = compType;
11292 return compType;
11293 }
11294
11295 // Type-checking. Ultimately the pointer's going to be in PExp;
11296 // note that we bias towards the LHS being the pointer.
11297 Expr *PExp = LHS.get(), *IExp = RHS.get();
11298
11299 bool isObjCPointer;
11300 if (PExp->getType()->isPointerType()) {
11301 isObjCPointer = false;
11302 } else if (PExp->getType()->isObjCObjectPointerType()) {
11303 isObjCPointer = true;
11304 } else {
11305 std::swap(PExp, IExp);
11306 if (PExp->getType()->isPointerType()) {
11307 isObjCPointer = false;
11308 } else if (PExp->getType()->isObjCObjectPointerType()) {
11309 isObjCPointer = true;
11310 } else {
11311 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11312 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11313 return ResultTy;
11314 }
11315 }
11316 assert(PExp->getType()->isAnyPointerType());
11317
11318 if (!IExp->getType()->isIntegerType())
11319 return InvalidOperands(Loc, LHS, RHS);
11320
11321 // Adding to a null pointer results in undefined behavior.
11324 // In C++ adding zero to a null pointer is defined.
11325 Expr::EvalResult KnownVal;
11326 if (!getLangOpts().CPlusPlus ||
11327 (!IExp->isValueDependent() &&
11328 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11329 KnownVal.Val.getInt() != 0))) {
11330 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11332 Context, BO_Add, PExp, IExp);
11333 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11334 }
11335 }
11336
11337 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11338 return QualType();
11339
11340 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11341 return QualType();
11342
11343 // Arithmetic on label addresses is normally allowed, except when we add
11344 // a ptrauth signature to the addresses.
11345 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11346 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11347 << /*addition*/ 1;
11348 return QualType();
11349 }
11350
11351 // Check array bounds for pointer arithemtic
11352 CheckArrayAccess(PExp, IExp);
11353
11354 if (CompLHSTy) {
11355 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11356 if (LHSTy.isNull()) {
11357 LHSTy = LHS.get()->getType();
11358 if (Context.isPromotableIntegerType(LHSTy))
11359 LHSTy = Context.getPromotedIntegerType(LHSTy);
11360 }
11361 *CompLHSTy = LHSTy;
11362 }
11363
11364 return PExp->getType();
11365}
11366
11367// C99 6.5.6
11369 SourceLocation Loc,
11371 QualType *CompLHSTy) {
11372 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11373
11374 if (LHS.get()->getType()->isVectorType() ||
11375 RHS.get()->getType()->isVectorType()) {
11376 QualType compType =
11377 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11378 /*AllowBothBool*/ getLangOpts().AltiVec,
11379 /*AllowBoolConversions*/ getLangOpts().ZVector,
11380 /*AllowBooleanOperation*/ false,
11381 /*ReportInvalid*/ true);
11382 if (CompLHSTy) *CompLHSTy = compType;
11383 return compType;
11384 }
11385
11386 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11387 RHS.get()->getType()->isSveVLSBuiltinType()) {
11388 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11390 if (CompLHSTy)
11391 *CompLHSTy = compType;
11392 return compType;
11393 }
11394
11395 if (LHS.get()->getType()->isConstantMatrixType() ||
11396 RHS.get()->getType()->isConstantMatrixType()) {
11397 QualType compType =
11398 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11399 if (CompLHSTy)
11400 *CompLHSTy = compType;
11401 return compType;
11402 }
11403
11405 LHS, RHS, Loc,
11407 if (LHS.isInvalid() || RHS.isInvalid())
11408 return QualType();
11409
11410 // Enforce type constraints: C99 6.5.6p3.
11411
11412 // Handle the common case first (both operands are arithmetic).
11413 if (!compType.isNull() && compType->isArithmeticType()) {
11414 if (CompLHSTy) *CompLHSTy = compType;
11415 return compType;
11416 }
11417
11418 // Either ptr - int or ptr - ptr.
11419 if (LHS.get()->getType()->isAnyPointerType()) {
11420 QualType lpointee = LHS.get()->getType()->getPointeeType();
11421
11422 // Diagnose bad cases where we step over interface counts.
11423 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11424 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11425 return QualType();
11426
11427 // Arithmetic on label addresses is normally allowed, except when we add
11428 // a ptrauth signature to the addresses.
11429 if (isa<AddrLabelExpr>(LHS.get()) &&
11430 getLangOpts().PointerAuthIndirectGotos) {
11431 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11432 << /*subtraction*/ 0;
11433 return QualType();
11434 }
11435
11436 // The result type of a pointer-int computation is the pointer type.
11437 if (RHS.get()->getType()->isIntegerType()) {
11438 // Subtracting from a null pointer should produce a warning.
11439 // The last argument to the diagnose call says this doesn't match the
11440 // GNU int-to-pointer idiom.
11443 // In C++ adding zero to a null pointer is defined.
11444 Expr::EvalResult KnownVal;
11445 if (!getLangOpts().CPlusPlus ||
11446 (!RHS.get()->isValueDependent() &&
11447 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11448 KnownVal.Val.getInt() != 0))) {
11449 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11450 }
11451 }
11452
11453 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11454 return QualType();
11455
11456 // Check array bounds for pointer arithemtic
11457 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11458 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11459
11460 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11461 return LHS.get()->getType();
11462 }
11463
11464 // Handle pointer-pointer subtractions.
11465 if (const PointerType *RHSPTy
11466 = RHS.get()->getType()->getAs<PointerType>()) {
11467 QualType rpointee = RHSPTy->getPointeeType();
11468
11469 if (getLangOpts().CPlusPlus) {
11470 // Pointee types must be the same: C++ [expr.add]
11471 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11472 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11473 }
11474 } else {
11475 // Pointee types must be compatible C99 6.5.6p3
11476 if (!Context.typesAreCompatible(
11477 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11478 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11479 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11480 return QualType();
11481 }
11482 }
11483
11485 LHS.get(), RHS.get()))
11486 return QualType();
11487
11488 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11490 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11492
11493 // Subtracting nullptr or from nullptr is suspect
11494 if (LHSIsNullPtr)
11495 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11496 if (RHSIsNullPtr)
11497 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11498
11499 // The pointee type may have zero size. As an extension, a structure or
11500 // union may have zero size or an array may have zero length. In this
11501 // case subtraction does not make sense.
11502 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11503 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11504 if (ElementSize.isZero()) {
11505 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11506 << rpointee.getUnqualifiedType()
11507 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11508 }
11509 }
11510
11511 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11512 return Context.getPointerDiffType();
11513 }
11514 }
11515
11516 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11517 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11518 return ResultTy;
11519}
11520
11522 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11523 return ET->getOriginalDecl()->isScoped();
11524 return false;
11525}
11526
11529 QualType LHSType) {
11530 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11531 // so skip remaining warnings as we don't want to modify values within Sema.
11532 if (S.getLangOpts().OpenCL)
11533 return;
11534
11535 if (Opc == BO_Shr &&
11537 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
11538
11539 // Check right/shifter operand
11540 Expr::EvalResult RHSResult;
11541 if (RHS.get()->isValueDependent() ||
11542 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11543 return;
11544 llvm::APSInt Right = RHSResult.Val.getInt();
11545
11546 if (Right.isNegative()) {
11547 S.DiagRuntimeBehavior(Loc, RHS.get(),
11548 S.PDiag(diag::warn_shift_negative)
11549 << RHS.get()->getSourceRange());
11550 return;
11551 }
11552
11553 QualType LHSExprType = LHS.get()->getType();
11554 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11555 if (LHSExprType->isBitIntType())
11556 LeftSize = S.Context.getIntWidth(LHSExprType);
11557 else if (LHSExprType->isFixedPointType()) {
11558 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11559 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11560 }
11561 if (Right.uge(LeftSize)) {
11562 S.DiagRuntimeBehavior(Loc, RHS.get(),
11563 S.PDiag(diag::warn_shift_gt_typewidth)
11564 << RHS.get()->getSourceRange());
11565 return;
11566 }
11567
11568 // FIXME: We probably need to handle fixed point types specially here.
11569 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11570 return;
11571
11572 // When left shifting an ICE which is signed, we can check for overflow which
11573 // according to C++ standards prior to C++2a has undefined behavior
11574 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11575 // more than the maximum value representable in the result type, so never
11576 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11577 // expression is still probably a bug.)
11578 Expr::EvalResult LHSResult;
11579 if (LHS.get()->isValueDependent() ||
11581 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11582 return;
11583 llvm::APSInt Left = LHSResult.Val.getInt();
11584
11585 // Don't warn if signed overflow is defined, then all the rest of the
11586 // diagnostics will not be triggered because the behavior is defined.
11587 // Also don't warn in C++20 mode (and newer), as signed left shifts
11588 // always wrap and never overflow.
11589 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11590 return;
11591
11592 // If LHS does not have a non-negative value then, the
11593 // behavior is undefined before C++2a. Warn about it.
11594 if (Left.isNegative()) {
11595 S.DiagRuntimeBehavior(Loc, LHS.get(),
11596 S.PDiag(diag::warn_shift_lhs_negative)
11597 << LHS.get()->getSourceRange());
11598 return;
11599 }
11600
11601 llvm::APInt ResultBits =
11602 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11603 if (ResultBits.ule(LeftSize))
11604 return;
11605 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11606 Result = Result.shl(Right);
11607
11608 // Print the bit representation of the signed integer as an unsigned
11609 // hexadecimal number.
11610 SmallString<40> HexResult;
11611 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11612
11613 // If we are only missing a sign bit, this is less likely to result in actual
11614 // bugs -- if the result is cast back to an unsigned type, it will have the
11615 // expected value. Thus we place this behind a different warning that can be
11616 // turned off separately if needed.
11617 if (ResultBits - 1 == LeftSize) {
11618 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11619 << HexResult << LHSType
11620 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11621 return;
11622 }
11623
11624 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11625 << HexResult.str() << Result.getSignificantBits() << LHSType
11626 << Left.getBitWidth() << LHS.get()->getSourceRange()
11627 << RHS.get()->getSourceRange();
11628}
11629
11630/// Return the resulting type when a vector is shifted
11631/// by a scalar or vector shift amount.
11633 SourceLocation Loc, bool IsCompAssign) {
11634 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11635 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11636 !LHS.get()->getType()->isVectorType()) {
11637 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11638 << RHS.get()->getType() << LHS.get()->getType()
11639 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11640 return QualType();
11641 }
11642
11643 if (!IsCompAssign) {
11644 LHS = S.UsualUnaryConversions(LHS.get());
11645 if (LHS.isInvalid()) return QualType();
11646 }
11647
11648 RHS = S.UsualUnaryConversions(RHS.get());
11649 if (RHS.isInvalid()) return QualType();
11650
11651 QualType LHSType = LHS.get()->getType();
11652 // Note that LHS might be a scalar because the routine calls not only in
11653 // OpenCL case.
11654 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11655 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11656
11657 // Note that RHS might not be a vector.
11658 QualType RHSType = RHS.get()->getType();
11659 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11660 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11661
11662 // Do not allow shifts for boolean vectors.
11663 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11664 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11665 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11666 << LHS.get()->getType() << RHS.get()->getType()
11667 << LHS.get()->getSourceRange();
11668 return QualType();
11669 }
11670
11671 // The operands need to be integers.
11672 if (!LHSEleType->isIntegerType()) {
11673 S.Diag(Loc, diag::err_typecheck_expect_int)
11674 << LHS.get()->getType() << LHS.get()->getSourceRange();
11675 return QualType();
11676 }
11677
11678 if (!RHSEleType->isIntegerType()) {
11679 S.Diag(Loc, diag::err_typecheck_expect_int)
11680 << RHS.get()->getType() << RHS.get()->getSourceRange();
11681 return QualType();
11682 }
11683
11684 if (!LHSVecTy) {
11685 assert(RHSVecTy);
11686 if (IsCompAssign)
11687 return RHSType;
11688 if (LHSEleType != RHSEleType) {
11689 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11690 LHSEleType = RHSEleType;
11691 }
11692 QualType VecTy =
11693 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11694 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11695 LHSType = VecTy;
11696 } else if (RHSVecTy) {
11697 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11698 // are applied component-wise. So if RHS is a vector, then ensure
11699 // that the number of elements is the same as LHS...
11700 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11701 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11702 << LHS.get()->getType() << RHS.get()->getType()
11703 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11704 return QualType();
11705 }
11706 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11707 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11708 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11709 if (LHSBT != RHSBT &&
11710 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11711 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11712 << LHS.get()->getType() << RHS.get()->getType()
11713 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11714 }
11715 }
11716 } else {
11717 // ...else expand RHS to match the number of elements in LHS.
11718 QualType VecTy =
11719 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11720 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11721 }
11722
11723 return LHSType;
11724}
11725
11727 ExprResult &RHS, SourceLocation Loc,
11728 bool IsCompAssign) {
11729 if (!IsCompAssign) {
11730 LHS = S.UsualUnaryConversions(LHS.get());
11731 if (LHS.isInvalid())
11732 return QualType();
11733 }
11734
11735 RHS = S.UsualUnaryConversions(RHS.get());
11736 if (RHS.isInvalid())
11737 return QualType();
11738
11739 QualType LHSType = LHS.get()->getType();
11740 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11741 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11742 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11743 : LHSType;
11744
11745 // Note that RHS might not be a vector
11746 QualType RHSType = RHS.get()->getType();
11747 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11748 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11749 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11750 : RHSType;
11751
11752 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11753 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11754 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11755 << LHSType << RHSType << LHS.get()->getSourceRange();
11756 return QualType();
11757 }
11758
11759 if (!LHSEleType->isIntegerType()) {
11760 S.Diag(Loc, diag::err_typecheck_expect_int)
11761 << LHS.get()->getType() << LHS.get()->getSourceRange();
11762 return QualType();
11763 }
11764
11765 if (!RHSEleType->isIntegerType()) {
11766 S.Diag(Loc, diag::err_typecheck_expect_int)
11767 << RHS.get()->getType() << RHS.get()->getSourceRange();
11768 return QualType();
11769 }
11770
11771 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11772 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11773 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11774 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11775 << LHSType << RHSType << LHS.get()->getSourceRange()
11776 << RHS.get()->getSourceRange();
11777 return QualType();
11778 }
11779
11780 if (!LHSType->isSveVLSBuiltinType()) {
11781 assert(RHSType->isSveVLSBuiltinType());
11782 if (IsCompAssign)
11783 return RHSType;
11784 if (LHSEleType != RHSEleType) {
11785 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11786 LHSEleType = RHSEleType;
11787 }
11788 const llvm::ElementCount VecSize =
11789 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11790 QualType VecTy =
11791 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11792 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11793 LHSType = VecTy;
11794 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11795 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11796 S.Context.getTypeSize(LHSBuiltinTy)) {
11797 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11798 << LHSType << RHSType << LHS.get()->getSourceRange()
11799 << RHS.get()->getSourceRange();
11800 return QualType();
11801 }
11802 } else {
11803 const llvm::ElementCount VecSize =
11804 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11805 if (LHSEleType != RHSEleType) {
11806 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11807 RHSEleType = LHSEleType;
11808 }
11809 QualType VecTy =
11810 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11811 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11812 }
11813
11814 return LHSType;
11815}
11816
11817// C99 6.5.7
11820 bool IsCompAssign) {
11821 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11822
11823 // Vector shifts promote their scalar inputs to vector type.
11824 if (LHS.get()->getType()->isVectorType() ||
11825 RHS.get()->getType()->isVectorType()) {
11826 if (LangOpts.ZVector) {
11827 // The shift operators for the z vector extensions work basically
11828 // like general shifts, except that neither the LHS nor the RHS is
11829 // allowed to be a "vector bool".
11830 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11831 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11832 return InvalidOperands(Loc, LHS, RHS);
11833 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11834 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11835 return InvalidOperands(Loc, LHS, RHS);
11836 }
11837 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11838 }
11839
11840 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11841 RHS.get()->getType()->isSveVLSBuiltinType())
11842 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11843
11844 // Shifts don't perform usual arithmetic conversions, they just do integer
11845 // promotions on each operand. C99 6.5.7p3
11846
11847 // For the LHS, do usual unary conversions, but then reset them away
11848 // if this is a compound assignment.
11849 ExprResult OldLHS = LHS;
11850 LHS = UsualUnaryConversions(LHS.get());
11851 if (LHS.isInvalid())
11852 return QualType();
11853 QualType LHSType = LHS.get()->getType();
11854 if (IsCompAssign) LHS = OldLHS;
11855
11856 // The RHS is simpler.
11857 RHS = UsualUnaryConversions(RHS.get());
11858 if (RHS.isInvalid())
11859 return QualType();
11860 QualType RHSType = RHS.get()->getType();
11861
11862 // C99 6.5.7p2: Each of the operands shall have integer type.
11863 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11864 if ((!LHSType->isFixedPointOrIntegerType() &&
11865 !LHSType->hasIntegerRepresentation()) ||
11866 !RHSType->hasIntegerRepresentation()) {
11867 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11868 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11869 return ResultTy;
11870 }
11871
11872 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11873
11874 // "The type of the result is that of the promoted left operand."
11875 return LHSType;
11876}
11877
11878/// Diagnose bad pointer comparisons.
11880 ExprResult &LHS, ExprResult &RHS,
11881 bool IsError) {
11882 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11883 : diag::ext_typecheck_comparison_of_distinct_pointers)
11884 << LHS.get()->getType() << RHS.get()->getType()
11885 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11886}
11887
11888/// Returns false if the pointers are converted to a composite type,
11889/// true otherwise.
11891 ExprResult &LHS, ExprResult &RHS) {
11892 // C++ [expr.rel]p2:
11893 // [...] Pointer conversions (4.10) and qualification
11894 // conversions (4.4) are performed on pointer operands (or on
11895 // a pointer operand and a null pointer constant) to bring
11896 // them to their composite pointer type. [...]
11897 //
11898 // C++ [expr.eq]p1 uses the same notion for (in)equality
11899 // comparisons of pointers.
11900
11901 QualType LHSType = LHS.get()->getType();
11902 QualType RHSType = RHS.get()->getType();
11903 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11904 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11905
11906 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11907 if (T.isNull()) {
11908 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11909 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11910 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11911 else
11912 S.InvalidOperands(Loc, LHS, RHS);
11913 return true;
11914 }
11915
11916 return false;
11917}
11918
11920 ExprResult &LHS,
11921 ExprResult &RHS,
11922 bool IsError) {
11923 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11924 : diag::ext_typecheck_comparison_of_fptr_to_void)
11925 << LHS.get()->getType() << RHS.get()->getType()
11926 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11927}
11928
11930 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11931 case Stmt::ObjCArrayLiteralClass:
11932 case Stmt::ObjCDictionaryLiteralClass:
11933 case Stmt::ObjCStringLiteralClass:
11934 case Stmt::ObjCBoxedExprClass:
11935 return true;
11936 default:
11937 // Note that ObjCBoolLiteral is NOT an object literal!
11938 return false;
11939 }
11940}
11941
11942static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11945
11946 // If this is not actually an Objective-C object, bail out.
11947 if (!Type)
11948 return false;
11949
11950 // Get the LHS object's interface type.
11951 QualType InterfaceType = Type->getPointeeType();
11952
11953 // If the RHS isn't an Objective-C object, bail out.
11954 if (!RHS->getType()->isObjCObjectPointerType())
11955 return false;
11956
11957 // Try to find the -isEqual: method.
11958 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11959 ObjCMethodDecl *Method =
11960 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11961 /*IsInstance=*/true);
11962 if (!Method) {
11963 if (Type->isObjCIdType()) {
11964 // For 'id', just check the global pool.
11965 Method =
11967 /*receiverId=*/true);
11968 } else {
11969 // Check protocols.
11970 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11971 /*IsInstance=*/true);
11972 }
11973 }
11974
11975 if (!Method)
11976 return false;
11977
11978 QualType T = Method->parameters()[0]->getType();
11979 if (!T->isObjCObjectPointerType())
11980 return false;
11981
11982 QualType R = Method->getReturnType();
11983 if (!R->isScalarType())
11984 return false;
11985
11986 return true;
11987}
11988
11990 ExprResult &LHS, ExprResult &RHS,
11992 Expr *Literal;
11993 Expr *Other;
11994 if (isObjCObjectLiteral(LHS)) {
11995 Literal = LHS.get();
11996 Other = RHS.get();
11997 } else {
11998 Literal = RHS.get();
11999 Other = LHS.get();
12000 }
12001
12002 // Don't warn on comparisons against nil.
12003 Other = Other->IgnoreParenCasts();
12004 if (Other->isNullPointerConstant(S.getASTContext(),
12006 return;
12007
12008 // This should be kept in sync with warn_objc_literal_comparison.
12009 // LK_String should always be after the other literals, since it has its own
12010 // warning flag.
12011 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12012 assert(LiteralKind != SemaObjC::LK_Block);
12013 if (LiteralKind == SemaObjC::LK_None) {
12014 llvm_unreachable("Unknown Objective-C object literal kind");
12015 }
12016
12017 if (LiteralKind == SemaObjC::LK_String)
12018 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12019 << Literal->getSourceRange();
12020 else
12021 S.Diag(Loc, diag::warn_objc_literal_comparison)
12022 << LiteralKind << Literal->getSourceRange();
12023
12025 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12026 SourceLocation Start = LHS.get()->getBeginLoc();
12028 CharSourceRange OpRange =
12030
12031 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12032 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12033 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12034 << FixItHint::CreateInsertion(End, "]");
12035 }
12036}
12037
12038/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12040 ExprResult &RHS, SourceLocation Loc,
12041 BinaryOperatorKind Opc) {
12042 // Check that left hand side is !something.
12043 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12044 if (!UO || UO->getOpcode() != UO_LNot) return;
12045
12046 // Only check if the right hand side is non-bool arithmetic type.
12047 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12048
12049 // Make sure that the something in !something is not bool.
12050 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12051 if (SubExpr->isKnownToHaveBooleanValue()) return;
12052
12053 // Emit warning.
12054 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12055 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12056 << Loc << IsBitwiseOp;
12057
12058 // First note suggest !(x < y)
12059 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12060 SourceLocation FirstClose = RHS.get()->getEndLoc();
12061 FirstClose = S.getLocForEndOfToken(FirstClose);
12062 if (FirstClose.isInvalid())
12063 FirstOpen = SourceLocation();
12064 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12065 << IsBitwiseOp
12066 << FixItHint::CreateInsertion(FirstOpen, "(")
12067 << FixItHint::CreateInsertion(FirstClose, ")");
12068
12069 // Second note suggests (!x) < y
12070 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12071 SourceLocation SecondClose = LHS.get()->getEndLoc();
12072 SecondClose = S.getLocForEndOfToken(SecondClose);
12073 if (SecondClose.isInvalid())
12074 SecondOpen = SourceLocation();
12075 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12076 << FixItHint::CreateInsertion(SecondOpen, "(")
12077 << FixItHint::CreateInsertion(SecondClose, ")");
12078}
12079
12080// Returns true if E refers to a non-weak array.
12081static bool checkForArray(const Expr *E) {
12082 const ValueDecl *D = nullptr;
12083 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12084 D = DR->getDecl();
12085 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12086 if (Mem->isImplicitAccess())
12087 D = Mem->getMemberDecl();
12088 }
12089 if (!D)
12090 return false;
12091 return D->getType()->isArrayType() && !D->isWeak();
12092}
12093
12094/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12095/// pointer and size is an unsigned integer. Return whether the result is
12096/// always true/false.
12097static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12098 const Expr *RHS,
12099 BinaryOperatorKind Opc) {
12100 if (!LHS->getType()->isPointerType() ||
12101 S.getLangOpts().PointerOverflowDefined)
12102 return std::nullopt;
12103
12104 // Canonicalize to >= or < predicate.
12105 switch (Opc) {
12106 case BO_GE:
12107 case BO_LT:
12108 break;
12109 case BO_GT:
12110 std::swap(LHS, RHS);
12111 Opc = BO_LT;
12112 break;
12113 case BO_LE:
12114 std::swap(LHS, RHS);
12115 Opc = BO_GE;
12116 break;
12117 default:
12118 return std::nullopt;
12119 }
12120
12121 auto *BO = dyn_cast<BinaryOperator>(LHS);
12122 if (!BO || BO->getOpcode() != BO_Add)
12123 return std::nullopt;
12124
12125 Expr *Other;
12126 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12127 Other = BO->getRHS();
12128 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12129 Other = BO->getLHS();
12130 else
12131 return std::nullopt;
12132
12133 if (!Other->getType()->isUnsignedIntegerType())
12134 return std::nullopt;
12135
12136 return Opc == BO_GE;
12137}
12138
12139/// Diagnose some forms of syntactically-obvious tautological comparison.
12141 Expr *LHS, Expr *RHS,
12142 BinaryOperatorKind Opc) {
12143 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12144 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12145
12146 QualType LHSType = LHS->getType();
12147 QualType RHSType = RHS->getType();
12148 if (LHSType->hasFloatingRepresentation() ||
12149 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12151 return;
12152
12153 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12154 // Tautological diagnostics.
12155 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12156 return;
12157
12158 // Comparisons between two array types are ill-formed for operator<=>, so
12159 // we shouldn't emit any additional warnings about it.
12160 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12161 return;
12162
12163 // For non-floating point types, check for self-comparisons of the form
12164 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12165 // often indicate logic errors in the program.
12166 //
12167 // NOTE: Don't warn about comparison expressions resulting from macro
12168 // expansion. Also don't warn about comparisons which are only self
12169 // comparisons within a template instantiation. The warnings should catch
12170 // obvious cases in the definition of the template anyways. The idea is to
12171 // warn when the typed comparison operator will always evaluate to the same
12172 // result.
12173
12174 // Used for indexing into %select in warn_comparison_always
12175 enum {
12176 AlwaysConstant,
12177 AlwaysTrue,
12178 AlwaysFalse,
12179 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12180 };
12181
12182 // C++1a [array.comp]:
12183 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12184 // operands of array type.
12185 // C++2a [depr.array.comp]:
12186 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12187 // operands of array type are deprecated.
12188 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12189 RHSStripped->getType()->isArrayType()) {
12190 auto IsDeprArrayComparionIgnored =
12191 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12192 auto DiagID = S.getLangOpts().CPlusPlus26
12193 ? diag::warn_array_comparison_cxx26
12194 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12195 ? diag::warn_array_comparison
12196 : diag::warn_depr_array_comparison;
12197 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12198 << LHSStripped->getType() << RHSStripped->getType();
12199 // Carry on to produce the tautological comparison warning, if this
12200 // expression is potentially-evaluated, we can resolve the array to a
12201 // non-weak declaration, and so on.
12202 }
12203
12204 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12205 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12206 unsigned Result;
12207 switch (Opc) {
12208 case BO_EQ:
12209 case BO_LE:
12210 case BO_GE:
12211 Result = AlwaysTrue;
12212 break;
12213 case BO_NE:
12214 case BO_LT:
12215 case BO_GT:
12216 Result = AlwaysFalse;
12217 break;
12218 case BO_Cmp:
12219 Result = AlwaysEqual;
12220 break;
12221 default:
12222 Result = AlwaysConstant;
12223 break;
12224 }
12225 S.DiagRuntimeBehavior(Loc, nullptr,
12226 S.PDiag(diag::warn_comparison_always)
12227 << 0 /*self-comparison*/
12228 << Result);
12229 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12230 // What is it always going to evaluate to?
12231 unsigned Result;
12232 switch (Opc) {
12233 case BO_EQ: // e.g. array1 == array2
12234 Result = AlwaysFalse;
12235 break;
12236 case BO_NE: // e.g. array1 != array2
12237 Result = AlwaysTrue;
12238 break;
12239 default: // e.g. array1 <= array2
12240 // The best we can say is 'a constant'
12241 Result = AlwaysConstant;
12242 break;
12243 }
12244 S.DiagRuntimeBehavior(Loc, nullptr,
12245 S.PDiag(diag::warn_comparison_always)
12246 << 1 /*array comparison*/
12247 << Result);
12248 } else if (std::optional<bool> Res =
12249 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12250 S.DiagRuntimeBehavior(Loc, nullptr,
12251 S.PDiag(diag::warn_comparison_always)
12252 << 2 /*pointer comparison*/
12253 << (*Res ? AlwaysTrue : AlwaysFalse));
12254 }
12255 }
12256
12257 if (isa<CastExpr>(LHSStripped))
12258 LHSStripped = LHSStripped->IgnoreParenCasts();
12259 if (isa<CastExpr>(RHSStripped))
12260 RHSStripped = RHSStripped->IgnoreParenCasts();
12261
12262 // Warn about comparisons against a string constant (unless the other
12263 // operand is null); the user probably wants string comparison function.
12264 Expr *LiteralString = nullptr;
12265 Expr *LiteralStringStripped = nullptr;
12266 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12267 !RHSStripped->isNullPointerConstant(S.Context,
12269 LiteralString = LHS;
12270 LiteralStringStripped = LHSStripped;
12271 } else if ((isa<StringLiteral>(RHSStripped) ||
12272 isa<ObjCEncodeExpr>(RHSStripped)) &&
12273 !LHSStripped->isNullPointerConstant(S.Context,
12275 LiteralString = RHS;
12276 LiteralStringStripped = RHSStripped;
12277 }
12278
12279 if (LiteralString) {
12280 S.DiagRuntimeBehavior(Loc, nullptr,
12281 S.PDiag(diag::warn_stringcompare)
12282 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12283 << LiteralString->getSourceRange());
12284 }
12285}
12286
12288 switch (CK) {
12289 default: {
12290#ifndef NDEBUG
12291 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12292 << "\n";
12293#endif
12294 llvm_unreachable("unhandled cast kind");
12295 }
12296 case CK_UserDefinedConversion:
12297 return ICK_Identity;
12298 case CK_LValueToRValue:
12299 return ICK_Lvalue_To_Rvalue;
12300 case CK_ArrayToPointerDecay:
12301 return ICK_Array_To_Pointer;
12302 case CK_FunctionToPointerDecay:
12304 case CK_IntegralCast:
12306 case CK_FloatingCast:
12308 case CK_IntegralToFloating:
12309 case CK_FloatingToIntegral:
12310 return ICK_Floating_Integral;
12311 case CK_IntegralComplexCast:
12312 case CK_FloatingComplexCast:
12313 case CK_FloatingComplexToIntegralComplex:
12314 case CK_IntegralComplexToFloatingComplex:
12316 case CK_FloatingComplexToReal:
12317 case CK_FloatingRealToComplex:
12318 case CK_IntegralComplexToReal:
12319 case CK_IntegralRealToComplex:
12320 return ICK_Complex_Real;
12321 case CK_HLSLArrayRValue:
12322 return ICK_HLSL_Array_RValue;
12323 }
12324}
12325
12327 QualType FromType,
12328 SourceLocation Loc) {
12329 // Check for a narrowing implicit conversion.
12332 SCS.setToType(0, FromType);
12333 SCS.setToType(1, ToType);
12334 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12335 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12336
12337 APValue PreNarrowingValue;
12338 QualType PreNarrowingType;
12339 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12340 PreNarrowingType,
12341 /*IgnoreFloatToIntegralConversion*/ true)) {
12343 // Implicit conversion to a narrower type, but the expression is
12344 // value-dependent so we can't tell whether it's actually narrowing.
12345 case NK_Not_Narrowing:
12346 return false;
12347
12349 // Implicit conversion to a narrower type, and the value is not a constant
12350 // expression.
12351 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12352 << /*Constant*/ 1
12353 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12354 return true;
12355
12357 // Implicit conversion to a narrower type, and the value is not a constant
12358 // expression.
12359 case NK_Type_Narrowing:
12360 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12361 << /*Constant*/ 0 << FromType << ToType;
12362 // TODO: It's not a constant expression, but what if the user intended it
12363 // to be? Can we produce notes to help them figure out why it isn't?
12364 return true;
12365 }
12366 llvm_unreachable("unhandled case in switch");
12367}
12368
12370 ExprResult &LHS,
12371 ExprResult &RHS,
12372 SourceLocation Loc) {
12373 QualType LHSType = LHS.get()->getType();
12374 QualType RHSType = RHS.get()->getType();
12375 // Dig out the original argument type and expression before implicit casts
12376 // were applied. These are the types/expressions we need to check the
12377 // [expr.spaceship] requirements against.
12378 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12379 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12380 QualType LHSStrippedType = LHSStripped.get()->getType();
12381 QualType RHSStrippedType = RHSStripped.get()->getType();
12382
12383 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12384 // other is not, the program is ill-formed.
12385 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12386 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12387 return QualType();
12388 }
12389
12390 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12391 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12392 RHSStrippedType->isEnumeralType();
12393 if (NumEnumArgs == 1) {
12394 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12395 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12396 if (OtherTy->hasFloatingRepresentation()) {
12397 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12398 return QualType();
12399 }
12400 }
12401 if (NumEnumArgs == 2) {
12402 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12403 // type E, the operator yields the result of converting the operands
12404 // to the underlying type of E and applying <=> to the converted operands.
12405 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12406 S.InvalidOperands(Loc, LHS, RHS);
12407 return QualType();
12408 }
12409 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12410 assert(IntType->isArithmeticType());
12411
12412 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12413 // promote the boolean type, and all other promotable integer types, to
12414 // avoid this.
12415 if (S.Context.isPromotableIntegerType(IntType))
12416 IntType = S.Context.getPromotedIntegerType(IntType);
12417
12418 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12419 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12420 LHSType = RHSType = IntType;
12421 }
12422
12423 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12424 // usual arithmetic conversions are applied to the operands.
12425 QualType Type =
12427 if (LHS.isInvalid() || RHS.isInvalid())
12428 return QualType();
12429 if (Type.isNull()) {
12430 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12431 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
12432 return ResultTy;
12433 }
12434
12435 std::optional<ComparisonCategoryType> CCT =
12437 if (!CCT)
12438 return S.InvalidOperands(Loc, LHS, RHS);
12439
12440 bool HasNarrowing = checkThreeWayNarrowingConversion(
12441 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12442 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12443 RHS.get()->getBeginLoc());
12444 if (HasNarrowing)
12445 return QualType();
12446
12447 assert(!Type.isNull() && "composite type for <=> has not been set");
12448
12451}
12452
12454 ExprResult &RHS,
12455 SourceLocation Loc,
12456 BinaryOperatorKind Opc) {
12457 if (Opc == BO_Cmp)
12458 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12459
12460 // C99 6.5.8p3 / C99 6.5.9p4
12461 QualType Type =
12463 if (LHS.isInvalid() || RHS.isInvalid())
12464 return QualType();
12465 if (Type.isNull()) {
12466 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12467 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12468 return ResultTy;
12469 }
12470 assert(Type->isArithmeticType() || Type->isEnumeralType());
12471
12473 return S.InvalidOperands(Loc, LHS, RHS);
12474
12475 // Check for comparisons of floating point operands using != and ==.
12477 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12478
12479 // The result of comparisons is 'bool' in C++, 'int' in C.
12481}
12482
12484 if (!NullE.get()->getType()->isAnyPointerType())
12485 return;
12486 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12487 if (!E.get()->getType()->isAnyPointerType() &&
12491 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12492 if (CL->getValue() == 0)
12493 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12494 << NullValue
12496 NullValue ? "NULL" : "(void *)0");
12497 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12498 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12499 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12500 if (T == Context.CharTy)
12501 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12502 << NullValue
12504 NullValue ? "NULL" : "(void *)0");
12505 }
12506 }
12507}
12508
12509// C99 6.5.8, C++ [expr.rel]
12511 SourceLocation Loc,
12512 BinaryOperatorKind Opc) {
12513 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12514 bool IsThreeWay = Opc == BO_Cmp;
12515 bool IsOrdered = IsRelational || IsThreeWay;
12516 auto IsAnyPointerType = [](ExprResult E) {
12517 QualType Ty = E.get()->getType();
12518 return Ty->isPointerType() || Ty->isMemberPointerType();
12519 };
12520
12521 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12522 // type, array-to-pointer, ..., conversions are performed on both operands to
12523 // bring them to their composite type.
12524 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12525 // any type-related checks.
12526 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12528 if (LHS.isInvalid())
12529 return QualType();
12531 if (RHS.isInvalid())
12532 return QualType();
12533 } else {
12534 LHS = DefaultLvalueConversion(LHS.get());
12535 if (LHS.isInvalid())
12536 return QualType();
12537 RHS = DefaultLvalueConversion(RHS.get());
12538 if (RHS.isInvalid())
12539 return QualType();
12540 }
12541
12542 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12546 }
12547
12548 // Handle vector comparisons separately.
12549 if (LHS.get()->getType()->isVectorType() ||
12550 RHS.get()->getType()->isVectorType())
12551 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12552
12553 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12554 RHS.get()->getType()->isSveVLSBuiltinType())
12555 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12556
12557 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12558 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12559
12560 QualType LHSType = LHS.get()->getType();
12561 QualType RHSType = RHS.get()->getType();
12562 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12563 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12564 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12565
12566 if ((LHSType->isPointerType() &&
12568 (RHSType->isPointerType() &&
12570 return InvalidOperands(Loc, LHS, RHS);
12571
12572 const Expr::NullPointerConstantKind LHSNullKind =
12574 const Expr::NullPointerConstantKind RHSNullKind =
12576 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12577 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12578
12579 auto computeResultTy = [&]() {
12580 if (Opc != BO_Cmp)
12581 return QualType(Context.getLogicalOperationType());
12582 assert(getLangOpts().CPlusPlus);
12583 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12584
12585 QualType CompositeTy = LHS.get()->getType();
12586 assert(!CompositeTy->isReferenceType());
12587
12588 std::optional<ComparisonCategoryType> CCT =
12590 if (!CCT)
12591 return InvalidOperands(Loc, LHS, RHS);
12592
12593 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12594 // P0946R0: Comparisons between a null pointer constant and an object
12595 // pointer result in std::strong_equality, which is ill-formed under
12596 // P1959R0.
12597 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12598 << (LHSIsNull ? LHS.get()->getSourceRange()
12599 : RHS.get()->getSourceRange());
12600 return QualType();
12601 }
12602
12605 };
12606
12607 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12608 bool IsEquality = Opc == BO_EQ;
12609 if (RHSIsNull)
12610 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12611 RHS.get()->getSourceRange());
12612 else
12613 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12614 LHS.get()->getSourceRange());
12615 }
12616
12617 if (IsOrdered && LHSType->isFunctionPointerType() &&
12618 RHSType->isFunctionPointerType()) {
12619 // Valid unless a relational comparison of function pointers
12620 bool IsError = Opc == BO_Cmp;
12621 auto DiagID =
12622 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12623 : getLangOpts().CPlusPlus
12624 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12625 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12626 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12627 << RHS.get()->getSourceRange();
12628 if (IsError)
12629 return QualType();
12630 }
12631
12632 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12633 (RHSType->isIntegerType() && !RHSIsNull)) {
12634 // Skip normal pointer conversion checks in this case; we have better
12635 // diagnostics for this below.
12636 } else if (getLangOpts().CPlusPlus) {
12637 // Equality comparison of a function pointer to a void pointer is invalid,
12638 // but we allow it as an extension.
12639 // FIXME: If we really want to allow this, should it be part of composite
12640 // pointer type computation so it works in conditionals too?
12641 if (!IsOrdered &&
12642 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12643 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12644 // This is a gcc extension compatibility comparison.
12645 // In a SFINAE context, we treat this as a hard error to maintain
12646 // conformance with the C++ standard.
12648 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12649
12650 if (isSFINAEContext())
12651 return QualType();
12652
12653 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12654 return computeResultTy();
12655 }
12656
12657 // C++ [expr.eq]p2:
12658 // If at least one operand is a pointer [...] bring them to their
12659 // composite pointer type.
12660 // C++ [expr.spaceship]p6
12661 // If at least one of the operands is of pointer type, [...] bring them
12662 // to their composite pointer type.
12663 // C++ [expr.rel]p2:
12664 // If both operands are pointers, [...] bring them to their composite
12665 // pointer type.
12666 // For <=>, the only valid non-pointer types are arrays and functions, and
12667 // we already decayed those, so this is really the same as the relational
12668 // comparison rule.
12669 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12670 (IsOrdered ? 2 : 1) &&
12671 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12672 RHSType->isObjCObjectPointerType()))) {
12673 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12674 return QualType();
12675 return computeResultTy();
12676 }
12677 } else if (LHSType->isPointerType() &&
12678 RHSType->isPointerType()) { // C99 6.5.8p2
12679 // All of the following pointer-related warnings are GCC extensions, except
12680 // when handling null pointer constants.
12681 QualType LCanPointeeTy =
12683 QualType RCanPointeeTy =
12685
12686 // C99 6.5.9p2 and C99 6.5.8p2
12687 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12688 RCanPointeeTy.getUnqualifiedType())) {
12689 if (IsRelational) {
12690 // Pointers both need to point to complete or incomplete types
12691 if ((LCanPointeeTy->isIncompleteType() !=
12692 RCanPointeeTy->isIncompleteType()) &&
12693 !getLangOpts().C11) {
12694 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12695 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12696 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12697 << RCanPointeeTy->isIncompleteType();
12698 }
12699 }
12700 } else if (!IsRelational &&
12701 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12702 // Valid unless comparison between non-null pointer and function pointer
12703 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12704 && !LHSIsNull && !RHSIsNull)
12705 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12706 /*isError*/false);
12707 } else {
12708 // Invalid
12709 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12710 }
12711 if (LCanPointeeTy != RCanPointeeTy) {
12712 // Treat NULL constant as a special case in OpenCL.
12713 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12714 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
12715 getASTContext())) {
12716 Diag(Loc,
12717 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12718 << LHSType << RHSType << 0 /* comparison */
12719 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12720 }
12721 }
12722 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12723 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12724 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12725 : CK_BitCast;
12726
12727 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
12728 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
12729 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
12730 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
12731 bool ChangingCFIUncheckedCallee =
12732 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
12733
12734 if (LHSIsNull && !RHSIsNull)
12735 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12736 else if (!ChangingCFIUncheckedCallee)
12737 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12738 }
12739 return computeResultTy();
12740 }
12741
12742
12743 // C++ [expr.eq]p4:
12744 // Two operands of type std::nullptr_t or one operand of type
12745 // std::nullptr_t and the other a null pointer constant compare
12746 // equal.
12747 // C23 6.5.9p5:
12748 // If both operands have type nullptr_t or one operand has type nullptr_t
12749 // and the other is a null pointer constant, they compare equal if the
12750 // former is a null pointer.
12751 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12752 if (LHSType->isNullPtrType()) {
12753 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12754 return computeResultTy();
12755 }
12756 if (RHSType->isNullPtrType()) {
12757 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12758 return computeResultTy();
12759 }
12760 }
12761
12762 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12763 // C23 6.5.9p6:
12764 // Otherwise, at least one operand is a pointer. If one is a pointer and
12765 // the other is a null pointer constant or has type nullptr_t, they
12766 // compare equal
12767 if (LHSIsNull && RHSType->isPointerType()) {
12768 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12769 return computeResultTy();
12770 }
12771 if (RHSIsNull && LHSType->isPointerType()) {
12772 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12773 return computeResultTy();
12774 }
12775 }
12776
12777 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12778 // These aren't covered by the composite pointer type rules.
12779 if (!IsOrdered && RHSType->isNullPtrType() &&
12780 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12781 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12782 return computeResultTy();
12783 }
12784 if (!IsOrdered && LHSType->isNullPtrType() &&
12785 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12786 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12787 return computeResultTy();
12788 }
12789
12790 if (getLangOpts().CPlusPlus) {
12791 if (IsRelational &&
12792 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12793 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12794 // HACK: Relational comparison of nullptr_t against a pointer type is
12795 // invalid per DR583, but we allow it within std::less<> and friends,
12796 // since otherwise common uses of it break.
12797 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12798 // friends to have std::nullptr_t overload candidates.
12799 DeclContext *DC = CurContext;
12800 if (isa<FunctionDecl>(DC))
12801 DC = DC->getParent();
12802 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12803 if (CTSD->isInStdNamespace() &&
12804 llvm::StringSwitch<bool>(CTSD->getName())
12805 .Cases("less", "less_equal", "greater", "greater_equal", true)
12806 .Default(false)) {
12807 if (RHSType->isNullPtrType())
12808 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12809 else
12810 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12811 return computeResultTy();
12812 }
12813 }
12814 }
12815
12816 // C++ [expr.eq]p2:
12817 // If at least one operand is a pointer to member, [...] bring them to
12818 // their composite pointer type.
12819 if (!IsOrdered &&
12820 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12821 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12822 return QualType();
12823 else
12824 return computeResultTy();
12825 }
12826 }
12827
12828 // Handle block pointer types.
12829 if (!IsOrdered && LHSType->isBlockPointerType() &&
12830 RHSType->isBlockPointerType()) {
12831 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12832 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12833
12834 if (!LHSIsNull && !RHSIsNull &&
12835 !Context.typesAreCompatible(lpointee, rpointee)) {
12836 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12837 << LHSType << RHSType << LHS.get()->getSourceRange()
12838 << RHS.get()->getSourceRange();
12839 }
12840 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12841 return computeResultTy();
12842 }
12843
12844 // Allow block pointers to be compared with null pointer constants.
12845 if (!IsOrdered
12846 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12847 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12848 if (!LHSIsNull && !RHSIsNull) {
12849 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12851 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12852 ->getPointeeType()->isVoidType())))
12853 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12854 << LHSType << RHSType << LHS.get()->getSourceRange()
12855 << RHS.get()->getSourceRange();
12856 }
12857 if (LHSIsNull && !RHSIsNull)
12858 LHS = ImpCastExprToType(LHS.get(), RHSType,
12859 RHSType->isPointerType() ? CK_BitCast
12860 : CK_AnyPointerToBlockPointerCast);
12861 else
12862 RHS = ImpCastExprToType(RHS.get(), LHSType,
12863 LHSType->isPointerType() ? CK_BitCast
12864 : CK_AnyPointerToBlockPointerCast);
12865 return computeResultTy();
12866 }
12867
12868 if (LHSType->isObjCObjectPointerType() ||
12869 RHSType->isObjCObjectPointerType()) {
12870 const PointerType *LPT = LHSType->getAs<PointerType>();
12871 const PointerType *RPT = RHSType->getAs<PointerType>();
12872 if (LPT || RPT) {
12873 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12874 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12875
12876 if (!LPtrToVoid && !RPtrToVoid &&
12877 !Context.typesAreCompatible(LHSType, RHSType)) {
12878 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12879 /*isError*/false);
12880 }
12881 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12882 // the RHS, but we have test coverage for this behavior.
12883 // FIXME: Consider using convertPointersToCompositeType in C++.
12884 if (LHSIsNull && !RHSIsNull) {
12885 Expr *E = LHS.get();
12886 if (getLangOpts().ObjCAutoRefCount)
12887 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12889 LHS = ImpCastExprToType(E, RHSType,
12890 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12891 }
12892 else {
12893 Expr *E = RHS.get();
12894 if (getLangOpts().ObjCAutoRefCount)
12895 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12897 /*Diagnose=*/true,
12898 /*DiagnoseCFAudited=*/false, Opc);
12899 RHS = ImpCastExprToType(E, LHSType,
12900 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12901 }
12902 return computeResultTy();
12903 }
12904 if (LHSType->isObjCObjectPointerType() &&
12905 RHSType->isObjCObjectPointerType()) {
12906 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12907 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12908 /*isError*/false);
12910 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12911
12912 if (LHSIsNull && !RHSIsNull)
12913 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12914 else
12915 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12916 return computeResultTy();
12917 }
12918
12919 if (!IsOrdered && LHSType->isBlockPointerType() &&
12921 LHS = ImpCastExprToType(LHS.get(), RHSType,
12922 CK_BlockPointerToObjCPointerCast);
12923 return computeResultTy();
12924 } else if (!IsOrdered &&
12926 RHSType->isBlockPointerType()) {
12927 RHS = ImpCastExprToType(RHS.get(), LHSType,
12928 CK_BlockPointerToObjCPointerCast);
12929 return computeResultTy();
12930 }
12931 }
12932 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12933 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12934 unsigned DiagID = 0;
12935 bool isError = false;
12936 if (LangOpts.DebuggerSupport) {
12937 // Under a debugger, allow the comparison of pointers to integers,
12938 // since users tend to want to compare addresses.
12939 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12940 (RHSIsNull && RHSType->isIntegerType())) {
12941 if (IsOrdered) {
12942 isError = getLangOpts().CPlusPlus;
12943 DiagID =
12944 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12945 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12946 }
12947 } else if (getLangOpts().CPlusPlus) {
12948 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12949 isError = true;
12950 } else if (IsOrdered)
12951 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12952 else
12953 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12954
12955 if (DiagID) {
12956 Diag(Loc, DiagID)
12957 << LHSType << RHSType << LHS.get()->getSourceRange()
12958 << RHS.get()->getSourceRange();
12959 if (isError)
12960 return QualType();
12961 }
12962
12963 if (LHSType->isIntegerType())
12964 LHS = ImpCastExprToType(LHS.get(), RHSType,
12965 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12966 else
12967 RHS = ImpCastExprToType(RHS.get(), LHSType,
12968 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12969 return computeResultTy();
12970 }
12971
12972 // Handle block pointers.
12973 if (!IsOrdered && RHSIsNull
12974 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12975 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12976 return computeResultTy();
12977 }
12978 if (!IsOrdered && LHSIsNull
12979 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12980 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12981 return computeResultTy();
12982 }
12983
12984 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12985 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12986 return computeResultTy();
12987 }
12988
12989 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12990 return computeResultTy();
12991 }
12992
12993 if (LHSIsNull && RHSType->isQueueT()) {
12994 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12995 return computeResultTy();
12996 }
12997
12998 if (LHSType->isQueueT() && RHSIsNull) {
12999 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13000 return computeResultTy();
13001 }
13002 }
13003
13004 return InvalidOperands(Loc, LHS, RHS);
13005}
13006
13008 const VectorType *VTy = V->castAs<VectorType>();
13009 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13010
13011 if (isa<ExtVectorType>(VTy)) {
13012 if (VTy->isExtVectorBoolType())
13013 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13014 if (TypeSize == Context.getTypeSize(Context.CharTy))
13015 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13016 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13017 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13018 if (TypeSize == Context.getTypeSize(Context.IntTy))
13019 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13020 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13021 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13022 if (TypeSize == Context.getTypeSize(Context.LongTy))
13023 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13024 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13025 "Unhandled vector element size in vector compare");
13026 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13027 }
13028
13029 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13030 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13032 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13033 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13035 if (TypeSize == Context.getTypeSize(Context.LongTy))
13036 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13038 if (TypeSize == Context.getTypeSize(Context.IntTy))
13039 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13041 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13042 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13044 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13045 "Unhandled vector element size in vector compare");
13046 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13048}
13049
13051 const BuiltinType *VTy = V->castAs<BuiltinType>();
13052 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13053
13054 const QualType ETy = V->getSveEltType(Context);
13055 const auto TypeSize = Context.getTypeSize(ETy);
13056
13057 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13058 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13059 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13060}
13061
13063 SourceLocation Loc,
13064 BinaryOperatorKind Opc) {
13065 if (Opc == BO_Cmp) {
13066 Diag(Loc, diag::err_three_way_vector_comparison);
13067 return QualType();
13068 }
13069
13070 // Check to make sure we're operating on vectors of the same type and width,
13071 // Allowing one side to be a scalar of element type.
13072 QualType vType =
13073 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13074 /*AllowBothBool*/ true,
13075 /*AllowBoolConversions*/ getLangOpts().ZVector,
13076 /*AllowBooleanOperation*/ true,
13077 /*ReportInvalid*/ true);
13078 if (vType.isNull())
13079 return vType;
13080
13081 QualType LHSType = LHS.get()->getType();
13082
13083 // Determine the return type of a vector compare. By default clang will return
13084 // a scalar for all vector compares except vector bool and vector pixel.
13085 // With the gcc compiler we will always return a vector type and with the xl
13086 // compiler we will always return a scalar type. This switch allows choosing
13087 // which behavior is prefered.
13088 if (getLangOpts().AltiVec) {
13089 switch (getLangOpts().getAltivecSrcCompat()) {
13091 // If AltiVec, the comparison results in a numeric type, i.e.
13092 // bool for C++, int for C
13093 if (vType->castAs<VectorType>()->getVectorKind() ==
13095 return Context.getLogicalOperationType();
13096 else
13097 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13098 break;
13100 // For GCC we always return the vector type.
13101 break;
13103 return Context.getLogicalOperationType();
13104 break;
13105 }
13106 }
13107
13108 // For non-floating point types, check for self-comparisons of the form
13109 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13110 // often indicate logic errors in the program.
13111 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13112
13113 // Check for comparisons of floating point operands using != and ==.
13114 if (LHSType->hasFloatingRepresentation()) {
13115 assert(RHS.get()->getType()->hasFloatingRepresentation());
13116 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13117 }
13118
13119 // Return a signed type for the vector.
13120 return GetSignedVectorType(vType);
13121}
13122
13124 ExprResult &RHS,
13125 SourceLocation Loc,
13126 BinaryOperatorKind Opc) {
13127 if (Opc == BO_Cmp) {
13128 Diag(Loc, diag::err_three_way_vector_comparison);
13129 return QualType();
13130 }
13131
13132 // Check to make sure we're operating on vectors of the same type and width,
13133 // Allowing one side to be a scalar of element type.
13135 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13136
13137 if (vType.isNull())
13138 return vType;
13139
13140 QualType LHSType = LHS.get()->getType();
13141
13142 // For non-floating point types, check for self-comparisons of the form
13143 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13144 // often indicate logic errors in the program.
13145 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13146
13147 // Check for comparisons of floating point operands using != and ==.
13148 if (LHSType->hasFloatingRepresentation()) {
13149 assert(RHS.get()->getType()->hasFloatingRepresentation());
13150 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13151 }
13152
13153 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13154 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13155
13156 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13157 RHSBuiltinTy->isSVEBool())
13158 return LHSType;
13159
13160 // Return a signed type for the vector.
13161 return GetSignedSizelessVectorType(vType);
13162}
13163
13164static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13165 const ExprResult &XorRHS,
13166 const SourceLocation Loc) {
13167 // Do not diagnose macros.
13168 if (Loc.isMacroID())
13169 return;
13170
13171 // Do not diagnose if both LHS and RHS are macros.
13172 if (XorLHS.get()->getExprLoc().isMacroID() &&
13173 XorRHS.get()->getExprLoc().isMacroID())
13174 return;
13175
13176 bool Negative = false;
13177 bool ExplicitPlus = false;
13178 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13179 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13180
13181 if (!LHSInt)
13182 return;
13183 if (!RHSInt) {
13184 // Check negative literals.
13185 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13186 UnaryOperatorKind Opc = UO->getOpcode();
13187 if (Opc != UO_Minus && Opc != UO_Plus)
13188 return;
13189 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13190 if (!RHSInt)
13191 return;
13192 Negative = (Opc == UO_Minus);
13193 ExplicitPlus = !Negative;
13194 } else {
13195 return;
13196 }
13197 }
13198
13199 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13200 llvm::APInt RightSideValue = RHSInt->getValue();
13201 if (LeftSideValue != 2 && LeftSideValue != 10)
13202 return;
13203
13204 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13205 return;
13206
13208 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13209 llvm::StringRef ExprStr =
13211
13212 CharSourceRange XorRange =
13214 llvm::StringRef XorStr =
13216 // Do not diagnose if xor keyword/macro is used.
13217 if (XorStr == "xor")
13218 return;
13219
13220 std::string LHSStr = std::string(Lexer::getSourceText(
13221 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13222 S.getSourceManager(), S.getLangOpts()));
13223 std::string RHSStr = std::string(Lexer::getSourceText(
13224 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13225 S.getSourceManager(), S.getLangOpts()));
13226
13227 if (Negative) {
13228 RightSideValue = -RightSideValue;
13229 RHSStr = "-" + RHSStr;
13230 } else if (ExplicitPlus) {
13231 RHSStr = "+" + RHSStr;
13232 }
13233
13234 StringRef LHSStrRef = LHSStr;
13235 StringRef RHSStrRef = RHSStr;
13236 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13237 // literals.
13238 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13239 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13240 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13241 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13242 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13243 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13244 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13245 return;
13246
13247 bool SuggestXor =
13248 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13249 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13250 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13251 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13252 std::string SuggestedExpr = "1 << " + RHSStr;
13253 bool Overflow = false;
13254 llvm::APInt One = (LeftSideValue - 1);
13255 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13256 if (Overflow) {
13257 if (RightSideIntValue < 64)
13258 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13259 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13260 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13261 else if (RightSideIntValue == 64)
13262 S.Diag(Loc, diag::warn_xor_used_as_pow)
13263 << ExprStr << toString(XorValue, 10, true);
13264 else
13265 return;
13266 } else {
13267 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13268 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13269 << toString(PowValue, 10, true)
13271 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13272 }
13273
13274 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13275 << ("0x2 ^ " + RHSStr) << SuggestXor;
13276 } else if (LeftSideValue == 10) {
13277 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13278 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13279 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13280 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13281 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13282 << ("0xA ^ " + RHSStr) << SuggestXor;
13283 }
13284}
13285
13287 SourceLocation Loc,
13288 BinaryOperatorKind Opc) {
13289 // Ensure that either both operands are of the same vector type, or
13290 // one operand is of a vector type and the other is of its element type.
13291 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13292 /*AllowBothBool*/ true,
13293 /*AllowBoolConversions*/ false,
13294 /*AllowBooleanOperation*/ false,
13295 /*ReportInvalid*/ false);
13296 if (vType.isNull())
13297 return InvalidOperands(Loc, LHS, RHS);
13298 if (getLangOpts().OpenCL &&
13299 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13301 return InvalidOperands(Loc, LHS, RHS);
13302 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13303 // usage of the logical operators && and || with vectors in C. This
13304 // check could be notionally dropped.
13305 if (!getLangOpts().CPlusPlus &&
13306 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13307 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13308 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13309 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13310 // `select` functions.
13311 if (getLangOpts().HLSL &&
13312 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13313 (void)InvalidOperands(Loc, LHS, RHS);
13314 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13315 return QualType();
13316 }
13317
13318 return GetSignedVectorType(LHS.get()->getType());
13319}
13320
13322 SourceLocation Loc,
13323 bool IsCompAssign) {
13324 if (!IsCompAssign) {
13326 if (LHS.isInvalid())
13327 return QualType();
13328 }
13330 if (RHS.isInvalid())
13331 return QualType();
13332
13333 // For conversion purposes, we ignore any qualifiers.
13334 // For example, "const float" and "float" are equivalent.
13335 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13336 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13337
13338 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13339 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13340 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13341
13342 if (Context.hasSameType(LHSType, RHSType))
13343 return Context.getCommonSugaredType(LHSType, RHSType);
13344
13345 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13346 // case we have to return InvalidOperands.
13347 ExprResult OriginalLHS = LHS;
13348 ExprResult OriginalRHS = RHS;
13349 if (LHSMatType && !RHSMatType) {
13350 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13351 if (!RHS.isInvalid())
13352 return LHSType;
13353
13354 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13355 }
13356
13357 if (!LHSMatType && RHSMatType) {
13358 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13359 if (!LHS.isInvalid())
13360 return RHSType;
13361 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13362 }
13363
13364 return InvalidOperands(Loc, LHS, RHS);
13365}
13366
13368 SourceLocation Loc,
13369 bool IsCompAssign) {
13370 if (!IsCompAssign) {
13372 if (LHS.isInvalid())
13373 return QualType();
13374 }
13376 if (RHS.isInvalid())
13377 return QualType();
13378
13379 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13380 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13381 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13382
13383 if (LHSMatType && RHSMatType) {
13384 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13385 return InvalidOperands(Loc, LHS, RHS);
13386
13387 if (Context.hasSameType(LHSMatType, RHSMatType))
13388 return Context.getCommonSugaredType(
13389 LHS.get()->getType().getUnqualifiedType(),
13390 RHS.get()->getType().getUnqualifiedType());
13391
13392 QualType LHSELTy = LHSMatType->getElementType(),
13393 RHSELTy = RHSMatType->getElementType();
13394 if (!Context.hasSameType(LHSELTy, RHSELTy))
13395 return InvalidOperands(Loc, LHS, RHS);
13396
13397 return Context.getConstantMatrixType(
13398 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13399 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13400 }
13401 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13402}
13403
13405 switch (Opc) {
13406 default:
13407 return false;
13408 case BO_And:
13409 case BO_AndAssign:
13410 case BO_Or:
13411 case BO_OrAssign:
13412 case BO_Xor:
13413 case BO_XorAssign:
13414 return true;
13415 }
13416}
13417
13419 SourceLocation Loc,
13420 BinaryOperatorKind Opc) {
13421 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13422
13423 bool IsCompAssign =
13424 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13425
13426 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13427
13428 if (LHS.get()->getType()->isVectorType() ||
13429 RHS.get()->getType()->isVectorType()) {
13430 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13432 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13433 /*AllowBothBool*/ true,
13434 /*AllowBoolConversions*/ getLangOpts().ZVector,
13435 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13436 /*ReportInvalid*/ true);
13437 return InvalidOperands(Loc, LHS, RHS);
13438 }
13439
13440 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13441 RHS.get()->getType()->isSveVLSBuiltinType()) {
13442 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13444 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13446 return InvalidOperands(Loc, LHS, RHS);
13447 }
13448
13449 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13450 RHS.get()->getType()->isSveVLSBuiltinType()) {
13451 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13453 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13455 return InvalidOperands(Loc, LHS, RHS);
13456 }
13457
13458 if (Opc == BO_And)
13459 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13460
13461 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13463 return InvalidOperands(Loc, LHS, RHS);
13464
13465 ExprResult LHSResult = LHS, RHSResult = RHS;
13467 LHSResult, RHSResult, Loc,
13469 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13470 return QualType();
13471 LHS = LHSResult.get();
13472 RHS = RHSResult.get();
13473
13474 if (Opc == BO_Xor)
13475 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13476
13477 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13478 return compType;
13479 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13480 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13481 return ResultTy;
13482}
13483
13484// C99 6.5.[13,14]
13486 SourceLocation Loc,
13487 BinaryOperatorKind Opc) {
13488 // Check vector operands differently.
13489 if (LHS.get()->getType()->isVectorType() ||
13490 RHS.get()->getType()->isVectorType())
13491 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13492
13493 bool EnumConstantInBoolContext = false;
13494 for (const ExprResult &HS : {LHS, RHS}) {
13495 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13496 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13497 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13498 EnumConstantInBoolContext = true;
13499 }
13500 }
13501
13502 if (EnumConstantInBoolContext)
13503 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13504
13505 // WebAssembly tables can't be used with logical operators.
13506 QualType LHSTy = LHS.get()->getType();
13507 QualType RHSTy = RHS.get()->getType();
13508 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13509 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13510 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13511 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13512 return InvalidOperands(Loc, LHS, RHS);
13513 }
13514
13515 // Diagnose cases where the user write a logical and/or but probably meant a
13516 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13517 // is a constant.
13518 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13519 !LHS.get()->getType()->isBooleanType() &&
13520 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13521 // Don't warn in macros or template instantiations.
13522 !Loc.isMacroID() && !inTemplateInstantiation()) {
13523 // If the RHS can be constant folded, and if it constant folds to something
13524 // that isn't 0 or 1 (which indicate a potential logical operation that
13525 // happened to fold to true/false) then warn.
13526 // Parens on the RHS are ignored.
13527 Expr::EvalResult EVResult;
13528 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13529 llvm::APSInt Result = EVResult.Val.getInt();
13530 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13531 !RHS.get()->getExprLoc().isMacroID()) ||
13532 (Result != 0 && Result != 1)) {
13533 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13534 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13535 // Suggest replacing the logical operator with the bitwise version
13536 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13537 << (Opc == BO_LAnd ? "&" : "|")
13540 Opc == BO_LAnd ? "&" : "|");
13541 if (Opc == BO_LAnd)
13542 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13543 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13546 RHS.get()->getEndLoc()));
13547 }
13548 }
13549 }
13550
13551 if (!Context.getLangOpts().CPlusPlus) {
13552 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13553 // not operate on the built-in scalar and vector float types.
13554 if (Context.getLangOpts().OpenCL &&
13555 Context.getLangOpts().OpenCLVersion < 120) {
13556 if (LHS.get()->getType()->isFloatingType() ||
13557 RHS.get()->getType()->isFloatingType())
13558 return InvalidOperands(Loc, LHS, RHS);
13559 }
13560
13561 LHS = UsualUnaryConversions(LHS.get());
13562 if (LHS.isInvalid())
13563 return QualType();
13564
13565 RHS = UsualUnaryConversions(RHS.get());
13566 if (RHS.isInvalid())
13567 return QualType();
13568
13569 if (!LHS.get()->getType()->isScalarType() ||
13570 !RHS.get()->getType()->isScalarType())
13571 return InvalidOperands(Loc, LHS, RHS);
13572
13573 return Context.IntTy;
13574 }
13575
13576 // The following is safe because we only use this method for
13577 // non-overloadable operands.
13578
13579 // C++ [expr.log.and]p1
13580 // C++ [expr.log.or]p1
13581 // The operands are both contextually converted to type bool.
13583 if (LHSRes.isInvalid()) {
13584 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13585 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13586 return ResultTy;
13587 }
13588 LHS = LHSRes;
13589
13591 if (RHSRes.isInvalid()) {
13592 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13593 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13594 return ResultTy;
13595 }
13596 RHS = RHSRes;
13597
13598 // C++ [expr.log.and]p2
13599 // C++ [expr.log.or]p2
13600 // The result is a bool.
13601 return Context.BoolTy;
13602}
13603
13604static bool IsReadonlyMessage(Expr *E, Sema &S) {
13605 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13606 if (!ME) return false;
13607 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13608 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13610 if (!Base) return false;
13611 return Base->getMethodDecl() != nullptr;
13612}
13613
13614/// Is the given expression (which must be 'const') a reference to a
13615/// variable which was originally non-const, but which has become
13616/// 'const' due to being captured within a block?
13619 assert(E->isLValue() && E->getType().isConstQualified());
13620 E = E->IgnoreParens();
13621
13622 // Must be a reference to a declaration from an enclosing scope.
13623 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13624 if (!DRE) return NCCK_None;
13626
13627 ValueDecl *Value = dyn_cast<ValueDecl>(DRE->getDecl());
13628
13629 // The declaration must be a value which is not declared 'const'.
13630 if (!Value || Value->getType().isConstQualified())
13631 return NCCK_None;
13632
13633 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
13634 if (Binding) {
13635 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13636 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13637 return NCCK_Lambda;
13638 }
13639
13640 VarDecl *Var = dyn_cast<VarDecl>(Value);
13641 if (!Var)
13642 return NCCK_None;
13643 if (Var->getType()->isReferenceType())
13644 return NCCK_None;
13645
13646 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13647
13648 // Decide whether the first capture was for a block or a lambda.
13649 DeclContext *DC = S.CurContext, *Prev = nullptr;
13650 // Decide whether the first capture was for a block or a lambda.
13651 while (DC) {
13652 // For init-capture, it is possible that the variable belongs to the
13653 // template pattern of the current context.
13654 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13655 if (Var->isInitCapture() &&
13656 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13657 break;
13658 if (DC == Var->getDeclContext())
13659 break;
13660 Prev = DC;
13661 DC = DC->getParent();
13662 }
13663 // Unless we have an init-capture, we've gone one step too far.
13664 if (!Var->isInitCapture())
13665 DC = Prev;
13666 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13667}
13668
13669static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13670 Ty = Ty.getNonReferenceType();
13671 if (IsDereference && Ty->isPointerType())
13672 Ty = Ty->getPointeeType();
13673 return !Ty.isConstQualified();
13674}
13675
13676// Update err_typecheck_assign_const and note_typecheck_assign_const
13677// when this enum is changed.
13678enum {
13684 ConstUnknown, // Keep as last element
13685};
13686
13687/// Emit the "read-only variable not assignable" error and print notes to give
13688/// more information about why the variable is not assignable, such as pointing
13689/// to the declaration of a const variable, showing that a method is const, or
13690/// that the function is returning a const reference.
13691static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13692 SourceLocation Loc) {
13693 SourceRange ExprRange = E->getSourceRange();
13694
13695 // Only emit one error on the first const found. All other consts will emit
13696 // a note to the error.
13697 bool DiagnosticEmitted = false;
13698
13699 // Track if the current expression is the result of a dereference, and if the
13700 // next checked expression is the result of a dereference.
13701 bool IsDereference = false;
13702 bool NextIsDereference = false;
13703
13704 // Loop to process MemberExpr chains.
13705 while (true) {
13706 IsDereference = NextIsDereference;
13707
13709 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13710 NextIsDereference = ME->isArrow();
13711 const ValueDecl *VD = ME->getMemberDecl();
13712 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13713 // Mutable fields can be modified even if the class is const.
13714 if (Field->isMutable()) {
13715 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13716 break;
13717 }
13718
13719 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13720 if (!DiagnosticEmitted) {
13721 S.Diag(Loc, diag::err_typecheck_assign_const)
13722 << ExprRange << ConstMember << false /*static*/ << Field
13723 << Field->getType();
13724 DiagnosticEmitted = true;
13725 }
13726 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13727 << ConstMember << false /*static*/ << Field << Field->getType()
13728 << Field->getSourceRange();
13729 }
13730 E = ME->getBase();
13731 continue;
13732 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13733 if (VDecl->getType().isConstQualified()) {
13734 if (!DiagnosticEmitted) {
13735 S.Diag(Loc, diag::err_typecheck_assign_const)
13736 << ExprRange << ConstMember << true /*static*/ << VDecl
13737 << VDecl->getType();
13738 DiagnosticEmitted = true;
13739 }
13740 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13741 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13742 << VDecl->getSourceRange();
13743 }
13744 // Static fields do not inherit constness from parents.
13745 break;
13746 }
13747 break; // End MemberExpr
13748 } else if (const ArraySubscriptExpr *ASE =
13749 dyn_cast<ArraySubscriptExpr>(E)) {
13750 E = ASE->getBase()->IgnoreParenImpCasts();
13751 continue;
13752 } else if (const ExtVectorElementExpr *EVE =
13753 dyn_cast<ExtVectorElementExpr>(E)) {
13754 E = EVE->getBase()->IgnoreParenImpCasts();
13755 continue;
13756 }
13757 break;
13758 }
13759
13760 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13761 // Function calls
13762 const FunctionDecl *FD = CE->getDirectCallee();
13763 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13764 if (!DiagnosticEmitted) {
13765 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13766 << ConstFunction << FD;
13767 DiagnosticEmitted = true;
13768 }
13770 diag::note_typecheck_assign_const)
13771 << ConstFunction << FD << FD->getReturnType()
13772 << FD->getReturnTypeSourceRange();
13773 }
13774 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13775 // Point to variable declaration.
13776 if (const ValueDecl *VD = DRE->getDecl()) {
13777 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13778 if (!DiagnosticEmitted) {
13779 S.Diag(Loc, diag::err_typecheck_assign_const)
13780 << ExprRange << ConstVariable << VD << VD->getType();
13781 DiagnosticEmitted = true;
13782 }
13783 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13784 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13785 }
13786 }
13787 } else if (isa<CXXThisExpr>(E)) {
13788 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13789 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13790 if (MD->isConst()) {
13791 if (!DiagnosticEmitted) {
13792 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13793 << ConstMethod << MD;
13794 DiagnosticEmitted = true;
13795 }
13796 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13797 << ConstMethod << MD << MD->getSourceRange();
13798 }
13799 }
13800 }
13801 }
13802
13803 if (DiagnosticEmitted)
13804 return;
13805
13806 // Can't determine a more specific message, so display the generic error.
13807 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13808}
13809
13815
13817 const RecordType *Ty,
13818 SourceLocation Loc, SourceRange Range,
13819 OriginalExprKind OEK,
13820 bool &DiagnosticEmitted) {
13821 std::vector<const RecordType *> RecordTypeList;
13822 RecordTypeList.push_back(Ty);
13823 unsigned NextToCheckIndex = 0;
13824 // We walk the record hierarchy breadth-first to ensure that we print
13825 // diagnostics in field nesting order.
13826 while (RecordTypeList.size() > NextToCheckIndex) {
13827 bool IsNested = NextToCheckIndex > 0;
13828 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
13829 ->getOriginalDecl()
13831 ->fields()) {
13832 // First, check every field for constness.
13833 QualType FieldTy = Field->getType();
13834 if (FieldTy.isConstQualified()) {
13835 if (!DiagnosticEmitted) {
13836 S.Diag(Loc, diag::err_typecheck_assign_const)
13837 << Range << NestedConstMember << OEK << VD
13838 << IsNested << Field;
13839 DiagnosticEmitted = true;
13840 }
13841 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13842 << NestedConstMember << IsNested << Field
13843 << FieldTy << Field->getSourceRange();
13844 }
13845
13846 // Then we append it to the list to check next in order.
13847 FieldTy = FieldTy.getCanonicalType();
13848 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
13849 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13850 RecordTypeList.push_back(FieldRecTy);
13851 }
13852 }
13853 ++NextToCheckIndex;
13854 }
13855}
13856
13857/// Emit an error for the case where a record we are trying to assign to has a
13858/// const-qualified field somewhere in its hierarchy.
13859static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13860 SourceLocation Loc) {
13861 QualType Ty = E->getType();
13862 assert(Ty->isRecordType() && "lvalue was not record?");
13863 SourceRange Range = E->getSourceRange();
13864 const auto *RTy = Ty->getAsCanonical<RecordType>();
13865 bool DiagEmitted = false;
13866
13867 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13868 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13869 Range, OEK_Member, DiagEmitted);
13870 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13871 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13872 Range, OEK_Variable, DiagEmitted);
13873 else
13874 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13875 Range, OEK_LValue, DiagEmitted);
13876 if (!DiagEmitted)
13877 DiagnoseConstAssignment(S, E, Loc);
13878}
13879
13880/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13881/// emit an error and return true. If so, return false.
13883 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13884
13886
13887 SourceLocation OrigLoc = Loc;
13889 &Loc);
13890 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13892 if (IsLV == Expr::MLV_Valid)
13893 return false;
13894
13895 unsigned DiagID = 0;
13896 bool NeedType = false;
13897 switch (IsLV) { // C99 6.5.16p2
13899 // Use a specialized diagnostic when we're assigning to an object
13900 // from an enclosing function or block.
13902 if (NCCK == NCCK_Block)
13903 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13904 else
13905 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13906 break;
13907 }
13908
13909 // In ARC, use some specialized diagnostics for occasions where we
13910 // infer 'const'. These are always pseudo-strong variables.
13911 if (S.getLangOpts().ObjCAutoRefCount) {
13912 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13913 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13914 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13915
13916 // Use the normal diagnostic if it's pseudo-__strong but the
13917 // user actually wrote 'const'.
13918 if (var->isARCPseudoStrong() &&
13919 (!var->getTypeSourceInfo() ||
13920 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13921 // There are three pseudo-strong cases:
13922 // - self
13923 ObjCMethodDecl *method = S.getCurMethodDecl();
13924 if (method && var == method->getSelfDecl()) {
13925 DiagID = method->isClassMethod()
13926 ? diag::err_typecheck_arc_assign_self_class_method
13927 : diag::err_typecheck_arc_assign_self;
13928
13929 // - Objective-C externally_retained attribute.
13930 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13931 isa<ParmVarDecl>(var)) {
13932 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13933
13934 // - fast enumeration variables
13935 } else {
13936 DiagID = diag::err_typecheck_arr_assign_enumeration;
13937 }
13938
13939 SourceRange Assign;
13940 if (Loc != OrigLoc)
13941 Assign = SourceRange(OrigLoc, OrigLoc);
13942 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13943 // We need to preserve the AST regardless, so migration tool
13944 // can do its job.
13945 return false;
13946 }
13947 }
13948 }
13949
13950 // If none of the special cases above are triggered, then this is a
13951 // simple const assignment.
13952 if (DiagID == 0) {
13953 DiagnoseConstAssignment(S, E, Loc);
13954 return true;
13955 }
13956
13957 break;
13959 DiagnoseConstAssignment(S, E, Loc);
13960 return true;
13963 return true;
13966 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13967 NeedType = true;
13968 break;
13970 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13971 NeedType = true;
13972 break;
13974 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13975 break;
13976 case Expr::MLV_Valid:
13977 llvm_unreachable("did not take early return for MLV_Valid");
13981 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13982 break;
13985 return S.RequireCompleteType(Loc, E->getType(),
13986 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13988 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13989 break;
13991 llvm_unreachable("readonly properties should be processed differently");
13993 DiagID = diag::err_readonly_message_assignment;
13994 break;
13996 DiagID = diag::err_no_subobject_property_setting;
13997 break;
13998 }
13999
14000 SourceRange Assign;
14001 if (Loc != OrigLoc)
14002 Assign = SourceRange(OrigLoc, OrigLoc);
14003 if (NeedType)
14004 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14005 else
14006 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14007 return true;
14008}
14009
14010static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14011 SourceLocation Loc,
14012 Sema &Sema) {
14014 return;
14016 return;
14017 if (Loc.isInvalid() || Loc.isMacroID())
14018 return;
14019 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14020 return;
14021
14022 // C / C++ fields
14023 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14024 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14025 if (ML && MR) {
14026 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14027 return;
14028 const ValueDecl *LHSDecl =
14030 const ValueDecl *RHSDecl =
14032 if (LHSDecl != RHSDecl)
14033 return;
14034 if (LHSDecl->getType().isVolatileQualified())
14035 return;
14036 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14037 if (RefTy->getPointeeType().isVolatileQualified())
14038 return;
14039
14040 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14041 }
14042
14043 // Objective-C instance variables
14044 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14045 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14046 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14047 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14048 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14049 if (RL && RR && RL->getDecl() == RR->getDecl())
14050 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14051 }
14052}
14053
14054// C99 6.5.16.1
14056 SourceLocation Loc,
14057 QualType CompoundType,
14058 BinaryOperatorKind Opc) {
14059 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14060
14061 // Verify that LHS is a modifiable lvalue, and emit error if not.
14062 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14063 return QualType();
14064
14065 QualType LHSType = LHSExpr->getType();
14066 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14067 CompoundType;
14068
14069 if (RHS.isUsable()) {
14070 // Even if this check fails don't return early to allow the best
14071 // possible error recovery and to allow any subsequent diagnostics to
14072 // work.
14073 const ValueDecl *Assignee = nullptr;
14074 bool ShowFullyQualifiedAssigneeName = false;
14075 // In simple cases describe what is being assigned to
14076 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14077 Assignee = DR->getDecl();
14078 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14079 Assignee = ME->getMemberDecl();
14080 ShowFullyQualifiedAssigneeName = true;
14081 }
14082
14084 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14085 ShowFullyQualifiedAssigneeName);
14086 }
14087
14088 // OpenCL v1.2 s6.1.1.1 p2:
14089 // The half data type can only be used to declare a pointer to a buffer that
14090 // contains half values
14091 if (getLangOpts().OpenCL &&
14092 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14093 LHSType->isHalfType()) {
14094 Diag(Loc, diag::err_opencl_half_load_store) << 1
14095 << LHSType.getUnqualifiedType();
14096 return QualType();
14097 }
14098
14099 // WebAssembly tables can't be used on RHS of an assignment expression.
14100 if (RHSType->isWebAssemblyTableType()) {
14101 Diag(Loc, diag::err_wasm_table_art) << 0;
14102 return QualType();
14103 }
14104
14105 AssignConvertType ConvTy;
14106 if (CompoundType.isNull()) {
14107 Expr *RHSCheck = RHS.get();
14108
14109 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14110
14111 QualType LHSTy(LHSType);
14112 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14113 if (RHS.isInvalid())
14114 return QualType();
14115 // Special case of NSObject attributes on c-style pointer types.
14117 ((Context.isObjCNSObjectType(LHSType) &&
14118 RHSType->isObjCObjectPointerType()) ||
14119 (Context.isObjCNSObjectType(RHSType) &&
14120 LHSType->isObjCObjectPointerType())))
14122
14123 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14124 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14125
14126 // If the RHS is a unary plus or minus, check to see if they = and + are
14127 // right next to each other. If so, the user may have typo'd "x =+ 4"
14128 // instead of "x += 4".
14129 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14130 RHSCheck = ICE->getSubExpr();
14131 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14132 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14133 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14134 // Only if the two operators are exactly adjacent.
14135 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14136 // And there is a space or other character before the subexpr of the
14137 // unary +/-. We don't want to warn on "x=-1".
14138 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14139 UO->getSubExpr()->getBeginLoc().isFileID()) {
14140 Diag(Loc, diag::warn_not_compound_assign)
14141 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14142 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14143 }
14144 }
14145
14146 if (IsAssignConvertCompatible(ConvTy)) {
14147 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14148 // Warn about retain cycles where a block captures the LHS, but
14149 // not if the LHS is a simple variable into which the block is
14150 // being stored...unless that variable can be captured by reference!
14151 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14152 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14153 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14154 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14155 }
14156
14157 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14159 // It is safe to assign a weak reference into a strong variable.
14160 // Although this code can still have problems:
14161 // id x = self.weakProp;
14162 // id y = self.weakProp;
14163 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14164 // paths through the function. This should be revisited if
14165 // -Wrepeated-use-of-weak is made flow-sensitive.
14166 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14167 // variable, which will be valid for the current autorelease scope.
14168 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14169 RHS.get()->getBeginLoc()))
14171
14172 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14173 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14174 }
14175 }
14176 } else {
14177 // Compound assignment "x += y"
14178 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14179 }
14180
14181 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14183 return QualType();
14184
14185 CheckForNullPointerDereference(*this, LHSExpr);
14186
14187 AssignedEntity AE{LHSExpr};
14188 checkAssignmentLifetime(*this, AE, RHS.get());
14189
14190 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14191 if (CompoundType.isNull()) {
14192 // C++2a [expr.ass]p5:
14193 // A simple-assignment whose left operand is of a volatile-qualified
14194 // type is deprecated unless the assignment is either a discarded-value
14195 // expression or an unevaluated operand
14196 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14197 }
14198 }
14199
14200 // C11 6.5.16p3: The type of an assignment expression is the type of the
14201 // left operand would have after lvalue conversion.
14202 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14203 // qualified type, the value has the unqualified version of the type of the
14204 // lvalue; additionally, if the lvalue has atomic type, the value has the
14205 // non-atomic version of the type of the lvalue.
14206 // C++ 5.17p1: the type of the assignment expression is that of its left
14207 // operand.
14208 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14209}
14210
14211// Scenarios to ignore if expression E is:
14212// 1. an explicit cast expression into void
14213// 2. a function call expression that returns void
14214static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14215 E = E->IgnoreParens();
14216
14217 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14218 if (CE->getCastKind() == CK_ToVoid) {
14219 return true;
14220 }
14221
14222 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14223 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14224 CE->getSubExpr()->getType()->isDependentType()) {
14225 return true;
14226 }
14227 }
14228
14229 if (const auto *CE = dyn_cast<CallExpr>(E))
14230 return CE->getCallReturnType(Context)->isVoidType();
14231 return false;
14232}
14233
14235 // No warnings in macros
14236 if (Loc.isMacroID())
14237 return;
14238
14239 // Don't warn in template instantiations.
14241 return;
14242
14243 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14244 // instead, skip more than needed, then call back into here with the
14245 // CommaVisitor in SemaStmt.cpp.
14246 // The listed locations are the initialization and increment portions
14247 // of a for loop. The additional checks are on the condition of
14248 // if statements, do/while loops, and for loops.
14249 // Differences in scope flags for C89 mode requires the extra logic.
14250 const unsigned ForIncrementFlags =
14251 getLangOpts().C99 || getLangOpts().CPlusPlus
14254 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14255 const unsigned ScopeFlags = getCurScope()->getFlags();
14256 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14257 (ScopeFlags & ForInitFlags) == ForInitFlags)
14258 return;
14259
14260 // If there are multiple comma operators used together, get the RHS of the
14261 // of the comma operator as the LHS.
14262 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14263 if (BO->getOpcode() != BO_Comma)
14264 break;
14265 LHS = BO->getRHS();
14266 }
14267
14268 // Only allow some expressions on LHS to not warn.
14269 if (IgnoreCommaOperand(LHS, Context))
14270 return;
14271
14272 Diag(Loc, diag::warn_comma_operator);
14273 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14274 << LHS->getSourceRange()
14276 LangOpts.CPlusPlus ? "static_cast<void>("
14277 : "(void)(")
14278 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14279 ")");
14280}
14281
14282// C99 6.5.17
14284 SourceLocation Loc) {
14285 LHS = S.CheckPlaceholderExpr(LHS.get());
14286 RHS = S.CheckPlaceholderExpr(RHS.get());
14287 if (LHS.isInvalid() || RHS.isInvalid())
14288 return QualType();
14289
14290 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14291 // operands, but not unary promotions.
14292 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14293
14294 // So we treat the LHS as a ignored value, and in C++ we allow the
14295 // containing site to determine what should be done with the RHS.
14296 LHS = S.IgnoredValueConversions(LHS.get());
14297 if (LHS.isInvalid())
14298 return QualType();
14299
14300 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14301
14302 if (!S.getLangOpts().CPlusPlus) {
14304 if (RHS.isInvalid())
14305 return QualType();
14306 if (!RHS.get()->getType()->isVoidType())
14307 S.RequireCompleteType(Loc, RHS.get()->getType(),
14308 diag::err_incomplete_type);
14309 }
14310
14311 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14312 S.DiagnoseCommaOperator(LHS.get(), Loc);
14313
14314 return RHS.get()->getType();
14315}
14316
14317/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14318/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14321 ExprObjectKind &OK,
14322 SourceLocation OpLoc, bool IsInc,
14323 bool IsPrefix) {
14324 QualType ResType = Op->getType();
14325 // Atomic types can be used for increment / decrement where the non-atomic
14326 // versions can, so ignore the _Atomic() specifier for the purpose of
14327 // checking.
14328 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14329 ResType = ResAtomicType->getValueType();
14330
14331 assert(!ResType.isNull() && "no type for increment/decrement expression");
14332
14333 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14334 // Decrement of bool is not allowed.
14335 if (!IsInc) {
14336 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14337 return QualType();
14338 }
14339 // Increment of bool sets it to true, but is deprecated.
14340 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14341 : diag::warn_increment_bool)
14342 << Op->getSourceRange();
14343 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14344 // Error on enum increments and decrements in C++ mode
14345 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14346 return QualType();
14347 } else if (ResType->isRealType()) {
14348 // OK!
14349 } else if (ResType->isPointerType()) {
14350 // C99 6.5.2.4p2, 6.5.6p2
14351 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14352 return QualType();
14353 } else if (ResType->isObjCObjectPointerType()) {
14354 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14355 // Otherwise, we just need a complete type.
14356 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14357 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14358 return QualType();
14359 } else if (ResType->isAnyComplexType()) {
14360 // C99 does not support ++/-- on complex types, we allow as an extension.
14361 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14362 : diag::ext_c2y_increment_complex)
14363 << IsInc << Op->getSourceRange();
14364 } else if (ResType->isPlaceholderType()) {
14366 if (PR.isInvalid()) return QualType();
14367 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14368 IsInc, IsPrefix);
14369 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14370 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14371 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14372 (ResType->castAs<VectorType>()->getVectorKind() !=
14374 // The z vector extensions allow ++ and -- for non-bool vectors.
14375 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14376 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14377 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14378 } else {
14379 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14380 << ResType << int(IsInc) << Op->getSourceRange();
14381 return QualType();
14382 }
14383 // At this point, we know we have a real, complex or pointer type.
14384 // Now make sure the operand is a modifiable lvalue.
14385 if (CheckForModifiableLvalue(Op, OpLoc, S))
14386 return QualType();
14387 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14388 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14389 // An operand with volatile-qualified type is deprecated
14390 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14391 << IsInc << ResType;
14392 }
14393 // In C++, a prefix increment is the same type as the operand. Otherwise
14394 // (in C or with postfix), the increment is the unqualified type of the
14395 // operand.
14396 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14397 VK = VK_LValue;
14398 OK = Op->getObjectKind();
14399 return ResType;
14400 } else {
14401 VK = VK_PRValue;
14402 return ResType.getUnqualifiedType();
14403 }
14404}
14405
14406/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14407/// This routine allows us to typecheck complex/recursive expressions
14408/// where the declaration is needed for type checking. We only need to
14409/// handle cases when the expression references a function designator
14410/// or is an lvalue. Here are some examples:
14411/// - &(x) => x
14412/// - &*****f => f for f a function designator.
14413/// - &s.xx => s
14414/// - &s.zz[1].yy -> s, if zz is an array
14415/// - *(x + 1) -> x, if x is an array
14416/// - &"123"[2] -> 0
14417/// - & __real__ x -> x
14418///
14419/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14420/// members.
14422 switch (E->getStmtClass()) {
14423 case Stmt::DeclRefExprClass:
14424 return cast<DeclRefExpr>(E)->getDecl();
14425 case Stmt::MemberExprClass:
14426 // If this is an arrow operator, the address is an offset from
14427 // the base's value, so the object the base refers to is
14428 // irrelevant.
14429 if (cast<MemberExpr>(E)->isArrow())
14430 return nullptr;
14431 // Otherwise, the expression refers to a part of the base
14432 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14433 case Stmt::ArraySubscriptExprClass: {
14434 // FIXME: This code shouldn't be necessary! We should catch the implicit
14435 // promotion of register arrays earlier.
14436 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14437 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14438 if (ICE->getSubExpr()->getType()->isArrayType())
14439 return getPrimaryDecl(ICE->getSubExpr());
14440 }
14441 return nullptr;
14442 }
14443 case Stmt::UnaryOperatorClass: {
14445
14446 switch(UO->getOpcode()) {
14447 case UO_Real:
14448 case UO_Imag:
14449 case UO_Extension:
14450 return getPrimaryDecl(UO->getSubExpr());
14451 default:
14452 return nullptr;
14453 }
14454 }
14455 case Stmt::ParenExprClass:
14456 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14457 case Stmt::ImplicitCastExprClass:
14458 // If the result of an implicit cast is an l-value, we care about
14459 // the sub-expression; otherwise, the result here doesn't matter.
14460 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14461 case Stmt::CXXUuidofExprClass:
14462 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14463 default:
14464 return nullptr;
14465 }
14466}
14467
14468namespace {
14469enum {
14470 AO_Bit_Field = 0,
14471 AO_Vector_Element = 1,
14472 AO_Property_Expansion = 2,
14473 AO_Register_Variable = 3,
14474 AO_Matrix_Element = 4,
14475 AO_No_Error = 5
14476};
14477}
14478/// Diagnose invalid operand for address of operations.
14479///
14480/// \param Type The type of operand which cannot have its address taken.
14482 Expr *E, unsigned Type) {
14483 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14484}
14485
14487 const Expr *Op,
14488 const CXXMethodDecl *MD) {
14489 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14490
14491 if (Op != DRE)
14492 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14493 << Op->getSourceRange();
14494
14495 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14496 if (isa<CXXDestructorDecl>(MD))
14497 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14498 << DRE->getSourceRange();
14499
14500 if (DRE->getQualifier())
14501 return false;
14502
14503 if (MD->getParent()->getName().empty())
14504 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14505 << DRE->getSourceRange();
14506
14507 SmallString<32> Str;
14508 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14509 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14510 << DRE->getSourceRange()
14511 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14512}
14513
14515 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14516 if (PTy->getKind() == BuiltinType::Overload) {
14517 Expr *E = OrigOp.get()->IgnoreParens();
14518 if (!isa<OverloadExpr>(E)) {
14519 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14520 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14521 << OrigOp.get()->getSourceRange();
14522 return QualType();
14523 }
14524
14528 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14529 << OrigOp.get()->getSourceRange();
14530 return QualType();
14531 }
14532
14533 return Context.OverloadTy;
14534 }
14535
14536 if (PTy->getKind() == BuiltinType::UnknownAny)
14537 return Context.UnknownAnyTy;
14538
14539 if (PTy->getKind() == BuiltinType::BoundMember) {
14540 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14541 << OrigOp.get()->getSourceRange();
14542 return QualType();
14543 }
14544
14545 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14546 if (OrigOp.isInvalid()) return QualType();
14547 }
14548
14549 if (OrigOp.get()->isTypeDependent())
14550 return Context.DependentTy;
14551
14552 assert(!OrigOp.get()->hasPlaceholderType());
14553
14554 // Make sure to ignore parentheses in subsequent checks
14555 Expr *op = OrigOp.get()->IgnoreParens();
14556
14557 // In OpenCL captures for blocks called as lambda functions
14558 // are located in the private address space. Blocks used in
14559 // enqueue_kernel can be located in a different address space
14560 // depending on a vendor implementation. Thus preventing
14561 // taking an address of the capture to avoid invalid AS casts.
14562 if (LangOpts.OpenCL) {
14563 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14564 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14565 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14566 return QualType();
14567 }
14568 }
14569
14570 if (getLangOpts().C99) {
14571 // Implement C99-only parts of addressof rules.
14572 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14573 if (uOp->getOpcode() == UO_Deref)
14574 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14575 // (assuming the deref expression is valid).
14576 return uOp->getSubExpr()->getType();
14577 }
14578 // Technically, there should be a check for array subscript
14579 // expressions here, but the result of one is always an lvalue anyway.
14580 }
14581 ValueDecl *dcl = getPrimaryDecl(op);
14582
14583 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14584 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14585 op->getBeginLoc()))
14586 return QualType();
14587
14589 unsigned AddressOfError = AO_No_Error;
14590
14591 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14592 bool sfinae = (bool)isSFINAEContext();
14593 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14594 : diag::ext_typecheck_addrof_temporary)
14595 << op->getType() << op->getSourceRange();
14596 if (sfinae)
14597 return QualType();
14598 // Materialize the temporary as an lvalue so that we can take its address.
14599 OrigOp = op =
14600 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14601 } else if (isa<ObjCSelectorExpr>(op)) {
14602 return Context.getPointerType(op->getType());
14603 } else if (lval == Expr::LV_MemberFunction) {
14604 // If it's an instance method, make a member pointer.
14605 // The expression must have exactly the form &A::foo.
14606
14607 // If the underlying expression isn't a decl ref, give up.
14608 if (!isa<DeclRefExpr>(op)) {
14609 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14610 << OrigOp.get()->getSourceRange();
14611 return QualType();
14612 }
14613 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14615
14616 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14617 QualType MPTy = Context.getMemberPointerType(
14618 op->getType(), DRE->getQualifier(), MD->getParent());
14619
14620 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14621 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14622 // When pointer authentication is enabled, argument and return types of
14623 // vitual member functions must be complete. This is because vitrual
14624 // member function pointers are implemented using virtual dispatch
14625 // thunks and the thunks cannot be emitted if the argument or return
14626 // types are incomplete.
14627 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14628 SourceLocation DeclRefLoc,
14629 SourceLocation RetArgTypeLoc) {
14630 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14631 Diag(DeclRefLoc,
14632 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14633 Diag(RetArgTypeLoc,
14634 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14635 << T;
14636 return true;
14637 }
14638 return false;
14639 };
14640 QualType RetTy = MD->getReturnType();
14641 bool IsIncomplete =
14642 !RetTy->isVoidType() &&
14643 ReturnOrParamTypeIsIncomplete(
14644 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14645 for (auto *PVD : MD->parameters())
14646 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14647 PVD->getBeginLoc());
14648 if (IsIncomplete)
14649 return QualType();
14650 }
14651
14652 // Under the MS ABI, lock down the inheritance model now.
14653 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14654 (void)isCompleteType(OpLoc, MPTy);
14655 return MPTy;
14656 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14657 // C99 6.5.3.2p1
14658 // The operand must be either an l-value or a function designator
14659 if (!op->getType()->isFunctionType()) {
14660 // Use a special diagnostic for loads from property references.
14661 if (isa<PseudoObjectExpr>(op)) {
14662 AddressOfError = AO_Property_Expansion;
14663 } else {
14664 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14665 << op->getType() << op->getSourceRange();
14666 return QualType();
14667 }
14668 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14669 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14670 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14671 }
14672
14673 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14674 // The operand cannot be a bit-field
14675 AddressOfError = AO_Bit_Field;
14676 } else if (op->getObjectKind() == OK_VectorComponent) {
14677 // The operand cannot be an element of a vector
14678 AddressOfError = AO_Vector_Element;
14679 } else if (op->getObjectKind() == OK_MatrixComponent) {
14680 // The operand cannot be an element of a matrix.
14681 AddressOfError = AO_Matrix_Element;
14682 } else if (dcl) { // C99 6.5.3.2p1
14683 // We have an lvalue with a decl. Make sure the decl is not declared
14684 // with the register storage-class specifier.
14685 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14686 // in C++ it is not error to take address of a register
14687 // variable (c++03 7.1.1P3)
14688 if (vd->getStorageClass() == SC_Register &&
14690 AddressOfError = AO_Register_Variable;
14691 }
14692 } else if (isa<MSPropertyDecl>(dcl)) {
14693 AddressOfError = AO_Property_Expansion;
14694 } else if (isa<FunctionTemplateDecl>(dcl)) {
14695 return Context.OverloadTy;
14696 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14697 // Okay: we can take the address of a field.
14698 // Could be a pointer to member, though, if there is an explicit
14699 // scope qualifier for the class.
14700
14701 // [C++26] [expr.prim.id.general]
14702 // If an id-expression E denotes a non-static non-type member
14703 // of some class C [...] and if E is a qualified-id, E is
14704 // not the un-parenthesized operand of the unary & operator [...]
14705 // the id-expression is transformed into a class member access expression.
14706 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
14707 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
14708 DeclContext *Ctx = dcl->getDeclContext();
14709 if (Ctx && Ctx->isRecord()) {
14710 if (dcl->getType()->isReferenceType()) {
14711 Diag(OpLoc,
14712 diag::err_cannot_form_pointer_to_member_of_reference_type)
14713 << dcl->getDeclName() << dcl->getType();
14714 return QualType();
14715 }
14716
14717 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14718 Ctx = Ctx->getParent();
14719
14720 QualType MPTy = Context.getMemberPointerType(
14721 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
14722 // Under the MS ABI, lock down the inheritance model now.
14723 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14724 (void)isCompleteType(OpLoc, MPTy);
14725 return MPTy;
14726 }
14727 }
14731 llvm_unreachable("Unknown/unexpected decl type");
14732 }
14733
14734 if (AddressOfError != AO_No_Error) {
14735 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14736 return QualType();
14737 }
14738
14739 if (lval == Expr::LV_IncompleteVoidType) {
14740 // Taking the address of a void variable is technically illegal, but we
14741 // allow it in cases which are otherwise valid.
14742 // Example: "extern void x; void* y = &x;".
14743 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14744 }
14745
14746 // If the operand has type "type", the result has type "pointer to type".
14747 if (op->getType()->isObjCObjectType())
14748 return Context.getObjCObjectPointerType(op->getType());
14749
14750 // Cannot take the address of WebAssembly references or tables.
14751 if (Context.getTargetInfo().getTriple().isWasm()) {
14752 QualType OpTy = op->getType();
14753 if (OpTy.isWebAssemblyReferenceType()) {
14754 Diag(OpLoc, diag::err_wasm_ca_reference)
14755 << 1 << OrigOp.get()->getSourceRange();
14756 return QualType();
14757 }
14758 if (OpTy->isWebAssemblyTableType()) {
14759 Diag(OpLoc, diag::err_wasm_table_pr)
14760 << 1 << OrigOp.get()->getSourceRange();
14761 return QualType();
14762 }
14763 }
14764
14765 CheckAddressOfPackedMember(op);
14766
14767 return Context.getPointerType(op->getType());
14768}
14769
14770static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14771 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14772 if (!DRE)
14773 return;
14774 const Decl *D = DRE->getDecl();
14775 if (!D)
14776 return;
14777 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14778 if (!Param)
14779 return;
14780 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14781 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14782 return;
14783 if (FunctionScopeInfo *FD = S.getCurFunction())
14784 FD->ModifiedNonNullParams.insert(Param);
14785}
14786
14787/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14789 SourceLocation OpLoc,
14790 bool IsAfterAmp = false) {
14791 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14792 if (ConvResult.isInvalid())
14793 return QualType();
14794 Op = ConvResult.get();
14795 QualType OpTy = Op->getType();
14796 QualType Result;
14797
14799 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14800 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14801 Op->getSourceRange());
14802 }
14803
14804 if (const PointerType *PT = OpTy->getAs<PointerType>())
14805 {
14806 Result = PT->getPointeeType();
14807 }
14808 else if (const ObjCObjectPointerType *OPT =
14810 Result = OPT->getPointeeType();
14811 else {
14813 if (PR.isInvalid()) return QualType();
14814 if (PR.get() != Op)
14815 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14816 }
14817
14818 if (Result.isNull()) {
14819 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14820 << OpTy << Op->getSourceRange();
14821 return QualType();
14822 }
14823
14824 if (Result->isVoidType()) {
14825 // C++ [expr.unary.op]p1:
14826 // [...] the expression to which [the unary * operator] is applied shall
14827 // be a pointer to an object type, or a pointer to a function type
14828 LangOptions LO = S.getLangOpts();
14829 if (LO.CPlusPlus)
14830 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14831 << OpTy << Op->getSourceRange();
14832 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14833 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14834 << OpTy << Op->getSourceRange();
14835 }
14836
14837 // Dereferences are usually l-values...
14838 VK = VK_LValue;
14839
14840 // ...except that certain expressions are never l-values in C.
14841 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14842 VK = VK_PRValue;
14843
14844 return Result;
14845}
14846
14847BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14849 switch (Kind) {
14850 default: llvm_unreachable("Unknown binop!");
14851 case tok::periodstar: Opc = BO_PtrMemD; break;
14852 case tok::arrowstar: Opc = BO_PtrMemI; break;
14853 case tok::star: Opc = BO_Mul; break;
14854 case tok::slash: Opc = BO_Div; break;
14855 case tok::percent: Opc = BO_Rem; break;
14856 case tok::plus: Opc = BO_Add; break;
14857 case tok::minus: Opc = BO_Sub; break;
14858 case tok::lessless: Opc = BO_Shl; break;
14859 case tok::greatergreater: Opc = BO_Shr; break;
14860 case tok::lessequal: Opc = BO_LE; break;
14861 case tok::less: Opc = BO_LT; break;
14862 case tok::greaterequal: Opc = BO_GE; break;
14863 case tok::greater: Opc = BO_GT; break;
14864 case tok::exclaimequal: Opc = BO_NE; break;
14865 case tok::equalequal: Opc = BO_EQ; break;
14866 case tok::spaceship: Opc = BO_Cmp; break;
14867 case tok::amp: Opc = BO_And; break;
14868 case tok::caret: Opc = BO_Xor; break;
14869 case tok::pipe: Opc = BO_Or; break;
14870 case tok::ampamp: Opc = BO_LAnd; break;
14871 case tok::pipepipe: Opc = BO_LOr; break;
14872 case tok::equal: Opc = BO_Assign; break;
14873 case tok::starequal: Opc = BO_MulAssign; break;
14874 case tok::slashequal: Opc = BO_DivAssign; break;
14875 case tok::percentequal: Opc = BO_RemAssign; break;
14876 case tok::plusequal: Opc = BO_AddAssign; break;
14877 case tok::minusequal: Opc = BO_SubAssign; break;
14878 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14879 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14880 case tok::ampequal: Opc = BO_AndAssign; break;
14881 case tok::caretequal: Opc = BO_XorAssign; break;
14882 case tok::pipeequal: Opc = BO_OrAssign; break;
14883 case tok::comma: Opc = BO_Comma; break;
14884 }
14885 return Opc;
14886}
14887
14889 tok::TokenKind Kind) {
14891 switch (Kind) {
14892 default: llvm_unreachable("Unknown unary op!");
14893 case tok::plusplus: Opc = UO_PreInc; break;
14894 case tok::minusminus: Opc = UO_PreDec; break;
14895 case tok::amp: Opc = UO_AddrOf; break;
14896 case tok::star: Opc = UO_Deref; break;
14897 case tok::plus: Opc = UO_Plus; break;
14898 case tok::minus: Opc = UO_Minus; break;
14899 case tok::tilde: Opc = UO_Not; break;
14900 case tok::exclaim: Opc = UO_LNot; break;
14901 case tok::kw___real: Opc = UO_Real; break;
14902 case tok::kw___imag: Opc = UO_Imag; break;
14903 case tok::kw___extension__: Opc = UO_Extension; break;
14904 }
14905 return Opc;
14906}
14907
14908const FieldDecl *
14910 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14911 // common for setters.
14912 // struct A {
14913 // int X;
14914 // -void setX(int X) { X = X; }
14915 // +void setX(int X) { this->X = X; }
14916 // };
14917
14918 // Only consider parameters for self assignment fixes.
14919 if (!isa<ParmVarDecl>(SelfAssigned))
14920 return nullptr;
14921 const auto *Method =
14922 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14923 if (!Method)
14924 return nullptr;
14925
14926 const CXXRecordDecl *Parent = Method->getParent();
14927 // In theory this is fixable if the lambda explicitly captures this, but
14928 // that's added complexity that's rarely going to be used.
14929 if (Parent->isLambda())
14930 return nullptr;
14931
14932 // FIXME: Use an actual Lookup operation instead of just traversing fields
14933 // in order to get base class fields.
14934 auto Field =
14935 llvm::find_if(Parent->fields(),
14936 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14937 return F->getDeclName() == Name;
14938 });
14939 return (Field != Parent->field_end()) ? *Field : nullptr;
14940}
14941
14942/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14943/// This warning suppressed in the event of macro expansions.
14944static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14945 SourceLocation OpLoc, bool IsBuiltin) {
14947 return;
14948 if (S.isUnevaluatedContext())
14949 return;
14950 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14951 return;
14952 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14953 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14954 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14955 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14956 if (!LHSDeclRef || !RHSDeclRef ||
14957 LHSDeclRef->getLocation().isMacroID() ||
14958 RHSDeclRef->getLocation().isMacroID())
14959 return;
14960 const ValueDecl *LHSDecl =
14961 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14962 const ValueDecl *RHSDecl =
14963 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14964 if (LHSDecl != RHSDecl)
14965 return;
14966 if (LHSDecl->getType().isVolatileQualified())
14967 return;
14968 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14969 if (RefTy->getPointeeType().isVolatileQualified())
14970 return;
14971
14972 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14973 : diag::warn_self_assignment_overloaded)
14974 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14975 << RHSExpr->getSourceRange();
14976 if (const FieldDecl *SelfAssignField =
14978 Diag << 1 << SelfAssignField
14979 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14980 else
14981 Diag << 0;
14982}
14983
14984/// Check if a bitwise-& is performed on an Objective-C pointer. This
14985/// is usually indicative of introspection within the Objective-C pointer.
14987 SourceLocation OpLoc) {
14988 if (!S.getLangOpts().ObjC)
14989 return;
14990
14991 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14992 const Expr *LHS = L.get();
14993 const Expr *RHS = R.get();
14994
14996 ObjCPointerExpr = LHS;
14997 OtherExpr = RHS;
14998 }
14999 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15000 ObjCPointerExpr = RHS;
15001 OtherExpr = LHS;
15002 }
15003
15004 // This warning is deliberately made very specific to reduce false
15005 // positives with logic that uses '&' for hashing. This logic mainly
15006 // looks for code trying to introspect into tagged pointers, which
15007 // code should generally never do.
15008 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15009 unsigned Diag = diag::warn_objc_pointer_masking;
15010 // Determine if we are introspecting the result of performSelectorXXX.
15011 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15012 // Special case messages to -performSelector and friends, which
15013 // can return non-pointer values boxed in a pointer value.
15014 // Some clients may wish to silence warnings in this subcase.
15015 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15016 Selector S = ME->getSelector();
15017 StringRef SelArg0 = S.getNameForSlot(0);
15018 if (SelArg0.starts_with("performSelector"))
15019 Diag = diag::warn_objc_pointer_masking_performSelector;
15020 }
15021
15022 S.Diag(OpLoc, Diag)
15023 << ObjCPointerExpr->getSourceRange();
15024 }
15025}
15026
15027// This helper function promotes a binary operator's operands (which are of a
15028// half vector type) to a vector of floats and then truncates the result to
15029// a vector of either half or short.
15031 BinaryOperatorKind Opc, QualType ResultTy,
15033 bool IsCompAssign, SourceLocation OpLoc,
15034 FPOptionsOverride FPFeatures) {
15035 auto &Context = S.getASTContext();
15036 assert((isVector(ResultTy, Context.HalfTy) ||
15037 isVector(ResultTy, Context.ShortTy)) &&
15038 "Result must be a vector of half or short");
15039 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15040 isVector(RHS.get()->getType(), Context.HalfTy) &&
15041 "both operands expected to be a half vector");
15042
15043 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15044 QualType BinOpResTy = RHS.get()->getType();
15045
15046 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15047 // change BinOpResTy to a vector of ints.
15048 if (isVector(ResultTy, Context.ShortTy))
15049 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15050
15051 if (IsCompAssign)
15052 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15053 ResultTy, VK, OK, OpLoc, FPFeatures,
15054 BinOpResTy, BinOpResTy);
15055
15056 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15057 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15058 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15059 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15060}
15061
15062/// Returns true if conversion between vectors of halfs and vectors of floats
15063/// is needed.
15064static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15065 Expr *E0, Expr *E1 = nullptr) {
15066 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15068 return false;
15069
15070 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15071 QualType Ty = E->IgnoreImplicit()->getType();
15072
15073 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15074 // to vectors of floats. Although the element type of the vectors is __fp16,
15075 // the vectors shouldn't be treated as storage-only types. See the
15076 // discussion here: https://reviews.llvm.org/rG825235c140e7
15077 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15078 if (VT->getVectorKind() == VectorKind::Neon)
15079 return false;
15080 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15081 }
15082 return false;
15083 };
15084
15085 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15086}
15087
15089 BinaryOperatorKind Opc, Expr *LHSExpr,
15090 Expr *RHSExpr, bool ForFoldExpression) {
15091 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15092 // The syntax only allows initializer lists on the RHS of assignment,
15093 // so we don't need to worry about accepting invalid code for
15094 // non-assignment operators.
15095 // C++11 5.17p9:
15096 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15097 // of x = {} is x = T().
15099 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15100 InitializedEntity Entity =
15102 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15103 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15104 if (Init.isInvalid())
15105 return Init;
15106 RHSExpr = Init.get();
15107 }
15108
15109 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15110 QualType ResultTy; // Result type of the binary operator.
15111 // The following two variables are used for compound assignment operators
15112 QualType CompLHSTy; // Type of LHS after promotions for computation
15113 QualType CompResultTy; // Type of computation result
15116 bool ConvertHalfVec = false;
15117
15118 if (!LHS.isUsable() || !RHS.isUsable())
15119 return ExprError();
15120
15121 if (getLangOpts().OpenCL) {
15122 QualType LHSTy = LHSExpr->getType();
15123 QualType RHSTy = RHSExpr->getType();
15124 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15125 // the ATOMIC_VAR_INIT macro.
15126 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15127 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15128 if (BO_Assign == Opc)
15129 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15130 else
15131 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15132 return ExprError();
15133 }
15134
15135 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15136 // only with a builtin functions and therefore should be disallowed here.
15137 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15138 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15139 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15140 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15141 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15142 return ExprError();
15143 }
15144 }
15145
15146 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15147 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15148
15149 switch (Opc) {
15150 case BO_Assign:
15151 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15152 if (getLangOpts().CPlusPlus &&
15153 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15154 VK = LHS.get()->getValueKind();
15155 OK = LHS.get()->getObjectKind();
15156 }
15157 if (!ResultTy.isNull()) {
15158 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15159 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15160
15161 // Avoid copying a block to the heap if the block is assigned to a local
15162 // auto variable that is declared in the same scope as the block. This
15163 // optimization is unsafe if the local variable is declared in an outer
15164 // scope. For example:
15165 //
15166 // BlockTy b;
15167 // {
15168 // b = ^{...};
15169 // }
15170 // // It is unsafe to invoke the block here if it wasn't copied to the
15171 // // heap.
15172 // b();
15173
15174 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15175 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15176 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15177 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15178 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15179
15181 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15183 }
15184 RecordModifiableNonNullParam(*this, LHS.get());
15185 break;
15186 case BO_PtrMemD:
15187 case BO_PtrMemI:
15188 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15189 Opc == BO_PtrMemI);
15190 break;
15191 case BO_Mul:
15192 case BO_Div:
15193 ConvertHalfVec = true;
15194 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15195 break;
15196 case BO_Rem:
15197 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15198 break;
15199 case BO_Add:
15200 ConvertHalfVec = true;
15201 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15202 break;
15203 case BO_Sub:
15204 ConvertHalfVec = true;
15205 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15206 break;
15207 case BO_Shl:
15208 case BO_Shr:
15209 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15210 break;
15211 case BO_LE:
15212 case BO_LT:
15213 case BO_GE:
15214 case BO_GT:
15215 ConvertHalfVec = true;
15216 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15217
15218 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15219 !ForFoldExpression && BI && BI->isComparisonOp())
15220 Diag(OpLoc, diag::warn_consecutive_comparison)
15221 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15222
15223 break;
15224 case BO_EQ:
15225 case BO_NE:
15226 ConvertHalfVec = true;
15227 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15228 break;
15229 case BO_Cmp:
15230 ConvertHalfVec = true;
15231 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15232 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15233 break;
15234 case BO_And:
15235 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15236 [[fallthrough]];
15237 case BO_Xor:
15238 case BO_Or:
15239 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15240 break;
15241 case BO_LAnd:
15242 case BO_LOr:
15243 ConvertHalfVec = true;
15244 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15245 break;
15246 case BO_MulAssign:
15247 case BO_DivAssign:
15248 ConvertHalfVec = true;
15249 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15250 CompLHSTy = CompResultTy;
15251 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15252 ResultTy =
15253 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15254 break;
15255 case BO_RemAssign:
15256 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15257 CompLHSTy = CompResultTy;
15258 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15259 ResultTy =
15260 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15261 break;
15262 case BO_AddAssign:
15263 ConvertHalfVec = true;
15264 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15265 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15266 ResultTy =
15267 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15268 break;
15269 case BO_SubAssign:
15270 ConvertHalfVec = true;
15271 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15272 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15273 ResultTy =
15274 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15275 break;
15276 case BO_ShlAssign:
15277 case BO_ShrAssign:
15278 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15279 CompLHSTy = CompResultTy;
15280 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15281 ResultTy =
15282 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15283 break;
15284 case BO_AndAssign:
15285 case BO_OrAssign: // fallthrough
15286 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15287 [[fallthrough]];
15288 case BO_XorAssign:
15289 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15290 CompLHSTy = CompResultTy;
15291 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15292 ResultTy =
15293 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15294 break;
15295 case BO_Comma:
15296 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15297 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15298 VK = RHS.get()->getValueKind();
15299 OK = RHS.get()->getObjectKind();
15300 }
15301 break;
15302 }
15303 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15304 return ExprError();
15305
15306 // Some of the binary operations require promoting operands of half vector to
15307 // float vectors and truncating the result back to half vector. For now, we do
15308 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15309 // arm64).
15310 assert(
15311 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15312 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15313 "both sides are half vectors or neither sides are");
15314 ConvertHalfVec =
15315 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15316
15317 // Check for array bounds violations for both sides of the BinaryOperator
15318 CheckArrayAccess(LHS.get());
15319 CheckArrayAccess(RHS.get());
15320
15321 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15322 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15323 &Context.Idents.get("object_setClass"),
15325 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15326 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15327 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15329 "object_setClass(")
15330 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15331 ",")
15332 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15333 }
15334 else
15335 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15336 }
15337 else if (const ObjCIvarRefExpr *OIRE =
15338 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15339 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15340
15341 // Opc is not a compound assignment if CompResultTy is null.
15342 if (CompResultTy.isNull()) {
15343 if (ConvertHalfVec)
15344 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15345 OpLoc, CurFPFeatureOverrides());
15346 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15347 VK, OK, OpLoc, CurFPFeatureOverrides());
15348 }
15349
15350 // Handle compound assignments.
15351 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15353 VK = VK_LValue;
15354 OK = LHS.get()->getObjectKind();
15355 }
15356
15357 // The LHS is not converted to the result type for fixed-point compound
15358 // assignment as the common type is computed on demand. Reset the CompLHSTy
15359 // to the LHS type we would have gotten after unary conversions.
15360 if (CompResultTy->isFixedPointType())
15361 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15362
15363 if (ConvertHalfVec)
15364 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15365 OpLoc, CurFPFeatureOverrides());
15366
15368 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15369 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15370}
15371
15372/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15373/// operators are mixed in a way that suggests that the programmer forgot that
15374/// comparison operators have higher precedence. The most typical example of
15375/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15377 SourceLocation OpLoc, Expr *LHSExpr,
15378 Expr *RHSExpr) {
15379 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15380 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15381
15382 // Check that one of the sides is a comparison operator and the other isn't.
15383 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15384 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15385 if (isLeftComp == isRightComp)
15386 return;
15387
15388 // Bitwise operations are sometimes used as eager logical ops.
15389 // Don't diagnose this.
15390 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15391 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15392 if (isLeftBitwise || isRightBitwise)
15393 return;
15394
15395 SourceRange DiagRange = isLeftComp
15396 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15397 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15398 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15399 SourceRange ParensRange =
15400 isLeftComp
15401 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15402 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15403
15404 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15405 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15406 SuggestParentheses(Self, OpLoc,
15407 Self.PDiag(diag::note_precedence_silence) << OpStr,
15408 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15409 SuggestParentheses(Self, OpLoc,
15410 Self.PDiag(diag::note_precedence_bitwise_first)
15412 ParensRange);
15413}
15414
15415/// It accepts a '&&' expr that is inside a '||' one.
15416/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15417/// in parentheses.
15418static void
15420 BinaryOperator *Bop) {
15421 assert(Bop->getOpcode() == BO_LAnd);
15422 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15423 << Bop->getSourceRange() << OpLoc;
15425 Self.PDiag(diag::note_precedence_silence)
15426 << Bop->getOpcodeStr(),
15427 Bop->getSourceRange());
15428}
15429
15430/// Look for '&&' in the left hand of a '||' expr.
15432 Expr *LHSExpr, Expr *RHSExpr) {
15433 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15434 if (Bop->getOpcode() == BO_LAnd) {
15435 // If it's "string_literal && a || b" don't warn since the precedence
15436 // doesn't matter.
15437 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15438 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15439 } else if (Bop->getOpcode() == BO_LOr) {
15440 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15441 // If it's "a || b && string_literal || c" we didn't warn earlier for
15442 // "a || b && string_literal", but warn now.
15443 if (RBop->getOpcode() == BO_LAnd &&
15444 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15445 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15446 }
15447 }
15448 }
15449}
15450
15451/// Look for '&&' in the right hand of a '||' expr.
15453 Expr *LHSExpr, Expr *RHSExpr) {
15454 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15455 if (Bop->getOpcode() == BO_LAnd) {
15456 // If it's "a || b && string_literal" don't warn since the precedence
15457 // doesn't matter.
15458 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15459 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15460 }
15461 }
15462}
15463
15464/// Look for bitwise op in the left or right hand of a bitwise op with
15465/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15466/// the '&' expression in parentheses.
15468 SourceLocation OpLoc, Expr *SubExpr) {
15469 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15470 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15471 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15472 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15473 << Bop->getSourceRange() << OpLoc;
15474 SuggestParentheses(S, Bop->getOperatorLoc(),
15475 S.PDiag(diag::note_precedence_silence)
15476 << Bop->getOpcodeStr(),
15477 Bop->getSourceRange());
15478 }
15479 }
15480}
15481
15483 Expr *SubExpr, StringRef Shift) {
15484 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15485 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15486 StringRef Op = Bop->getOpcodeStr();
15487 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15488 << Bop->getSourceRange() << OpLoc << Shift << Op;
15489 SuggestParentheses(S, Bop->getOperatorLoc(),
15490 S.PDiag(diag::note_precedence_silence) << Op,
15491 Bop->getSourceRange());
15492 }
15493 }
15494}
15495
15497 Expr *LHSExpr, Expr *RHSExpr) {
15498 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15499 if (!OCE)
15500 return;
15501
15502 FunctionDecl *FD = OCE->getDirectCallee();
15503 if (!FD || !FD->isOverloadedOperator())
15504 return;
15505
15507 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15508 return;
15509
15510 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15511 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15512 << (Kind == OO_LessLess);
15514 S.PDiag(diag::note_precedence_silence)
15515 << (Kind == OO_LessLess ? "<<" : ">>"),
15516 OCE->getSourceRange());
15518 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15519 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15520}
15521
15522/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15523/// precedence.
15525 SourceLocation OpLoc, Expr *LHSExpr,
15526 Expr *RHSExpr){
15527 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15529 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15530
15531 // Diagnose "arg1 & arg2 | arg3"
15532 if ((Opc == BO_Or || Opc == BO_Xor) &&
15533 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15534 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15535 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15536 }
15537
15538 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15539 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15540 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15541 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15542 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15543 }
15544
15545 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15546 || Opc == BO_Shr) {
15547 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15548 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15549 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15550 }
15551
15552 // Warn on overloaded shift operators and comparisons, such as:
15553 // cout << 5 == 4;
15555 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15556}
15557
15559 tok::TokenKind Kind,
15560 Expr *LHSExpr, Expr *RHSExpr) {
15561 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15562 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15563 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15564
15565 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15566 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15567
15571
15572 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15573 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15574
15575 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15576}
15577
15579 UnresolvedSetImpl &Functions) {
15581 if (OverOp != OO_None && OverOp != OO_Equal)
15582 LookupOverloadedOperatorName(OverOp, S, Functions);
15583
15584 // In C++20 onwards, we may have a second operator to look up.
15585 if (getLangOpts().CPlusPlus20) {
15587 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15588 }
15589}
15590
15591/// Build an overloaded binary operator expression in the given scope.
15594 Expr *LHS, Expr *RHS) {
15595 switch (Opc) {
15596 case BO_Assign:
15597 // In the non-overloaded case, we warn about self-assignment (x = x) for
15598 // both simple assignment and certain compound assignments where algebra
15599 // tells us the operation yields a constant result. When the operator is
15600 // overloaded, we can't do the latter because we don't want to assume that
15601 // those algebraic identities still apply; for example, a path-building
15602 // library might use operator/= to append paths. But it's still reasonable
15603 // to assume that simple assignment is just moving/copying values around
15604 // and so self-assignment is likely a bug.
15605 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15606 [[fallthrough]];
15607 case BO_DivAssign:
15608 case BO_RemAssign:
15609 case BO_SubAssign:
15610 case BO_AndAssign:
15611 case BO_OrAssign:
15612 case BO_XorAssign:
15613 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15614 break;
15615 default:
15616 break;
15617 }
15618
15619 // Find all of the overloaded operators visible from this point.
15620 UnresolvedSet<16> Functions;
15621 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15622
15623 // Build the (potentially-overloaded, potentially-dependent)
15624 // binary operation.
15625 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15626}
15627
15629 BinaryOperatorKind Opc, Expr *LHSExpr,
15630 Expr *RHSExpr, bool ForFoldExpression) {
15631 if (!LHSExpr || !RHSExpr)
15632 return ExprError();
15633
15634 // We want to end up calling one of SemaPseudoObject::checkAssignment
15635 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15636 // both expressions are overloadable or either is type-dependent),
15637 // or CreateBuiltinBinOp (in any other case). We also want to get
15638 // any placeholder types out of the way.
15639
15640 // Handle pseudo-objects in the LHS.
15641 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15642 // Assignments with a pseudo-object l-value need special analysis.
15643 if (pty->getKind() == BuiltinType::PseudoObject &&
15645 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15646
15647 // Don't resolve overloads if the other type is overloadable.
15648 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15649 // We can't actually test that if we still have a placeholder,
15650 // though. Fortunately, none of the exceptions we see in that
15651 // code below are valid when the LHS is an overload set. Note
15652 // that an overload set can be dependently-typed, but it never
15653 // instantiates to having an overloadable type.
15654 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15655 if (resolvedRHS.isInvalid()) return ExprError();
15656 RHSExpr = resolvedRHS.get();
15657
15658 if (RHSExpr->isTypeDependent() ||
15659 RHSExpr->getType()->isOverloadableType())
15660 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15661 }
15662
15663 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15664 // template, diagnose the missing 'template' keyword instead of diagnosing
15665 // an invalid use of a bound member function.
15666 //
15667 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15668 // to C++1z [over.over]/1.4, but we already checked for that case above.
15669 if (Opc == BO_LT && inTemplateInstantiation() &&
15670 (pty->getKind() == BuiltinType::BoundMember ||
15671 pty->getKind() == BuiltinType::Overload)) {
15672 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15673 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15674 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15675 return isa<FunctionTemplateDecl>(ND);
15676 })) {
15677 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15678 : OE->getNameLoc(),
15679 diag::err_template_kw_missing)
15680 << OE->getName().getAsIdentifierInfo();
15681 return ExprError();
15682 }
15683 }
15684
15685 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15686 if (LHS.isInvalid()) return ExprError();
15687 LHSExpr = LHS.get();
15688 }
15689
15690 // Handle pseudo-objects in the RHS.
15691 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15692 // An overload in the RHS can potentially be resolved by the type
15693 // being assigned to.
15694 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15695 if (getLangOpts().CPlusPlus &&
15696 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15697 LHSExpr->getType()->isOverloadableType()))
15698 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15699
15700 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
15701 ForFoldExpression);
15702 }
15703
15704 // Don't resolve overloads if the other type is overloadable.
15705 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15706 LHSExpr->getType()->isOverloadableType())
15707 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15708
15709 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15710 if (!resolvedRHS.isUsable()) return ExprError();
15711 RHSExpr = resolvedRHS.get();
15712 }
15713
15714 if (getLangOpts().CPlusPlus) {
15715 // Otherwise, build an overloaded op if either expression is type-dependent
15716 // or has an overloadable type.
15717 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15718 LHSExpr->getType()->isOverloadableType() ||
15719 RHSExpr->getType()->isOverloadableType())
15720 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15721 }
15722
15723 if (getLangOpts().RecoveryAST &&
15724 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15725 assert(!getLangOpts().CPlusPlus);
15726 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15727 "Should only occur in error-recovery path.");
15729 // C [6.15.16] p3:
15730 // An assignment expression has the value of the left operand after the
15731 // assignment, but is not an lvalue.
15733 Context, LHSExpr, RHSExpr, Opc,
15735 OpLoc, CurFPFeatureOverrides());
15736 QualType ResultType;
15737 switch (Opc) {
15738 case BO_Assign:
15739 ResultType = LHSExpr->getType().getUnqualifiedType();
15740 break;
15741 case BO_LT:
15742 case BO_GT:
15743 case BO_LE:
15744 case BO_GE:
15745 case BO_EQ:
15746 case BO_NE:
15747 case BO_LAnd:
15748 case BO_LOr:
15749 // These operators have a fixed result type regardless of operands.
15750 ResultType = Context.IntTy;
15751 break;
15752 case BO_Comma:
15753 ResultType = RHSExpr->getType();
15754 break;
15755 default:
15756 ResultType = Context.DependentTy;
15757 break;
15758 }
15759 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15760 VK_PRValue, OK_Ordinary, OpLoc,
15762 }
15763
15764 // Build a built-in binary operation.
15765 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
15766}
15767
15769 if (T.isNull() || T->isDependentType())
15770 return false;
15771
15772 if (!Ctx.isPromotableIntegerType(T))
15773 return true;
15774
15775 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15776}
15777
15779 UnaryOperatorKind Opc, Expr *InputExpr,
15780 bool IsAfterAmp) {
15781 ExprResult Input = InputExpr;
15784 QualType resultType;
15785 bool CanOverflow = false;
15786
15787 bool ConvertHalfVec = false;
15788 if (getLangOpts().OpenCL) {
15789 QualType Ty = InputExpr->getType();
15790 // The only legal unary operation for atomics is '&'.
15791 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15792 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15793 // only with a builtin functions and therefore should be disallowed here.
15794 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15795 || Ty->isBlockPointerType())) {
15796 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15797 << InputExpr->getType()
15798 << Input.get()->getSourceRange());
15799 }
15800 }
15801
15802 if (getLangOpts().HLSL && OpLoc.isValid()) {
15803 if (Opc == UO_AddrOf)
15804 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15805 if (Opc == UO_Deref)
15806 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15807 }
15808
15809 if (InputExpr->isTypeDependent() &&
15810 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15811 resultType = Context.DependentTy;
15812 } else {
15813 switch (Opc) {
15814 case UO_PreInc:
15815 case UO_PreDec:
15816 case UO_PostInc:
15817 case UO_PostDec:
15818 resultType =
15819 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15820 Opc == UO_PreInc || Opc == UO_PostInc,
15821 Opc == UO_PreInc || Opc == UO_PreDec);
15822 CanOverflow = isOverflowingIntegerType(Context, resultType);
15823 break;
15824 case UO_AddrOf:
15825 resultType = CheckAddressOfOperand(Input, OpLoc);
15826 CheckAddressOfNoDeref(InputExpr);
15827 RecordModifiableNonNullParam(*this, InputExpr);
15828 break;
15829 case UO_Deref: {
15831 if (Input.isInvalid())
15832 return ExprError();
15833 resultType =
15834 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15835 break;
15836 }
15837 case UO_Plus:
15838 case UO_Minus:
15839 CanOverflow = Opc == UO_Minus &&
15841 Input = UsualUnaryConversions(Input.get());
15842 if (Input.isInvalid())
15843 return ExprError();
15844 // Unary plus and minus require promoting an operand of half vector to a
15845 // float vector and truncating the result back to a half vector. For now,
15846 // we do this only when HalfArgsAndReturns is set (that is, when the
15847 // target is arm or arm64).
15848 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15849
15850 // If the operand is a half vector, promote it to a float vector.
15851 if (ConvertHalfVec)
15852 Input = convertVector(Input.get(), Context.FloatTy, *this);
15853 resultType = Input.get()->getType();
15854 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15855 break;
15856 else if (resultType->isVectorType() &&
15857 // The z vector extensions don't allow + or - with bool vectors.
15858 (!Context.getLangOpts().ZVector ||
15859 resultType->castAs<VectorType>()->getVectorKind() !=
15861 break;
15862 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15863 break;
15864 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15865 Opc == UO_Plus && resultType->isPointerType())
15866 break;
15867
15868 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15869 << resultType << Input.get()->getSourceRange());
15870
15871 case UO_Not: // bitwise complement
15872 Input = UsualUnaryConversions(Input.get());
15873 if (Input.isInvalid())
15874 return ExprError();
15875 resultType = Input.get()->getType();
15876 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15877 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15878 // C99 does not support '~' for complex conjugation.
15879 Diag(OpLoc, diag::ext_integer_complement_complex)
15880 << resultType << Input.get()->getSourceRange();
15881 else if (resultType->hasIntegerRepresentation())
15882 break;
15883 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15884 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15885 // on vector float types.
15886 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15887 if (!T->isIntegerType())
15888 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15889 << resultType << Input.get()->getSourceRange());
15890 } else {
15891 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15892 << resultType << Input.get()->getSourceRange());
15893 }
15894 break;
15895
15896 case UO_LNot: // logical negation
15897 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15899 if (Input.isInvalid())
15900 return ExprError();
15901 resultType = Input.get()->getType();
15902
15903 // Though we still have to promote half FP to float...
15904 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15905 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15906 .get();
15907 resultType = Context.FloatTy;
15908 }
15909
15910 // WebAsembly tables can't be used in unary expressions.
15911 if (resultType->isPointerType() &&
15913 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15914 << resultType << Input.get()->getSourceRange());
15915 }
15916
15917 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15918 // C99 6.5.3.3p1: ok, fallthrough;
15919 if (Context.getLangOpts().CPlusPlus) {
15920 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15921 // operand contextually converted to bool.
15922 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15923 ScalarTypeToBooleanCastKind(resultType));
15924 } else if (Context.getLangOpts().OpenCL &&
15925 Context.getLangOpts().OpenCLVersion < 120) {
15926 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15927 // operate on scalar float types.
15928 if (!resultType->isIntegerType() && !resultType->isPointerType())
15929 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15930 << resultType << Input.get()->getSourceRange());
15931 }
15932 } else if (resultType->isExtVectorType()) {
15933 if (Context.getLangOpts().OpenCL &&
15934 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15935 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15936 // operate on vector float types.
15937 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15938 if (!T->isIntegerType())
15939 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15940 << resultType << Input.get()->getSourceRange());
15941 }
15942 // Vector logical not returns the signed variant of the operand type.
15943 resultType = GetSignedVectorType(resultType);
15944 break;
15945 } else if (Context.getLangOpts().CPlusPlus &&
15946 resultType->isVectorType()) {
15947 const VectorType *VTy = resultType->castAs<VectorType>();
15948 if (VTy->getVectorKind() != VectorKind::Generic)
15949 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15950 << resultType << Input.get()->getSourceRange());
15951
15952 // Vector logical not returns the signed variant of the operand type.
15953 resultType = GetSignedVectorType(resultType);
15954 break;
15955 } else {
15956 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15957 << resultType << Input.get()->getSourceRange());
15958 }
15959
15960 // LNot always has type int. C99 6.5.3.3p5.
15961 // In C++, it's bool. C++ 5.3.1p8
15962 resultType = Context.getLogicalOperationType();
15963 break;
15964 case UO_Real:
15965 case UO_Imag:
15966 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15967 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15968 // ordinary complex l-values to ordinary l-values and all other values to
15969 // r-values.
15970 if (Input.isInvalid())
15971 return ExprError();
15972 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15973 if (Input.get()->isGLValue() &&
15974 Input.get()->getObjectKind() == OK_Ordinary)
15975 VK = Input.get()->getValueKind();
15976 } else if (!getLangOpts().CPlusPlus) {
15977 // In C, a volatile scalar is read by __imag. In C++, it is not.
15978 Input = DefaultLvalueConversion(Input.get());
15979 }
15980 break;
15981 case UO_Extension:
15982 resultType = Input.get()->getType();
15983 VK = Input.get()->getValueKind();
15984 OK = Input.get()->getObjectKind();
15985 break;
15986 case UO_Coawait:
15987 // It's unnecessary to represent the pass-through operator co_await in the
15988 // AST; just return the input expression instead.
15989 assert(!Input.get()->getType()->isDependentType() &&
15990 "the co_await expression must be non-dependant before "
15991 "building operator co_await");
15992 return Input;
15993 }
15994 }
15995 if (resultType.isNull() || Input.isInvalid())
15996 return ExprError();
15997
15998 // Check for array bounds violations in the operand of the UnaryOperator,
15999 // except for the '*' and '&' operators that have to be handled specially
16000 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16001 // that are explicitly defined as valid by the standard).
16002 if (Opc != UO_AddrOf && Opc != UO_Deref)
16003 CheckArrayAccess(Input.get());
16004
16005 auto *UO =
16006 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16007 OpLoc, CanOverflow, CurFPFeatureOverrides());
16008
16009 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16010 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16012 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16013
16014 // Convert the result back to a half vector.
16015 if (ConvertHalfVec)
16016 return convertVector(UO, Context.HalfTy, *this);
16017 return UO;
16018}
16019
16021 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16022 if (!DRE->getQualifier())
16023 return false;
16024
16025 ValueDecl *VD = DRE->getDecl();
16026 if (!VD->isCXXClassMember())
16027 return false;
16028
16030 return true;
16031 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16032 return Method->isImplicitObjectMemberFunction();
16033
16034 return false;
16035 }
16036
16037 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16038 if (!ULE->getQualifier())
16039 return false;
16040
16041 for (NamedDecl *D : ULE->decls()) {
16042 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16043 if (Method->isImplicitObjectMemberFunction())
16044 return true;
16045 } else {
16046 // Overload set does not contain methods.
16047 break;
16048 }
16049 }
16050
16051 return false;
16052 }
16053
16054 return false;
16055}
16056
16058 UnaryOperatorKind Opc, Expr *Input,
16059 bool IsAfterAmp) {
16060 // First things first: handle placeholders so that the
16061 // overloaded-operator check considers the right type.
16062 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16063 // Increment and decrement of pseudo-object references.
16064 if (pty->getKind() == BuiltinType::PseudoObject &&
16066 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16067
16068 // extension is always a builtin operator.
16069 if (Opc == UO_Extension)
16070 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16071
16072 // & gets special logic for several kinds of placeholder.
16073 // The builtin code knows what to do.
16074 if (Opc == UO_AddrOf &&
16075 (pty->getKind() == BuiltinType::Overload ||
16076 pty->getKind() == BuiltinType::UnknownAny ||
16077 pty->getKind() == BuiltinType::BoundMember))
16078 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16079
16080 // Anything else needs to be handled now.
16082 if (Result.isInvalid()) return ExprError();
16083 Input = Result.get();
16084 }
16085
16086 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16088 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16089 // Find all of the overloaded operators visible from this point.
16090 UnresolvedSet<16> Functions;
16092 if (S && OverOp != OO_None)
16093 LookupOverloadedOperatorName(OverOp, S, Functions);
16094
16095 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16096 }
16097
16098 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16099}
16100
16102 Expr *Input, bool IsAfterAmp) {
16103 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16104 IsAfterAmp);
16105}
16106
16108 LabelDecl *TheDecl) {
16109 TheDecl->markUsed(Context);
16110 // Create the AST node. The address of a label always has type 'void*'.
16111 auto *Res = new (Context) AddrLabelExpr(
16112 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16113
16114 if (getCurFunction())
16115 getCurFunction()->AddrLabels.push_back(Res);
16116
16117 return Res;
16118}
16119
16122 // Make sure we diagnose jumping into a statement expression.
16124}
16125
16127 // Note that function is also called by TreeTransform when leaving a
16128 // StmtExpr scope without rebuilding anything.
16129
16132}
16133
16135 SourceLocation RPLoc) {
16136 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16137}
16138
16140 SourceLocation RPLoc, unsigned TemplateDepth) {
16141 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16142 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16143
16146 assert(!Cleanup.exprNeedsCleanups() &&
16147 "cleanups within StmtExpr not correctly bound!");
16149
16150 // FIXME: there are a variety of strange constraints to enforce here, for
16151 // example, it is not possible to goto into a stmt expression apparently.
16152 // More semantic analysis is needed.
16153
16154 // If there are sub-stmts in the compound stmt, take the type of the last one
16155 // as the type of the stmtexpr.
16156 QualType Ty = Context.VoidTy;
16157 bool StmtExprMayBindToTemp = false;
16158 if (!Compound->body_empty()) {
16159 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16160 if (const auto *LastStmt =
16161 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16162 if (const Expr *Value = LastStmt->getExprStmt()) {
16163 StmtExprMayBindToTemp = true;
16164 Ty = Value->getType();
16165 }
16166 }
16167 }
16168
16169 // FIXME: Check that expression type is complete/non-abstract; statement
16170 // expressions are not lvalues.
16171 Expr *ResStmtExpr =
16172 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16173 if (StmtExprMayBindToTemp)
16174 return MaybeBindToTemporary(ResStmtExpr);
16175 return ResStmtExpr;
16176}
16177
16179 if (ER.isInvalid())
16180 return ExprError();
16181
16182 // Do function/array conversion on the last expression, but not
16183 // lvalue-to-rvalue. However, initialize an unqualified type.
16185 if (ER.isInvalid())
16186 return ExprError();
16187 Expr *E = ER.get();
16188
16189 if (E->isTypeDependent())
16190 return E;
16191
16192 // In ARC, if the final expression ends in a consume, splice
16193 // the consume out and bind it later. In the alternate case
16194 // (when dealing with a retainable type), the result
16195 // initialization will create a produce. In both cases the
16196 // result will be +1, and we'll need to balance that out with
16197 // a bind.
16198 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16199 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16200 return Cast->getSubExpr();
16201
16202 // FIXME: Provide a better location for the initialization.
16206 SourceLocation(), E);
16207}
16208
16210 TypeSourceInfo *TInfo,
16211 ArrayRef<OffsetOfComponent> Components,
16212 SourceLocation RParenLoc) {
16213 QualType ArgTy = TInfo->getType();
16214 bool Dependent = ArgTy->isDependentType();
16215 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16216
16217 // We must have at least one component that refers to the type, and the first
16218 // one is known to be a field designator. Verify that the ArgTy represents
16219 // a struct/union/class.
16220 if (!Dependent && !ArgTy->isRecordType())
16221 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16222 << ArgTy << TypeRange);
16223
16224 // Type must be complete per C99 7.17p3 because a declaring a variable
16225 // with an incomplete type would be ill-formed.
16226 if (!Dependent
16227 && RequireCompleteType(BuiltinLoc, ArgTy,
16228 diag::err_offsetof_incomplete_type, TypeRange))
16229 return ExprError();
16230
16231 bool DidWarnAboutNonPOD = false;
16232 QualType CurrentType = ArgTy;
16235 for (const OffsetOfComponent &OC : Components) {
16236 if (OC.isBrackets) {
16237 // Offset of an array sub-field. TODO: Should we allow vector elements?
16238 if (!CurrentType->isDependentType()) {
16239 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16240 if(!AT)
16241 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16242 << CurrentType);
16243 CurrentType = AT->getElementType();
16244 } else
16245 CurrentType = Context.DependentTy;
16246
16247 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16248 if (IdxRval.isInvalid())
16249 return ExprError();
16250 Expr *Idx = IdxRval.get();
16251
16252 // The expression must be an integral expression.
16253 // FIXME: An integral constant expression?
16254 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16255 !Idx->getType()->isIntegerType())
16256 return ExprError(
16257 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16258 << Idx->getSourceRange());
16259
16260 // Record this array index.
16261 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16262 Exprs.push_back(Idx);
16263 continue;
16264 }
16265
16266 // Offset of a field.
16267 if (CurrentType->isDependentType()) {
16268 // We have the offset of a field, but we can't look into the dependent
16269 // type. Just record the identifier of the field.
16270 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16271 CurrentType = Context.DependentTy;
16272 continue;
16273 }
16274
16275 // We need to have a complete type to look into.
16276 if (RequireCompleteType(OC.LocStart, CurrentType,
16277 diag::err_offsetof_incomplete_type))
16278 return ExprError();
16279
16280 // Look for the designated field.
16281 auto *RD = CurrentType->getAsRecordDecl();
16282 if (!RD)
16283 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16284 << CurrentType);
16285
16286 // C++ [lib.support.types]p5:
16287 // The macro offsetof accepts a restricted set of type arguments in this
16288 // International Standard. type shall be a POD structure or a POD union
16289 // (clause 9).
16290 // C++11 [support.types]p4:
16291 // If type is not a standard-layout class (Clause 9), the results are
16292 // undefined.
16293 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16294 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16295 unsigned DiagID =
16296 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16297 : diag::ext_offsetof_non_pod_type;
16298
16299 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16300 Diag(BuiltinLoc, DiagID)
16301 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16302 DidWarnAboutNonPOD = true;
16303 }
16304 }
16305
16306 // Look for the field.
16307 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16308 LookupQualifiedName(R, RD);
16309 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16310 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16311 if (!MemberDecl) {
16312 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16313 MemberDecl = IndirectMemberDecl->getAnonField();
16314 }
16315
16316 if (!MemberDecl) {
16317 // Lookup could be ambiguous when looking up a placeholder variable
16318 // __builtin_offsetof(S, _).
16319 // In that case we would already have emitted a diagnostic
16320 if (!R.isAmbiguous())
16321 Diag(BuiltinLoc, diag::err_no_member)
16322 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16323 return ExprError();
16324 }
16325
16326 // C99 7.17p3:
16327 // (If the specified member is a bit-field, the behavior is undefined.)
16328 //
16329 // We diagnose this as an error.
16330 if (MemberDecl->isBitField()) {
16331 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16332 << MemberDecl->getDeclName()
16333 << SourceRange(BuiltinLoc, RParenLoc);
16334 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16335 return ExprError();
16336 }
16337
16338 RecordDecl *Parent = MemberDecl->getParent();
16339 if (IndirectMemberDecl)
16340 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16341
16342 // If the member was found in a base class, introduce OffsetOfNodes for
16343 // the base class indirections.
16344 CXXBasePaths Paths;
16345 if (IsDerivedFrom(OC.LocStart, CurrentType,
16346 Context.getCanonicalTagType(Parent), Paths)) {
16347 if (Paths.getDetectedVirtual()) {
16348 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16349 << MemberDecl->getDeclName()
16350 << SourceRange(BuiltinLoc, RParenLoc);
16351 return ExprError();
16352 }
16353
16354 CXXBasePath &Path = Paths.front();
16355 for (const CXXBasePathElement &B : Path)
16356 Comps.push_back(OffsetOfNode(B.Base));
16357 }
16358
16359 if (IndirectMemberDecl) {
16360 for (auto *FI : IndirectMemberDecl->chain()) {
16361 assert(isa<FieldDecl>(FI));
16362 Comps.push_back(OffsetOfNode(OC.LocStart,
16363 cast<FieldDecl>(FI), OC.LocEnd));
16364 }
16365 } else
16366 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16367
16368 CurrentType = MemberDecl->getType().getNonReferenceType();
16369 }
16370
16371 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16372 Comps, Exprs, RParenLoc);
16373}
16374
16376 SourceLocation BuiltinLoc,
16378 ParsedType ParsedArgTy,
16379 ArrayRef<OffsetOfComponent> Components,
16380 SourceLocation RParenLoc) {
16381
16382 TypeSourceInfo *ArgTInfo;
16383 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16384 if (ArgTy.isNull())
16385 return ExprError();
16386
16387 if (!ArgTInfo)
16388 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16389
16390 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16391}
16392
16393
16395 Expr *CondExpr,
16396 Expr *LHSExpr, Expr *RHSExpr,
16397 SourceLocation RPLoc) {
16398 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16399
16402 QualType resType;
16403 bool CondIsTrue = false;
16404 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16405 resType = Context.DependentTy;
16406 } else {
16407 // The conditional expression is required to be a constant expression.
16408 llvm::APSInt condEval(32);
16410 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16411 if (CondICE.isInvalid())
16412 return ExprError();
16413 CondExpr = CondICE.get();
16414 CondIsTrue = condEval.getZExtValue();
16415
16416 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16417 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16418
16419 resType = ActiveExpr->getType();
16420 VK = ActiveExpr->getValueKind();
16421 OK = ActiveExpr->getObjectKind();
16422 }
16423
16424 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16425 resType, VK, OK, RPLoc, CondIsTrue);
16426}
16427
16428//===----------------------------------------------------------------------===//
16429// Clang Extensions.
16430//===----------------------------------------------------------------------===//
16431
16432void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16434
16435 if (LangOpts.CPlusPlus) {
16437 Decl *ManglingContextDecl;
16438 std::tie(MCtx, ManglingContextDecl) =
16439 getCurrentMangleNumberContext(Block->getDeclContext());
16440 if (MCtx) {
16441 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16442 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16443 }
16444 }
16445
16446 PushBlockScope(CurScope, Block);
16447 CurContext->addDecl(Block);
16448 if (CurScope)
16449 PushDeclContext(CurScope, Block);
16450 else
16451 CurContext = Block;
16452
16454
16455 // Enter a new evaluation context to insulate the block from any
16456 // cleanups from the enclosing full-expression.
16459}
16460
16462 Scope *CurScope) {
16463 assert(ParamInfo.getIdentifier() == nullptr &&
16464 "block-id should have no identifier!");
16465 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16466 BlockScopeInfo *CurBlock = getCurBlock();
16467
16468 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16469 QualType T = Sig->getType();
16471
16472 // GetTypeForDeclarator always produces a function type for a block
16473 // literal signature. Furthermore, it is always a FunctionProtoType
16474 // unless the function was written with a typedef.
16475 assert(T->isFunctionType() &&
16476 "GetTypeForDeclarator made a non-function block signature");
16477
16478 // Look for an explicit signature in that function type.
16479 FunctionProtoTypeLoc ExplicitSignature;
16480
16481 if ((ExplicitSignature = Sig->getTypeLoc()
16483
16484 // Check whether that explicit signature was synthesized by
16485 // GetTypeForDeclarator. If so, don't save that as part of the
16486 // written signature.
16487 if (ExplicitSignature.getLocalRangeBegin() ==
16488 ExplicitSignature.getLocalRangeEnd()) {
16489 // This would be much cheaper if we stored TypeLocs instead of
16490 // TypeSourceInfos.
16491 TypeLoc Result = ExplicitSignature.getReturnLoc();
16492 unsigned Size = Result.getFullDataSize();
16493 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16494 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16495
16496 ExplicitSignature = FunctionProtoTypeLoc();
16497 }
16498 }
16499
16500 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16501 CurBlock->FunctionType = T;
16502
16503 const auto *Fn = T->castAs<FunctionType>();
16504 QualType RetTy = Fn->getReturnType();
16505 bool isVariadic =
16506 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16507
16508 CurBlock->TheDecl->setIsVariadic(isVariadic);
16509
16510 // Context.DependentTy is used as a placeholder for a missing block
16511 // return type. TODO: what should we do with declarators like:
16512 // ^ * { ... }
16513 // If the answer is "apply template argument deduction"....
16514 if (RetTy != Context.DependentTy) {
16515 CurBlock->ReturnType = RetTy;
16516 CurBlock->TheDecl->setBlockMissingReturnType(false);
16517 CurBlock->HasImplicitReturnType = false;
16518 }
16519
16520 // Push block parameters from the declarator if we had them.
16522 if (ExplicitSignature) {
16523 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16524 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16525 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16526 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16527 // Diagnose this as an extension in C17 and earlier.
16528 if (!getLangOpts().C23)
16529 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16530 }
16531 Params.push_back(Param);
16532 }
16533
16534 // Fake up parameter variables if we have a typedef, like
16535 // ^ fntype { ... }
16536 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16537 for (const auto &I : Fn->param_types()) {
16539 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16540 Params.push_back(Param);
16541 }
16542 }
16543
16544 // Set the parameters on the block decl.
16545 if (!Params.empty()) {
16546 CurBlock->TheDecl->setParams(Params);
16548 /*CheckParameterNames=*/false);
16549 }
16550
16551 // Finally we can process decl attributes.
16552 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16553
16554 // Put the parameter variables in scope.
16555 for (auto *AI : CurBlock->TheDecl->parameters()) {
16556 AI->setOwningFunction(CurBlock->TheDecl);
16557
16558 // If this has an identifier, add it to the scope stack.
16559 if (AI->getIdentifier()) {
16560 CheckShadow(CurBlock->TheScope, AI);
16561
16562 PushOnScopeChains(AI, CurBlock->TheScope);
16563 }
16564
16565 if (AI->isInvalidDecl())
16566 CurBlock->TheDecl->setInvalidDecl();
16567 }
16568}
16569
16570void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16571 // Leave the expression-evaluation context.
16574
16575 // Pop off CurBlock, handle nested blocks.
16578}
16579
16581 Stmt *Body, Scope *CurScope) {
16582 // If blocks are disabled, emit an error.
16583 if (!LangOpts.Blocks)
16584 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16585
16586 // Leave the expression-evaluation context.
16589 assert(!Cleanup.exprNeedsCleanups() &&
16590 "cleanups within block not correctly bound!");
16592
16594 BlockDecl *BD = BSI->TheDecl;
16595
16597
16598 if (BSI->HasImplicitReturnType)
16600
16601 QualType RetTy = Context.VoidTy;
16602 if (!BSI->ReturnType.isNull())
16603 RetTy = BSI->ReturnType;
16604
16605 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16606 QualType BlockTy;
16607
16608 // If the user wrote a function type in some form, try to use that.
16609 if (!BSI->FunctionType.isNull()) {
16610 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16611
16612 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16613 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16614
16615 // Turn protoless block types into nullary block types.
16616 if (isa<FunctionNoProtoType>(FTy)) {
16618 EPI.ExtInfo = Ext;
16619 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16620
16621 // Otherwise, if we don't need to change anything about the function type,
16622 // preserve its sugar structure.
16623 } else if (FTy->getReturnType() == RetTy &&
16624 (!NoReturn || FTy->getNoReturnAttr())) {
16625 BlockTy = BSI->FunctionType;
16626
16627 // Otherwise, make the minimal modifications to the function type.
16628 } else {
16631 EPI.TypeQuals = Qualifiers();
16632 EPI.ExtInfo = Ext;
16633 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16634 }
16635
16636 // If we don't have a function type, just build one from nothing.
16637 } else {
16639 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16640 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16641 }
16642
16644 BlockTy = Context.getBlockPointerType(BlockTy);
16645
16646 // If needed, diagnose invalid gotos and switches in the block.
16647 if (getCurFunction()->NeedsScopeChecking() &&
16648 !PP.isCodeCompletionEnabled())
16650
16651 BD->setBody(cast<CompoundStmt>(Body));
16652
16653 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16655
16656 // Try to apply the named return value optimization. We have to check again
16657 // if we can do this, though, because blocks keep return statements around
16658 // to deduce an implicit return type.
16659 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16660 !BD->isDependentContext())
16661 computeNRVO(Body, BSI);
16662
16668
16670
16671 // Set the captured variables on the block.
16673 for (Capture &Cap : BSI->Captures) {
16674 if (Cap.isInvalid() || Cap.isThisCapture())
16675 continue;
16676 // Cap.getVariable() is always a VarDecl because
16677 // blocks cannot capture structured bindings or other ValueDecl kinds.
16678 auto *Var = cast<VarDecl>(Cap.getVariable());
16679 Expr *CopyExpr = nullptr;
16680 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16681 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
16682 // The capture logic needs the destructor, so make sure we mark it.
16683 // Usually this is unnecessary because most local variables have
16684 // their destructors marked at declaration time, but parameters are
16685 // an exception because it's technically only the call site that
16686 // actually requires the destructor.
16687 if (isa<ParmVarDecl>(Var))
16689
16690 // Enter a separate potentially-evaluated context while building block
16691 // initializers to isolate their cleanups from those of the block
16692 // itself.
16693 // FIXME: Is this appropriate even when the block itself occurs in an
16694 // unevaluated operand?
16697
16698 SourceLocation Loc = Cap.getLocation();
16699
16701 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16702
16703 // According to the blocks spec, the capture of a variable from
16704 // the stack requires a const copy constructor. This is not true
16705 // of the copy/move done to move a __block variable to the heap.
16706 if (!Result.isInvalid() &&
16707 !Result.get()->getType().isConstQualified()) {
16709 Result.get()->getType().withConst(),
16710 CK_NoOp, VK_LValue);
16711 }
16712
16713 if (!Result.isInvalid()) {
16715 InitializedEntity::InitializeBlock(Var->getLocation(),
16716 Cap.getCaptureType()),
16717 Loc, Result.get());
16718 }
16719
16720 // Build a full-expression copy expression if initialization
16721 // succeeded and used a non-trivial constructor. Recover from
16722 // errors by pretending that the copy isn't necessary.
16723 if (!Result.isInvalid() &&
16724 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16725 ->isTrivial()) {
16727 CopyExpr = Result.get();
16728 }
16729 }
16730 }
16731
16732 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16733 CopyExpr);
16734 Captures.push_back(NewCap);
16735 }
16736 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16737
16738 // Pop the block scope now but keep it alive to the end of this function.
16740 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
16741 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16742
16743 BlockExpr *Result = new (Context)
16744 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
16745
16746 // If the block isn't obviously global, i.e. it captures anything at
16747 // all, then we need to do a few things in the surrounding context:
16748 if (Result->getBlockDecl()->hasCaptures()) {
16749 // First, this expression has a new cleanup object.
16750 ExprCleanupObjects.push_back(Result->getBlockDecl());
16751 Cleanup.setExprNeedsCleanups(true);
16752
16753 // It also gets a branch-protected scope if any of the captured
16754 // variables needs destruction.
16755 for (const auto &CI : Result->getBlockDecl()->captures()) {
16756 const VarDecl *var = CI.getVariable();
16757 if (var->getType().isDestructedType() != QualType::DK_none) {
16759 break;
16760 }
16761 }
16762 }
16763
16764 if (getCurFunction())
16765 getCurFunction()->addBlock(BD);
16766
16767 // This can happen if the block's return type is deduced, but
16768 // the return expression is invalid.
16769 if (BD->isInvalidDecl())
16770 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16771 {Result}, Result->getType());
16772 return Result;
16773}
16774
16776 SourceLocation RPLoc) {
16777 TypeSourceInfo *TInfo;
16778 GetTypeFromParser(Ty, &TInfo);
16779 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16780}
16781
16783 Expr *E, TypeSourceInfo *TInfo,
16784 SourceLocation RPLoc) {
16785 Expr *OrigExpr = E;
16786 bool IsMS = false;
16787
16788 // CUDA device code does not support varargs.
16789 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16790 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16794 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16795 }
16796 }
16797
16798 // NVPTX does not support va_arg expression.
16799 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16800 Context.getTargetInfo().getTriple().isNVPTX())
16801 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16802
16803 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16804 // as Microsoft ABI on an actual Microsoft platform, where
16805 // __builtin_ms_va_list and __builtin_va_list are the same.)
16806 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16807 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16808 QualType MSVaListType = Context.getBuiltinMSVaListType();
16809 if (Context.hasSameType(MSVaListType, E->getType())) {
16810 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16811 return ExprError();
16812 IsMS = true;
16813 }
16814 }
16815
16816 // Get the va_list type
16817 QualType VaListType = Context.getBuiltinVaListType();
16818 if (!IsMS) {
16819 if (VaListType->isArrayType()) {
16820 // Deal with implicit array decay; for example, on x86-64,
16821 // va_list is an array, but it's supposed to decay to
16822 // a pointer for va_arg.
16823 VaListType = Context.getArrayDecayedType(VaListType);
16824 // Make sure the input expression also decays appropriately.
16826 if (Result.isInvalid())
16827 return ExprError();
16828 E = Result.get();
16829 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16830 // If va_list is a record type and we are compiling in C++ mode,
16831 // check the argument using reference binding.
16833 Context, Context.getLValueReferenceType(VaListType), false);
16835 if (Init.isInvalid())
16836 return ExprError();
16837 E = Init.getAs<Expr>();
16838 } else {
16839 // Otherwise, the va_list argument must be an l-value because
16840 // it is modified by va_arg.
16841 if (!E->isTypeDependent() &&
16842 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16843 return ExprError();
16844 }
16845 }
16846
16847 if (!IsMS && !E->isTypeDependent() &&
16848 !Context.hasSameType(VaListType, E->getType()))
16849 return ExprError(
16850 Diag(E->getBeginLoc(),
16851 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16852 << OrigExpr->getType() << E->getSourceRange());
16853
16854 if (!TInfo->getType()->isDependentType()) {
16855 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16856 diag::err_second_parameter_to_va_arg_incomplete,
16857 TInfo->getTypeLoc()))
16858 return ExprError();
16859
16861 TInfo->getType(),
16862 diag::err_second_parameter_to_va_arg_abstract,
16863 TInfo->getTypeLoc()))
16864 return ExprError();
16865
16866 if (!TInfo->getType().isPODType(Context)) {
16867 Diag(TInfo->getTypeLoc().getBeginLoc(),
16868 TInfo->getType()->isObjCLifetimeType()
16869 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16870 : diag::warn_second_parameter_to_va_arg_not_pod)
16871 << TInfo->getType()
16872 << TInfo->getTypeLoc().getSourceRange();
16873 }
16874
16875 if (TInfo->getType()->isArrayType()) {
16877 PDiag(diag::warn_second_parameter_to_va_arg_array)
16878 << TInfo->getType()
16879 << TInfo->getTypeLoc().getSourceRange());
16880 }
16881
16882 // Check for va_arg where arguments of the given type will be promoted
16883 // (i.e. this va_arg is guaranteed to have undefined behavior).
16884 QualType PromoteType;
16885 if (Context.isPromotableIntegerType(TInfo->getType())) {
16886 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16887 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16888 // and C23 7.16.1.1p2 says, in part:
16889 // If type is not compatible with the type of the actual next argument
16890 // (as promoted according to the default argument promotions), the
16891 // behavior is undefined, except for the following cases:
16892 // - both types are pointers to qualified or unqualified versions of
16893 // compatible types;
16894 // - one type is compatible with a signed integer type, the other
16895 // type is compatible with the corresponding unsigned integer type,
16896 // and the value is representable in both types;
16897 // - one type is pointer to qualified or unqualified void and the
16898 // other is a pointer to a qualified or unqualified character type;
16899 // - or, the type of the next argument is nullptr_t and type is a
16900 // pointer type that has the same representation and alignment
16901 // requirements as a pointer to a character type.
16902 // Given that type compatibility is the primary requirement (ignoring
16903 // qualifications), you would think we could call typesAreCompatible()
16904 // directly to test this. However, in C++, that checks for *same type*,
16905 // which causes false positives when passing an enumeration type to
16906 // va_arg. Instead, get the underlying type of the enumeration and pass
16907 // that.
16908 QualType UnderlyingType = TInfo->getType();
16909 if (const auto *ED = UnderlyingType->getAsEnumDecl())
16910 UnderlyingType = ED->getIntegerType();
16911 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16912 /*CompareUnqualified*/ true))
16913 PromoteType = QualType();
16914
16915 // If the types are still not compatible, we need to test whether the
16916 // promoted type and the underlying type are the same except for
16917 // signedness. Ask the AST for the correctly corresponding type and see
16918 // if that's compatible.
16919 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16920 PromoteType->isUnsignedIntegerType() !=
16921 UnderlyingType->isUnsignedIntegerType()) {
16922 UnderlyingType =
16923 UnderlyingType->isUnsignedIntegerType()
16924 ? Context.getCorrespondingSignedType(UnderlyingType)
16925 : Context.getCorrespondingUnsignedType(UnderlyingType);
16926 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16927 /*CompareUnqualified*/ true))
16928 PromoteType = QualType();
16929 }
16930 }
16931 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16932 PromoteType = Context.DoubleTy;
16933 if (!PromoteType.isNull())
16935 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16936 << TInfo->getType()
16937 << PromoteType
16938 << TInfo->getTypeLoc().getSourceRange());
16939 }
16940
16942 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16943}
16944
16946 // The type of __null will be int or long, depending on the size of
16947 // pointers on the target.
16948 QualType Ty;
16949 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
16950 if (pw == Context.getTargetInfo().getIntWidth())
16951 Ty = Context.IntTy;
16952 else if (pw == Context.getTargetInfo().getLongWidth())
16953 Ty = Context.LongTy;
16954 else if (pw == Context.getTargetInfo().getLongLongWidth())
16955 Ty = Context.LongLongTy;
16956 else {
16957 llvm_unreachable("I don't know size of pointer!");
16958 }
16959
16960 return new (Context) GNUNullExpr(Ty, TokenLoc);
16961}
16962
16964 CXXRecordDecl *ImplDecl = nullptr;
16965
16966 // Fetch the std::source_location::__impl decl.
16967 if (NamespaceDecl *Std = S.getStdNamespace()) {
16968 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16970 if (S.LookupQualifiedName(ResultSL, Std)) {
16971 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16972 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16974 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16975 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16976 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16977 }
16978 }
16979 }
16980 }
16981
16982 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16983 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16984 return nullptr;
16985 }
16986
16987 // Verify that __impl is a trivial struct type, with no base classes, and with
16988 // only the four expected fields.
16989 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16990 ImplDecl->getNumBases() != 0) {
16991 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16992 return nullptr;
16993 }
16994
16995 unsigned Count = 0;
16996 for (FieldDecl *F : ImplDecl->fields()) {
16997 StringRef Name = F->getName();
16998
16999 if (Name == "_M_file_name") {
17000 if (F->getType() !=
17002 break;
17003 Count++;
17004 } else if (Name == "_M_function_name") {
17005 if (F->getType() !=
17007 break;
17008 Count++;
17009 } else if (Name == "_M_line") {
17010 if (!F->getType()->isIntegerType())
17011 break;
17012 Count++;
17013 } else if (Name == "_M_column") {
17014 if (!F->getType()->isIntegerType())
17015 break;
17016 Count++;
17017 } else {
17018 Count = 100; // invalid
17019 break;
17020 }
17021 }
17022 if (Count != 4) {
17023 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17024 return nullptr;
17025 }
17026
17027 return ImplDecl;
17028}
17029
17031 SourceLocation BuiltinLoc,
17032 SourceLocation RPLoc) {
17033 QualType ResultTy;
17034 switch (Kind) {
17039 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17040 ResultTy =
17041 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17042 break;
17043 }
17046 ResultTy = Context.UnsignedIntTy;
17047 break;
17051 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17053 return ExprError();
17054 }
17055 ResultTy = Context.getPointerType(
17056 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17057 break;
17058 }
17059
17060 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17061}
17062
17064 SourceLocation BuiltinLoc,
17065 SourceLocation RPLoc,
17066 DeclContext *ParentContext) {
17067 return new (Context)
17068 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17069}
17070
17072 StringLiteral *BinaryData, StringRef FileName) {
17074 Data->BinaryData = BinaryData;
17075 Data->FileName = FileName;
17076 return new (Context)
17077 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17078 Data->getDataElementCount());
17079}
17080
17082 const Expr *SrcExpr) {
17083 if (!DstType->isFunctionPointerType() ||
17084 !SrcExpr->getType()->isFunctionType())
17085 return false;
17086
17087 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17088 if (!DRE)
17089 return false;
17090
17091 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17092 if (!FD)
17093 return false;
17094
17096 /*Complain=*/true,
17097 SrcExpr->getBeginLoc());
17098}
17099
17101 SourceLocation Loc,
17102 QualType DstType, QualType SrcType,
17103 Expr *SrcExpr, AssignmentAction Action,
17104 bool *Complained) {
17105 if (Complained)
17106 *Complained = false;
17107
17108 // Decode the result (notice that AST's are still created for extensions).
17109 bool CheckInferredResultType = false;
17110 bool isInvalid = false;
17111 unsigned DiagKind = 0;
17112 ConversionFixItGenerator ConvHints;
17113 bool MayHaveConvFixit = false;
17114 bool MayHaveFunctionDiff = false;
17115 const ObjCInterfaceDecl *IFace = nullptr;
17116 const ObjCProtocolDecl *PDecl = nullptr;
17117
17118 switch (ConvTy) {
17120 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17121 return false;
17123 // Still a valid conversion, but we may want to diagnose for C++
17124 // compatibility reasons.
17125 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17126 break;
17128 if (getLangOpts().CPlusPlus) {
17129 DiagKind = diag::err_typecheck_convert_pointer_int;
17130 isInvalid = true;
17131 } else {
17132 DiagKind = diag::ext_typecheck_convert_pointer_int;
17133 }
17134 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17135 MayHaveConvFixit = true;
17136 break;
17138 if (getLangOpts().CPlusPlus) {
17139 DiagKind = diag::err_typecheck_convert_int_pointer;
17140 isInvalid = true;
17141 } else {
17142 DiagKind = diag::ext_typecheck_convert_int_pointer;
17143 }
17144 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17145 MayHaveConvFixit = true;
17146 break;
17148 DiagKind =
17149 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17150 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17151 MayHaveConvFixit = true;
17152 break;
17154 if (getLangOpts().CPlusPlus) {
17155 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17156 isInvalid = true;
17157 } else {
17158 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17159 }
17160 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17161 MayHaveConvFixit = true;
17162 break;
17165 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17166 } else if (getLangOpts().CPlusPlus) {
17167 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17168 isInvalid = true;
17169 } else {
17170 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17171 }
17172 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17173 SrcType->isObjCObjectPointerType();
17174 if (CheckInferredResultType) {
17175 SrcType = SrcType.getUnqualifiedType();
17176 DstType = DstType.getUnqualifiedType();
17177 } else {
17178 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17179 }
17180 MayHaveConvFixit = true;
17181 break;
17183 if (getLangOpts().CPlusPlus) {
17184 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17185 isInvalid = true;
17186 } else {
17187 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17188 }
17189 break;
17191 if (getLangOpts().CPlusPlus) {
17192 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17193 isInvalid = true;
17194 } else {
17195 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17196 }
17197 break;
17199 // Perform array-to-pointer decay if necessary.
17200 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17201
17202 isInvalid = true;
17203
17204 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17205 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17206 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17207 DiagKind = diag::err_typecheck_incompatible_address_space;
17208 break;
17209 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17210 DiagKind = diag::err_typecheck_incompatible_ownership;
17211 break;
17212 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17213 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17214 break;
17215 }
17216
17217 llvm_unreachable("unknown error case for discarding qualifiers!");
17218 // fallthrough
17219 }
17221 // If the qualifiers lost were because we were applying the
17222 // (deprecated) C++ conversion from a string literal to a char*
17223 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17224 // Ideally, this check would be performed in
17225 // checkPointerTypesForAssignment. However, that would require a
17226 // bit of refactoring (so that the second argument is an
17227 // expression, rather than a type), which should be done as part
17228 // of a larger effort to fix checkPointerTypesForAssignment for
17229 // C++ semantics.
17230 if (getLangOpts().CPlusPlus &&
17232 return false;
17233 if (getLangOpts().CPlusPlus) {
17234 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17235 isInvalid = true;
17236 } else {
17237 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17238 }
17239
17240 break;
17242 if (getLangOpts().CPlusPlus) {
17243 isInvalid = true;
17244 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17245 } else {
17246 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17247 }
17248 break;
17250 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17251 isInvalid = true;
17252 break;
17254 DiagKind = diag::err_int_to_block_pointer;
17255 isInvalid = true;
17256 break;
17258 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17259 isInvalid = true;
17260 break;
17262 if (SrcType->isObjCQualifiedIdType()) {
17263 const ObjCObjectPointerType *srcOPT =
17264 SrcType->castAs<ObjCObjectPointerType>();
17265 for (auto *srcProto : srcOPT->quals()) {
17266 PDecl = srcProto;
17267 break;
17268 }
17269 if (const ObjCInterfaceType *IFaceT =
17271 IFace = IFaceT->getDecl();
17272 }
17273 else if (DstType->isObjCQualifiedIdType()) {
17274 const ObjCObjectPointerType *dstOPT =
17275 DstType->castAs<ObjCObjectPointerType>();
17276 for (auto *dstProto : dstOPT->quals()) {
17277 PDecl = dstProto;
17278 break;
17279 }
17280 if (const ObjCInterfaceType *IFaceT =
17282 IFace = IFaceT->getDecl();
17283 }
17284 if (getLangOpts().CPlusPlus) {
17285 DiagKind = diag::err_incompatible_qualified_id;
17286 isInvalid = true;
17287 } else {
17288 DiagKind = diag::warn_incompatible_qualified_id;
17289 }
17290 break;
17291 }
17293 if (getLangOpts().CPlusPlus) {
17294 DiagKind = diag::err_incompatible_vectors;
17295 isInvalid = true;
17296 } else {
17297 DiagKind = diag::warn_incompatible_vectors;
17298 }
17299 break;
17301 DiagKind = diag::err_arc_weak_unavailable_assign;
17302 isInvalid = true;
17303 break;
17305 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17306 if (Complained)
17307 *Complained = true;
17308 return true;
17309 }
17310
17311 DiagKind = diag::err_typecheck_convert_incompatible;
17312 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17313 MayHaveConvFixit = true;
17314 isInvalid = true;
17315 MayHaveFunctionDiff = true;
17316 break;
17317 }
17318
17319 QualType FirstType, SecondType;
17320 switch (Action) {
17323 // The destination type comes first.
17324 FirstType = DstType;
17325 SecondType = SrcType;
17326 break;
17327
17334 // The source type comes first.
17335 FirstType = SrcType;
17336 SecondType = DstType;
17337 break;
17338 }
17339
17340 PartialDiagnostic FDiag = PDiag(DiagKind);
17341 AssignmentAction ActionForDiag = Action;
17343 ActionForDiag = AssignmentAction::Passing;
17344
17345 FDiag << FirstType << SecondType << ActionForDiag
17346 << SrcExpr->getSourceRange();
17347
17348 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17349 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17350 auto isPlainChar = [](const clang::Type *Type) {
17351 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17352 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17353 };
17354 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17355 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17356 }
17357
17358 // If we can fix the conversion, suggest the FixIts.
17359 if (!ConvHints.isNull()) {
17360 for (FixItHint &H : ConvHints.Hints)
17361 FDiag << H;
17362 }
17363
17364 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17365
17366 if (MayHaveFunctionDiff)
17367 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17368
17369 Diag(Loc, FDiag);
17370 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17371 DiagKind == diag::err_incompatible_qualified_id) &&
17372 PDecl && IFace && !IFace->hasDefinition())
17373 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17374 << IFace << PDecl;
17375
17376 if (SecondType == Context.OverloadTy)
17378 FirstType, /*TakingAddress=*/true);
17379
17380 if (CheckInferredResultType)
17382
17383 if (Action == AssignmentAction::Returning &&
17386
17387 if (Complained)
17388 *Complained = true;
17389 return isInvalid;
17390}
17391
17393 llvm::APSInt *Result,
17394 AllowFoldKind CanFold) {
17395 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17396 public:
17397 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17398 QualType T) override {
17399 return S.Diag(Loc, diag::err_ice_not_integral)
17400 << T << S.LangOpts.CPlusPlus;
17401 }
17402 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17403 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17404 }
17405 } Diagnoser;
17406
17407 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17408}
17409
17411 llvm::APSInt *Result,
17412 unsigned DiagID,
17413 AllowFoldKind CanFold) {
17414 class IDDiagnoser : public VerifyICEDiagnoser {
17415 unsigned DiagID;
17416
17417 public:
17418 IDDiagnoser(unsigned DiagID)
17419 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17420
17421 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17422 return S.Diag(Loc, DiagID);
17423 }
17424 } Diagnoser(DiagID);
17425
17426 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17427}
17428
17434
17437 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17438}
17439
17442 VerifyICEDiagnoser &Diagnoser,
17443 AllowFoldKind CanFold) {
17444 SourceLocation DiagLoc = E->getBeginLoc();
17445
17446 if (getLangOpts().CPlusPlus11) {
17447 // C++11 [expr.const]p5:
17448 // If an expression of literal class type is used in a context where an
17449 // integral constant expression is required, then that class type shall
17450 // have a single non-explicit conversion function to an integral or
17451 // unscoped enumeration type
17452 ExprResult Converted;
17453 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17454 VerifyICEDiagnoser &BaseDiagnoser;
17455 public:
17456 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17457 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17458 BaseDiagnoser.Suppress, true),
17459 BaseDiagnoser(BaseDiagnoser) {}
17460
17461 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17462 QualType T) override {
17463 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17464 }
17465
17466 SemaDiagnosticBuilder diagnoseIncomplete(
17467 Sema &S, SourceLocation Loc, QualType T) override {
17468 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17469 }
17470
17471 SemaDiagnosticBuilder diagnoseExplicitConv(
17472 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17473 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17474 }
17475
17476 SemaDiagnosticBuilder noteExplicitConv(
17477 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17478 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17479 << ConvTy->isEnumeralType() << ConvTy;
17480 }
17481
17482 SemaDiagnosticBuilder diagnoseAmbiguous(
17483 Sema &S, SourceLocation Loc, QualType T) override {
17484 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17485 }
17486
17487 SemaDiagnosticBuilder noteAmbiguous(
17488 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17489 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17490 << ConvTy->isEnumeralType() << ConvTy;
17491 }
17492
17493 SemaDiagnosticBuilder diagnoseConversion(
17494 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17495 llvm_unreachable("conversion functions are permitted");
17496 }
17497 } ConvertDiagnoser(Diagnoser);
17498
17499 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17500 ConvertDiagnoser);
17501 if (Converted.isInvalid())
17502 return Converted;
17503 E = Converted.get();
17504 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17505 // don't try to evaluate it later. We also don't want to return the
17506 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17507 // this function will attempt to use 'Value'.
17508 if (isa<RecoveryExpr>(E))
17509 return ExprError();
17511 return ExprError();
17512 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17513 // An ICE must be of integral or unscoped enumeration type.
17514 if (!Diagnoser.Suppress)
17515 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17516 << E->getSourceRange();
17517 return ExprError();
17518 }
17519
17520 ExprResult RValueExpr = DefaultLvalueConversion(E);
17521 if (RValueExpr.isInvalid())
17522 return ExprError();
17523
17524 E = RValueExpr.get();
17525
17526 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17527 // in the non-ICE case.
17530 if (Result)
17532 if (!isa<ConstantExpr>(E))
17535
17536 if (Notes.empty())
17537 return E;
17538
17539 // If our only note is the usual "invalid subexpression" note, just point
17540 // the caret at its location rather than producing an essentially
17541 // redundant note.
17542 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17543 diag::note_invalid_subexpr_in_const_expr) {
17544 DiagLoc = Notes[0].first;
17545 Notes.clear();
17546 }
17547
17548 if (getLangOpts().CPlusPlus) {
17549 if (!Diagnoser.Suppress) {
17550 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17551 for (const PartialDiagnosticAt &Note : Notes)
17552 Diag(Note.first, Note.second);
17553 }
17554 return ExprError();
17555 }
17556
17557 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17558 for (const PartialDiagnosticAt &Note : Notes)
17559 Diag(Note.first, Note.second);
17560
17561 return E;
17562 }
17563
17564 Expr::EvalResult EvalResult;
17566 EvalResult.Diag = &Notes;
17567
17568 // Try to evaluate the expression, and produce diagnostics explaining why it's
17569 // not a constant expression as a side-effect.
17570 bool Folded =
17571 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17572 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17573 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17574
17575 if (!isa<ConstantExpr>(E))
17576 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17577
17578 // In C++11, we can rely on diagnostics being produced for any expression
17579 // which is not a constant expression. If no diagnostics were produced, then
17580 // this is a constant expression.
17581 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17582 if (Result)
17583 *Result = EvalResult.Val.getInt();
17584 return E;
17585 }
17586
17587 // If our only note is the usual "invalid subexpression" note, just point
17588 // the caret at its location rather than producing an essentially
17589 // redundant note.
17590 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17591 diag::note_invalid_subexpr_in_const_expr) {
17592 DiagLoc = Notes[0].first;
17593 Notes.clear();
17594 }
17595
17596 if (!Folded || CanFold == AllowFoldKind::No) {
17597 if (!Diagnoser.Suppress) {
17598 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17599 for (const PartialDiagnosticAt &Note : Notes)
17600 Diag(Note.first, Note.second);
17601 }
17602
17603 return ExprError();
17604 }
17605
17606 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17607 for (const PartialDiagnosticAt &Note : Notes)
17608 Diag(Note.first, Note.second);
17609
17610 if (Result)
17611 *Result = EvalResult.Val.getInt();
17612 return E;
17613}
17614
17615namespace {
17616 // Handle the case where we conclude a expression which we speculatively
17617 // considered to be unevaluated is actually evaluated.
17618 class TransformToPE : public TreeTransform<TransformToPE> {
17619 typedef TreeTransform<TransformToPE> BaseTransform;
17620
17621 public:
17622 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17623
17624 // Make sure we redo semantic analysis
17625 bool AlwaysRebuild() { return true; }
17626 bool ReplacingOriginal() { return true; }
17627
17628 // We need to special-case DeclRefExprs referring to FieldDecls which
17629 // are not part of a member pointer formation; normal TreeTransforming
17630 // doesn't catch this case because of the way we represent them in the AST.
17631 // FIXME: This is a bit ugly; is it really the best way to handle this
17632 // case?
17633 //
17634 // Error on DeclRefExprs referring to FieldDecls.
17635 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17636 if (isa<FieldDecl>(E->getDecl()) &&
17637 !SemaRef.isUnevaluatedContext())
17638 return SemaRef.Diag(E->getLocation(),
17639 diag::err_invalid_non_static_member_use)
17640 << E->getDecl() << E->getSourceRange();
17641
17642 return BaseTransform::TransformDeclRefExpr(E);
17643 }
17644
17645 // Exception: filter out member pointer formation
17646 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17647 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17648 return E;
17649
17650 return BaseTransform::TransformUnaryOperator(E);
17651 }
17652
17653 // The body of a lambda-expression is in a separate expression evaluation
17654 // context so never needs to be transformed.
17655 // FIXME: Ideally we wouldn't transform the closure type either, and would
17656 // just recreate the capture expressions and lambda expression.
17657 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17658 return SkipLambdaBody(E, Body);
17659 }
17660 };
17661}
17662
17664 assert(isUnevaluatedContext() &&
17665 "Should only transform unevaluated expressions");
17666 ExprEvalContexts.back().Context =
17667 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17669 return E;
17670 return TransformToPE(*this).TransformExpr(E);
17671}
17672
17674 assert(isUnevaluatedContext() &&
17675 "Should only transform unevaluated expressions");
17678 return TInfo;
17679 return TransformToPE(*this).TransformType(TInfo);
17680}
17681
17682void
17684 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17686 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17687 LambdaContextDecl, ExprContext);
17688
17689 // Discarded statements and immediate contexts nested in other
17690 // discarded statements or immediate context are themselves
17691 // a discarded statement or an immediate context, respectively.
17692 ExprEvalContexts.back().InDiscardedStatement =
17694
17695 // C++23 [expr.const]/p15
17696 // An expression or conversion is in an immediate function context if [...]
17697 // it is a subexpression of a manifestly constant-evaluated expression or
17698 // conversion.
17699 const auto &Prev = parentEvaluationContext();
17700 ExprEvalContexts.back().InImmediateFunctionContext =
17701 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17702
17703 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17704 Prev.InImmediateEscalatingFunctionContext;
17705
17706 Cleanup.reset();
17707 if (!MaybeODRUseExprs.empty())
17708 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17709}
17710
17711void
17715 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17716 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17717}
17718
17720 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
17721 // [expr.const]/p14.1
17722 // An expression or conversion is in an immediate function context if it is
17723 // potentially evaluated and either: its innermost enclosing non-block scope
17724 // is a function parameter scope of an immediate function.
17726 FD && FD->isConsteval()
17728 : NewContext);
17732
17733 Current.InDiscardedStatement = false;
17734
17735 if (FD) {
17736
17737 // Each ExpressionEvaluationContextRecord also keeps track of whether the
17738 // context is nested in an immediate function context, so smaller contexts
17739 // that appear inside immediate functions (like variable initializers) are
17740 // considered to be inside an immediate function context even though by
17741 // themselves they are not immediate function contexts. But when a new
17742 // function is entered, we need to reset this tracking, since the entered
17743 // function might be not an immediate function.
17744
17746 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
17747
17748 if (isLambdaMethod(FD))
17750 FD->isConsteval() ||
17751 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
17752 Parent.isImmediateFunctionContext()));
17753 else
17755 }
17756}
17757
17758namespace {
17759
17760const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17761 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17762 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17763 if (E->getOpcode() == UO_Deref)
17764 return CheckPossibleDeref(S, E->getSubExpr());
17765 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17766 return CheckPossibleDeref(S, E->getBase());
17767 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17768 return CheckPossibleDeref(S, E->getBase());
17769 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17770 QualType Inner;
17771 QualType Ty = E->getType();
17772 if (const auto *Ptr = Ty->getAs<PointerType>())
17773 Inner = Ptr->getPointeeType();
17774 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17775 Inner = Arr->getElementType();
17776 else
17777 return nullptr;
17778
17779 if (Inner->hasAttr(attr::NoDeref))
17780 return E;
17781 }
17782 return nullptr;
17783}
17784
17785} // namespace
17786
17788 for (const Expr *E : Rec.PossibleDerefs) {
17789 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17790 if (DeclRef) {
17791 const ValueDecl *Decl = DeclRef->getDecl();
17792 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17793 << Decl->getName() << E->getSourceRange();
17794 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17795 } else {
17796 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17797 << E->getSourceRange();
17798 }
17799 }
17800 Rec.PossibleDerefs.clear();
17801}
17802
17805 return;
17806
17807 // Note: ignoring parens here is not justified by the standard rules, but
17808 // ignoring parentheses seems like a more reasonable approach, and this only
17809 // drives a deprecation warning so doesn't affect conformance.
17810 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17811 if (BO->getOpcode() == BO_Assign) {
17812 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17813 llvm::erase(LHSs, BO->getLHS());
17814 }
17815 }
17816}
17817
17819 assert(getLangOpts().CPlusPlus20 &&
17820 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17821 "Cannot mark an immediate escalating expression outside of an "
17822 "immediate escalating context");
17823 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17824 Call && Call->getCallee()) {
17825 if (auto *DeclRef =
17826 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17827 DeclRef->setIsImmediateEscalating(true);
17828 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17829 Ctr->setIsImmediateEscalating(true);
17830 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17831 DeclRef->setIsImmediateEscalating(true);
17832 } else {
17833 assert(false && "expected an immediately escalating expression");
17834 }
17836 FI->FoundImmediateEscalatingExpression = true;
17837}
17838
17840 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17841 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17844 return E;
17845
17846 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17847 /// It's OK if this fails; we'll also remove this in
17848 /// HandleImmediateInvocations, but catching it here allows us to avoid
17849 /// walking the AST looking for it in simple cases.
17850 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17851 if (auto *DeclRef =
17852 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17853 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17854
17855 // C++23 [expr.const]/p16
17856 // An expression or conversion is immediate-escalating if it is not initially
17857 // in an immediate function context and it is [...] an immediate invocation
17858 // that is not a constant expression and is not a subexpression of an
17859 // immediate invocation.
17860 APValue Cached;
17861 auto CheckConstantExpressionAndKeepResult = [&]() {
17863 Expr::EvalResult Eval;
17864 Eval.Diag = &Notes;
17865 bool Res = E.get()->EvaluateAsConstantExpr(
17866 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17867 if (Res && Notes.empty()) {
17868 Cached = std::move(Eval.Val);
17869 return true;
17870 }
17871 return false;
17872 };
17873
17874 if (!E.get()->isValueDependent() &&
17875 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17876 !CheckConstantExpressionAndKeepResult()) {
17878 return E;
17879 }
17880
17881 if (Cleanup.exprNeedsCleanups()) {
17882 // Since an immediate invocation is a full expression itself - it requires
17883 // an additional ExprWithCleanups node, but it can participate to a bigger
17884 // full expression which actually requires cleanups to be run after so
17885 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17886 // may discard cleanups for outer expression too early.
17887
17888 // Note that ExprWithCleanups created here must always have empty cleanup
17889 // objects:
17890 // - compound literals do not create cleanup objects in C++ and immediate
17891 // invocations are C++-only.
17892 // - blocks are not allowed inside constant expressions and compiler will
17893 // issue an error if they appear there.
17894 //
17895 // Hence, in correct code any cleanup objects created inside current
17896 // evaluation context must be outside the immediate invocation.
17898 Cleanup.cleanupsHaveSideEffects(), {});
17899 }
17900
17902 getASTContext(), E.get(),
17903 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17904 getASTContext()),
17905 /*IsImmediateInvocation*/ true);
17906 if (Cached.hasValue())
17907 Res->MoveIntoResult(Cached, getASTContext());
17908 /// Value-dependent constant expressions should not be immediately
17909 /// evaluated until they are instantiated.
17910 if (!Res->isValueDependent())
17911 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17912 return Res;
17913}
17914
17918 Expr::EvalResult Eval;
17919 Eval.Diag = &Notes;
17920 ConstantExpr *CE = Candidate.getPointer();
17921 bool Result = CE->EvaluateAsConstantExpr(
17922 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17923 if (!Result || !Notes.empty()) {
17925 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17926 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17927 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17928 FunctionDecl *FD = nullptr;
17929 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17930 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17931 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17932 FD = Call->getConstructor();
17933 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17934 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17935
17936 assert(FD && FD->isImmediateFunction() &&
17937 "could not find an immediate function in this expression");
17938 if (FD->isInvalidDecl())
17939 return;
17940 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17941 << FD << FD->isConsteval();
17942 if (auto Context =
17944 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17945 << Context->Decl;
17946 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17947 }
17948 if (!FD->isConsteval())
17950 for (auto &Note : Notes)
17951 SemaRef.Diag(Note.first, Note.second);
17952 return;
17953 }
17955}
17956
17960 struct ComplexRemove : TreeTransform<ComplexRemove> {
17962 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17965 CurrentII;
17966 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17969 4>::reverse_iterator Current)
17970 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17971 void RemoveImmediateInvocation(ConstantExpr* E) {
17972 auto It = std::find_if(CurrentII, IISet.rend(),
17974 return Elem.getPointer() == E;
17975 });
17976 // It is possible that some subexpression of the current immediate
17977 // invocation was handled from another expression evaluation context. Do
17978 // not handle the current immediate invocation if some of its
17979 // subexpressions failed before.
17980 if (It == IISet.rend()) {
17981 if (SemaRef.FailedImmediateInvocations.contains(E))
17982 CurrentII->setInt(1);
17983 } else {
17984 It->setInt(1); // Mark as deleted
17985 }
17986 }
17987 ExprResult TransformConstantExpr(ConstantExpr *E) {
17988 if (!E->isImmediateInvocation())
17989 return Base::TransformConstantExpr(E);
17990 RemoveImmediateInvocation(E);
17991 return Base::TransformExpr(E->getSubExpr());
17992 }
17993 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17994 /// we need to remove its DeclRefExpr from the DRSet.
17995 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17996 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17997 return Base::TransformCXXOperatorCallExpr(E);
17998 }
17999 /// Base::TransformUserDefinedLiteral doesn't preserve the
18000 /// UserDefinedLiteral node.
18001 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18002 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18003 /// here.
18004 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18005 if (!Init)
18006 return Init;
18007
18008 // We cannot use IgnoreImpCasts because we need to preserve
18009 // full expressions.
18010 while (true) {
18011 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18012 Init = ICE->getSubExpr();
18013 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18014 Init = ICE->getSubExpr();
18015 else
18016 break;
18017 }
18018 /// ConstantExprs are the first layer of implicit node to be removed so if
18019 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18020 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18021 CE && CE->isImmediateInvocation())
18022 RemoveImmediateInvocation(CE);
18023 return Base::TransformInitializer(Init, NotCopyInit);
18024 }
18025 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18026 DRSet.erase(E);
18027 return E;
18028 }
18029 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18030 // Do not rebuild lambdas to avoid creating a new type.
18031 // Lambdas have already been processed inside their eval contexts.
18032 return E;
18033 }
18034 bool AlwaysRebuild() { return false; }
18035 bool ReplacingOriginal() { return true; }
18036 bool AllowSkippingCXXConstructExpr() {
18037 bool Res = AllowSkippingFirstCXXConstructExpr;
18038 AllowSkippingFirstCXXConstructExpr = true;
18039 return Res;
18040 }
18041 bool AllowSkippingFirstCXXConstructExpr = true;
18042 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18044
18045 /// CXXConstructExpr with a single argument are getting skipped by
18046 /// TreeTransform in some situtation because they could be implicit. This
18047 /// can only occur for the top-level CXXConstructExpr because it is used
18048 /// nowhere in the expression being transformed therefore will not be rebuilt.
18049 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18050 /// skipping the first CXXConstructExpr.
18051 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18052 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18053
18054 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18055 // The result may not be usable in case of previous compilation errors.
18056 // In this case evaluation of the expression may result in crash so just
18057 // don't do anything further with the result.
18058 if (Res.isUsable()) {
18060 It->getPointer()->setSubExpr(Res.get());
18061 }
18062}
18063
18064static void
18067 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18068 Rec.ReferenceToConsteval.size() == 0) ||
18070 return;
18071
18072 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18073 // [...]
18074 // - the initializer of a variable that is usable in constant expressions or
18075 // has constant initialization.
18076 if (SemaRef.getLangOpts().CPlusPlus23 &&
18077 Rec.ExprContext ==
18079 auto *VD = cast<VarDecl>(Rec.ManglingContextDecl);
18080 if (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18081 VD->hasConstantInitialization()) {
18082 // An expression or conversion is in an 'immediate function context' if it
18083 // is potentially evaluated and either:
18084 // [...]
18085 // - it is a subexpression of a manifestly constant-evaluated expression
18086 // or conversion.
18087 return;
18088 }
18089 }
18090
18091 /// When we have more than 1 ImmediateInvocationCandidates or previously
18092 /// failed immediate invocations, we need to check for nested
18093 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18094 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18095 /// invocation.
18096 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18098
18099 /// Prevent sema calls during the tree transform from adding pointers that
18100 /// are already in the sets.
18101 llvm::SaveAndRestore DisableIITracking(
18103
18104 /// Prevent diagnostic during tree transfrom as they are duplicates
18106
18107 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18108 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18109 if (!It->getInt())
18111 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18112 Rec.ReferenceToConsteval.size()) {
18113 struct SimpleRemove : DynamicRecursiveASTVisitor {
18114 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18115 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18116 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18117 DRSet.erase(E);
18118 return DRSet.size();
18119 }
18120 } Visitor(Rec.ReferenceToConsteval);
18121 Visitor.TraverseStmt(
18122 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18123 }
18124 for (auto CE : Rec.ImmediateInvocationCandidates)
18125 if (!CE.getInt())
18127 for (auto *DR : Rec.ReferenceToConsteval) {
18128 // If the expression is immediate escalating, it is not an error;
18129 // The outer context itself becomes immediate and further errors,
18130 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18131 if (DR->isImmediateEscalating())
18132 continue;
18133 auto *FD = cast<FunctionDecl>(DR->getDecl());
18134 const NamedDecl *ND = FD;
18135 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18136 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18137 ND = MD->getParent();
18138
18139 // C++23 [expr.const]/p16
18140 // An expression or conversion is immediate-escalating if it is not
18141 // initially in an immediate function context and it is [...] a
18142 // potentially-evaluated id-expression that denotes an immediate function
18143 // that is not a subexpression of an immediate invocation.
18144 bool ImmediateEscalating = false;
18145 bool IsPotentiallyEvaluated =
18146 Rec.Context ==
18148 Rec.Context ==
18150 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18151 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18152
18154 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18155 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18156 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18157 if (!FD->getBuiltinID())
18158 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18159 if (auto Context =
18161 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18162 << Context->Decl;
18163 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18164 }
18165 if (FD->isImmediateEscalating() && !FD->isConsteval())
18167
18168 } else {
18170 }
18171 }
18172}
18173
18176 if (!Rec.Lambdas.empty()) {
18178 if (!getLangOpts().CPlusPlus20 &&
18179 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18180 Rec.isUnevaluated() ||
18182 unsigned D;
18183 if (Rec.isUnevaluated()) {
18184 // C++11 [expr.prim.lambda]p2:
18185 // A lambda-expression shall not appear in an unevaluated operand
18186 // (Clause 5).
18187 D = diag::err_lambda_unevaluated_operand;
18188 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18189 // C++1y [expr.const]p2:
18190 // A conditional-expression e is a core constant expression unless the
18191 // evaluation of e, following the rules of the abstract machine, would
18192 // evaluate [...] a lambda-expression.
18193 D = diag::err_lambda_in_constant_expression;
18194 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18195 // C++17 [expr.prim.lamda]p2:
18196 // A lambda-expression shall not appear [...] in a template-argument.
18197 D = diag::err_lambda_in_invalid_context;
18198 } else
18199 llvm_unreachable("Couldn't infer lambda error message.");
18200
18201 for (const auto *L : Rec.Lambdas)
18202 Diag(L->getBeginLoc(), D);
18203 }
18204 }
18205
18206 // Append the collected materialized temporaries into previous context before
18207 // exit if the previous also is a lifetime extending context.
18209 parentEvaluationContext().InLifetimeExtendingContext &&
18210 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18213 }
18214
18216 HandleImmediateInvocations(*this, Rec);
18217
18218 // Warn on any volatile-qualified simple-assignments that are not discarded-
18219 // value expressions nor unevaluated operands (those cases get removed from
18220 // this list by CheckUnusedVolatileAssignment).
18221 for (auto *BO : Rec.VolatileAssignmentLHSs)
18222 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18223 << BO->getType();
18224
18225 // When are coming out of an unevaluated context, clear out any
18226 // temporaries that we may have created as part of the evaluation of
18227 // the expression in that context: they aren't relevant because they
18228 // will never be constructed.
18229 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18231 ExprCleanupObjects.end());
18232 Cleanup = Rec.ParentCleanup;
18235 // Otherwise, merge the contexts together.
18236 } else {
18237 Cleanup.mergeFrom(Rec.ParentCleanup);
18238 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18239 }
18240
18242
18243 // Pop the current expression evaluation context off the stack.
18244 ExprEvalContexts.pop_back();
18245}
18246
18248 ExprCleanupObjects.erase(
18249 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18250 ExprCleanupObjects.end());
18251 Cleanup.reset();
18252 MaybeODRUseExprs.clear();
18253}
18254
18257 if (Result.isInvalid())
18258 return ExprError();
18259 E = Result.get();
18260 if (!E->getType()->isVariablyModifiedType())
18261 return E;
18263}
18264
18265/// Are we in a context that is potentially constant evaluated per C++20
18266/// [expr.const]p12?
18268 /// C++2a [expr.const]p12:
18269 // An expression or conversion is potentially constant evaluated if it is
18270 switch (SemaRef.ExprEvalContexts.back().Context) {
18273
18274 // -- a manifestly constant-evaluated expression,
18278 // -- a potentially-evaluated expression,
18280 // -- an immediate subexpression of a braced-init-list,
18281
18282 // -- [FIXME] an expression of the form & cast-expression that occurs
18283 // within a templated entity
18284 // -- a subexpression of one of the above that is not a subexpression of
18285 // a nested unevaluated operand.
18286 return true;
18287
18290 // Expressions in this context are never evaluated.
18291 return false;
18292 }
18293 llvm_unreachable("Invalid context");
18294}
18295
18296/// Return true if this function has a calling convention that requires mangling
18297/// in the size of the parameter pack.
18299 // These manglings are only applicable for targets whcih use Microsoft
18300 // mangling scheme for C.
18302 return false;
18303
18304 // If this is C++ and this isn't an extern "C" function, parameters do not
18305 // need to be complete. In this case, C++ mangling will apply, which doesn't
18306 // use the size of the parameters.
18307 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18308 return false;
18309
18310 // Stdcall, fastcall, and vectorcall need this special treatment.
18311 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18312 switch (CC) {
18313 case CC_X86StdCall:
18314 case CC_X86FastCall:
18315 case CC_X86VectorCall:
18316 return true;
18317 default:
18318 break;
18319 }
18320 return false;
18321}
18322
18323/// Require that all of the parameter types of function be complete. Normally,
18324/// parameter types are only required to be complete when a function is called
18325/// or defined, but to mangle functions with certain calling conventions, the
18326/// mangler needs to know the size of the parameter list. In this situation,
18327/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18328/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18329/// result in a linker error. Clang doesn't implement this behavior, and instead
18330/// attempts to error at compile time.
18332 SourceLocation Loc) {
18333 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18334 FunctionDecl *FD;
18335 ParmVarDecl *Param;
18336
18337 public:
18338 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18339 : FD(FD), Param(Param) {}
18340
18341 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18342 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18343 StringRef CCName;
18344 switch (CC) {
18345 case CC_X86StdCall:
18346 CCName = "stdcall";
18347 break;
18348 case CC_X86FastCall:
18349 CCName = "fastcall";
18350 break;
18351 case CC_X86VectorCall:
18352 CCName = "vectorcall";
18353 break;
18354 default:
18355 llvm_unreachable("CC does not need mangling");
18356 }
18357
18358 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18359 << Param->getDeclName() << FD->getDeclName() << CCName;
18360 }
18361 };
18362
18363 for (ParmVarDecl *Param : FD->parameters()) {
18364 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18365 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18366 }
18367}
18368
18369namespace {
18370enum class OdrUseContext {
18371 /// Declarations in this context are not odr-used.
18372 None,
18373 /// Declarations in this context are formally odr-used, but this is a
18374 /// dependent context.
18375 Dependent,
18376 /// Declarations in this context are odr-used but not actually used (yet).
18377 FormallyOdrUsed,
18378 /// Declarations in this context are used.
18379 Used
18380};
18381}
18382
18383/// Are we within a context in which references to resolved functions or to
18384/// variables result in odr-use?
18385static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18388
18389 if (Context.isUnevaluated())
18390 return OdrUseContext::None;
18391
18393 return OdrUseContext::Dependent;
18394
18395 if (Context.isDiscardedStatementContext())
18396 return OdrUseContext::FormallyOdrUsed;
18397
18398 else if (Context.Context ==
18400 return OdrUseContext::FormallyOdrUsed;
18401
18402 return OdrUseContext::Used;
18403}
18404
18406 if (!Func->isConstexpr())
18407 return false;
18408
18409 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18410 return true;
18411
18412 // Lambda conversion operators are never user provided.
18413 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18414 return isLambdaConversionOperator(Conv);
18415
18416 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18417 return CCD && CCD->getInheritedConstructor();
18418}
18419
18421 bool MightBeOdrUse) {
18422 assert(Func && "No function?");
18423
18424 Func->setReferenced();
18425
18426 // Recursive functions aren't really used until they're used from some other
18427 // context.
18428 bool IsRecursiveCall = CurContext == Func;
18429
18430 // C++11 [basic.def.odr]p3:
18431 // A function whose name appears as a potentially-evaluated expression is
18432 // odr-used if it is the unique lookup result or the selected member of a
18433 // set of overloaded functions [...].
18434 //
18435 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18436 // can just check that here.
18437 OdrUseContext OdrUse =
18438 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18439 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18440 OdrUse = OdrUseContext::FormallyOdrUsed;
18441
18442 // Trivial default constructors and destructors are never actually used.
18443 // FIXME: What about other special members?
18444 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18445 OdrUse == OdrUseContext::Used) {
18446 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18447 if (Constructor->isDefaultConstructor())
18448 OdrUse = OdrUseContext::FormallyOdrUsed;
18450 OdrUse = OdrUseContext::FormallyOdrUsed;
18451 }
18452
18453 // C++20 [expr.const]p12:
18454 // A function [...] is needed for constant evaluation if it is [...] a
18455 // constexpr function that is named by an expression that is potentially
18456 // constant evaluated
18457 bool NeededForConstantEvaluation =
18460
18461 // Determine whether we require a function definition to exist, per
18462 // C++11 [temp.inst]p3:
18463 // Unless a function template specialization has been explicitly
18464 // instantiated or explicitly specialized, the function template
18465 // specialization is implicitly instantiated when the specialization is
18466 // referenced in a context that requires a function definition to exist.
18467 // C++20 [temp.inst]p7:
18468 // The existence of a definition of a [...] function is considered to
18469 // affect the semantics of the program if the [...] function is needed for
18470 // constant evaluation by an expression
18471 // C++20 [basic.def.odr]p10:
18472 // Every program shall contain exactly one definition of every non-inline
18473 // function or variable that is odr-used in that program outside of a
18474 // discarded statement
18475 // C++20 [special]p1:
18476 // The implementation will implicitly define [defaulted special members]
18477 // if they are odr-used or needed for constant evaluation.
18478 //
18479 // Note that we skip the implicit instantiation of templates that are only
18480 // used in unused default arguments or by recursive calls to themselves.
18481 // This is formally non-conforming, but seems reasonable in practice.
18482 bool NeedDefinition =
18483 !IsRecursiveCall &&
18484 (OdrUse == OdrUseContext::Used ||
18485 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18486
18487 // C++14 [temp.expl.spec]p6:
18488 // If a template [...] is explicitly specialized then that specialization
18489 // shall be declared before the first use of that specialization that would
18490 // cause an implicit instantiation to take place, in every translation unit
18491 // in which such a use occurs
18492 if (NeedDefinition &&
18493 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18494 Func->getMemberSpecializationInfo()))
18496
18497 if (getLangOpts().CUDA)
18498 CUDA().CheckCall(Loc, Func);
18499
18500 // If we need a definition, try to create one.
18501 if (NeedDefinition && !Func->getBody()) {
18504 dyn_cast<CXXConstructorDecl>(Func)) {
18506 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18507 if (Constructor->isDefaultConstructor()) {
18508 if (Constructor->isTrivial() &&
18509 !Constructor->hasAttr<DLLExportAttr>())
18510 return;
18512 } else if (Constructor->isCopyConstructor()) {
18514 } else if (Constructor->isMoveConstructor()) {
18516 }
18517 } else if (Constructor->getInheritedConstructor()) {
18519 }
18520 } else if (CXXDestructorDecl *Destructor =
18521 dyn_cast<CXXDestructorDecl>(Func)) {
18523 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18524 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18525 return;
18527 }
18528 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18529 MarkVTableUsed(Loc, Destructor->getParent());
18530 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18531 if (MethodDecl->isOverloadedOperator() &&
18532 MethodDecl->getOverloadedOperator() == OO_Equal) {
18533 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18534 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18535 if (MethodDecl->isCopyAssignmentOperator())
18536 DefineImplicitCopyAssignment(Loc, MethodDecl);
18537 else if (MethodDecl->isMoveAssignmentOperator())
18538 DefineImplicitMoveAssignment(Loc, MethodDecl);
18539 }
18540 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18541 MethodDecl->getParent()->isLambda()) {
18542 CXXConversionDecl *Conversion =
18543 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18544 if (Conversion->isLambdaToBlockPointerConversion())
18546 else
18548 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18549 MarkVTableUsed(Loc, MethodDecl->getParent());
18550 }
18551
18552 if (Func->isDefaulted() && !Func->isDeleted()) {
18556 }
18557
18558 // Implicit instantiation of function templates and member functions of
18559 // class templates.
18560 if (Func->isImplicitlyInstantiable()) {
18562 Func->getTemplateSpecializationKindForInstantiation();
18563 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18564 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18565 if (FirstInstantiation) {
18566 PointOfInstantiation = Loc;
18567 if (auto *MSI = Func->getMemberSpecializationInfo())
18568 MSI->setPointOfInstantiation(Loc);
18569 // FIXME: Notify listener.
18570 else
18571 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18572 } else if (TSK != TSK_ImplicitInstantiation) {
18573 // Use the point of use as the point of instantiation, instead of the
18574 // point of explicit instantiation (which we track as the actual point
18575 // of instantiation). This gives better backtraces in diagnostics.
18576 PointOfInstantiation = Loc;
18577 }
18578
18579 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18580 Func->isConstexpr()) {
18581 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18582 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18583 CodeSynthesisContexts.size())
18585 std::make_pair(Func, PointOfInstantiation));
18586 else if (Func->isConstexpr())
18587 // Do not defer instantiations of constexpr functions, to avoid the
18588 // expression evaluator needing to call back into Sema if it sees a
18589 // call to such a function.
18590 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18591 else {
18592 Func->setInstantiationIsPending(true);
18593 PendingInstantiations.push_back(
18594 std::make_pair(Func, PointOfInstantiation));
18595 if (llvm::isTimeTraceVerbose()) {
18596 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
18597 std::string Name;
18598 llvm::raw_string_ostream OS(Name);
18599 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
18600 /*Qualified=*/true);
18601 return Name;
18602 });
18603 }
18604 // Notify the consumer that a function was implicitly instantiated.
18605 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18606 }
18607 }
18608 } else {
18609 // Walk redefinitions, as some of them may be instantiable.
18610 for (auto *i : Func->redecls()) {
18611 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18612 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18613 }
18614 }
18615 });
18616 }
18617
18618 // If a constructor was defined in the context of a default parameter
18619 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18620 // context), its initializers may not be referenced yet.
18621 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18623 *this,
18624 Constructor->isImmediateFunction()
18627 Constructor);
18628 for (CXXCtorInitializer *Init : Constructor->inits()) {
18629 if (Init->isInClassMemberInitializer())
18630 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18631 MarkDeclarationsReferencedInExpr(Init->getInit());
18632 });
18633 }
18634 }
18635
18636 // C++14 [except.spec]p17:
18637 // An exception-specification is considered to be needed when:
18638 // - the function is odr-used or, if it appears in an unevaluated operand,
18639 // would be odr-used if the expression were potentially-evaluated;
18640 //
18641 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18642 // function is a pure virtual function we're calling, and in that case the
18643 // function was selected by overload resolution and we need to resolve its
18644 // exception specification for a different reason.
18645 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18647 ResolveExceptionSpec(Loc, FPT);
18648
18649 // A callee could be called by a host function then by a device function.
18650 // If we only try recording once, we will miss recording the use on device
18651 // side. Therefore keep trying until it is recorded.
18652 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18653 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
18655
18656 // If this is the first "real" use, act on that.
18657 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18658 // Keep track of used but undefined functions.
18659 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
18660 if (mightHaveNonExternalLinkage(Func))
18661 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18662 else if (Func->getMostRecentDecl()->isInlined() &&
18663 !LangOpts.GNUInline &&
18664 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18665 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18667 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18668 }
18669
18670 // Some x86 Windows calling conventions mangle the size of the parameter
18671 // pack into the name. Computing the size of the parameters requires the
18672 // parameter types to be complete. Check that now.
18675
18676 // In the MS C++ ABI, the compiler emits destructor variants where they are
18677 // used. If the destructor is used here but defined elsewhere, mark the
18678 // virtual base destructors referenced. If those virtual base destructors
18679 // are inline, this will ensure they are defined when emitting the complete
18680 // destructor variant. This checking may be redundant if the destructor is
18681 // provided later in this TU.
18682 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18683 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18684 CXXRecordDecl *Parent = Dtor->getParent();
18685 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18687 }
18688 }
18689
18690 Func->markUsed(Context);
18691 }
18692}
18693
18694/// Directly mark a variable odr-used. Given a choice, prefer to use
18695/// MarkVariableReferenced since it does additional checks and then
18696/// calls MarkVarDeclODRUsed.
18697/// If the variable must be captured:
18698/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18699/// - else capture it in the DeclContext that maps to the
18700/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18701static void
18703 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18704 // Keep track of used but undefined variables.
18705 // FIXME: We shouldn't suppress this warning for static data members.
18706 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18707 assert(Var && "expected a capturable variable");
18708
18710 (!Var->isExternallyVisible() || Var->isInline() ||
18712 !(Var->isStaticDataMember() && Var->hasInit())) {
18714 if (old.isInvalid())
18715 old = Loc;
18716 }
18717 QualType CaptureType, DeclRefType;
18718 if (SemaRef.LangOpts.OpenMP)
18721 /*EllipsisLoc*/ SourceLocation(),
18722 /*BuildAndDiagnose*/ true, CaptureType,
18723 DeclRefType, FunctionScopeIndexToStopAt);
18724
18725 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18726 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18727 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18728 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18729 if (VarTarget == SemaCUDA::CVT_Host &&
18730 (UserTarget == CUDAFunctionTarget::Device ||
18731 UserTarget == CUDAFunctionTarget::HostDevice ||
18732 UserTarget == CUDAFunctionTarget::Global)) {
18733 // Diagnose ODR-use of host global variables in device functions.
18734 // Reference of device global variables in host functions is allowed
18735 // through shadow variables therefore it is not diagnosed.
18736 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18737 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18738 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18740 Var->getType().isConstQualified()
18741 ? diag::note_cuda_const_var_unpromoted
18742 : diag::note_cuda_host_var);
18743 }
18744 } else if (VarTarget == SemaCUDA::CVT_Device &&
18745 !Var->hasAttr<CUDASharedAttr>() &&
18746 (UserTarget == CUDAFunctionTarget::Host ||
18747 UserTarget == CUDAFunctionTarget::HostDevice)) {
18748 // Record a CUDA/HIP device side variable if it is ODR-used
18749 // by host code. This is done conservatively, when the variable is
18750 // referenced in any of the following contexts:
18751 // - a non-function context
18752 // - a host function
18753 // - a host device function
18754 // This makes the ODR-use of the device side variable by host code to
18755 // be visible in the device compilation for the compiler to be able to
18756 // emit template variables instantiated by host code only and to
18757 // externalize the static device side variable ODR-used by host code.
18758 if (!Var->hasExternalStorage())
18760 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18761 (!FD || (!FD->getDescribedFunctionTemplate() &&
18765 }
18766 }
18767
18768 V->markUsed(SemaRef.Context);
18769}
18770
18772 SourceLocation Loc,
18773 unsigned CapturingScopeIndex) {
18774 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18775}
18776
18778 SourceLocation loc,
18779 ValueDecl *var) {
18780 DeclContext *VarDC = var->getDeclContext();
18781
18782 // If the parameter still belongs to the translation unit, then
18783 // we're actually just using one parameter in the declaration of
18784 // the next.
18785 if (isa<ParmVarDecl>(var) &&
18787 return;
18788
18789 // For C code, don't diagnose about capture if we're not actually in code
18790 // right now; it's impossible to write a non-constant expression outside of
18791 // function context, so we'll get other (more useful) diagnostics later.
18792 //
18793 // For C++, things get a bit more nasty... it would be nice to suppress this
18794 // diagnostic for certain cases like using a local variable in an array bound
18795 // for a member of a local class, but the correct predicate is not obvious.
18796 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18797 return;
18798
18799 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18800 unsigned ContextKind = 3; // unknown
18801 if (isa<CXXMethodDecl>(VarDC) &&
18802 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18803 ContextKind = 2;
18804 } else if (isa<FunctionDecl>(VarDC)) {
18805 ContextKind = 0;
18806 } else if (isa<BlockDecl>(VarDC)) {
18807 ContextKind = 1;
18808 }
18809
18810 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18811 << var << ValueKind << ContextKind << VarDC;
18812 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18813 << var;
18814
18815 // FIXME: Add additional diagnostic info about class etc. which prevents
18816 // capture.
18817}
18818
18820 ValueDecl *Var,
18821 bool &SubCapturesAreNested,
18822 QualType &CaptureType,
18823 QualType &DeclRefType) {
18824 // Check whether we've already captured it.
18825 if (CSI->CaptureMap.count(Var)) {
18826 // If we found a capture, any subcaptures are nested.
18827 SubCapturesAreNested = true;
18828
18829 // Retrieve the capture type for this variable.
18830 CaptureType = CSI->getCapture(Var).getCaptureType();
18831
18832 // Compute the type of an expression that refers to this variable.
18833 DeclRefType = CaptureType.getNonReferenceType();
18834
18835 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18836 // are mutable in the sense that user can change their value - they are
18837 // private instances of the captured declarations.
18838 const Capture &Cap = CSI->getCapture(Var);
18839 // C++ [expr.prim.lambda]p10:
18840 // The type of such a data member is [...] an lvalue reference to the
18841 // referenced function type if the entity is a reference to a function.
18842 // [...]
18843 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
18844 !(isa<LambdaScopeInfo>(CSI) &&
18845 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18847 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18848 DeclRefType.addConst();
18849 return true;
18850 }
18851 return false;
18852}
18853
18854// Only block literals, captured statements, and lambda expressions can
18855// capture; other scopes don't work.
18857 ValueDecl *Var,
18858 SourceLocation Loc,
18859 const bool Diagnose,
18860 Sema &S) {
18863
18864 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18865 if (Underlying) {
18866 if (Underlying->hasLocalStorage() && Diagnose)
18868 }
18869 return nullptr;
18870}
18871
18872// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18873// certain types of variables (unnamed, variably modified types etc.)
18874// so check for eligibility.
18876 SourceLocation Loc, const bool Diagnose,
18877 Sema &S) {
18878
18879 assert((isa<VarDecl, BindingDecl>(Var)) &&
18880 "Only variables and structured bindings can be captured");
18881
18882 bool IsBlock = isa<BlockScopeInfo>(CSI);
18883 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18884
18885 // Lambdas are not allowed to capture unnamed variables
18886 // (e.g. anonymous unions).
18887 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18888 // assuming that's the intent.
18889 if (IsLambda && !Var->getDeclName()) {
18890 if (Diagnose) {
18891 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18892 S.Diag(Var->getLocation(), diag::note_declared_at);
18893 }
18894 return false;
18895 }
18896
18897 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18898 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18899 if (Diagnose) {
18900 S.Diag(Loc, diag::err_ref_vm_type);
18901 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18902 }
18903 return false;
18904 }
18905 // Prohibit structs with flexible array members too.
18906 // We cannot capture what is in the tail end of the struct.
18907 if (const auto *VTD = Var->getType()->getAsRecordDecl();
18908 VTD && VTD->hasFlexibleArrayMember()) {
18909 if (Diagnose) {
18910 if (IsBlock)
18911 S.Diag(Loc, diag::err_ref_flexarray_type);
18912 else
18913 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18914 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18915 }
18916 return false;
18917 }
18918 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18919 // Lambdas and captured statements are not allowed to capture __block
18920 // variables; they don't support the expected semantics.
18921 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18922 if (Diagnose) {
18923 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18924 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18925 }
18926 return false;
18927 }
18928 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18929 if (S.getLangOpts().OpenCL && IsBlock &&
18930 Var->getType()->isBlockPointerType()) {
18931 if (Diagnose)
18932 S.Diag(Loc, diag::err_opencl_block_ref_block);
18933 return false;
18934 }
18935
18936 if (isa<BindingDecl>(Var)) {
18937 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18938 if (Diagnose)
18940 return false;
18941 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18942 S.Diag(Loc, S.LangOpts.CPlusPlus20
18943 ? diag::warn_cxx17_compat_capture_binding
18944 : diag::ext_capture_binding)
18945 << Var;
18946 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18947 }
18948 }
18949
18950 return true;
18951}
18952
18953// Returns true if the capture by block was successful.
18955 SourceLocation Loc, const bool BuildAndDiagnose,
18956 QualType &CaptureType, QualType &DeclRefType,
18957 const bool Nested, Sema &S, bool Invalid) {
18958 bool ByRef = false;
18959
18960 // Blocks are not allowed to capture arrays, excepting OpenCL.
18961 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18962 // (decayed to pointers).
18963 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18964 if (BuildAndDiagnose) {
18965 S.Diag(Loc, diag::err_ref_array_type);
18966 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18967 Invalid = true;
18968 } else {
18969 return false;
18970 }
18971 }
18972
18973 // Forbid the block-capture of autoreleasing variables.
18974 if (!Invalid &&
18976 if (BuildAndDiagnose) {
18977 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18978 << /*block*/ 0;
18979 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18980 Invalid = true;
18981 } else {
18982 return false;
18983 }
18984 }
18985
18986 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18987 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18988 QualType PointeeTy = PT->getPointeeType();
18989
18990 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18992 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18993 if (BuildAndDiagnose) {
18994 SourceLocation VarLoc = Var->getLocation();
18995 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18996 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18997 }
18998 }
18999 }
19000
19001 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19002 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19003 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19004 // Block capture by reference does not change the capture or
19005 // declaration reference types.
19006 ByRef = true;
19007 } else {
19008 // Block capture by copy introduces 'const'.
19009 CaptureType = CaptureType.getNonReferenceType().withConst();
19010 DeclRefType = CaptureType;
19011 }
19012
19013 // Actually capture the variable.
19014 if (BuildAndDiagnose)
19015 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19016 CaptureType, Invalid);
19017
19018 return !Invalid;
19019}
19020
19021/// Capture the given variable in the captured region.
19024 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19025 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19026 Sema &S, bool Invalid) {
19027 // By default, capture variables by reference.
19028 bool ByRef = true;
19029 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19030 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19031 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19032 // Using an LValue reference type is consistent with Lambdas (see below).
19033 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19034 bool HasConst = DeclRefType.isConstQualified();
19035 DeclRefType = DeclRefType.getUnqualifiedType();
19036 // Don't lose diagnostics about assignments to const.
19037 if (HasConst)
19038 DeclRefType.addConst();
19039 }
19040 // Do not capture firstprivates in tasks.
19041 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19042 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19043 return true;
19044 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19045 RSI->OpenMPCaptureLevel);
19046 }
19047
19048 if (ByRef)
19049 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19050 else
19051 CaptureType = DeclRefType;
19052
19053 // Actually capture the variable.
19054 if (BuildAndDiagnose)
19055 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19056 Loc, SourceLocation(), CaptureType, Invalid);
19057
19058 return !Invalid;
19059}
19060
19061/// Capture the given variable in the lambda.
19063 SourceLocation Loc, const bool BuildAndDiagnose,
19064 QualType &CaptureType, QualType &DeclRefType,
19065 const bool RefersToCapturedVariable,
19066 const TryCaptureKind Kind,
19067 SourceLocation EllipsisLoc, const bool IsTopScope,
19068 Sema &S, bool Invalid) {
19069 // Determine whether we are capturing by reference or by value.
19070 bool ByRef = false;
19071 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19072 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19073 } else {
19074 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19075 }
19076
19077 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19079 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19080 Invalid = true;
19081 }
19082
19083 // Compute the type of the field that will capture this variable.
19084 if (ByRef) {
19085 // C++11 [expr.prim.lambda]p15:
19086 // An entity is captured by reference if it is implicitly or
19087 // explicitly captured but not captured by copy. It is
19088 // unspecified whether additional unnamed non-static data
19089 // members are declared in the closure type for entities
19090 // captured by reference.
19091 //
19092 // FIXME: It is not clear whether we want to build an lvalue reference
19093 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19094 // to do the former, while EDG does the latter. Core issue 1249 will
19095 // clarify, but for now we follow GCC because it's a more permissive and
19096 // easily defensible position.
19097 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19098 } else {
19099 // C++11 [expr.prim.lambda]p14:
19100 // For each entity captured by copy, an unnamed non-static
19101 // data member is declared in the closure type. The
19102 // declaration order of these members is unspecified. The type
19103 // of such a data member is the type of the corresponding
19104 // captured entity if the entity is not a reference to an
19105 // object, or the referenced type otherwise. [Note: If the
19106 // captured entity is a reference to a function, the
19107 // corresponding data member is also a reference to a
19108 // function. - end note ]
19109 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19110 if (!RefType->getPointeeType()->isFunctionType())
19111 CaptureType = RefType->getPointeeType();
19112 }
19113
19114 // Forbid the lambda copy-capture of autoreleasing variables.
19115 if (!Invalid &&
19117 if (BuildAndDiagnose) {
19118 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19119 S.Diag(Var->getLocation(), diag::note_previous_decl)
19120 << Var->getDeclName();
19121 Invalid = true;
19122 } else {
19123 return false;
19124 }
19125 }
19126
19127 // Make sure that by-copy captures are of a complete and non-abstract type.
19128 if (!Invalid && BuildAndDiagnose) {
19129 if (!CaptureType->isDependentType() &&
19131 Loc, CaptureType,
19132 diag::err_capture_of_incomplete_or_sizeless_type,
19133 Var->getDeclName()))
19134 Invalid = true;
19135 else if (S.RequireNonAbstractType(Loc, CaptureType,
19136 diag::err_capture_of_abstract_type))
19137 Invalid = true;
19138 }
19139 }
19140
19141 // Compute the type of a reference to this captured variable.
19142 if (ByRef)
19143 DeclRefType = CaptureType.getNonReferenceType();
19144 else {
19145 // C++ [expr.prim.lambda]p5:
19146 // The closure type for a lambda-expression has a public inline
19147 // function call operator [...]. This function call operator is
19148 // declared const (9.3.1) if and only if the lambda-expression's
19149 // parameter-declaration-clause is not followed by mutable.
19150 DeclRefType = CaptureType.getNonReferenceType();
19151 bool Const = LSI->lambdaCaptureShouldBeConst();
19152 // C++ [expr.prim.lambda]p10:
19153 // The type of such a data member is [...] an lvalue reference to the
19154 // referenced function type if the entity is a reference to a function.
19155 // [...]
19156 if (Const && !CaptureType->isReferenceType() &&
19157 !DeclRefType->isFunctionType())
19158 DeclRefType.addConst();
19159 }
19160
19161 // Add the capture.
19162 if (BuildAndDiagnose)
19163 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19164 Loc, EllipsisLoc, CaptureType, Invalid);
19165
19166 return !Invalid;
19167}
19168
19170 const ASTContext &Context) {
19171 // Offer a Copy fix even if the type is dependent.
19172 if (Var->getType()->isDependentType())
19173 return true;
19175 if (T.isTriviallyCopyableType(Context))
19176 return true;
19177 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19178
19179 if (!(RD = RD->getDefinition()))
19180 return false;
19181 if (RD->hasSimpleCopyConstructor())
19182 return true;
19183 if (RD->hasUserDeclaredCopyConstructor())
19184 for (CXXConstructorDecl *Ctor : RD->ctors())
19185 if (Ctor->isCopyConstructor())
19186 return !Ctor->isDeleted();
19187 }
19188 return false;
19189}
19190
19191/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19192/// default capture. Fixes may be omitted if they aren't allowed by the
19193/// standard, for example we can't emit a default copy capture fix-it if we
19194/// already explicitly copy capture capture another variable.
19196 ValueDecl *Var) {
19198 // Don't offer Capture by copy of default capture by copy fixes if Var is
19199 // known not to be copy constructible.
19200 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19201
19202 SmallString<32> FixBuffer;
19203 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19204 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19205 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19206 if (ShouldOfferCopyFix) {
19207 // Offer fixes to insert an explicit capture for the variable.
19208 // [] -> [VarName]
19209 // [OtherCapture] -> [OtherCapture, VarName]
19210 FixBuffer.assign({Separator, Var->getName()});
19211 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19212 << Var << /*value*/ 0
19213 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19214 }
19215 // As above but capture by reference.
19216 FixBuffer.assign({Separator, "&", Var->getName()});
19217 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19218 << Var << /*reference*/ 1
19219 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19220 }
19221
19222 // Only try to offer default capture if there are no captures excluding this
19223 // and init captures.
19224 // [this]: OK.
19225 // [X = Y]: OK.
19226 // [&A, &B]: Don't offer.
19227 // [A, B]: Don't offer.
19228 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19229 return !C.isThisCapture() && !C.isInitCapture();
19230 }))
19231 return;
19232
19233 // The default capture specifiers, '=' or '&', must appear first in the
19234 // capture body.
19235 SourceLocation DefaultInsertLoc =
19237
19238 if (ShouldOfferCopyFix) {
19239 bool CanDefaultCopyCapture = true;
19240 // [=, *this] OK since c++17
19241 // [=, this] OK since c++20
19242 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19243 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19245 : false;
19246 // We can't use default capture by copy if any captures already specified
19247 // capture by copy.
19248 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19249 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19250 })) {
19251 FixBuffer.assign({"=", Separator});
19252 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19253 << /*value*/ 0
19254 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19255 }
19256 }
19257
19258 // We can't use default capture by reference if any captures already specified
19259 // capture by reference.
19260 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19261 return !C.isInitCapture() && C.isReferenceCapture() &&
19262 !C.isThisCapture();
19263 })) {
19264 FixBuffer.assign({"&", Separator});
19265 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19266 << /*reference*/ 1
19267 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19268 }
19269}
19270
19272 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19273 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19274 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19275 // An init-capture is notionally from the context surrounding its
19276 // declaration, but its parent DC is the lambda class.
19277 DeclContext *VarDC = Var->getDeclContext();
19278 DeclContext *DC = CurContext;
19279
19280 // Skip past RequiresExprBodys because they don't constitute function scopes.
19281 while (DC->isRequiresExprBody())
19282 DC = DC->getParent();
19283
19284 // tryCaptureVariable is called every time a DeclRef is formed,
19285 // it can therefore have non-negigible impact on performances.
19286 // For local variables and when there is no capturing scope,
19287 // we can bailout early.
19288 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19289 return true;
19290
19291 // Exception: Function parameters are not tied to the function's DeclContext
19292 // until we enter the function definition. Capturing them anyway would result
19293 // in an out-of-bounds error while traversing DC and its parents.
19294 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19295 return true;
19296
19297 const auto *VD = dyn_cast<VarDecl>(Var);
19298 if (VD) {
19299 if (VD->isInitCapture())
19300 VarDC = VarDC->getParent();
19301 } else {
19303 }
19304 assert(VD && "Cannot capture a null variable");
19305
19306 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19307 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19308 // We need to sync up the Declaration Context with the
19309 // FunctionScopeIndexToStopAt
19310 if (FunctionScopeIndexToStopAt) {
19311 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19312 unsigned FSIndex = FunctionScopes.size() - 1;
19313 // When we're parsing the lambda parameter list, the current DeclContext is
19314 // NOT the lambda but its parent. So move away the current LSI before
19315 // aligning DC and FunctionScopeIndexToStopAt.
19316 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19317 FSIndex && LSI && !LSI->AfterParameterList)
19318 --FSIndex;
19319 assert(MaxFunctionScopesIndex <= FSIndex &&
19320 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19321 "FunctionScopes.");
19322 while (FSIndex != MaxFunctionScopesIndex) {
19324 --FSIndex;
19325 }
19326 }
19327
19328 // Capture global variables if it is required to use private copy of this
19329 // variable.
19330 bool IsGlobal = !VD->hasLocalStorage();
19331 if (IsGlobal && !(LangOpts.OpenMP &&
19332 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19333 MaxFunctionScopesIndex)))
19334 return true;
19335
19336 if (isa<VarDecl>(Var))
19337 Var = cast<VarDecl>(Var->getCanonicalDecl());
19338
19339 // Walk up the stack to determine whether we can capture the variable,
19340 // performing the "simple" checks that don't depend on type. We stop when
19341 // we've either hit the declared scope of the variable or find an existing
19342 // capture of that variable. We start from the innermost capturing-entity
19343 // (the DC) and ensure that all intervening capturing-entities
19344 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19345 // declcontext can either capture the variable or have already captured
19346 // the variable.
19347 CaptureType = Var->getType();
19348 DeclRefType = CaptureType.getNonReferenceType();
19349 bool Nested = false;
19350 bool Explicit = (Kind != TryCaptureKind::Implicit);
19351 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19352 do {
19353
19354 LambdaScopeInfo *LSI = nullptr;
19355 if (!FunctionScopes.empty())
19356 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19357 FunctionScopes[FunctionScopesIndex]);
19358
19359 bool IsInScopeDeclarationContext =
19360 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19361
19362 if (LSI && !LSI->AfterParameterList) {
19363 // This allows capturing parameters from a default value which does not
19364 // seems correct
19365 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19366 return true;
19367 }
19368 // If the variable is declared in the current context, there is no need to
19369 // capture it.
19370 if (IsInScopeDeclarationContext &&
19371 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19372 return true;
19373
19374 // Only block literals, captured statements, and lambda expressions can
19375 // capture; other scopes don't work.
19376 DeclContext *ParentDC =
19377 !IsInScopeDeclarationContext
19378 ? DC->getParent()
19379 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19380 BuildAndDiagnose, *this);
19381 // We need to check for the parent *first* because, if we *have*
19382 // private-captured a global variable, we need to recursively capture it in
19383 // intermediate blocks, lambdas, etc.
19384 if (!ParentDC) {
19385 if (IsGlobal) {
19386 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19387 break;
19388 }
19389 return true;
19390 }
19391
19392 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19394
19395 // Check whether we've already captured it.
19396 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19397 DeclRefType)) {
19398 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19399 break;
19400 }
19401
19402 // When evaluating some attributes (like enable_if) we might refer to a
19403 // function parameter appertaining to the same declaration as that
19404 // attribute.
19405 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19406 Parm && Parm->getDeclContext() == DC)
19407 return true;
19408
19409 // If we are instantiating a generic lambda call operator body,
19410 // we do not want to capture new variables. What was captured
19411 // during either a lambdas transformation or initial parsing
19412 // should be used.
19414 if (BuildAndDiagnose) {
19417 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19418 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19419 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19420 buildLambdaCaptureFixit(*this, LSI, Var);
19421 } else
19423 }
19424 return true;
19425 }
19426
19427 // Try to capture variable-length arrays types.
19428 if (Var->getType()->isVariablyModifiedType()) {
19429 // We're going to walk down into the type and look for VLA
19430 // expressions.
19431 QualType QTy = Var->getType();
19432 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19433 QTy = PVD->getOriginalType();
19435 }
19436
19437 if (getLangOpts().OpenMP) {
19438 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19439 // OpenMP private variables should not be captured in outer scope, so
19440 // just break here. Similarly, global variables that are captured in a
19441 // target region should not be captured outside the scope of the region.
19442 if (RSI->CapRegionKind == CR_OpenMP) {
19443 // FIXME: We should support capturing structured bindings in OpenMP.
19444 if (isa<BindingDecl>(Var)) {
19445 if (BuildAndDiagnose) {
19446 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19447 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19448 }
19449 return true;
19450 }
19451 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19452 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19453 // If the variable is private (i.e. not captured) and has variably
19454 // modified type, we still need to capture the type for correct
19455 // codegen in all regions, associated with the construct. Currently,
19456 // it is captured in the innermost captured region only.
19457 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19458 Var->getType()->isVariablyModifiedType()) {
19459 QualType QTy = Var->getType();
19460 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19461 QTy = PVD->getOriginalType();
19462 for (int I = 1,
19463 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19464 I < E; ++I) {
19465 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19466 FunctionScopes[FunctionScopesIndex - I]);
19467 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19468 "Wrong number of captured regions associated with the "
19469 "OpenMP construct.");
19470 captureVariablyModifiedType(Context, QTy, OuterRSI);
19471 }
19472 }
19473 bool IsTargetCap =
19474 IsOpenMPPrivateDecl != OMPC_private &&
19475 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19476 RSI->OpenMPCaptureLevel);
19477 // Do not capture global if it is not privatized in outer regions.
19478 bool IsGlobalCap =
19479 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19480 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19481
19482 // When we detect target captures we are looking from inside the
19483 // target region, therefore we need to propagate the capture from the
19484 // enclosing region. Therefore, the capture is not initially nested.
19485 if (IsTargetCap)
19486 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19487 RSI->OpenMPLevel);
19488
19489 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19490 (IsGlobal && !IsGlobalCap)) {
19491 Nested = !IsTargetCap;
19492 bool HasConst = DeclRefType.isConstQualified();
19493 DeclRefType = DeclRefType.getUnqualifiedType();
19494 // Don't lose diagnostics about assignments to const.
19495 if (HasConst)
19496 DeclRefType.addConst();
19497 CaptureType = Context.getLValueReferenceType(DeclRefType);
19498 break;
19499 }
19500 }
19501 }
19502 }
19504 // No capture-default, and this is not an explicit capture
19505 // so cannot capture this variable.
19506 if (BuildAndDiagnose) {
19507 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19508 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19509 auto *LSI = cast<LambdaScopeInfo>(CSI);
19510 if (LSI->Lambda) {
19511 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19512 buildLambdaCaptureFixit(*this, LSI, Var);
19513 }
19514 // FIXME: If we error out because an outer lambda can not implicitly
19515 // capture a variable that an inner lambda explicitly captures, we
19516 // should have the inner lambda do the explicit capture - because
19517 // it makes for cleaner diagnostics later. This would purely be done
19518 // so that the diagnostic does not misleadingly claim that a variable
19519 // can not be captured by a lambda implicitly even though it is captured
19520 // explicitly. Suggestion:
19521 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19522 // at the function head
19523 // - cache the StartingDeclContext - this must be a lambda
19524 // - captureInLambda in the innermost lambda the variable.
19525 }
19526 return true;
19527 }
19528 Explicit = false;
19529 FunctionScopesIndex--;
19530 if (IsInScopeDeclarationContext)
19531 DC = ParentDC;
19532 } while (!VarDC->Equals(DC));
19533
19534 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19535 // computing the type of the capture at each step, checking type-specific
19536 // requirements, and adding captures if requested.
19537 // If the variable had already been captured previously, we start capturing
19538 // at the lambda nested within that one.
19539 bool Invalid = false;
19540 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19541 ++I) {
19543
19544 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19545 // certain types of variables (unnamed, variably modified types etc.)
19546 // so check for eligibility.
19547 if (!Invalid)
19548 Invalid =
19549 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19550
19551 // After encountering an error, if we're actually supposed to capture, keep
19552 // capturing in nested contexts to suppress any follow-on diagnostics.
19553 if (Invalid && !BuildAndDiagnose)
19554 return true;
19555
19556 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19557 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19558 DeclRefType, Nested, *this, Invalid);
19559 Nested = true;
19560 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19562 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19563 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19564 Nested = true;
19565 } else {
19567 Invalid =
19568 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19569 DeclRefType, Nested, Kind, EllipsisLoc,
19570 /*IsTopScope*/ I == N - 1, *this, Invalid);
19571 Nested = true;
19572 }
19573
19574 if (Invalid && !BuildAndDiagnose)
19575 return true;
19576 }
19577 return Invalid;
19578}
19579
19581 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19582 QualType CaptureType;
19583 QualType DeclRefType;
19584 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19585 /*BuildAndDiagnose=*/true, CaptureType,
19586 DeclRefType, nullptr);
19587}
19588
19590 QualType CaptureType;
19591 QualType DeclRefType;
19592 return !tryCaptureVariable(
19594 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
19595}
19596
19598 assert(Var && "Null value cannot be captured");
19599
19600 QualType CaptureType;
19601 QualType DeclRefType;
19602
19603 // Determine whether we can capture this variable.
19605 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
19606 nullptr))
19607 return QualType();
19608
19609 return DeclRefType;
19610}
19611
19612namespace {
19613// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19614// The produced TemplateArgumentListInfo* points to data stored within this
19615// object, so should only be used in contexts where the pointer will not be
19616// used after the CopiedTemplateArgs object is destroyed.
19617class CopiedTemplateArgs {
19618 bool HasArgs;
19619 TemplateArgumentListInfo TemplateArgStorage;
19620public:
19621 template<typename RefExpr>
19622 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19623 if (HasArgs)
19624 E->copyTemplateArgumentsInto(TemplateArgStorage);
19625 }
19626 operator TemplateArgumentListInfo*()
19627#ifdef __has_cpp_attribute
19628#if __has_cpp_attribute(clang::lifetimebound)
19629 [[clang::lifetimebound]]
19630#endif
19631#endif
19632 {
19633 return HasArgs ? &TemplateArgStorage : nullptr;
19634 }
19635};
19636}
19637
19638/// Walk the set of potential results of an expression and mark them all as
19639/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19640///
19641/// \return A new expression if we found any potential results, ExprEmpty() if
19642/// not, and ExprError() if we diagnosed an error.
19644 NonOdrUseReason NOUR) {
19645 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19646 // an object that satisfies the requirements for appearing in a
19647 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19648 // is immediately applied." This function handles the lvalue-to-rvalue
19649 // conversion part.
19650 //
19651 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19652 // transform it into the relevant kind of non-odr-use node and rebuild the
19653 // tree of nodes leading to it.
19654 //
19655 // This is a mini-TreeTransform that only transforms a restricted subset of
19656 // nodes (and only certain operands of them).
19657
19658 // Rebuild a subexpression.
19659 auto Rebuild = [&](Expr *Sub) {
19660 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19661 };
19662
19663 // Check whether a potential result satisfies the requirements of NOUR.
19664 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19665 // Any entity other than a VarDecl is always odr-used whenever it's named
19666 // in a potentially-evaluated expression.
19667 auto *VD = dyn_cast<VarDecl>(D);
19668 if (!VD)
19669 return true;
19670
19671 // C++2a [basic.def.odr]p4:
19672 // A variable x whose name appears as a potentially-evalauted expression
19673 // e is odr-used by e unless
19674 // -- x is a reference that is usable in constant expressions, or
19675 // -- x is a variable of non-reference type that is usable in constant
19676 // expressions and has no mutable subobjects, and e is an element of
19677 // the set of potential results of an expression of
19678 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19679 // conversion is applied, or
19680 // -- x is a variable of non-reference type, and e is an element of the
19681 // set of potential results of a discarded-value expression to which
19682 // the lvalue-to-rvalue conversion is not applied
19683 //
19684 // We check the first bullet and the "potentially-evaluated" condition in
19685 // BuildDeclRefExpr. We check the type requirements in the second bullet
19686 // in CheckLValueToRValueConversionOperand below.
19687 switch (NOUR) {
19688 case NOUR_None:
19689 case NOUR_Unevaluated:
19690 llvm_unreachable("unexpected non-odr-use-reason");
19691
19692 case NOUR_Constant:
19693 // Constant references were handled when they were built.
19694 if (VD->getType()->isReferenceType())
19695 return true;
19696 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19697 if (RD->hasDefinition() && RD->hasMutableFields())
19698 return true;
19699 if (!VD->isUsableInConstantExpressions(S.Context))
19700 return true;
19701 break;
19702
19703 case NOUR_Discarded:
19704 if (VD->getType()->isReferenceType())
19705 return true;
19706 break;
19707 }
19708 return false;
19709 };
19710
19711 // Check whether this expression may be odr-used in CUDA/HIP.
19712 auto MaybeCUDAODRUsed = [&]() -> bool {
19713 if (!S.LangOpts.CUDA)
19714 return false;
19715 LambdaScopeInfo *LSI = S.getCurLambda();
19716 if (!LSI)
19717 return false;
19718 auto *DRE = dyn_cast<DeclRefExpr>(E);
19719 if (!DRE)
19720 return false;
19721 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
19722 if (!VD)
19723 return false;
19724 return LSI->CUDAPotentialODRUsedVars.count(VD);
19725 };
19726
19727 // Mark that this expression does not constitute an odr-use.
19728 auto MarkNotOdrUsed = [&] {
19729 if (!MaybeCUDAODRUsed()) {
19730 S.MaybeODRUseExprs.remove(E);
19731 if (LambdaScopeInfo *LSI = S.getCurLambda())
19732 LSI->markVariableExprAsNonODRUsed(E);
19733 }
19734 };
19735
19736 // C++2a [basic.def.odr]p2:
19737 // The set of potential results of an expression e is defined as follows:
19738 switch (E->getStmtClass()) {
19739 // -- If e is an id-expression, ...
19740 case Expr::DeclRefExprClass: {
19741 auto *DRE = cast<DeclRefExpr>(E);
19742 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19743 break;
19744
19745 // Rebuild as a non-odr-use DeclRefExpr.
19746 MarkNotOdrUsed();
19747 return DeclRefExpr::Create(
19748 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19749 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19750 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19751 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19752 }
19753
19754 case Expr::FunctionParmPackExprClass: {
19755 auto *FPPE = cast<FunctionParmPackExpr>(E);
19756 // If any of the declarations in the pack is odr-used, then the expression
19757 // as a whole constitutes an odr-use.
19758 for (ValueDecl *D : *FPPE)
19759 if (IsPotentialResultOdrUsed(D))
19760 return ExprEmpty();
19761
19762 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19763 // nothing cares about whether we marked this as an odr-use, but it might
19764 // be useful for non-compiler tools.
19765 MarkNotOdrUsed();
19766 break;
19767 }
19768
19769 // -- If e is a subscripting operation with an array operand...
19770 case Expr::ArraySubscriptExprClass: {
19771 auto *ASE = cast<ArraySubscriptExpr>(E);
19772 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19773 if (!OldBase->getType()->isArrayType())
19774 break;
19775 ExprResult Base = Rebuild(OldBase);
19776 if (!Base.isUsable())
19777 return Base;
19778 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19779 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19780 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19781 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19782 ASE->getRBracketLoc());
19783 }
19784
19785 case Expr::MemberExprClass: {
19786 auto *ME = cast<MemberExpr>(E);
19787 // -- If e is a class member access expression [...] naming a non-static
19788 // data member...
19789 if (isa<FieldDecl>(ME->getMemberDecl())) {
19790 ExprResult Base = Rebuild(ME->getBase());
19791 if (!Base.isUsable())
19792 return Base;
19793 return MemberExpr::Create(
19794 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19795 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19796 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19797 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19798 ME->getObjectKind(), ME->isNonOdrUse());
19799 }
19800
19801 if (ME->getMemberDecl()->isCXXInstanceMember())
19802 break;
19803
19804 // -- If e is a class member access expression naming a static data member,
19805 // ...
19806 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19807 break;
19808
19809 // Rebuild as a non-odr-use MemberExpr.
19810 MarkNotOdrUsed();
19811 return MemberExpr::Create(
19812 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19813 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19814 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19815 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19816 }
19817
19818 case Expr::BinaryOperatorClass: {
19819 auto *BO = cast<BinaryOperator>(E);
19820 Expr *LHS = BO->getLHS();
19821 Expr *RHS = BO->getRHS();
19822 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19823 if (BO->getOpcode() == BO_PtrMemD) {
19824 ExprResult Sub = Rebuild(LHS);
19825 if (!Sub.isUsable())
19826 return Sub;
19827 BO->setLHS(Sub.get());
19828 // -- If e is a comma expression, ...
19829 } else if (BO->getOpcode() == BO_Comma) {
19830 ExprResult Sub = Rebuild(RHS);
19831 if (!Sub.isUsable())
19832 return Sub;
19833 BO->setRHS(Sub.get());
19834 } else {
19835 break;
19836 }
19837 return ExprResult(BO);
19838 }
19839
19840 // -- If e has the form (e1)...
19841 case Expr::ParenExprClass: {
19842 auto *PE = cast<ParenExpr>(E);
19843 ExprResult Sub = Rebuild(PE->getSubExpr());
19844 if (!Sub.isUsable())
19845 return Sub;
19846 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19847 }
19848
19849 // -- If e is a glvalue conditional expression, ...
19850 // We don't apply this to a binary conditional operator. FIXME: Should we?
19851 case Expr::ConditionalOperatorClass: {
19852 auto *CO = cast<ConditionalOperator>(E);
19853 ExprResult LHS = Rebuild(CO->getLHS());
19854 if (LHS.isInvalid())
19855 return ExprError();
19856 ExprResult RHS = Rebuild(CO->getRHS());
19857 if (RHS.isInvalid())
19858 return ExprError();
19859 if (!LHS.isUsable() && !RHS.isUsable())
19860 return ExprEmpty();
19861 if (!LHS.isUsable())
19862 LHS = CO->getLHS();
19863 if (!RHS.isUsable())
19864 RHS = CO->getRHS();
19865 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19866 CO->getCond(), LHS.get(), RHS.get());
19867 }
19868
19869 // [Clang extension]
19870 // -- If e has the form __extension__ e1...
19871 case Expr::UnaryOperatorClass: {
19872 auto *UO = cast<UnaryOperator>(E);
19873 if (UO->getOpcode() != UO_Extension)
19874 break;
19875 ExprResult Sub = Rebuild(UO->getSubExpr());
19876 if (!Sub.isUsable())
19877 return Sub;
19878 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19879 Sub.get());
19880 }
19881
19882 // [Clang extension]
19883 // -- If e has the form _Generic(...), the set of potential results is the
19884 // union of the sets of potential results of the associated expressions.
19885 case Expr::GenericSelectionExprClass: {
19886 auto *GSE = cast<GenericSelectionExpr>(E);
19887
19888 SmallVector<Expr *, 4> AssocExprs;
19889 bool AnyChanged = false;
19890 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19891 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19892 if (AssocExpr.isInvalid())
19893 return ExprError();
19894 if (AssocExpr.isUsable()) {
19895 AssocExprs.push_back(AssocExpr.get());
19896 AnyChanged = true;
19897 } else {
19898 AssocExprs.push_back(OrigAssocExpr);
19899 }
19900 }
19901
19902 void *ExOrTy = nullptr;
19903 bool IsExpr = GSE->isExprPredicate();
19904 if (IsExpr)
19905 ExOrTy = GSE->getControllingExpr();
19906 else
19907 ExOrTy = GSE->getControllingType();
19908 return AnyChanged ? S.CreateGenericSelectionExpr(
19909 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19910 GSE->getRParenLoc(), IsExpr, ExOrTy,
19911 GSE->getAssocTypeSourceInfos(), AssocExprs)
19912 : ExprEmpty();
19913 }
19914
19915 // [Clang extension]
19916 // -- If e has the form __builtin_choose_expr(...), the set of potential
19917 // results is the union of the sets of potential results of the
19918 // second and third subexpressions.
19919 case Expr::ChooseExprClass: {
19920 auto *CE = cast<ChooseExpr>(E);
19921
19922 ExprResult LHS = Rebuild(CE->getLHS());
19923 if (LHS.isInvalid())
19924 return ExprError();
19925
19926 ExprResult RHS = Rebuild(CE->getLHS());
19927 if (RHS.isInvalid())
19928 return ExprError();
19929
19930 if (!LHS.get() && !RHS.get())
19931 return ExprEmpty();
19932 if (!LHS.isUsable())
19933 LHS = CE->getLHS();
19934 if (!RHS.isUsable())
19935 RHS = CE->getRHS();
19936
19937 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19938 RHS.get(), CE->getRParenLoc());
19939 }
19940
19941 // Step through non-syntactic nodes.
19942 case Expr::ConstantExprClass: {
19943 auto *CE = cast<ConstantExpr>(E);
19944 ExprResult Sub = Rebuild(CE->getSubExpr());
19945 if (!Sub.isUsable())
19946 return Sub;
19947 return ConstantExpr::Create(S.Context, Sub.get());
19948 }
19949
19950 // We could mostly rely on the recursive rebuilding to rebuild implicit
19951 // casts, but not at the top level, so rebuild them here.
19952 case Expr::ImplicitCastExprClass: {
19953 auto *ICE = cast<ImplicitCastExpr>(E);
19954 // Only step through the narrow set of cast kinds we expect to encounter.
19955 // Anything else suggests we've left the region in which potential results
19956 // can be found.
19957 switch (ICE->getCastKind()) {
19958 case CK_NoOp:
19959 case CK_DerivedToBase:
19960 case CK_UncheckedDerivedToBase: {
19961 ExprResult Sub = Rebuild(ICE->getSubExpr());
19962 if (!Sub.isUsable())
19963 return Sub;
19964 CXXCastPath Path(ICE->path());
19965 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19966 ICE->getValueKind(), &Path);
19967 }
19968
19969 default:
19970 break;
19971 }
19972 break;
19973 }
19974
19975 default:
19976 break;
19977 }
19978
19979 // Can't traverse through this node. Nothing to do.
19980 return ExprEmpty();
19981}
19982
19984 // Check whether the operand is or contains an object of non-trivial C union
19985 // type.
19986 if (E->getType().isVolatileQualified() &&
19992
19993 // C++2a [basic.def.odr]p4:
19994 // [...] an expression of non-volatile-qualified non-class type to which
19995 // the lvalue-to-rvalue conversion is applied [...]
19996 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
19997 return E;
19998
20001 if (Result.isInvalid())
20002 return ExprError();
20003 return Result.get() ? Result : E;
20004}
20005
20007 if (!Res.isUsable())
20008 return Res;
20009
20010 // If a constant-expression is a reference to a variable where we delay
20011 // deciding whether it is an odr-use, just assume we will apply the
20012 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20013 // (a non-type template argument), we have special handling anyway.
20015}
20016
20018 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20019 // call.
20020 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20021 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20022
20023 for (Expr *E : LocalMaybeODRUseExprs) {
20024 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20025 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20026 DRE->getLocation(), *this);
20027 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20028 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20029 *this);
20030 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20031 for (ValueDecl *VD : *FP)
20032 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20033 } else {
20034 llvm_unreachable("Unexpected expression");
20035 }
20036 }
20037
20038 assert(MaybeODRUseExprs.empty() &&
20039 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20040}
20041
20043 ValueDecl *Var, Expr *E) {
20045 if (!VD)
20046 return;
20047
20048 const bool RefersToEnclosingScope =
20049 (SemaRef.CurContext != VD->getDeclContext() &&
20051 if (RefersToEnclosingScope) {
20052 LambdaScopeInfo *const LSI =
20053 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20054 if (LSI && (!LSI->CallOperator ||
20055 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20056 // If a variable could potentially be odr-used, defer marking it so
20057 // until we finish analyzing the full expression for any
20058 // lvalue-to-rvalue
20059 // or discarded value conversions that would obviate odr-use.
20060 // Add it to the list of potential captures that will be analyzed
20061 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20062 // unless the variable is a reference that was initialized by a constant
20063 // expression (this will never need to be captured or odr-used).
20064 //
20065 // FIXME: We can simplify this a lot after implementing P0588R1.
20066 assert(E && "Capture variable should be used in an expression.");
20067 if (!Var->getType()->isReferenceType() ||
20070 }
20071 }
20072}
20073
20075 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20076 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20077 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20079 "Invalid Expr argument to DoMarkVarDeclReferenced");
20080 Var->setReferenced();
20081
20082 if (Var->isInvalidDecl())
20083 return;
20084
20085 auto *MSI = Var->getMemberSpecializationInfo();
20086 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20088
20089 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20090 bool UsableInConstantExpr =
20092
20093 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20094 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
20095 }
20096
20097 // C++20 [expr.const]p12:
20098 // A variable [...] is needed for constant evaluation if it is [...] a
20099 // variable whose name appears as a potentially constant evaluated
20100 // expression that is either a contexpr variable or is of non-volatile
20101 // const-qualified integral type or of reference type
20102 bool NeededForConstantEvaluation =
20103 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20104
20105 bool NeedDefinition =
20106 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
20107
20109 "Can't instantiate a partial template specialization.");
20110
20111 // If this might be a member specialization of a static data member, check
20112 // the specialization is visible. We already did the checks for variable
20113 // template specializations when we created them.
20114 if (NeedDefinition && TSK != TSK_Undeclared &&
20117
20118 // Perform implicit instantiation of static data members, static data member
20119 // templates of class templates, and variable template specializations. Delay
20120 // instantiations of variable templates, except for those that could be used
20121 // in a constant expression.
20122 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20123 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20124 // instantiation declaration if a variable is usable in a constant
20125 // expression (among other cases).
20126 bool TryInstantiating =
20128 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20129
20130 if (TryInstantiating) {
20131 SourceLocation PointOfInstantiation =
20132 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20133 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20134 if (FirstInstantiation) {
20135 PointOfInstantiation = Loc;
20136 if (MSI)
20137 MSI->setPointOfInstantiation(PointOfInstantiation);
20138 // FIXME: Notify listener.
20139 else
20140 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20141 }
20142
20143 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20144 // Do not defer instantiations of variables that could be used in a
20145 // constant expression.
20146 // The type deduction also needs a complete initializer.
20147 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20148 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20149 });
20150
20151 // The size of an incomplete array type can be updated by
20152 // instantiating the initializer. The DeclRefExpr's type should be
20153 // updated accordingly too, or users of it would be confused!
20154 if (E)
20156
20157 // Re-set the member to trigger a recomputation of the dependence bits
20158 // for the expression.
20159 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20160 DRE->setDecl(DRE->getDecl());
20161 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20162 ME->setMemberDecl(ME->getMemberDecl());
20163 } else if (FirstInstantiation) {
20165 .push_back(std::make_pair(Var, PointOfInstantiation));
20166 } else {
20167 bool Inserted = false;
20168 for (auto &I : SemaRef.SavedPendingInstantiations) {
20169 auto Iter = llvm::find_if(
20170 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20171 return P.first == Var;
20172 });
20173 if (Iter != I.end()) {
20174 SemaRef.PendingInstantiations.push_back(*Iter);
20175 I.erase(Iter);
20176 Inserted = true;
20177 break;
20178 }
20179 }
20180
20181 // FIXME: For a specialization of a variable template, we don't
20182 // distinguish between "declaration and type implicitly instantiated"
20183 // and "implicit instantiation of definition requested", so we have
20184 // no direct way to avoid enqueueing the pending instantiation
20185 // multiple times.
20186 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20188 .push_back(std::make_pair(Var, PointOfInstantiation));
20189 }
20190 }
20191 }
20192
20193 // C++2a [basic.def.odr]p4:
20194 // A variable x whose name appears as a potentially-evaluated expression e
20195 // is odr-used by e unless
20196 // -- x is a reference that is usable in constant expressions
20197 // -- x is a variable of non-reference type that is usable in constant
20198 // expressions and has no mutable subobjects [FIXME], and e is an
20199 // element of the set of potential results of an expression of
20200 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20201 // conversion is applied
20202 // -- x is a variable of non-reference type, and e is an element of the set
20203 // of potential results of a discarded-value expression to which the
20204 // lvalue-to-rvalue conversion is not applied [FIXME]
20205 //
20206 // We check the first part of the second bullet here, and
20207 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20208 // FIXME: To get the third bullet right, we need to delay this even for
20209 // variables that are not usable in constant expressions.
20210
20211 // If we already know this isn't an odr-use, there's nothing more to do.
20212 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20213 if (DRE->isNonOdrUse())
20214 return;
20215 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20216 if (ME->isNonOdrUse())
20217 return;
20218
20219 switch (OdrUse) {
20220 case OdrUseContext::None:
20221 // In some cases, a variable may not have been marked unevaluated, if it
20222 // appears in a defaukt initializer.
20223 assert((!E || isa<FunctionParmPackExpr>(E) ||
20225 "missing non-odr-use marking for unevaluated decl ref");
20226 break;
20227
20228 case OdrUseContext::FormallyOdrUsed:
20229 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20230 // behavior.
20231 break;
20232
20233 case OdrUseContext::Used:
20234 // If we might later find that this expression isn't actually an odr-use,
20235 // delay the marking.
20237 SemaRef.MaybeODRUseExprs.insert(E);
20238 else
20239 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20240 break;
20241
20242 case OdrUseContext::Dependent:
20243 // If this is a dependent context, we don't need to mark variables as
20244 // odr-used, but we may still need to track them for lambda capture.
20245 // FIXME: Do we also need to do this inside dependent typeid expressions
20246 // (which are modeled as unevaluated at this point)?
20247 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20248 break;
20249 }
20250}
20251
20253 BindingDecl *BD, Expr *E) {
20254 BD->setReferenced();
20255
20256 if (BD->isInvalidDecl())
20257 return;
20258
20259 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20260 if (OdrUse == OdrUseContext::Used) {
20261 QualType CaptureType, DeclRefType;
20263 /*EllipsisLoc*/ SourceLocation(),
20264 /*BuildAndDiagnose*/ true, CaptureType,
20265 DeclRefType,
20266 /*FunctionScopeIndexToStopAt*/ nullptr);
20267 } else if (OdrUse == OdrUseContext::Dependent) {
20268 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20269 }
20270}
20271
20273 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20274}
20275
20276// C++ [temp.dep.expr]p3:
20277// An id-expression is type-dependent if it contains:
20278// - an identifier associated by name lookup with an entity captured by copy
20279// in a lambda-expression that has an explicit object parameter whose type
20280// is dependent ([dcl.fct]),
20282 Sema &SemaRef, ValueDecl *D, Expr *E) {
20283 auto *ID = dyn_cast<DeclRefExpr>(E);
20284 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20285 return;
20286
20287 // If any enclosing lambda with a dependent explicit object parameter either
20288 // explicitly captures the variable by value, or has a capture default of '='
20289 // and does not capture the variable by reference, then the type of the DRE
20290 // is dependent on the type of that lambda's explicit object parameter.
20291 auto IsDependent = [&]() {
20292 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20293 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20294 if (!LSI)
20295 continue;
20296
20297 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20298 LSI->AfterParameterList)
20299 return false;
20300
20301 const auto *MD = LSI->CallOperator;
20302 if (MD->getType().isNull())
20303 continue;
20304
20305 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20306 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20307 !Ty->getParamType(0)->isDependentType())
20308 continue;
20309
20310 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20311 if (C->isCopyCapture())
20312 return true;
20313 continue;
20314 }
20315
20316 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20317 return true;
20318 }
20319 return false;
20320 }();
20321
20322 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20323 IsDependent, SemaRef.getASTContext());
20324}
20325
20326static void
20328 bool MightBeOdrUse,
20329 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20332
20333 if (SemaRef.getLangOpts().OpenACC)
20334 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20335
20336 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20338 if (SemaRef.getLangOpts().CPlusPlus)
20340 Var, E);
20341 return;
20342 }
20343
20344 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20346 if (SemaRef.getLangOpts().CPlusPlus)
20348 Decl, E);
20349 return;
20350 }
20351 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20352
20353 // If this is a call to a method via a cast, also mark the method in the
20354 // derived class used in case codegen can devirtualize the call.
20355 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20356 if (!ME)
20357 return;
20358 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20359 if (!MD)
20360 return;
20361 // Only attempt to devirtualize if this is truly a virtual call.
20362 bool IsVirtualCall = MD->isVirtual() &&
20364 if (!IsVirtualCall)
20365 return;
20366
20367 // If it's possible to devirtualize the call, mark the called function
20368 // referenced.
20370 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20371 if (DM)
20372 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20373}
20374
20376 // [basic.def.odr] (CWG 1614)
20377 // A function is named by an expression or conversion [...]
20378 // unless it is a pure virtual function and either the expression is not an
20379 // id-expression naming the function with an explicitly qualified name or
20380 // the expression forms a pointer to member
20381 bool OdrUse = true;
20382 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20383 if (Method->isVirtual() &&
20384 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20385 OdrUse = false;
20386
20387 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20391 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20392 !FD->isDependentContext())
20393 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20394 }
20395 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20397}
20398
20400 // C++11 [basic.def.odr]p2:
20401 // A non-overloaded function whose name appears as a potentially-evaluated
20402 // expression or a member of a set of candidate functions, if selected by
20403 // overload resolution when referred to from a potentially-evaluated
20404 // expression, is odr-used, unless it is a pure virtual function and its
20405 // name is not explicitly qualified.
20406 bool MightBeOdrUse = true;
20408 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20409 if (Method->isPureVirtual())
20410 MightBeOdrUse = false;
20411 }
20412 SourceLocation Loc =
20413 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20414 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20416}
20417
20423
20424/// Perform marking for a reference to an arbitrary declaration. It
20425/// marks the declaration referenced, and performs odr-use checking for
20426/// functions and variables. This method should not be used when building a
20427/// normal expression which refers to a variable.
20429 bool MightBeOdrUse) {
20430 if (MightBeOdrUse) {
20431 if (auto *VD = dyn_cast<VarDecl>(D)) {
20432 MarkVariableReferenced(Loc, VD);
20433 return;
20434 }
20435 }
20436 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20437 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20438 return;
20439 }
20440 D->setReferenced();
20441}
20442
20443namespace {
20444 // Mark all of the declarations used by a type as referenced.
20445 // FIXME: Not fully implemented yet! We need to have a better understanding
20446 // of when we're entering a context we should not recurse into.
20447 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20448 // TreeTransforms rebuilding the type in a new context. Rather than
20449 // duplicating the TreeTransform logic, we should consider reusing it here.
20450 // Currently that causes problems when rebuilding LambdaExprs.
20451class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20452 Sema &S;
20453 SourceLocation Loc;
20454
20455public:
20456 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20457
20458 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20459};
20460}
20461
20462bool MarkReferencedDecls::TraverseTemplateArgument(
20463 const TemplateArgument &Arg) {
20464 {
20465 // A non-type template argument is a constant-evaluated context.
20466 EnterExpressionEvaluationContext Evaluated(
20469 if (Decl *D = Arg.getAsDecl())
20470 S.MarkAnyDeclReferenced(Loc, D, true);
20471 } else if (Arg.getKind() == TemplateArgument::Expression) {
20473 }
20474 }
20475
20477}
20478
20480 MarkReferencedDecls Marker(*this, Loc);
20481 Marker.TraverseType(T);
20482}
20483
20484namespace {
20485/// Helper class that marks all of the declarations referenced by
20486/// potentially-evaluated subexpressions as "referenced".
20487class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20488public:
20489 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20490 bool SkipLocalVariables;
20492
20493 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20495 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20496
20497 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20499 }
20500
20501 void Visit(Expr *E) {
20502 if (llvm::is_contained(StopAt, E))
20503 return;
20504 Inherited::Visit(E);
20505 }
20506
20507 void VisitConstantExpr(ConstantExpr *E) {
20508 // Don't mark declarations within a ConstantExpression, as this expression
20509 // will be evaluated and folded to a value.
20510 }
20511
20512 void VisitDeclRefExpr(DeclRefExpr *E) {
20513 // If we were asked not to visit local variables, don't.
20514 if (SkipLocalVariables) {
20515 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20516 if (VD->hasLocalStorage())
20517 return;
20518 }
20519
20520 // FIXME: This can trigger the instantiation of the initializer of a
20521 // variable, which can cause the expression to become value-dependent
20522 // or error-dependent. Do we need to propagate the new dependence bits?
20524 }
20525
20526 void VisitMemberExpr(MemberExpr *E) {
20528 Visit(E->getBase());
20529 }
20530};
20531} // namespace
20532
20534 bool SkipLocalVariables,
20535 ArrayRef<const Expr*> StopAt) {
20536 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20537}
20538
20539/// Emit a diagnostic when statements are reachable.
20540/// FIXME: check for reachability even in expressions for which we don't build a
20541/// CFG (eg, in the initializer of a global or in a constant expression).
20542/// For example,
20543/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20545 const PartialDiagnostic &PD) {
20546 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20547 if (!FunctionScopes.empty())
20548 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20549 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20550 return true;
20551 }
20552
20553 // The initializer of a constexpr variable or of the first declaration of a
20554 // static data member is not syntactically a constant evaluated constant,
20555 // but nonetheless is always required to be a constant expression, so we
20556 // can skip diagnosing.
20557 // FIXME: Using the mangling context here is a hack.
20558 if (auto *VD = dyn_cast_or_null<VarDecl>(
20559 ExprEvalContexts.back().ManglingContextDecl)) {
20560 if (VD->isConstexpr() ||
20561 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20562 return false;
20563 // FIXME: For any other kind of variable, we should build a CFG for its
20564 // initializer and check whether the context in question is reachable.
20565 }
20566
20567 Diag(Loc, PD);
20568 return true;
20569}
20570
20571/// Emit a diagnostic that describes an effect on the run-time behavior
20572/// of the program being compiled.
20573///
20574/// This routine emits the given diagnostic when the code currently being
20575/// type-checked is "potentially evaluated", meaning that there is a
20576/// possibility that the code will actually be executable. Code in sizeof()
20577/// expressions, code used only during overload resolution, etc., are not
20578/// potentially evaluated. This routine will suppress such diagnostics or,
20579/// in the absolutely nutty case of potentially potentially evaluated
20580/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20581/// later.
20582///
20583/// This routine should be used for all diagnostics that describe the run-time
20584/// behavior of a program, such as passing a non-POD value through an ellipsis.
20585/// Failure to do so will likely result in spurious diagnostics or failures
20586/// during overload resolution or within sizeof/alignof/typeof/typeid.
20588 const PartialDiagnostic &PD) {
20589
20590 if (ExprEvalContexts.back().isDiscardedStatementContext())
20591 return false;
20592
20593 switch (ExprEvalContexts.back().Context) {
20598 // The argument will never be evaluated, so don't complain.
20599 break;
20600
20603 // Relevant diagnostics should be produced by constant evaluation.
20604 break;
20605
20608 return DiagIfReachable(Loc, Stmts, PD);
20609 }
20610
20611 return false;
20612}
20613
20615 const PartialDiagnostic &PD) {
20616 return DiagRuntimeBehavior(
20617 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
20618 PD);
20619}
20620
20622 CallExpr *CE, FunctionDecl *FD) {
20623 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20624 return false;
20625
20626 // If we're inside a decltype's expression, don't check for a valid return
20627 // type or construct temporaries until we know whether this is the last call.
20628 if (ExprEvalContexts.back().ExprContext ==
20630 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20631 return false;
20632 }
20633
20634 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20635 FunctionDecl *FD;
20636 CallExpr *CE;
20637
20638 public:
20639 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20640 : FD(FD), CE(CE) { }
20641
20642 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20643 if (!FD) {
20644 S.Diag(Loc, diag::err_call_incomplete_return)
20645 << T << CE->getSourceRange();
20646 return;
20647 }
20648
20649 S.Diag(Loc, diag::err_call_function_incomplete_return)
20650 << CE->getSourceRange() << FD << T;
20651 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20652 << FD->getDeclName();
20653 }
20654 } Diagnoser(FD, CE);
20655
20656 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20657 return true;
20658
20659 return false;
20660}
20661
20662// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20663// will prevent this condition from triggering, which is what we want.
20665 SourceLocation Loc;
20666
20667 unsigned diagnostic = diag::warn_condition_is_assignment;
20668 bool IsOrAssign = false;
20669
20670 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20671 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20672 return;
20673
20674 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20675
20676 // Greylist some idioms by putting them into a warning subcategory.
20677 if (ObjCMessageExpr *ME
20678 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20679 Selector Sel = ME->getSelector();
20680
20681 // self = [<foo> init...]
20682 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20683 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20684
20685 // <foo> = [<bar> nextObject]
20686 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20687 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20688 }
20689
20690 Loc = Op->getOperatorLoc();
20691 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20692 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20693 return;
20694
20695 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20696 Loc = Op->getOperatorLoc();
20697 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20698 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20699 else {
20700 // Not an assignment.
20701 return;
20702 }
20703
20704 Diag(Loc, diagnostic) << E->getSourceRange();
20705
20708 Diag(Loc, diag::note_condition_assign_silence)
20710 << FixItHint::CreateInsertion(Close, ")");
20711
20712 if (IsOrAssign)
20713 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20714 << FixItHint::CreateReplacement(Loc, "!=");
20715 else
20716 Diag(Loc, diag::note_condition_assign_to_comparison)
20717 << FixItHint::CreateReplacement(Loc, "==");
20718}
20719
20721 // Don't warn if the parens came from a macro.
20722 SourceLocation parenLoc = ParenE->getBeginLoc();
20723 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20724 return;
20725 // Don't warn for dependent expressions.
20726 if (ParenE->isTypeDependent())
20727 return;
20728
20729 Expr *E = ParenE->IgnoreParens();
20730 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
20731 return;
20732
20733 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20734 if (opE->getOpcode() == BO_EQ &&
20735 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20736 == Expr::MLV_Valid) {
20737 SourceLocation Loc = opE->getOperatorLoc();
20738
20739 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20740 SourceRange ParenERange = ParenE->getSourceRange();
20741 Diag(Loc, diag::note_equality_comparison_silence)
20742 << FixItHint::CreateRemoval(ParenERange.getBegin())
20743 << FixItHint::CreateRemoval(ParenERange.getEnd());
20744 Diag(Loc, diag::note_equality_comparison_to_assign)
20745 << FixItHint::CreateReplacement(Loc, "=");
20746 }
20747}
20748
20750 bool IsConstexpr) {
20752 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20754
20755 ExprResult result = CheckPlaceholderExpr(E);
20756 if (result.isInvalid()) return ExprError();
20757 E = result.get();
20758
20759 if (!E->isTypeDependent()) {
20760 if (getLangOpts().CPlusPlus)
20761 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20762
20764 if (ERes.isInvalid())
20765 return ExprError();
20766 E = ERes.get();
20767
20768 QualType T = E->getType();
20769 if (!T->isScalarType()) { // C99 6.8.4.1p1
20770 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20771 << T << E->getSourceRange();
20772 return ExprError();
20773 }
20774 CheckBoolLikeConversion(E, Loc);
20775 }
20776
20777 return E;
20778}
20779
20781 Expr *SubExpr, ConditionKind CK,
20782 bool MissingOK) {
20783 // MissingOK indicates whether having no condition expression is valid
20784 // (for loop) or invalid (e.g. while loop).
20785 if (!SubExpr)
20786 return MissingOK ? ConditionResult() : ConditionError();
20787
20789 switch (CK) {
20791 Cond = CheckBooleanCondition(Loc, SubExpr);
20792 break;
20793
20795 // Note: this might produce a FullExpr
20796 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20797 break;
20798
20800 Cond = CheckSwitchCondition(Loc, SubExpr);
20801 break;
20802 }
20803 if (Cond.isInvalid()) {
20804 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20805 {SubExpr}, PreferredConditionType(CK));
20806 if (!Cond.get())
20807 return ConditionError();
20808 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
20809 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
20810
20811 if (!Cond.isUsable())
20812 return ConditionError();
20813
20814 return ConditionResult(*this, nullptr, Cond,
20816}
20817
20818namespace {
20819 /// A visitor for rebuilding a call to an __unknown_any expression
20820 /// to have an appropriate type.
20821 struct RebuildUnknownAnyFunction
20822 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20823
20824 Sema &S;
20825
20826 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20827
20828 ExprResult VisitStmt(Stmt *S) {
20829 llvm_unreachable("unexpected statement!");
20830 }
20831
20832 ExprResult VisitExpr(Expr *E) {
20833 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20834 << E->getSourceRange();
20835 return ExprError();
20836 }
20837
20838 /// Rebuild an expression which simply semantically wraps another
20839 /// expression which it shares the type and value kind of.
20840 template <class T> ExprResult rebuildSugarExpr(T *E) {
20841 ExprResult SubResult = Visit(E->getSubExpr());
20842 if (SubResult.isInvalid()) return ExprError();
20843
20844 Expr *SubExpr = SubResult.get();
20845 E->setSubExpr(SubExpr);
20846 E->setType(SubExpr->getType());
20847 E->setValueKind(SubExpr->getValueKind());
20848 assert(E->getObjectKind() == OK_Ordinary);
20849 return E;
20850 }
20851
20852 ExprResult VisitParenExpr(ParenExpr *E) {
20853 return rebuildSugarExpr(E);
20854 }
20855
20856 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20857 return rebuildSugarExpr(E);
20858 }
20859
20860 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20861 ExprResult SubResult = Visit(E->getSubExpr());
20862 if (SubResult.isInvalid()) return ExprError();
20863
20864 Expr *SubExpr = SubResult.get();
20865 E->setSubExpr(SubExpr);
20866 E->setType(S.Context.getPointerType(SubExpr->getType()));
20867 assert(E->isPRValue());
20868 assert(E->getObjectKind() == OK_Ordinary);
20869 return E;
20870 }
20871
20872 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20873 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20874
20875 E->setType(VD->getType());
20876
20877 assert(E->isPRValue());
20878 if (S.getLangOpts().CPlusPlus &&
20879 !(isa<CXXMethodDecl>(VD) &&
20880 cast<CXXMethodDecl>(VD)->isInstance()))
20882
20883 return E;
20884 }
20885
20886 ExprResult VisitMemberExpr(MemberExpr *E) {
20887 return resolveDecl(E, E->getMemberDecl());
20888 }
20889
20890 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20891 return resolveDecl(E, E->getDecl());
20892 }
20893 };
20894}
20895
20896/// Given a function expression of unknown-any type, try to rebuild it
20897/// to have a function type.
20899 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20900 if (Result.isInvalid()) return ExprError();
20901 return S.DefaultFunctionArrayConversion(Result.get());
20902}
20903
20904namespace {
20905 /// A visitor for rebuilding an expression of type __unknown_anytype
20906 /// into one which resolves the type directly on the referring
20907 /// expression. Strict preservation of the original source
20908 /// structure is not a goal.
20909 struct RebuildUnknownAnyExpr
20910 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20911
20912 Sema &S;
20913
20914 /// The current destination type.
20915 QualType DestType;
20916
20917 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20918 : S(S), DestType(CastType) {}
20919
20920 ExprResult VisitStmt(Stmt *S) {
20921 llvm_unreachable("unexpected statement!");
20922 }
20923
20924 ExprResult VisitExpr(Expr *E) {
20925 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20926 << E->getSourceRange();
20927 return ExprError();
20928 }
20929
20930 ExprResult VisitCallExpr(CallExpr *E);
20931 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20932
20933 /// Rebuild an expression which simply semantically wraps another
20934 /// expression which it shares the type and value kind of.
20935 template <class T> ExprResult rebuildSugarExpr(T *E) {
20936 ExprResult SubResult = Visit(E->getSubExpr());
20937 if (SubResult.isInvalid()) return ExprError();
20938 Expr *SubExpr = SubResult.get();
20939 E->setSubExpr(SubExpr);
20940 E->setType(SubExpr->getType());
20941 E->setValueKind(SubExpr->getValueKind());
20942 assert(E->getObjectKind() == OK_Ordinary);
20943 return E;
20944 }
20945
20946 ExprResult VisitParenExpr(ParenExpr *E) {
20947 return rebuildSugarExpr(E);
20948 }
20949
20950 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20951 return rebuildSugarExpr(E);
20952 }
20953
20954 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20955 const PointerType *Ptr = DestType->getAs<PointerType>();
20956 if (!Ptr) {
20957 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20958 << E->getSourceRange();
20959 return ExprError();
20960 }
20961
20962 if (isa<CallExpr>(E->getSubExpr())) {
20963 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20964 << E->getSourceRange();
20965 return ExprError();
20966 }
20967
20968 assert(E->isPRValue());
20969 assert(E->getObjectKind() == OK_Ordinary);
20970 E->setType(DestType);
20971
20972 // Build the sub-expression as if it were an object of the pointee type.
20973 DestType = Ptr->getPointeeType();
20974 ExprResult SubResult = Visit(E->getSubExpr());
20975 if (SubResult.isInvalid()) return ExprError();
20976 E->setSubExpr(SubResult.get());
20977 return E;
20978 }
20979
20980 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20981
20982 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20983
20984 ExprResult VisitMemberExpr(MemberExpr *E) {
20985 return resolveDecl(E, E->getMemberDecl());
20986 }
20987
20988 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20989 return resolveDecl(E, E->getDecl());
20990 }
20991 };
20992}
20993
20994/// Rebuilds a call expression which yielded __unknown_anytype.
20995ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20996 Expr *CalleeExpr = E->getCallee();
20997
20998 enum FnKind {
20999 FK_MemberFunction,
21000 FK_FunctionPointer,
21001 FK_BlockPointer
21002 };
21003
21004 FnKind Kind;
21005 QualType CalleeType = CalleeExpr->getType();
21006 if (CalleeType == S.Context.BoundMemberTy) {
21008 Kind = FK_MemberFunction;
21009 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21010 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21011 CalleeType = Ptr->getPointeeType();
21012 Kind = FK_FunctionPointer;
21013 } else {
21014 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21015 Kind = FK_BlockPointer;
21016 }
21017 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21018
21019 // Verify that this is a legal result type of a function.
21020 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21021 DestType->isFunctionType()) {
21022 unsigned diagID = diag::err_func_returning_array_function;
21023 if (Kind == FK_BlockPointer)
21024 diagID = diag::err_block_returning_array_function;
21025
21026 S.Diag(E->getExprLoc(), diagID)
21027 << DestType->isFunctionType() << DestType;
21028 return ExprError();
21029 }
21030
21031 // Otherwise, go ahead and set DestType as the call's result.
21032 E->setType(DestType.getNonLValueExprType(S.Context));
21034 assert(E->getObjectKind() == OK_Ordinary);
21035
21036 // Rebuild the function type, replacing the result type with DestType.
21037 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21038 if (Proto) {
21039 // __unknown_anytype(...) is a special case used by the debugger when
21040 // it has no idea what a function's signature is.
21041 //
21042 // We want to build this call essentially under the K&R
21043 // unprototyped rules, but making a FunctionNoProtoType in C++
21044 // would foul up all sorts of assumptions. However, we cannot
21045 // simply pass all arguments as variadic arguments, nor can we
21046 // portably just call the function under a non-variadic type; see
21047 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21048 // However, it turns out that in practice it is generally safe to
21049 // call a function declared as "A foo(B,C,D);" under the prototype
21050 // "A foo(B,C,D,...);". The only known exception is with the
21051 // Windows ABI, where any variadic function is implicitly cdecl
21052 // regardless of its normal CC. Therefore we change the parameter
21053 // types to match the types of the arguments.
21054 //
21055 // This is a hack, but it is far superior to moving the
21056 // corresponding target-specific code from IR-gen to Sema/AST.
21057
21058 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21059 SmallVector<QualType, 8> ArgTypes;
21060 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21061 ArgTypes.reserve(E->getNumArgs());
21062 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21063 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21064 }
21065 ParamTypes = ArgTypes;
21066 }
21067 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21068 Proto->getExtProtoInfo());
21069 } else {
21070 DestType = S.Context.getFunctionNoProtoType(DestType,
21071 FnType->getExtInfo());
21072 }
21073
21074 // Rebuild the appropriate pointer-to-function type.
21075 switch (Kind) {
21076 case FK_MemberFunction:
21077 // Nothing to do.
21078 break;
21079
21080 case FK_FunctionPointer:
21081 DestType = S.Context.getPointerType(DestType);
21082 break;
21083
21084 case FK_BlockPointer:
21085 DestType = S.Context.getBlockPointerType(DestType);
21086 break;
21087 }
21088
21089 // Finally, we can recurse.
21090 ExprResult CalleeResult = Visit(CalleeExpr);
21091 if (!CalleeResult.isUsable()) return ExprError();
21092 E->setCallee(CalleeResult.get());
21093
21094 // Bind a temporary if necessary.
21095 return S.MaybeBindToTemporary(E);
21096}
21097
21098ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21099 // Verify that this is a legal result type of a call.
21100 if (DestType->isArrayType() || DestType->isFunctionType()) {
21101 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21102 << DestType->isFunctionType() << DestType;
21103 return ExprError();
21104 }
21105
21106 // Rewrite the method result type if available.
21107 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21108 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21109 Method->setReturnType(DestType);
21110 }
21111
21112 // Change the type of the message.
21113 E->setType(DestType.getNonReferenceType());
21115
21116 return S.MaybeBindToTemporary(E);
21117}
21118
21119ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21120 // The only case we should ever see here is a function-to-pointer decay.
21121 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21122 assert(E->isPRValue());
21123 assert(E->getObjectKind() == OK_Ordinary);
21124
21125 E->setType(DestType);
21126
21127 // Rebuild the sub-expression as the pointee (function) type.
21128 DestType = DestType->castAs<PointerType>()->getPointeeType();
21129
21130 ExprResult Result = Visit(E->getSubExpr());
21131 if (!Result.isUsable()) return ExprError();
21132
21133 E->setSubExpr(Result.get());
21134 return E;
21135 } else if (E->getCastKind() == CK_LValueToRValue) {
21136 assert(E->isPRValue());
21137 assert(E->getObjectKind() == OK_Ordinary);
21138
21139 assert(isa<BlockPointerType>(E->getType()));
21140
21141 E->setType(DestType);
21142
21143 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21144 DestType = S.Context.getLValueReferenceType(DestType);
21145
21146 ExprResult Result = Visit(E->getSubExpr());
21147 if (!Result.isUsable()) return ExprError();
21148
21149 E->setSubExpr(Result.get());
21150 return E;
21151 } else {
21152 llvm_unreachable("Unhandled cast type!");
21153 }
21154}
21155
21156ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21157 ExprValueKind ValueKind = VK_LValue;
21158 QualType Type = DestType;
21159
21160 // We know how to make this work for certain kinds of decls:
21161
21162 // - functions
21163 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21164 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21165 DestType = Ptr->getPointeeType();
21166 ExprResult Result = resolveDecl(E, VD);
21167 if (Result.isInvalid()) return ExprError();
21168 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21169 VK_PRValue);
21170 }
21171
21172 if (!Type->isFunctionType()) {
21173 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21174 << VD << E->getSourceRange();
21175 return ExprError();
21176 }
21177 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21178 // We must match the FunctionDecl's type to the hack introduced in
21179 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21180 // type. See the lengthy commentary in that routine.
21181 QualType FDT = FD->getType();
21182 const FunctionType *FnType = FDT->castAs<FunctionType>();
21183 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21184 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21185 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21186 SourceLocation Loc = FD->getLocation();
21187 FunctionDecl *NewFD = FunctionDecl::Create(
21188 S.Context, FD->getDeclContext(), Loc, Loc,
21189 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21191 false /*isInlineSpecified*/, FD->hasPrototype(),
21192 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21193
21194 if (FD->getQualifier())
21195 NewFD->setQualifierInfo(FD->getQualifierLoc());
21196
21197 SmallVector<ParmVarDecl*, 16> Params;
21198 for (const auto &AI : FT->param_types()) {
21199 ParmVarDecl *Param =
21200 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21201 Param->setScopeInfo(0, Params.size());
21202 Params.push_back(Param);
21203 }
21204 NewFD->setParams(Params);
21205 DRE->setDecl(NewFD);
21206 VD = DRE->getDecl();
21207 }
21208 }
21209
21210 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21211 if (MD->isInstance()) {
21212 ValueKind = VK_PRValue;
21214 }
21215
21216 // Function references aren't l-values in C.
21217 if (!S.getLangOpts().CPlusPlus)
21218 ValueKind = VK_PRValue;
21219
21220 // - variables
21221 } else if (isa<VarDecl>(VD)) {
21222 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21223 Type = RefTy->getPointeeType();
21224 } else if (Type->isFunctionType()) {
21225 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21226 << VD << E->getSourceRange();
21227 return ExprError();
21228 }
21229
21230 // - nothing else
21231 } else {
21232 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21233 << VD << E->getSourceRange();
21234 return ExprError();
21235 }
21236
21237 // Modifying the declaration like this is friendly to IR-gen but
21238 // also really dangerous.
21239 VD->setType(DestType);
21240 E->setType(Type);
21241 E->setValueKind(ValueKind);
21242 return E;
21243}
21244
21247 ExprValueKind &VK, CXXCastPath &Path) {
21248 // The type we're casting to must be either void or complete.
21249 if (!CastType->isVoidType() &&
21251 diag::err_typecheck_cast_to_incomplete))
21252 return ExprError();
21253
21254 // Rewrite the casted expression from scratch.
21255 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21256 if (!result.isUsable()) return ExprError();
21257
21258 CastExpr = result.get();
21260 CastKind = CK_NoOp;
21261
21262 return CastExpr;
21263}
21264
21266 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21267}
21268
21270 Expr *arg, QualType &paramType) {
21271 // If the syntactic form of the argument is not an explicit cast of
21272 // any sort, just do default argument promotion.
21273 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21274 if (!castArg) {
21276 if (result.isInvalid()) return ExprError();
21277 paramType = result.get()->getType();
21278 return result;
21279 }
21280
21281 // Otherwise, use the type that was written in the explicit cast.
21282 assert(!arg->hasPlaceholderType());
21283 paramType = castArg->getTypeAsWritten();
21284
21285 // Copy-initialize a parameter of that type.
21286 InitializedEntity entity =
21288 /*consumed*/ false);
21289 return PerformCopyInitialization(entity, callLoc, arg);
21290}
21291
21293 Expr *orig = E;
21294 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21295 while (true) {
21296 E = E->IgnoreParenImpCasts();
21297 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21298 E = call->getCallee();
21299 diagID = diag::err_uncasted_call_of_unknown_any;
21300 } else {
21301 break;
21302 }
21303 }
21304
21305 SourceLocation loc;
21306 NamedDecl *d;
21307 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21308 loc = ref->getLocation();
21309 d = ref->getDecl();
21310 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21311 loc = mem->getMemberLoc();
21312 d = mem->getMemberDecl();
21313 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21314 diagID = diag::err_uncasted_call_of_unknown_any;
21315 loc = msg->getSelectorStartLoc();
21316 d = msg->getMethodDecl();
21317 if (!d) {
21318 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21319 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21320 << orig->getSourceRange();
21321 return ExprError();
21322 }
21323 } else {
21324 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21325 << E->getSourceRange();
21326 return ExprError();
21327 }
21328
21329 S.Diag(loc, diagID) << d << orig->getSourceRange();
21330
21331 // Never recoverable.
21332 return ExprError();
21333}
21334
21336 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21337 if (!placeholderType) return E;
21338
21339 switch (placeholderType->getKind()) {
21340 case BuiltinType::UnresolvedTemplate: {
21341 auto *ULE = cast<UnresolvedLookupExpr>(E);
21342 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21343 // There's only one FoundDecl for UnresolvedTemplate type. See
21344 // BuildTemplateIdExpr.
21345 NamedDecl *Temp = *ULE->decls_begin();
21346 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21347
21348 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21349 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21350 // as it models only the unqualified-id case, where this case can clearly be
21351 // qualified. Thus we can't just qualify an assumed template.
21352 TemplateName TN;
21353 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21354 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21355 TemplateName(TD));
21356 else
21357 TN = Context.getAssumedTemplateName(NameInfo.getName());
21358
21359 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21360 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21361 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21362 << IsTypeAliasTemplateDecl;
21363
21364 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21365 bool HasAnyDependentTA = false;
21366 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21367 HasAnyDependentTA |= Arg.getArgument().isDependent();
21368 TAL.addArgument(Arg);
21369 }
21370
21371 QualType TST;
21372 {
21373 SFINAETrap Trap(*this);
21374 TST = CheckTemplateIdType(
21375 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
21376 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21377 }
21378 if (TST.isNull())
21379 TST = Context.getTemplateSpecializationType(
21380 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21381 /*CanonicalArgs=*/{},
21382 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21383 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21384 TST);
21385 }
21386
21387 // Overloaded expressions.
21388 case BuiltinType::Overload: {
21389 // Try to resolve a single function template specialization.
21390 // This is obligatory.
21391 ExprResult Result = E;
21393 return Result;
21394
21395 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21396 // leaves Result unchanged on failure.
21397 Result = E;
21399 return Result;
21400
21401 // If that failed, try to recover with a call.
21402 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21403 /*complain*/ true);
21404 return Result;
21405 }
21406
21407 // Bound member functions.
21408 case BuiltinType::BoundMember: {
21409 ExprResult result = E;
21410 const Expr *BME = E->IgnoreParens();
21411 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21412 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21414 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21415 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21416 if (ME->getMemberNameInfo().getName().getNameKind() ==
21418 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21419 }
21420 tryToRecoverWithCall(result, PD,
21421 /*complain*/ true);
21422 return result;
21423 }
21424
21425 // ARC unbridged casts.
21426 case BuiltinType::ARCUnbridgedCast: {
21427 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21428 ObjC().diagnoseARCUnbridgedCast(realCast);
21429 return realCast;
21430 }
21431
21432 // Expressions of unknown type.
21433 case BuiltinType::UnknownAny:
21434 return diagnoseUnknownAnyExpr(*this, E);
21435
21436 // Pseudo-objects.
21437 case BuiltinType::PseudoObject:
21438 return PseudoObject().checkRValue(E);
21439
21440 case BuiltinType::BuiltinFn: {
21441 // Accept __noop without parens by implicitly converting it to a call expr.
21442 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21443 if (DRE) {
21444 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21445 unsigned BuiltinID = FD->getBuiltinID();
21446 if (BuiltinID == Builtin::BI__noop) {
21447 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21448 CK_BuiltinFnToFnPtr)
21449 .get();
21450 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21453 }
21454
21455 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21456 // Any use of these other than a direct call is ill-formed as of C++20,
21457 // because they are not addressable functions. In earlier language
21458 // modes, warn and force an instantiation of the real body.
21459 Diag(E->getBeginLoc(),
21461 ? diag::err_use_of_unaddressable_function
21462 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21463 if (FD->isImplicitlyInstantiable()) {
21464 // Require a definition here because a normal attempt at
21465 // instantiation for a builtin will be ignored, and we won't try
21466 // again later. We assume that the definition of the template
21467 // precedes this use.
21469 /*Recursive=*/false,
21470 /*DefinitionRequired=*/true,
21471 /*AtEndOfTU=*/false);
21472 }
21473 // Produce a properly-typed reference to the function.
21474 CXXScopeSpec SS;
21475 SS.Adopt(DRE->getQualifierLoc());
21476 TemplateArgumentListInfo TemplateArgs;
21477 DRE->copyTemplateArgumentsInto(TemplateArgs);
21478 return BuildDeclRefExpr(
21479 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21480 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21481 DRE->getTemplateKeywordLoc(),
21482 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21483 }
21484 }
21485
21486 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21487 return ExprError();
21488 }
21489
21490 case BuiltinType::IncompleteMatrixIdx:
21492 ->getRowIdx()
21493 ->getBeginLoc(),
21494 diag::err_matrix_incomplete_index);
21495 return ExprError();
21496
21497 // Expressions of unknown type.
21498 case BuiltinType::ArraySection:
21499 // If we've already diagnosed something on the array section type, we
21500 // shouldn't need to do any further diagnostic here.
21501 if (!E->containsErrors())
21502 Diag(E->getBeginLoc(), diag::err_array_section_use)
21503 << cast<ArraySectionExpr>(E)->isOMPArraySection();
21504 return ExprError();
21505
21506 // Expressions of unknown type.
21507 case BuiltinType::OMPArrayShaping:
21508 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21509
21510 case BuiltinType::OMPIterator:
21511 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21512
21513 // Everything else should be impossible.
21514#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21515 case BuiltinType::Id:
21516#include "clang/Basic/OpenCLImageTypes.def"
21517#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21518 case BuiltinType::Id:
21519#include "clang/Basic/OpenCLExtensionTypes.def"
21520#define SVE_TYPE(Name, Id, SingletonId) \
21521 case BuiltinType::Id:
21522#include "clang/Basic/AArch64ACLETypes.def"
21523#define PPC_VECTOR_TYPE(Name, Id, Size) \
21524 case BuiltinType::Id:
21525#include "clang/Basic/PPCTypes.def"
21526#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21527#include "clang/Basic/RISCVVTypes.def"
21528#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21529#include "clang/Basic/WebAssemblyReferenceTypes.def"
21530#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21531#include "clang/Basic/AMDGPUTypes.def"
21532#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21533#include "clang/Basic/HLSLIntangibleTypes.def"
21534#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21535#define PLACEHOLDER_TYPE(Id, SingletonId)
21536#include "clang/AST/BuiltinTypes.def"
21537 break;
21538 }
21539
21540 llvm_unreachable("invalid placeholder type!");
21541}
21542
21544 if (E->isTypeDependent())
21545 return true;
21547 return E->getType()->isIntegralOrEnumerationType();
21548 return false;
21549}
21550
21552 ArrayRef<Expr *> SubExprs, QualType T) {
21553 if (!Context.getLangOpts().RecoveryAST)
21554 return ExprError();
21555
21556 if (isSFINAEContext())
21557 return ExprError();
21558
21559 if (T.isNull() || T->isUndeducedType() ||
21560 !Context.getLangOpts().RecoveryASTType)
21561 // We don't know the concrete type, fallback to dependent type.
21562 T = Context.DependentTy;
21563
21564 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21565}
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:2691
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Token Tok
The Token.
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 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 ARM.
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:49
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 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)
@ ConstMethod
@ 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 bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
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:147
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:163
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:551
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 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:576
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:109
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:489
bool hasValue() const
Definition APValue.h:465
bool isInt() const
Definition APValue.h:467
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
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.
DeclarationNameTable DeclarationNames
Definition ASTContext.h:741
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
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
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:737
const LangOptions & getLangOpts() const
Definition ASTContext.h:891
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:859
bool typesAreBlockPointerCompatible(QualType, QualType)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
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
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
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)
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
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.
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:856
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) 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.
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:4486
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2723
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2778
Wrapper for source info for arrays.
Definition TypeLoc.h:1757
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3720
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3734
QualType getElementType() const
Definition TypeBase.h:3732
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition Expr.h:6621
Attr - This represents one attribute.
Definition Attr.h:44
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4389
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3974
Expr * getLHS() const
Definition Expr.h:4024
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4068
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2175
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4074
StringRef getOpcodeStr() const
Definition Expr.h:4040
bool isRelationalOp() const
Definition Expr.h:4069
SourceLocation getOperatorLoc() const
Definition Expr.h:4016
bool isMultiplicativeOp() const
Definition Expr.h:4059
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2128
bool isShiftOp() const
Definition Expr.h:4063
Expr * getRHS() const
Definition Expr.h:4026
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:4938
bool isBitwiseOp() const
Definition Expr.h:4066
bool isAdditiveOp() const
Definition Expr.h:4061
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4110
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4115
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:2200
Opcode getOpcode() const
Definition Expr.h:4019
bool isAssignmentOp() const
Definition Expr.h:4113
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2137
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4071
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4065
BinaryOperatorKind Opcode
Definition Expr.h:3979
A binding in a decomposition declaration.
Definition DeclCXX.h:4185
A class which contains all the information about a particular captured value.
Definition Decl.h:4640
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4634
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.cpp:5314
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition Decl.h:4716
void setBlockMissingReturnType(bool val=true)
Definition Decl.h:4773
void setIsVariadic(bool value)
Definition Decl.h:4710
SourceLocation getCaretLocation() const
Definition Decl.h:4707
void setBody(CompoundStmt *B)
Definition Decl.h:4714
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4720
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition Decl.cpp:5325
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5513
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6560
Pointer to a block type.
Definition TypeBase.h:3540
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
bool isSVEBool() const
Definition TypeBase.h:3241
Kind getKind() const
Definition TypeBase.h:3212
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:1956
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:1549
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2943
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition DeclCXX.cpp:3184
Represents a C++ base or member initializer.
Definition DeclCXX.h:2369
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1271
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition ExprCXX.cpp:1039
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1378
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:1093
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1105
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:1550
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isVirtual() const
Definition DeclCXX.h:2184
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
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:2508
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:152
SourceRange getSourceRange() const
Definition ExprCXX.h:164
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:1987
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2739
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:600
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:2075
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.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:180
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
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:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
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:183
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
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:1155
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2879
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3083
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3096
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:1513
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3062
Expr * getCallee()
Definition Expr.h:3026
void computeDependence()
Compute and set dependence bits.
Definition Expr.h:3102
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3070
void setCallee(Expr *F)
Definition Expr.h:3028
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:3612
CastKind getCastKind() const
Definition Expr.h:3656
const char * getCastKindName() const
Definition Expr.h:3660
void setSubExpr(Expr *E)
Definition Expr.h:3664
Expr * getSubExpr()
Definition Expr.h:3662
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a character-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:1631
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4784
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
QualType getElementType() const
Definition TypeBase.h:3285
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:4960
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3541
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1720
bool body_empty() const
Definition Stmt.h:1764
Stmt * getStmtExprResult()
Definition Stmt.h:1842
ConditionalOperator - The ?
Definition Expr.h:4327
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3758
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3814
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3834
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1084
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition Expr.cpp:298
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition Expr.cpp:374
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1134
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
bool isImmediateInvocation() const
Definition Expr.h:1156
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4371
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4392
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4389
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:37
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:1454
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:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isRequiresExprBody() const
Definition DeclBase.h:2194
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
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:2189
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:2161
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:1272
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1383
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition Expr.h:1427
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1373
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1476
void setDecl(ValueDecl *NewD)
Definition Expr.cpp:540
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition Expr.h:1431
DeclarationNameInfo getNameInfo() const
Definition Expr.h:1344
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition Expr.h:1399
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:484
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition Expr.h:1361
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1365
ValueDecl * getDecl()
Definition Expr.h:1340
SourceLocation getBeginLoc() const
Definition Expr.h:1351
SourceLocation getLocation() const
Definition Expr.h:1348
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition DeclBase.cpp:753
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:156
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:568
bool isInvalidDecl() const
Definition DeclBase.h:588
SourceLocation getLocation() const
Definition DeclBase.h:439
void setReferenced(bool R=true)
Definition DeclBase.h:623
DeclContext * getDeclContext()
Definition DeclBase.h:448
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
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:2000
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition Decl.h:844
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
DeclaratorContext getContext() const
Definition DeclSpec.h:2046
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2057
bool isInvalidType() const
Definition DeclSpec.h:2688
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2304
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:544
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:950
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:722
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Represents a reference to emded data.
Definition Expr.h:5062
RAII object that enters a new expression evaluation context.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4168
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3864
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3891
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1464
This represents one expression.
Definition Expr.h:112
LValueClassification
Definition Expr.h:289
@ LV_ArrayTemporary
Definition Expr.h:299
@ LV_ClassTemporary
Definition Expr.h:298
@ LV_MemberFunction
Definition Expr.h:296
@ 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:3100
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:674
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition Expr.cpp:3029
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:3078
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:444
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:3073
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3061
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3082
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:3069
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:3293
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:833
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:829
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:837
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
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:3624
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:3053
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:804
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:813
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:816
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition Expr.h:819
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:806
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:4001
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:262
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:461
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
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:4255
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:464
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:476
isModifiableLvalueResult
Definition Expr.h:304
@ MLV_DuplicateVectorComponents
Definition Expr.h:308
@ MLV_LValueCast
Definition Expr.h:310
@ MLV_InvalidMessageExpression
Definition Expr.h:319
@ MLV_ConstQualifiedField
Definition Expr.h:313
@ MLV_InvalidExpression
Definition Expr.h:309
@ MLV_IncompleteType
Definition Expr.h:311
@ MLV_Valid
Definition Expr.h:305
@ MLV_ConstQualified
Definition Expr.h:312
@ MLV_NoSetterProperty
Definition Expr.h:316
@ MLV_ArrayTemporary
Definition Expr.h:321
@ MLV_SubObjCPropertySetting
Definition Expr.h:318
@ MLV_ConstAddrSpace
Definition Expr.h:314
@ MLV_MemberFunction
Definition Expr.h:317
@ MLV_NotObjectType
Definition Expr.h:306
@ MLV_ArrayType
Definition Expr.h:315
@ MLV_ClassTemporary
Definition Expr.h:320
@ MLV_IncompleteVoidType
Definition Expr.h:307
QualType getType() const
Definition Expr.h:144
bool isOrdinaryOrBitFieldObject() const
Definition Expr.h:455
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
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:133
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6500
ExtVectorType - Extended vector type.
Definition TypeBase.h:4265
Represents difference between two FPOptions values.
bool isFPConstrained() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3260
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3337
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
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:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:128
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:102
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:993
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1072
const Expr * getSubExpr() const
Definition Expr.h:1064
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:1999
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:2188
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3788
bool isImmediateFunction() const
Definition Decl.cpp:3328
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:3965
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3806
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2918
QualType getReturnType() const
Definition Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2771
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2442
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3559
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isImmediateEscalating() const
Definition Decl.cpp:3303
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2930
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4071
bool isConsteval() const
Definition Decl.h:2481
size_t param_size() const
Definition Decl.h:2787
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3191
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition Decl.cpp:3981
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition Decl.h:2878
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4835
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4864
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5264
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5768
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5571
bool isParamConsumed(unsigned I) const
Definition TypeBase.h:5782
unsigned getNumParams() const
Definition TypeBase.h:5542
QualType getParamType(unsigned i) const
Definition TypeBase.h:5544
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5668
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5553
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5549
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5704
Declaration of a template function.
unsigned getNumParams() const
Definition TypeLoc.h:1696
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1702
SourceLocation getLocalRangeEnd() const
Definition TypeLoc.h:1648
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1705
SourceLocation getLocalRangeBegin() const
Definition TypeLoc.h:1640
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4571
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4642
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4499
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4460
ExtInfo getExtInfo() const
Definition TypeBase.h:4816
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4808
bool getCFIUncheckedCalleeAttr() const
Determine whether this is a function prototype that includes the cfi_unchecked_callee attribute.
Definition Type.cpp:3572
QualType getReturnType() const
Definition TypeBase.h:4800
bool getCmseNSCallAttr() const
Definition TypeBase.h:4814
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4828
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4859
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:4560
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:1733
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3789
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2068
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:615
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3464
Describes an C or C++ initializer list.
Definition Expr.h:5235
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:971
Represents the declaration of a label.
Definition Decl.h:523
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1970
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition ExprCXX.cpp:1404
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:1020
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:399
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:309
Represents the results of name lookup.
Definition Lookup.h:147
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
DeclClass * getAsSingle() const
Definition Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
Definition Lookup.h:457
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
A global _GUID constant.
Definition DeclCXX.h:4398
MS property subscript expression.
Definition ExprCXX.h:1007
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...
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2801
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4335
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4349
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3300
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3489
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3383
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:1746
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3518
Expr * getBase() const
Definition Expr.h:3377
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1790
This represents a decl that may have a name.
Definition Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
bool isExternallyVisible() const
Definition Decl.h:432
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:396
Represent a C++ namespace.
Definition Decl.h:591
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:7847
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition ExprObjC.h:1498
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:548
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprObjC.h:594
SourceLocation getLocation() const
Definition ExprObjC.h:591
SourceLocation getOpLoc() const
Definition ExprObjC.h:599
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:578
bool isArrow() const
Definition ExprObjC.h:586
SourceLocation getEndLoc() const LLVM_READONLY
Definition ExprObjC.h:597
const Expr * getBase() const
Definition ExprObjC.h:582
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:940
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1364
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:7903
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1840
qual_range quals() const
Definition TypeBase.h:8022
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:1649
Helper class for OffsetOfExpr.
Definition Expr.h:2423
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:1180
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1153
@ CSK_Normal
Normal lookup.
Definition Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1369
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:3122
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3183
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2184
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2205
const Expr * getSubExpr() const
Definition Expr.h:2201
bool isProducedByFoldExpansion() const
Definition Expr.h:2226
Expr * getExpr(unsigned Init)
Definition Expr.h:6048
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4810
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6046
SourceLocation getLParenLoc() const
Definition Expr.h:6061
SourceLocation getRParenLoc() const
Definition Expr.h:6062
Represents a parameter to a function.
Definition Decl.h:1789
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1822
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:2946
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition Expr.cpp:629
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition Expr.cpp:669
bool isMacroDefined(StringRef Id)
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6692
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8369
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8374
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:87
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3556
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:2921
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition TypeBase.h:1416
QualType withConst() const
Definition TypeBase.h:1159
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
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:8285
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8411
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:81
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8325
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:2703
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
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:8470
QualType getCanonicalType() const
Definition TypeBase.h:8337
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:2940
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition TypeBase.h:8477
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8358
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1670
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8342
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1309
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2695
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:8450
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8317
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:75
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:4309
bool hasFlexibleArrayMember() const
Definition Decl.h:4342
field_iterator field_end() const
Definition Decl.h:4515
field_range fields() const
Definition Decl.h:4512
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition Expr.cpp:5265
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:3571
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:428
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
bool isInCFunctionScope() const
isInObjcMethodScope - Return true if this scope is, or is contained, in an C function body.
Definition Scope.h:448
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:487
@ ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition Scope.h:59
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition Scope.h:66
@ BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it.
Definition Scope.h:55
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId, bool DeferHint=false)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:91
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
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:726
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:134
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition SemaCUDA.cpp:902
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition SemaCUDA.h:120
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:371
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)
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8401
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12367
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12409
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7676
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:854
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.
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:8154
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13438
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1120
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:8204
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8122
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:935
bool isAttrContext() const
Definition Sema.h:6912
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:8197
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9291
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9330
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9299
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:405
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:1505
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:1230
SemaCUDA & CUDA()
Definition Sema.h:1445
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:7797
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7799
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7798
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
bool needsRebuildOfDefaultArgOrInit() const
Definition Sema.h:8142
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:8284
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1223
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2442
Preprocessor & getPreprocessor() const
Definition Sema.h:924
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6890
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2311
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:8273
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition Sema.h:8185
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:6724
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:2049
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.
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:6902
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:1647
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:827
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:1283
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:8109
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...
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
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:1490
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:2821
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:748
bool isImmediateFunctionContext() const
Definition Sema.h:8134
ASTContext & getASTContext() const
Definition Sema.h:925
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1059
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:758
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:756
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition SemaExpr.cpp:877
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:6042
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6044
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:1191
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1652
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:11370
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:500
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:8169
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:920
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8267
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
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:83
@ UPPC_Block
Block expression.
Definition Sema.h:14287
const LangOptions & getLangOpts() const
Definition Sema.h:918
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)
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:1495
ReuseLambdaContextDecl_t
Definition Sema.h:6978
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.
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:1282
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:2113
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:1281
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:2557
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:946
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6468
SemaHLSL & HLSL()
Definition Sema.h:1455
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:15511
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:207
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5204
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:75
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:6923
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6498
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1659
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:13849
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:849
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:1314
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:6920
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.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
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:2294
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:633
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:8138
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:8005
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2512
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1418
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:12433
SemaOpenCL & OpenCL()
Definition Sema.h:1500
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:13858
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:8130
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1627
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:6727
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:13799
SourceManager & getSourceManager() const
Definition Sema.h:923
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 ?
bool IsFunctionConversion(QualType FromType, QualType ToType, bool *DiscardingCFIUncheckedCallee=nullptr, bool *AddingCFIUncheckedCallee=nullptr) const
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
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:7430
@ NTCUK_Destruct
Definition Sema.h:4073
@ NTCUK_Copy
Definition Sema.h:4074
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8283
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:2342
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:6725
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 InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:218
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....
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15286
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:2497
bool isConstantEvaluatedContext() const
Definition Sema.h:2591
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:1284
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4630
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:6927
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:123
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1319
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:13841
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:6669
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6691
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6681
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6696
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6686
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6706
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6675
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6701
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6716
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:1246
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:8120
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:8270
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:1286
@ TemplateNameIsRequired
Definition Sema.h:11347
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:777
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:1285
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:919
FPOptions CurFPFeatures
Definition Sema.h:1279
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:509
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 ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
friend class InitializationSequence
Definition Sema.h:1560
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:6502
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:627
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:2096
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)
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
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:7928
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9344
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9350
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9342
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9347
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9358
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9354
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:6383
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:13837
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:7783
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:1515
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2488
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:8146
SemaARM & ARM()
Definition Sema.h:1425
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
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:8609
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:4953
SourceLocation getBeginLoc() const
Definition Expr.h:4998
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition Expr.h:4994
SourceLocation getEndLoc() const
Definition Expr.h:4999
SourceLocIdentKind getIdentKind() const
Definition Expr.h:4973
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:292
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:303
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition Overload.h:390
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:4531
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:358
StmtClass getStmtClass() const
Definition Stmt.h:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
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:1801
unsigned getLength() const
Definition Expr.h:1911
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:1184
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1884
StringRef getString() const
Definition Expr.h:1869
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3809
bool isUnion() const
Definition Decl.h:3919
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:810
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition TargetInfo.h:730
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:332
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
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:98
void startToken()
Reset all flags to cleared.
Definition Token.h:179
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:3510
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3544
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:222
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:2715
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8256
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8267
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:556
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2485
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition TypeBase.h:8942
bool isBlockPointerType() const
Definition TypeBase.h:8542
bool isVoidType() const
Definition TypeBase.h:8878
bool isBooleanType() const
Definition TypeBase.h:9008
bool isObjCBuiltinType() const
Definition TypeBase.h:8742
bool isMFloat8Type() const
Definition TypeBase.h:8903
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:1951
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9058
bool isIncompleteArrayType() const
Definition TypeBase.h:8629
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:8854
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:724
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
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:9038
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:2066
bool isVoidPointerType() const
Definition Type.cpp:712
const ComplexType * getAsComplexIntegerType() const
Definition Type.cpp:745
bool isArrayType() const
Definition TypeBase.h:8621
bool isCharType() const
Definition Type.cpp:2132
bool isFunctionPointerType() const
Definition TypeBase.h:8589
bool isArithmeticType() const
Definition Type.cpp:2337
bool isConstantMatrixType() const
Definition TypeBase.h:8683
bool isPointerType() const
Definition TypeBase.h:8522
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2574
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9165
bool isReferenceType() const
Definition TypeBase.h:8546
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:8962
bool isEnumeralType() const
Definition TypeBase.h:8653
bool isScalarType() const
Definition TypeBase.h:8980
bool isVariableArrayType() const
Definition TypeBase.h:8633
bool isSizelessBuiltinType() const
Definition Type.cpp:2532
bool isClkEventT() const
Definition TypeBase.h:8764
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2608
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8712
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8996
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2291
bool isExtVectorType() const
Definition TypeBase.h:8665
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2168
bool isExtVectorBoolType() const
Definition TypeBase.h:8669
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2647
bool isImageType() const
Definition TypeBase.h:8776
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition TypeBase.h:8872
bool isPipeType() const
Definition TypeBase.h:8783
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isBitIntType() const
Definition TypeBase.h:8787
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8847
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8645
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool isAnyComplexType() const
Definition TypeBase.h:8657
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8934
bool isHalfType() const
Definition TypeBase.h:8882
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8950
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2364
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8860
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2243
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2558
bool isQueueT() const
Definition TypeBase.h:8768
bool isMemberPointerType() const
Definition TypeBase.h:8603
bool isAtomicType() const
Definition TypeBase.h:8704
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9021
bool isObjCIdType() const
Definition TypeBase.h:8724
bool isMatrixType() const
Definition TypeBase.h:8679
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:2800
bool isComplexIntegerType() const
Definition Type.cpp:730
bool isUnscopedEnumerationType() const
Definition Type.cpp:2125
bool isObjCObjectType() const
Definition TypeBase.h:8695
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition Type.cpp:5221
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9151
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5310
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9014
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isDoubleType() const
Definition TypeBase.h:8895
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8518
bool isObjCObjectPointerType() const
Definition TypeBase.h:8691
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2312
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:8976
bool isVectorType() const
Definition TypeBase.h:8661
bool isObjCQualifiedClassType() const
Definition TypeBase.h:8718
bool isObjCClassType() const
Definition TypeBase.h:8730
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2595
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
@ STK_FloatingComplex
Definition TypeBase.h:2764
@ STK_ObjCObjectPointer
Definition TypeBase.h:2758
@ STK_IntegralComplex
Definition TypeBase.h:2763
@ STK_MemberPointer
Definition TypeBase.h:2759
bool isFloatingType() const
Definition Type.cpp:2304
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:2253
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2928
bool isAnyPointerType() const
Definition TypeBase.h:8530
bool isRealType() const
Definition Type.cpp:2326
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isSubscriptableVectorType() const
Definition TypeBase.h:8675
bool isSamplerT() const
Definition TypeBase.h:8756
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9098
bool isNullPtrType() const
Definition TypeBase.h:8915
bool isRecordType() const
Definition TypeBase.h:8649
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5022
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition Type.cpp:735
bool isUnicodeCharacterType() const
Definition Type.cpp:2188
Wrapper for source info for typedefs.
Definition TypeLoc.h:782
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:2627
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2246
void setSubExpr(Expr *E)
Definition Expr.h:2288
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition Expr.h:2291
Expr * getSubExpr() const
Definition Expr.h:2287
Opcode getOpcode() const
Definition Expr.h:2282
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1426
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2342
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:4995
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4455
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1086
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1080
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1050
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3384
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:432
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4120
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition ExprCXX.cpp:1683
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:1645
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:640
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:4893
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
void setType(QualType newType)
Definition Decl.h:723
QualType getType() const
Definition Decl.h:722
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5449
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3582
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:925
bool hasInit() const
Definition Decl.cpp:2398
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2257
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1577
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1282
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1225
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:2486
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:2907
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1550
const Expr * getInit() const
Definition Decl.h:1367
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1216
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1183
@ TLS_None
Not a TLS variable.
Definition Decl.h:945
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1294
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2375
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:2528
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:2800
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1261
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:2779
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2898
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3964
Expr * getSizeExpr() const
Definition TypeBase.h:3978
Represents a GCC generic vector type.
Definition TypeBase.h:4173
unsigned getNumElements() const
Definition TypeBase.h:4188
VectorKind getVectorKind() const
Definition TypeBase.h:4193
QualType getElementType() const
Definition TypeBase.h:4187
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:790
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition ScopeInfo.h:796
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition ScopeInfo.h:800
ValueDecl * getVariable() const
Definition ScopeInfo.h:675
bool isBlockCapture() const
Definition ScopeInfo.h:656
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:686
void markUsed(bool IsODRUse)
Definition ScopeInfo.h:668
bool isInvalid() const
Definition ScopeInfo.h:661
bool isThisCapture() const
Definition ScopeInfo.h:649
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition ScopeInfo.h:695
bool isCopyCapture() const
Definition ScopeInfo.h:654
bool isNested() const
Definition ScopeInfo.h:659
Retains information about a captured region.
Definition ScopeInfo.h:816
unsigned short CapRegionKind
The kind of captured region.
Definition ScopeInfo.h:831
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:732
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:728
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:708
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition ScopeInfo.h:718
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:758
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition ScopeInfo.h:714
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:755
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:737
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition ScopeInfo.h:771
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:1090
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:493
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:884
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:992
void addPotentialThisCapture(SourceLocation Loc)
Definition ScopeInfo.h:998
llvm::SmallPtrSet< VarDecl *, 4 > CUDAPotentialODRUsedVars
Variables that are potentially ODR-used in CUDA/HIP.
Definition ScopeInfo.h:953
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:871
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:892
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:874
#define bool
Definition gpuintrin.h:32
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:89
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:212
@ 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:511
bool isTargetAddressSpace(LangAS AS)
CUDAFunctionTarget
Definition Cuda.h:60
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
TryCaptureKind
Definition Sema.h:651
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition Sema.h:659
@ BitwiseOp
A bitwise operation.
Definition Sema.h:663
@ Arithmetic
An arithmetic operation.
Definition Sema.h:661
@ Conditional
A conditional (?:) operator.
Definition Sema.h:667
@ CompAssign
A compound assignment expression.
Definition Sema.h:669
@ Comparison
A comparison.
Definition Sema.h:665
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:348
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:357
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:149
@ OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition Specifiers.h:157
@ 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:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition Specifiers.h:154
@ OK_MatrixComponent
A matrix component is a single element of a matrix.
Definition Specifiers.h:169
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:992
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ AS_none
Definition Specifiers.h:127
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:251
@ SC_Register
Definition Specifiers.h:257
@ SC_None
Definition Specifiers.h:250
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
const FunctionProtoType * T
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:202
@ 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:687
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:710
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:773
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:702
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:752
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:742
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:769
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:756
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:694
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:736
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:731
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:765
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:689
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:721
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:698
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:706
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:748
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:715
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:727
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:760
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:562
@ 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:653
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
VarArgKind
Definition Sema.h:674
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
AssignmentAction
Definition Sema.h:213
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:519
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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
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:117
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:280
StringLiteralKind
Definition Expr.h:1765
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_X86VectorCall
Definition Specifiers.h:283
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4143
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4152
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4137
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4140
@ Neon
is ARM Neon vector
Definition TypeBase.h:4146
@ Generic
not a target-specific vector type
Definition TypeBase.h:4134
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4158
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4161
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4155
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:4940
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5884
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:1745
PredefinedIdentKind
Definition Expr.h:1991
@ Implicit
An implicit conversion.
Definition Sema.h:437
CharacterLiteralKind
Definition Expr.h:1605
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:173
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition Specifiers.h:183
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:177
@ NOUR_None
This is an odr-use.
Definition Specifiers.h:175
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition Specifiers.h:180
#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.
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
SourceLocation getEndLoc() const LLVM_READONLY
Stores data related to a single embed directive.
Definition Expr.h:5029
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
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:633
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition Expr.h:617
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:612
Extra information about a function prototype.
Definition TypeBase.h:5349
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:12978
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6731
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6761
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6812
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6751
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6766
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:6774
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6770
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6780
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:6746
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6788
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6736
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6733
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6740
Abstract class used to diagnose incomplete types.
Definition Sema.h:8211
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.