clang 24.0.0git
SemaExpr.cpp
Go to the documentation of this file.
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
19#include "clang/AST/ASTLambda.h"
21#include "clang/AST/Attr.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ExprObjC.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
46#include "clang/Sema/DeclSpec.h"
51#include "clang/Sema/Lookup.h"
52#include "clang/Sema/Overload.h"
54#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaARM.h"
58#include "clang/Sema/SemaCUDA.h"
60#include "clang/Sema/SemaHLSL.h"
61#include "clang/Sema/SemaObjC.h"
65#include "clang/Sema/Template.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/StringExtras.h"
68#include "llvm/IR/DerivedTypes.h"
69#include "llvm/Support/ConvertUTF.h"
70#include "llvm/Support/SaveAndRestore.h"
71#include "llvm/Support/TimeProfiler.h"
72#include "llvm/Support/TypeSize.h"
73#include <limits>
74#include <optional>
75
76using namespace clang;
77using namespace sema;
78
79bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
80 // See if this is an auto-typed variable whose initializer we are parsing.
81 if (ParsingInitForAutoVars.count(D))
82 return false;
83
84 // See if this is a deleted function.
85 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
86 if (FD->isDeleted())
87 return false;
88
89 // If the function has a deduced return type, and we can't deduce it,
90 // then we can't use it either.
91 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
92 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
93 return false;
94
95 // See if this is an aligned allocation/deallocation function that is
96 // unavailable.
97 if (TreatUnavailableAsInvalid &&
99 return false;
100 }
101
102 // See if this function is unavailable.
103 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
104 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
105 return false;
106
108 return false;
109
110 return true;
111}
112
114 // Warn if this is used but marked unused.
115 if (const auto *A = D->getAttr<UnusedAttr>()) {
116 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
117 // should diagnose them.
118 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
119 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
120 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
121 if (DC && !DC->hasAttr<UnusedAttr>())
122 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
123 }
124 }
125}
126
128 assert(Decl && Decl->isDeleted());
129
130 if (Decl->isDefaulted()) {
131 // If the method was explicitly defaulted, point at that declaration.
132 if (!Decl->isImplicit())
133 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
134
135 // Try to diagnose why this special member function was implicitly
136 // deleted. This might fail, if that reason no longer applies.
138 return;
139 }
140
141 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
142 if (Ctor && Ctor->isInheritingConstructor())
144
145 Diag(Decl->getLocation(), diag::note_availability_specified_here)
146 << Decl << 1;
147}
148
149/// Determine whether a FunctionDecl was ever declared with an
150/// explicit storage class.
152 for (auto *I : D->redecls()) {
153 if (I->getStorageClass() != SC_None)
154 return true;
155 }
156 return false;
157}
158
159/// Check whether we're in an extern inline function and referring to a
160/// variable or function with internal linkage (C11 6.7.4p3).
161///
162/// This is only a warning because we used to silently accept this code, but
163/// in many cases it will not behave correctly. This is not enabled in C++ mode
164/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
165/// and so while there may still be user mistakes, most of the time we can't
166/// prove that there are errors.
168 const NamedDecl *D,
169 SourceLocation Loc) {
170 // This is disabled under C++; there are too many ways for this to fire in
171 // contexts where the warning is a false positive, or where it is technically
172 // correct but benign.
173 //
174 // WG14 N3622 which removed the constraint entirely in C2y. It is left
175 // enabled in earlier language modes because this is a constraint in those
176 // language modes. But in C2y mode, we still want to issue the "incompatible
177 // with previous standards" diagnostic, too.
178 if (S.getLangOpts().CPlusPlus)
179 return;
180
181 // Check if this is an inlined function or method.
182 FunctionDecl *Current = S.getCurFunctionDecl();
183 if (!Current)
184 return;
185 if (!Current->isInlined())
186 return;
187 if (!Current->isExternallyVisible())
188 return;
189
190 // Check if the decl has internal linkage.
192 return;
193
194 // Downgrade from ExtWarn to Extension if
195 // (1) the supposedly external inline function is in the main file,
196 // and probably won't be included anywhere else.
197 // (2) the thing we're referencing is a pure function.
198 // (3) the thing we're referencing is another inline function.
199 // This last can give us false negatives, but it's better than warning on
200 // wrappers for simple C library functions.
201 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
202 unsigned DiagID;
203 if (S.getLangOpts().C2y)
204 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
205 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
207 DiagID = diag::ext_internal_in_extern_inline_quiet;
208 else
209 DiagID = diag::ext_internal_in_extern_inline;
210
211 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
213 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
214 << D;
215}
216
218 const FunctionDecl *First = Cur->getFirstDecl();
219
220 // Suggest "static" on the function, if possible.
222 SourceLocation DeclBegin = First->getSourceRange().getBegin();
223 Diag(DeclBegin, diag::note_convert_inline_to_static)
224 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
225 }
226}
227
229 const ObjCInterfaceDecl *UnknownObjCClass,
230 bool ObjCPropertyAccess,
231 bool AvoidPartialAvailabilityChecks,
232 ObjCInterfaceDecl *ClassReceiver,
233 bool SkipTrailingRequiresClause) {
234 SourceLocation Loc = Locs.front();
236 // If there were any diagnostics suppressed by template argument deduction,
237 // emit them now.
238 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
239 if (Pos != SuppressedDiagnostics.end()) {
240 for (const auto &[DiagLoc, PD] : Pos->second) {
241 DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID()));
242 PD.Emit(Builder);
243 }
244 // Clear out the list of suppressed diagnostics, so that we don't emit
245 // them again for this specialization. However, we don't obsolete this
246 // entry from the table, because we want to avoid ever emitting these
247 // diagnostics again.
248 Pos->second.clear();
249 }
250
251 // C++ [basic.start.main]p3:
252 // The function 'main' shall not be used within a program.
253 if (cast<FunctionDecl>(D)->isMain())
254 Diag(Loc, diag::ext_main_used);
255
257 }
258
259 // See if this is an auto-typed variable whose initializer we are parsing.
260 if (ParsingInitForAutoVars.count(D)) {
261 if (isa<BindingDecl>(D)) {
262 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
263 << D->getDeclName();
264 } else {
265 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
266 << diag::ParsingInitFor::Var << D->getDeclName()
267 << cast<VarDecl>(D)->getType();
268 }
269 return true;
270 }
271
272 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
273 // See if this is a deleted function.
274 if (FD->isDeleted()) {
275 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
276 if (Ctor && Ctor->isInheritingConstructor())
277 Diag(Loc, diag::err_deleted_inherited_ctor_use)
278 << Ctor->getParent()
279 << Ctor->getInheritedConstructor().getConstructor()->getParent();
280 else {
281 StringLiteral *Msg = FD->getDeletedMessage();
282 Diag(Loc, diag::err_deleted_function_use)
283 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
284 }
286 return true;
287 }
288
289 // [expr.prim.id]p4
290 // A program that refers explicitly or implicitly to a function with a
291 // trailing requires-clause whose constraint-expression is not satisfied,
292 // other than to declare it, is ill-formed. [...]
293 //
294 // See if this is a function with constraints that need to be satisfied.
295 // Check this before deducing the return type, as it might instantiate the
296 // definition.
297 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
298 ConstraintSatisfaction Satisfaction;
299 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
300 /*ForOverloadResolution*/ true))
301 // A diagnostic will have already been generated (non-constant
302 // constraint expression, for example)
303 return true;
304 if (!Satisfaction.IsSatisfied) {
305 Diag(Loc,
306 diag::err_reference_to_function_with_unsatisfied_constraints)
307 << D;
308 DiagnoseUnsatisfiedConstraint(Satisfaction);
309 return true;
310 }
311 }
312
313 // If the function has a deduced return type, and we can't deduce it,
314 // then we can't use it either.
315 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
316 DeduceReturnType(FD, Loc))
317 return true;
318
319 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
320 return true;
321
322 }
323
324 if (auto *Concept = dyn_cast<ConceptDecl>(D);
326 return true;
327
328 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
329 // Lambdas are only default-constructible or assignable in C++2a onwards.
330 if (MD->getParent()->isLambda() &&
332 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
333 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
334 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
336 }
337 }
338
339 auto getReferencedObjCProp = [](const NamedDecl *D) ->
340 const ObjCPropertyDecl * {
341 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
342 return MD->findPropertyDecl();
343 return nullptr;
344 };
345 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
346 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
347 return true;
348 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
349 return true;
350 }
351
352 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
353 // Only the variables omp_in and omp_out are allowed in the combiner.
354 // Only the variables omp_priv and omp_orig are allowed in the
355 // initializer-clause.
356 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
357 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
358 isa<VarDecl>(D)) {
359 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
361 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
362 return true;
363 }
364
365 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
366 // List-items in map clauses on this construct may only refer to the declared
367 // variable var and entities that could be referenced by a procedure defined
368 // at the same location.
369 // [OpenMP 5.2] Also allow iterator declared variables.
370 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
371 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
372 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
374 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
375 return true;
376 }
377
378 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
379 Diag(Loc, diag::err_use_of_empty_using_if_exists);
380 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
381 return true;
382 }
383
384 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
385 AvoidPartialAvailabilityChecks, ClassReceiver);
386
387 DiagnoseUnusedOfDecl(*this, D, Loc);
388
390
391 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
392 if (getLangOpts().getFPEvalMethod() !=
394 PP.getLastFPEvalPragmaLocation().isValid() &&
395 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
396 Diag(D->getLocation(),
397 diag::err_type_available_only_in_default_eval_method)
398 << D->getName();
399 }
400
401 if (auto *VD = dyn_cast<ValueDecl>(D))
402 checkTypeSupport(VD->getType(), Loc, VD);
403
404 if (LangOpts.SYCLIsDevice ||
405 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
406 if (!Context.getTargetInfo().isTLSSupported())
407 if (const auto *VD = dyn_cast<VarDecl>(D))
408 if (VD->getTLSKind() != VarDecl::TLS_None)
409 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
410 }
411
412 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(D))
413 SYCL().CheckDeviceUseOfDecl(D, Loc);
414
415 return false;
416}
417
419 ArrayRef<Expr *> Args) {
420 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
421 if (!Attr)
422 return;
423
424 // The number of formal parameters of the declaration.
425 unsigned NumFormalParams;
426
427 // The kind of declaration. This is also an index into a %select in
428 // the diagnostic.
429 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
430
431 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
432 NumFormalParams = MD->param_size();
433 CalleeKind = CK_Method;
434 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
435 NumFormalParams = FD->param_size();
436 CalleeKind = CK_Function;
437 if (FD->hasCXXExplicitFunctionObjectParameter())
438 NumFormalParams++;
439 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
440 QualType Ty = VD->getType();
441 const FunctionType *Fn = nullptr;
442 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
443 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
444 if (!Fn)
445 return;
446 CalleeKind = CK_Function;
447 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
448 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
449 CalleeKind = CK_Block;
450 } else {
451 return;
452 }
453
454 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
455 NumFormalParams = proto->getNumParams();
456 else
457 NumFormalParams = 0;
458 } else {
459 return;
460 }
461
462 // "NullPos" is the number of formal parameters at the end which
463 // effectively count as part of the variadic arguments. This is
464 // useful if you would prefer to not have *any* formal parameters,
465 // but the language forces you to have at least one.
466 unsigned NullPos = Attr->getNullPos();
467 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
468 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
469
470 // The number of arguments which should follow the sentinel.
471 unsigned NumArgsAfterSentinel = Attr->getSentinel();
472
473 // If there aren't enough arguments for all the formal parameters,
474 // the sentinel, and the args after the sentinel, complain.
475 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
476 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
477 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
478 return;
479 }
480
481 // Otherwise, find the sentinel expression.
482 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
483 if (!SentinelExpr)
484 return;
485 if (SentinelExpr->isValueDependent())
486 return;
487 if (Context.isSentinelNullExpr(SentinelExpr))
488 return;
489
490 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
491 // or 'NULL' if those are actually defined in the context. Only use
492 // 'nil' for ObjC methods, where it's much more likely that the
493 // variadic arguments form a list of object pointers.
494 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
495 std::string NullValue;
496 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
497 NullValue = "nil";
498 else if (getLangOpts().CPlusPlus11)
499 NullValue = "nullptr";
500 else if (PP.isMacroDefined("NULL"))
501 NullValue = "NULL";
502 else
503 NullValue = "(void*) 0";
504
505 if (MissingNilLoc.isInvalid())
506 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
507 else
508 Diag(MissingNilLoc, diag::warn_missing_sentinel)
509 << int(CalleeKind)
510 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
511 Diag(D->getLocation(), diag::note_sentinel_here)
512 << int(CalleeKind) << Attr->getRange();
513}
514
516 return E ? E->getSourceRange() : SourceRange();
517}
518
519//===----------------------------------------------------------------------===//
520// Standard Promotions and Conversions
521//===----------------------------------------------------------------------===//
522
523/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
525 // Handle any placeholder expressions which made it here.
526 if (E->hasPlaceholderType()) {
528 if (result.isInvalid()) return ExprError();
529 E = result.get();
530 }
531
532 QualType Ty = E->getType();
533 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
534
535 if (Ty->isFunctionType()) {
536 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
537 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
539 return ExprError();
540
541 E = ImpCastExprToType(E, Context.getPointerType(Ty),
542 CK_FunctionToPointerDecay).get();
543 } else if (Ty->isArrayType()) {
544 // In C90 mode, arrays only promote to pointers if the array expression is
545 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
546 // type 'array of type' is converted to an expression that has type 'pointer
547 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
548 // that has type 'array of type' ...". The relevant change is "an lvalue"
549 // (C90) to "an expression" (C99).
550 //
551 // C++ 4.2p1:
552 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
553 // T" can be converted to an rvalue of type "pointer to T".
554 //
555 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
556 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
557 CK_ArrayToPointerDecay);
558 if (Res.isInvalid())
559 return ExprError();
560 E = Res.get();
561 }
562 }
563 return E;
564}
565
567 // Check to see if we are dereferencing a null pointer. If so,
568 // and if not volatile-qualified, this is undefined behavior that the
569 // optimizer will delete, so warn about it. People sometimes try to use this
570 // to get a deterministic trap and are surprised by clang's behavior. This
571 // only handles the pattern "*null", which is a very syntactic check.
572 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
573 if (UO && UO->getOpcode() == UO_Deref &&
574 UO->getSubExpr()->getType()->isPointerType()) {
575 const LangAS AS =
576 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
577 if ((!isTargetAddressSpace(AS) ||
578 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
579 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
581 !UO->getType().isVolatileQualified()) {
582 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
583 S.PDiag(diag::warn_indirection_through_null)
584 << UO->getSubExpr()->getSourceRange());
585 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
586 S.PDiag(diag::note_indirection_through_null));
587 }
588 }
589}
590
591static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
592 SourceLocation AssignLoc,
593 const Expr* RHS) {
594 const ObjCIvarDecl *IV = OIRE->getDecl();
595 if (!IV)
596 return;
597
598 DeclarationName MemberName = IV->getDeclName();
600 if (!Member || !Member->isStr("isa"))
601 return;
602
603 const Expr *Base = OIRE->getBase();
604 QualType BaseType = Base->getType();
605 if (OIRE->isArrow())
606 BaseType = BaseType->getPointeeType();
607 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
608 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
609 ObjCInterfaceDecl *ClassDeclared = nullptr;
610 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
611 if (!ClassDeclared->getSuperClass()
612 && (*ClassDeclared->ivar_begin()) == IV) {
613 if (RHS) {
614 NamedDecl *ObjectSetClass =
616 &S.Context.Idents.get("object_setClass"),
618 if (ObjectSetClass) {
619 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
620 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
622 "object_setClass(")
624 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
625 << FixItHint::CreateInsertion(RHSLocEnd, ")");
626 }
627 else
628 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
629 } else {
630 NamedDecl *ObjectGetClass =
632 &S.Context.Idents.get("object_getClass"),
634 if (ObjectGetClass)
635 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
637 "object_getClass(")
639 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
640 else
641 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
642 }
643 S.Diag(IV->getLocation(), diag::note_ivar_decl);
644 }
645 }
646}
647
649 // Handle any placeholder expressions which made it here.
650 if (E->hasPlaceholderType()) {
652 if (result.isInvalid()) return ExprError();
653 E = result.get();
654 }
655
656 // C++ [conv.lval]p1:
657 // A glvalue of a non-function, non-array type T can be
658 // converted to a prvalue.
659 if (!E->isGLValue()) return E;
660
661 QualType T = E->getType();
662 assert(!T.isNull() && "r-value conversion on typeless expression?");
663
664 // lvalue-to-rvalue conversion cannot be applied to types that decay to
665 // pointers (i.e. function or array types).
666 if (T->canDecayToPointerType())
667 return E;
668
669 // We don't want to throw lvalue-to-rvalue casts on top of
670 // expressions of certain types in C++.
671 // In HLSL LvaluetoRvalue conversion is allowed on records.
672 if (getLangOpts().CPlusPlus) {
673 if (T == Context.OverloadTy || (T->isRecordType() && !getLangOpts().HLSL) ||
674 (T->isDependentType() && !T->isAnyPointerType() &&
675 !T->isMemberPointerType()))
676 return E;
677 }
678
679 // The C standard is actually really unclear on this point, and
680 // DR106 tells us what the result should be but not why. It's
681 // generally best to say that void types just doesn't undergo
682 // lvalue-to-rvalue at all. Note that expressions of unqualified
683 // 'void' type are never l-values, but qualified void can be.
684 if (T->isVoidType())
685 return E;
686
687 // OpenCL usually rejects direct accesses to values of 'half' type.
688 if (getLangOpts().OpenCL &&
689 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
690 T->isHalfType()) {
691 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
692 << 0 << T;
693 return ExprError();
694 }
695
697 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
698 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
699 &Context.Idents.get("object_getClass"),
701 if (ObjectGetClass)
702 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
703 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
705 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
706 else
707 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
708 }
709 else if (const ObjCIvarRefExpr *OIRE =
710 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
711 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
712
713 // C++ [conv.lval]p1:
714 // [...] If T is a non-class type, the type of the prvalue is the
715 // cv-unqualified version of T. Otherwise, the type of the
716 // rvalue is T.
717 //
718 // C99 6.3.2.1p2:
719 // If the lvalue has qualified type, the value has the unqualified
720 // version of the type of the lvalue; otherwise, the value has the
721 // type of the lvalue.
722 if (T.hasQualifiers())
723 T = T.getUnqualifiedType();
724
725 if (getLangOpts().HLSL)
726 if (const auto *MT = T->getAs<ConstantMatrixType>(); MT && MT->getLayout())
727 T = Context.getCanonicalType(T);
728
729 // Under the MS ABI, lock down the inheritance model now.
730 if (T->isMemberPointerType() &&
731 Context.getTargetInfo().getCXXABI().isMicrosoft())
732 (void)isCompleteType(E->getExprLoc(), T);
733
735 if (Res.isInvalid())
736 return Res;
737 E = Res.get();
738
739 // Loading a __weak object implicitly retains the value, so we need a cleanup to
740 // balance that.
742 Cleanup.setExprNeedsCleanups(true);
743
745 Cleanup.setExprNeedsCleanups(true);
746
748 return ExprError();
749
750 // C++ [conv.lval]p3:
751 // If T is cv std::nullptr_t, the result is a null pointer constant.
752 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
753 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
755
756 // C11 6.3.2.1p2:
757 // ... if the lvalue has atomic type, the value has the non-atomic version
758 // of the type of the lvalue ...
759 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
760 T = Atomic->getValueType().getUnqualifiedType();
761 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
762 nullptr, VK_PRValue, FPOptionsOverride());
763 }
764
765 return Res;
766}
767
770 if (Res.isInvalid())
771 return ExprError();
772 Res = DefaultLvalueConversion(Res.get());
773 if (Res.isInvalid())
774 return ExprError();
775 return Res;
776}
777
779 QualType Ty = E->getType();
780 ExprResult Res = E;
781 // Only do implicit cast for a function type, but not for a pointer
782 // to function type.
783 if (Ty->isFunctionType()) {
784 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
785 CK_FunctionToPointerDecay);
786 if (Res.isInvalid())
787 return ExprError();
788 }
789 Res = DefaultLvalueConversion(Res.get());
790 if (Res.isInvalid())
791 return ExprError();
792 return Res.get();
793}
794
795/// UsualUnaryFPConversions - Promotes floating-point types according to the
796/// current language semantics.
798 QualType Ty = E->getType();
799 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
800
801 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
802 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
803 (getLangOpts().getFPEvalMethod() !=
805 PP.getLastFPEvalPragmaLocation().isValid())) {
806 switch (EvalMethod) {
807 default:
808 llvm_unreachable("Unrecognized float evaluation method");
809 break;
811 llvm_unreachable("Float evaluation method should be set by now");
812 break;
814 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
815 // Widen the expression to double.
816 return Ty->isComplexType()
818 Context.getComplexType(Context.DoubleTy),
819 CK_FloatingComplexCast)
820 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
821 break;
823 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
824 // Widen the expression to long double.
825 return Ty->isComplexType()
827 E, Context.getComplexType(Context.LongDoubleTy),
828 CK_FloatingComplexCast)
829 : ImpCastExprToType(E, Context.LongDoubleTy,
830 CK_FloatingCast);
831 break;
832 }
833 }
834
835 // Half FP have to be promoted to float unless it is natively supported
836 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
837 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
838
839 return E;
840}
841
842/// UsualUnaryConversions - Performs various conversions that are common to most
843/// operators (C99 6.3). The conversions of array and function types are
844/// sometimes suppressed. For example, the array->pointer conversion doesn't
845/// apply if the array is an argument to the sizeof or address (&) operators.
846/// In these instances, this routine should *not* be called.
848 // First, convert to an r-value.
850 if (Res.isInvalid())
851 return ExprError();
852
853 // Promote floating-point types.
854 Res = UsualUnaryFPConversions(Res.get());
855 if (Res.isInvalid())
856 return ExprError();
857 E = Res.get();
858
859 QualType Ty = E->getType();
860 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
861
862 // Try to perform integral promotions if the object has a theoretically
863 // promotable type.
865 // C99 6.3.1.1p2:
866 //
867 // The following may be used in an expression wherever an int or
868 // unsigned int may be used:
869 // - an object or expression with an integer type whose integer
870 // conversion rank is less than or equal to the rank of int
871 // and unsigned int.
872 // - A bit-field of type _Bool, int, signed int, or unsigned int.
873 //
874 // If an int can represent all values of the original type, the
875 // value is converted to an int; otherwise, it is converted to an
876 // unsigned int. These are called the integer promotions. All
877 // other types are unchanged by the integer promotions.
878
879 QualType PTy = Context.isPromotableBitField(E);
880 if (!PTy.isNull()) {
881 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
882 return E;
883 }
884 if (Context.isPromotableIntegerType(Ty)) {
885 QualType PT = Context.getPromotedIntegerType(Ty);
886 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
887 return E;
888 }
889 }
890 return E;
891}
892
893/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
894/// do not have a prototype. Arguments that have type float or __fp16
895/// are promoted to double. All other argument types are converted by
896/// UsualUnaryConversions().
898 QualType Ty = E->getType();
899 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
900
902 if (Res.isInvalid())
903 return ExprError();
904 E = Res.get();
905
906 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
907 // promote to double.
908 // Note that default argument promotion applies only to float (and
909 // half/fp16); it does not apply to _Float16.
910 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
911 if (BTy && (BTy->getKind() == BuiltinType::Half ||
912 BTy->getKind() == BuiltinType::Float)) {
913 if (getLangOpts().OpenCL &&
914 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
915 if (BTy->getKind() == BuiltinType::Half) {
916 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
917 }
918 } else {
919 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
920 }
921 }
922 if (BTy &&
923 getLangOpts().getExtendIntArgs() ==
925 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
926 Context.getTypeSizeInChars(BTy) <
927 Context.getTypeSizeInChars(Context.LongLongTy)) {
928 E = (Ty->isUnsignedIntegerType())
929 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
930 .get()
931 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
932 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
933 "Unexpected typesize for LongLongTy");
934 }
935
936 // C++ performs lvalue-to-rvalue conversion as a default argument
937 // promotion, even on class types, but note:
938 // C++11 [conv.lval]p2:
939 // When an lvalue-to-rvalue conversion occurs in an unevaluated
940 // operand or a subexpression thereof the value contained in the
941 // referenced object is not accessed. Otherwise, if the glvalue
942 // has a class type, the conversion copy-initializes a temporary
943 // of type T from the glvalue and the result of the conversion
944 // is a prvalue for the temporary.
945 // FIXME: add some way to gate this entire thing for correctness in
946 // potentially potentially evaluated contexts.
950 E->getExprLoc(), E);
951 if (Temp.isInvalid())
952 return ExprError();
953 E = Temp.get();
954 }
955
956 // C++ [expr.call]p7, per CWG722:
957 // An argument that has (possibly cv-qualified) type std::nullptr_t is
958 // converted to void* ([conv.ptr]).
959 // (This does not apply to C23 nullptr)
961 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
962
963 return E;
964}
965
967 if (Ty->isIncompleteType()) {
968 // C++11 [expr.call]p7:
969 // After these conversions, if the argument does not have arithmetic,
970 // enumeration, pointer, pointer to member, or class type, the program
971 // is ill-formed.
972 //
973 // Since we've already performed null pointer conversion, array-to-pointer
974 // decay and function-to-pointer decay, the only such type in C++ is cv
975 // void. This also handles initializer lists as variadic arguments.
976 if (Ty->isVoidType())
977 return VarArgKind::Invalid;
978
979 if (Ty->isObjCObjectType())
980 return VarArgKind::Invalid;
981 return VarArgKind::Valid;
982 }
983
985 return VarArgKind::Invalid;
986
987 if (Context.getTargetInfo().getTriple().isWasm() &&
989 return VarArgKind::Invalid;
990 }
991
992 if (Ty.isCXX98PODType(Context))
993 return VarArgKind::Valid;
994
995 // C++11 [expr.call]p7:
996 // Passing a potentially-evaluated argument of class type (Clause 9)
997 // having a non-trivial copy constructor, a non-trivial move constructor,
998 // or a non-trivial destructor, with no corresponding parameter,
999 // is conditionally-supported with implementation-defined semantics.
1000 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
1002 if (!Record->hasNonTrivialCopyConstructor() &&
1003 !Record->hasNonTrivialMoveConstructor() &&
1004 !Record->hasNonTrivialDestructor())
1006
1007 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1008 return VarArgKind::Valid;
1009
1010 if (Ty->isObjCObjectType())
1011 return VarArgKind::Invalid;
1012
1013 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1014 return VarArgKind::Valid;
1015
1016 if (getLangOpts().MSVCCompat)
1018
1019 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1020 return VarArgKind::Valid;
1021
1022 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1023 // permitted to reject them. We should consider doing so.
1024 return VarArgKind::Undefined;
1025}
1026
1028 // Don't allow one to pass an Objective-C interface to a vararg.
1029 const QualType &Ty = E->getType();
1030 VarArgKind VAK = isValidVarArgType(Ty);
1031
1032 // Complain about passing non-POD types through varargs.
1033 switch (VAK) {
1036 E->getBeginLoc(), nullptr,
1037 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1038 [[fallthrough]];
1039 case VarArgKind::Valid:
1040 if (Ty->isRecordType()) {
1041 // This is unlikely to be what the user intended. If the class has a
1042 // 'c_str' member function, the user probably meant to call that.
1043 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1044 PDiag(diag::warn_pass_class_arg_to_vararg)
1045 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1046 }
1047 break;
1048
1051 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1052 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1053 << getLangOpts().CPlusPlus11 << Ty << CT);
1054 break;
1055
1058 Diag(E->getBeginLoc(),
1059 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1060 << Ty << CT;
1061 else if (Ty->isObjCObjectType())
1062 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1063 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1064 << Ty << CT);
1065 else
1066 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1067 << isa<InitListExpr>(E) << Ty << CT;
1068 break;
1069 }
1070}
1071
1073 FunctionDecl *FDecl) {
1074 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1075 // Strip the unbridged-cast placeholder expression off, if applicable.
1076 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1077 (CT == VariadicCallType::Method ||
1078 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1079 E = ObjC().stripARCUnbridgedCast(E);
1080
1081 // Otherwise, do normal placeholder checking.
1082 } else {
1083 ExprResult ExprRes = CheckPlaceholderExpr(E);
1084 if (ExprRes.isInvalid())
1085 return ExprError();
1086 E = ExprRes.get();
1087 }
1088 }
1089
1091 if (ExprRes.isInvalid())
1092 return ExprError();
1093
1094 // Copy blocks to the heap.
1095 if (ExprRes.get()->getType()->isBlockPointerType())
1096 maybeExtendBlockObject(ExprRes);
1097
1098 E = ExprRes.get();
1099
1100 // Diagnostics regarding non-POD argument types are
1101 // emitted along with format string checking in Sema::CheckFunctionCall().
1103 // Turn this into a trap.
1104 CXXScopeSpec SS;
1105 SourceLocation TemplateKWLoc;
1106 UnqualifiedId Name;
1107 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1108 E->getBeginLoc());
1109 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1110 /*HasTrailingLParen=*/true,
1111 /*IsAddressOfOperand=*/false);
1112 if (TrapFn.isInvalid())
1113 return ExprError();
1114
1115 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1116 E->getEndLoc());
1117 if (Call.isInvalid())
1118 return ExprError();
1119
1120 ExprResult Comma =
1121 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1122 if (Comma.isInvalid())
1123 return ExprError();
1124 return Comma.get();
1125 }
1126
1127 if (!getLangOpts().CPlusPlus &&
1129 diag::err_call_incomplete_argument))
1130 return ExprError();
1131
1132 return E;
1133}
1134
1135/// Convert complex integers to complex floats and real integers to
1136/// real floats as required for complex arithmetic. Helper function of
1137/// UsualArithmeticConversions()
1138///
1139/// \return false if the integer expression is an integer type and is
1140/// successfully converted to the (complex) float type.
1142 ExprResult &ComplexExpr,
1143 QualType IntTy,
1144 QualType ComplexTy,
1145 bool SkipCast) {
1146 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1147 if (SkipCast) return false;
1148 if (IntTy->isIntegerType()) {
1149 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1150 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1151 } else {
1152 assert(IntTy->isComplexIntegerType());
1153 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1154 CK_IntegralComplexToFloatingComplex);
1155 }
1156 return false;
1157}
1158
1159// This handles complex/complex, complex/float, or float/complex.
1160// When both operands are complex, the shorter operand is converted to the
1161// type of the longer, and that is the type of the result. This corresponds
1162// to what is done when combining two real floating-point operands.
1163// The fun begins when size promotion occur across type domains.
1164// From H&S 6.3.4: When one operand is complex and the other is a real
1165// floating-point type, the less precise type is converted, within it's
1166// real or complex domain, to the precision of the other type. For example,
1167// when combining a "long double" with a "double _Complex", the
1168// "double _Complex" is promoted to "long double _Complex".
1170 QualType ShorterType,
1171 QualType LongerType,
1172 bool PromotePrecision) {
1173 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1175 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1176
1177 if (PromotePrecision) {
1178 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1179 Shorter =
1180 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1181 } else {
1182 if (LongerIsComplex)
1183 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1184 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1185 }
1186 }
1187 return Result;
1188}
1189
1190/// Handle arithmetic conversion with complex types. Helper function of
1191/// UsualArithmeticConversions()
1193 ExprResult &RHS, QualType LHSType,
1194 QualType RHSType, bool IsCompAssign) {
1195 // Handle (complex) integer types.
1196 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1197 /*SkipCast=*/false))
1198 return LHSType;
1199 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1200 /*SkipCast=*/IsCompAssign))
1201 return RHSType;
1202
1203 // Compute the rank of the two types, regardless of whether they are complex.
1204 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1205 if (Order < 0)
1206 // Promote the precision of the LHS if not an assignment.
1207 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1208 /*PromotePrecision=*/!IsCompAssign);
1209 // Promote the precision of the RHS unless it is already the same as the LHS.
1210 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1211 /*PromotePrecision=*/Order > 0);
1212}
1213
1214/// Handle arithmetic conversion from integer to float. Helper function
1215/// of UsualArithmeticConversions()
1217 ExprResult &IntExpr,
1218 QualType FloatTy, QualType IntTy,
1219 bool ConvertFloat, bool ConvertInt) {
1220 if (IntTy->isIntegerType()) {
1221 if (ConvertInt)
1222 // Convert intExpr to the lhs floating point type.
1223 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1224 CK_IntegralToFloating);
1225 return FloatTy;
1226 }
1227
1228 // Convert both sides to the appropriate complex float.
1229 assert(IntTy->isComplexIntegerType());
1230 QualType result = S.Context.getComplexType(FloatTy);
1231
1232 // _Complex int -> _Complex float
1233 if (ConvertInt)
1234 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1235 CK_IntegralComplexToFloatingComplex);
1236
1237 // float -> _Complex float
1238 if (ConvertFloat)
1239 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1240 CK_FloatingRealToComplex);
1241
1242 return result;
1243}
1244
1245/// Handle arithmethic conversion with floating point types. Helper
1246/// function of UsualArithmeticConversions()
1248 ExprResult &RHS, QualType LHSType,
1249 QualType RHSType, bool IsCompAssign) {
1250 bool LHSFloat = LHSType->isRealFloatingType();
1251 bool RHSFloat = RHSType->isRealFloatingType();
1252
1253 // N1169 4.1.4: If one of the operands has a floating type and the other
1254 // operand has a fixed-point type, the fixed-point operand
1255 // is converted to the floating type [...]
1256 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1257 if (LHSFloat)
1258 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1259 else if (!IsCompAssign)
1260 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1261 return LHSFloat ? LHSType : RHSType;
1262 }
1263
1264 // If we have two real floating types, convert the smaller operand
1265 // to the bigger result.
1266 if (LHSFloat && RHSFloat) {
1267 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1268 if (order > 0) {
1269 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1270 return LHSType;
1271 }
1272
1273 assert(order < 0 && "illegal float comparison");
1274 if (!IsCompAssign)
1275 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1276 return RHSType;
1277 }
1278
1279 if (LHSFloat) {
1280 // Half FP has to be promoted to float unless it is natively supported
1281 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1282 LHSType = S.Context.FloatTy;
1283
1284 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1285 /*ConvertFloat=*/!IsCompAssign,
1286 /*ConvertInt=*/ true);
1287 }
1288 assert(RHSFloat);
1289 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1290 /*ConvertFloat=*/ true,
1291 /*ConvertInt=*/!IsCompAssign);
1292}
1293
1294/// Diagnose attempts to convert between __float128, __ibm128 and
1295/// long double if there is no support for such conversion.
1296/// Helper function of UsualArithmeticConversions().
1297static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1298 QualType RHSType) {
1299 // No issue if either is not a floating point type.
1300 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1301 return false;
1302
1303 // No issue if both have the same 128-bit float semantics.
1304 auto *LHSComplex = LHSType->getAs<ComplexType>();
1305 auto *RHSComplex = RHSType->getAs<ComplexType>();
1306
1307 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1308 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1309
1310 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1311 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1312
1313 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1314 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1315 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1316 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1317 return false;
1318
1319 return true;
1320}
1321
1322typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1323
1324namespace {
1325/// These helper callbacks are placed in an anonymous namespace to
1326/// permit their use as function template parameters.
1327ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1328 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1329}
1330
1331ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1332 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1333 CK_IntegralComplexCast);
1334}
1335}
1336
1337/// Handle integer arithmetic conversions. Helper function of
1338/// UsualArithmeticConversions()
1339template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1341 ExprResult &RHS, QualType LHSType,
1342 QualType RHSType, bool IsCompAssign) {
1343 // The rules for this case are in C99 6.3.1.8
1344 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1345 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1346 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1347 if (LHSSigned == RHSSigned) {
1348 // Same signedness; use the higher-ranked type
1349 if (order >= 0) {
1350 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1351 return LHSType;
1352 } else if (!IsCompAssign)
1353 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1354 return RHSType;
1355 } else if (order != (LHSSigned ? 1 : -1)) {
1356 // The unsigned type has greater than or equal rank to the
1357 // signed type, so use the unsigned type
1358 if (RHSSigned) {
1359 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1360 return LHSType;
1361 } else if (!IsCompAssign)
1362 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1363 return RHSType;
1364 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1365 // The two types are different widths; if we are here, that
1366 // means the signed type is larger than the unsigned type, so
1367 // use the signed type.
1368 if (LHSSigned) {
1369 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1370 return LHSType;
1371 } else if (!IsCompAssign)
1372 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1373 return RHSType;
1374 } else {
1375 // The signed type is higher-ranked than the unsigned type,
1376 // but isn't actually any bigger (like unsigned int and long
1377 // on most 32-bit systems). Use the unsigned type corresponding
1378 // to the signed type.
1379 QualType result =
1380 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1381 RHS = (*doRHSCast)(S, RHS.get(), result);
1382 if (!IsCompAssign)
1383 LHS = (*doLHSCast)(S, LHS.get(), result);
1384 return result;
1385 }
1386}
1387
1388/// Handle conversions with GCC complex int extension. Helper function
1389/// of UsualArithmeticConversions()
1391 ExprResult &RHS, QualType LHSType,
1392 QualType RHSType,
1393 bool IsCompAssign) {
1394 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1395 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1396
1397 if (LHSComplexInt && RHSComplexInt) {
1398 QualType LHSEltType = LHSComplexInt->getElementType();
1399 QualType RHSEltType = RHSComplexInt->getElementType();
1400 QualType ScalarType =
1402 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1403
1404 return S.Context.getComplexType(ScalarType);
1405 }
1406
1407 if (LHSComplexInt) {
1408 QualType LHSEltType = LHSComplexInt->getElementType();
1409 QualType ScalarType =
1411 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1413 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1414 CK_IntegralRealToComplex);
1415
1416 return ComplexType;
1417 }
1418
1419 assert(RHSComplexInt);
1420
1421 QualType RHSEltType = RHSComplexInt->getElementType();
1422 QualType ScalarType =
1424 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1426
1427 if (!IsCompAssign)
1428 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1429 CK_IntegralRealToComplex);
1430 return ComplexType;
1431}
1432
1434 ExprResult &RHS,
1435 QualType LHSType,
1436 QualType RHSType,
1437 bool IsCompAssign) {
1438
1439 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1440 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1441
1442 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1443 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1444
1445 bool LHSHasTrap =
1446 LhsOBT && LhsOBT->getBehaviorKind() ==
1447 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1448 bool RHSHasTrap =
1449 RhsOBT && RhsOBT->getBehaviorKind() ==
1450 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1451 bool LHSHasWrap =
1452 LhsOBT && LhsOBT->getBehaviorKind() ==
1453 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1454 bool RHSHasWrap =
1455 RhsOBT && RhsOBT->getBehaviorKind() ==
1456 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1457
1458 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1459 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1460
1461 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1462 if (LHSHasTrap || RHSHasTrap)
1463 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1464 else if (LHSHasWrap || RHSHasWrap)
1465 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1466
1467 QualType LHSConvType = LHSUnderlyingType;
1468 QualType RHSConvType = RHSUnderlyingType;
1469 if (DominantBehavior) {
1470 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1471 LHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1472 LHSUnderlyingType);
1473 else
1474 LHSConvType = LHSType;
1475
1476 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1477 RHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1478 RHSUnderlyingType);
1479 else
1480 RHSConvType = RHSType;
1481 }
1482
1484 S, LHS, RHS, LHSConvType, RHSConvType, IsCompAssign);
1485}
1486
1487/// Return the rank of a given fixed point or integer type. The value itself
1488/// doesn't matter, but the values must be increasing with proper increasing
1489/// rank as described in N1169 4.1.1.
1490static unsigned GetFixedPointRank(QualType Ty) {
1491 const auto *BTy = Ty->getAs<BuiltinType>();
1492 assert(BTy && "Expected a builtin type.");
1493
1494 switch (BTy->getKind()) {
1495 case BuiltinType::ShortFract:
1496 case BuiltinType::UShortFract:
1497 case BuiltinType::SatShortFract:
1498 case BuiltinType::SatUShortFract:
1499 return 1;
1500 case BuiltinType::Fract:
1501 case BuiltinType::UFract:
1502 case BuiltinType::SatFract:
1503 case BuiltinType::SatUFract:
1504 return 2;
1505 case BuiltinType::LongFract:
1506 case BuiltinType::ULongFract:
1507 case BuiltinType::SatLongFract:
1508 case BuiltinType::SatULongFract:
1509 return 3;
1510 case BuiltinType::ShortAccum:
1511 case BuiltinType::UShortAccum:
1512 case BuiltinType::SatShortAccum:
1513 case BuiltinType::SatUShortAccum:
1514 return 4;
1515 case BuiltinType::Accum:
1516 case BuiltinType::UAccum:
1517 case BuiltinType::SatAccum:
1518 case BuiltinType::SatUAccum:
1519 return 5;
1520 case BuiltinType::LongAccum:
1521 case BuiltinType::ULongAccum:
1522 case BuiltinType::SatLongAccum:
1523 case BuiltinType::SatULongAccum:
1524 return 6;
1525 default:
1526 if (BTy->isInteger())
1527 return 0;
1528 llvm_unreachable("Unexpected fixed point or integer type");
1529 }
1530}
1531
1532/// handleFixedPointConversion - Fixed point operations between fixed
1533/// point types and integers or other fixed point types do not fall under
1534/// usual arithmetic conversion since these conversions could result in loss
1535/// of precsision (N1169 4.1.4). These operations should be calculated with
1536/// the full precision of their result type (N1169 4.1.6.2.1).
1538 QualType RHSTy) {
1539 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1540 "Expected at least one of the operands to be a fixed point type");
1541 assert((LHSTy->isFixedPointOrIntegerType() ||
1542 RHSTy->isFixedPointOrIntegerType()) &&
1543 "Special fixed point arithmetic operation conversions are only "
1544 "applied to ints or other fixed point types");
1545
1546 // If one operand has signed fixed-point type and the other operand has
1547 // unsigned fixed-point type, then the unsigned fixed-point operand is
1548 // converted to its corresponding signed fixed-point type and the resulting
1549 // type is the type of the converted operand.
1550 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1552 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1554
1555 // The result type is the type with the highest rank, whereby a fixed-point
1556 // conversion rank is always greater than an integer conversion rank; if the
1557 // type of either of the operands is a saturating fixedpoint type, the result
1558 // type shall be the saturating fixed-point type corresponding to the type
1559 // with the highest rank; the resulting value is converted (taking into
1560 // account rounding and overflow) to the precision of the resulting type.
1561 // Same ranks between signed and unsigned types are resolved earlier, so both
1562 // types are either signed or both unsigned at this point.
1563 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1564 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1565
1566 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1567
1569 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1570
1571 return ResultTy;
1572}
1573
1574/// Check that the usual arithmetic conversions can be performed on this pair of
1575/// expressions that might be of enumeration type.
1577 SourceLocation Loc,
1578 ArithConvKind ACK) {
1579 // C++2a [expr.arith.conv]p1:
1580 // If one operand is of enumeration type and the other operand is of a
1581 // different enumeration type or a floating-point type, this behavior is
1582 // deprecated ([depr.arith.conv.enum]).
1583 //
1584 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1585 // Eventually we will presumably reject these cases (in C++23 onwards?).
1587 R = RHS->getEnumCoercedType(Context);
1588 bool LEnum = L->isUnscopedEnumerationType(),
1589 REnum = R->isUnscopedEnumerationType();
1590 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1591 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1592 (REnum && L->isFloatingType())) {
1593 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1595 ? diag::warn_arith_conv_enum_float_cxx20
1596 : diag::warn_arith_conv_enum_float)
1597 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1598 << L << R;
1599 } else if (!IsCompAssign && LEnum && REnum &&
1600 !Context.hasSameUnqualifiedType(L, R)) {
1601 unsigned DiagID;
1602 // In C++ 26, usual arithmetic conversions between 2 different enum types
1603 // are ill-formed.
1605 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1606 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1607 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1608 // If either enumeration type is unnamed, it's less likely that the
1609 // user cares about this, but this situation is still deprecated in
1610 // C++2a. Use a different warning group.
1611 DiagID = getLangOpts().CPlusPlus20
1612 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1613 : diag::warn_arith_conv_mixed_anon_enum_types;
1614 } else if (ACK == ArithConvKind::Conditional) {
1615 // Conditional expressions are separated out because they have
1616 // historically had a different warning flag.
1617 DiagID = getLangOpts().CPlusPlus20
1618 ? diag::warn_conditional_mixed_enum_types_cxx20
1619 : diag::warn_conditional_mixed_enum_types;
1620 } else if (ACK == ArithConvKind::Comparison) {
1621 // Comparison expressions are separated out because they have
1622 // historically had a different warning flag.
1623 DiagID = getLangOpts().CPlusPlus20
1624 ? diag::warn_comparison_mixed_enum_types_cxx20
1625 : diag::warn_comparison_mixed_enum_types;
1626 } else {
1627 DiagID = getLangOpts().CPlusPlus20
1628 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1629 : diag::warn_arith_conv_mixed_enum_types;
1630 }
1631 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1632 << (int)ACK << L << R;
1633 }
1634}
1635
1637 Expr *RHS, SourceLocation Loc,
1638 ArithConvKind ACK) {
1639 QualType LHSType = LHS->getType().getUnqualifiedType();
1640 QualType RHSType = RHS->getType().getUnqualifiedType();
1641
1642 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1643 !RHSType->isUnicodeCharacterType())
1644 return;
1645
1646 if (ACK == ArithConvKind::Comparison) {
1647 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1648 return;
1649
1650 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1651 if (T->isChar8Type())
1652 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1653 if (T->isChar16Type())
1654 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1655 assert(T->isChar32Type());
1656 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1657 };
1658
1659 Expr::EvalResult LHSRes, RHSRes;
1660 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1662 SemaRef.isConstantEvaluatedContext());
1663 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1665 SemaRef.isConstantEvaluatedContext());
1666
1667 // Don't warn if the one known value is a representable
1668 // in the type of both expressions.
1669 if (LHSSuccess != RHSuccess) {
1670 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1671 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1672 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1673 return;
1674 }
1675
1676 if (!LHSSuccess || !RHSuccess) {
1677 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1678 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1679 << RHSType;
1680 return;
1681 }
1682
1683 llvm::APSInt LHSValue(32);
1684 LHSValue = LHSRes.Val.getInt();
1685 llvm::APSInt RHSValue(32);
1686 RHSValue = RHSRes.Val.getInt();
1687
1688 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1689 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1690 if (LHSSafe && RHSSafe)
1691 return;
1692
1693 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1694 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1695 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1696 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1697 return;
1698 }
1699
1700 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1701 return;
1702
1703 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1704 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1705 << RHSType;
1706}
1707
1708/// UsualArithmeticConversions - Performs various conversions that are common to
1709/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1710/// routine returns the first non-arithmetic type found. The client is
1711/// responsible for emitting appropriate error diagnostics.
1713 SourceLocation Loc,
1714 ArithConvKind ACK) {
1715
1716 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1717
1718 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1719
1720 if (ACK != ArithConvKind::CompAssign) {
1721 LHS = UsualUnaryConversions(LHS.get());
1722 if (LHS.isInvalid())
1723 return QualType();
1724 }
1725
1726 RHS = UsualUnaryConversions(RHS.get());
1727 if (RHS.isInvalid())
1728 return QualType();
1729
1730 // For conversion purposes, we ignore any qualifiers.
1731 // For example, "const float" and "float" are equivalent.
1732 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1733 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1734
1735 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1736 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1737 LHSType = AtomicLHS->getValueType();
1738
1739 // If both types are identical, no conversion is needed.
1740 if (Context.hasSameType(LHSType, RHSType))
1741 return Context.getCommonSugaredType(LHSType, RHSType);
1742
1743 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1744 // The caller can deal with this (e.g. pointer + int).
1745 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1746 return QualType();
1747
1748 // Apply unary and bitfield promotions to the LHS's type.
1749 QualType LHSUnpromotedType = LHSType;
1750 if (Context.isPromotableIntegerType(LHSType))
1751 LHSType = Context.getPromotedIntegerType(LHSType);
1752 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1753 if (!LHSBitfieldPromoteTy.isNull())
1754 LHSType = LHSBitfieldPromoteTy;
1755 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1756 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1757
1758 // If both types are identical, no conversion is needed.
1759 if (Context.hasSameType(LHSType, RHSType))
1760 return Context.getCommonSugaredType(LHSType, RHSType);
1761
1762 // At this point, we have two different arithmetic types.
1763
1764 if ((LHSType->isFixedPointType() && RHSType->isBitIntType()) ||
1765 (LHSType->isBitIntType() && RHSType->isFixedPointType()))
1766 return QualType();
1767
1768 // Diagnose attempts to convert between __ibm128, __float128 and long double
1769 // where such conversions currently can't be handled.
1770 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1771 return QualType();
1772
1773 // Handle complex types first (C99 6.3.1.8p1).
1774 if (LHSType->isComplexType() || RHSType->isComplexType())
1775 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1777
1778 // Now handle "real" floating types (i.e. float, double, long double).
1779 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1780 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1782
1783 // Handle GCC complex int extension.
1784 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1785 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1787
1788 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1789 return handleFixedPointConversion(*this, LHSType, RHSType);
1790
1791 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1793 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1794
1795 // Finally, we have two differing integer types.
1797 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1798}
1799
1800//===----------------------------------------------------------------------===//
1801// Semantic Analysis for various Expression Types
1802//===----------------------------------------------------------------------===//
1803
1804
1806 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1807 bool PredicateIsExpr, void *ControllingExprOrType,
1808 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1809 unsigned NumAssocs = ArgTypes.size();
1810 assert(NumAssocs == ArgExprs.size());
1811
1812 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1813 for (unsigned i = 0; i < NumAssocs; ++i) {
1814 if (ArgTypes[i])
1815 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1816 else
1817 Types[i] = nullptr;
1818 }
1819
1820 // If we have a controlling type, we need to convert it from a parsed type
1821 // into a semantic type and then pass that along.
1822 if (!PredicateIsExpr) {
1823 TypeSourceInfo *ControllingType;
1824 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1825 &ControllingType);
1826 assert(ControllingType && "couldn't get the type out of the parser");
1827 ControllingExprOrType = ControllingType;
1828 }
1829
1831 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1832 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1833 delete [] Types;
1834 return ER;
1835}
1836
1837// Helper function to determine type compatibility for C _Generic expressions.
1838// Multiple compatible types within the same _Generic expression is ambiguous
1839// and not valid.
1841 QualType U) {
1842 // Try to handle special types like OverflowBehaviorTypes
1843 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1844 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1845
1846 if (TOBT || UOBT) {
1847 if (TOBT && UOBT) {
1848 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1849 return Ctx.typesAreCompatible(TOBT->getUnderlyingType(),
1850 UOBT->getUnderlyingType());
1851 return false;
1852 }
1853 return false;
1854 }
1855
1856 // We're dealing with types that don't require special handling.
1857 return Ctx.typesAreCompatible(T, U);
1858}
1859
1861 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1862 bool PredicateIsExpr, void *ControllingExprOrType,
1864 unsigned NumAssocs = Types.size();
1865 assert(NumAssocs == Exprs.size());
1866 assert(ControllingExprOrType &&
1867 "Must have either a controlling expression or a controlling type");
1868
1869 Expr *ControllingExpr = nullptr;
1870 TypeSourceInfo *ControllingType = nullptr;
1871 if (PredicateIsExpr) {
1872 // Decay and strip qualifiers for the controlling expression type, and
1873 // handle placeholder type replacement. See committee discussion from WG14
1874 // DR423.
1878 reinterpret_cast<Expr *>(ControllingExprOrType));
1879 if (R.isInvalid())
1880 return ExprError();
1881 ControllingExpr = R.get();
1882 } else {
1883 // The extension form uses the type directly rather than converting it.
1884 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1885 if (!ControllingType)
1886 return ExprError();
1887 }
1888
1889 bool TypeErrorFound = false,
1890 IsResultDependent = ControllingExpr
1891 ? ControllingExpr->isTypeDependent()
1892 : ControllingType->getType()->isDependentType(),
1893 ContainsUnexpandedParameterPack =
1894 ControllingExpr
1895 ? ControllingExpr->containsUnexpandedParameterPack()
1896 : ControllingType->getType()->containsUnexpandedParameterPack();
1897
1898 // The controlling expression is an unevaluated operand, so side effects are
1899 // likely unintended.
1900 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1901 ControllingExpr->HasSideEffects(Context, false))
1902 Diag(ControllingExpr->getExprLoc(),
1903 diag::warn_side_effects_unevaluated_context);
1904
1905 for (unsigned i = 0; i < NumAssocs; ++i) {
1906 if (Exprs[i]->containsUnexpandedParameterPack())
1907 ContainsUnexpandedParameterPack = true;
1908
1909 if (Types[i]) {
1910 if (Types[i]->getType()->containsUnexpandedParameterPack())
1911 ContainsUnexpandedParameterPack = true;
1912
1913 if (Types[i]->getType()->isDependentType()) {
1914 IsResultDependent = true;
1915 } else {
1916 // We relax the restriction on use of incomplete types and non-object
1917 // types with the type-based extension of _Generic. Allowing incomplete
1918 // objects means those can be used as "tags" for a type-safe way to map
1919 // to a value. Similarly, matching on function types rather than
1920 // function pointer types can be useful. However, the restriction on VM
1921 // types makes sense to retain as there are open questions about how
1922 // the selection can be made at compile time.
1923 //
1924 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1925 // complete object type other than a variably modified type."
1926 // C2y removed the requirement that an expression form must
1927 // use a complete type, though it's still as-if the type has undergone
1928 // lvalue conversion. We support this as an extension in C23 and
1929 // earlier because GCC does so.
1930 unsigned D = 0;
1931 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1932 D = LangOpts.C2y ? diag::compat_c2y_assoc_type_incomplete
1933 : diag::compat_pre_c2y_assoc_type_incomplete;
1934 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1935 D = diag::err_assoc_type_nonobject;
1936 else if (Types[i]->getType()->isVariablyModifiedType())
1937 D = diag::err_assoc_type_variably_modified;
1938 else if (ControllingExpr) {
1939 // Because the controlling expression undergoes lvalue conversion,
1940 // array conversion, and function conversion, an association which is
1941 // of array type, function type, or is qualified can never be
1942 // reached. We will warn about this so users are less surprised by
1943 // the unreachable association. However, we don't have to handle
1944 // function types; that's not an object type, so it's handled above.
1945 //
1946 // The logic is somewhat different for C++ because C++ has different
1947 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1948 // If T is a non-class type, the type of the prvalue is the cv-
1949 // unqualified version of T. Otherwise, the type of the prvalue is T.
1950 // The result of these rules is that all qualified types in an
1951 // association in C are unreachable, and in C++, only qualified non-
1952 // class types are unreachable.
1953 //
1954 // NB: this does not apply when the first operand is a type rather
1955 // than an expression, because the type form does not undergo
1956 // conversion.
1957 unsigned Reason = 0;
1958 QualType QT = Types[i]->getType();
1959 if (QT->isArrayType())
1960 Reason = 1;
1961 else if (QT.hasQualifiers() &&
1962 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1963 Reason = 2;
1964
1965 if (Reason)
1966 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1967 diag::warn_unreachable_association)
1968 << QT << (Reason - 1);
1969 }
1970
1971 if (D != 0) {
1972 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1973 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1974 if (getDiagnostics().getDiagnosticLevel(
1975 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1977 TypeErrorFound = true;
1978 }
1979
1980 // C11 6.5.1.1p2 "No two generic associations in the same generic
1981 // selection shall specify compatible types."
1982 for (unsigned j = i+1; j < NumAssocs; ++j)
1983 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1985 Types[j]->getType())) {
1986 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1987 diag::err_assoc_compatible_types)
1988 << Types[j]->getTypeLoc().getSourceRange()
1989 << Types[j]->getType()
1990 << Types[i]->getType();
1991 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1992 diag::note_compat_assoc)
1993 << Types[i]->getTypeLoc().getSourceRange()
1994 << Types[i]->getType();
1995 TypeErrorFound = true;
1996 }
1997 }
1998 }
1999 }
2000 if (TypeErrorFound)
2001 return ExprError();
2002
2003 // If we determined that the generic selection is result-dependent, don't
2004 // try to compute the result expression.
2005 if (IsResultDependent) {
2006 if (ControllingExpr)
2007 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
2008 Types, Exprs, DefaultLoc, RParenLoc,
2009 ContainsUnexpandedParameterPack);
2010 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
2011 Exprs, DefaultLoc, RParenLoc,
2012 ContainsUnexpandedParameterPack);
2013 }
2014
2015 SmallVector<unsigned, 1> CompatIndices;
2016 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2017 // Look at the canonical type of the controlling expression in case it was a
2018 // deduced type like __auto_type. However, when issuing diagnostics, use the
2019 // type the user wrote in source rather than the canonical one.
2020 for (unsigned i = 0; i < NumAssocs; ++i) {
2021 if (!Types[i])
2022 DefaultIndex = i;
2023 else {
2024 bool Compatible;
2025 QualType ControllingQT =
2026 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2027 : ControllingType->getType().getCanonicalType();
2028 QualType AssocQT = Types[i]->getType();
2029
2030 Compatible =
2031 areTypesCompatibleForGeneric(Context, ControllingQT, AssocQT);
2032
2033 if (Compatible)
2034 CompatIndices.push_back(i);
2035 }
2036 }
2037
2038 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2039 TypeSourceInfo *ControllingType) {
2040 // We strip parens here because the controlling expression is typically
2041 // parenthesized in macro definitions.
2042 if (ControllingExpr)
2043 ControllingExpr = ControllingExpr->IgnoreParens();
2044
2045 SourceRange SR = ControllingExpr
2046 ? ControllingExpr->getSourceRange()
2047 : ControllingType->getTypeLoc().getSourceRange();
2048 QualType QT = ControllingExpr ? ControllingExpr->getType()
2049 : ControllingType->getType();
2050
2051 return std::make_pair(SR, QT);
2052 };
2053
2054 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2055 // type compatible with at most one of the types named in its generic
2056 // association list."
2057 if (CompatIndices.size() > 1) {
2058 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2059 SourceRange SR = P.first;
2060 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
2061 << SR << P.second << (unsigned)CompatIndices.size();
2062 for (unsigned I : CompatIndices) {
2063 Diag(Types[I]->getTypeLoc().getBeginLoc(),
2064 diag::note_compat_assoc)
2065 << Types[I]->getTypeLoc().getSourceRange()
2066 << Types[I]->getType();
2067 }
2068 return ExprError();
2069 }
2070
2071 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2072 // its controlling expression shall have type compatible with exactly one of
2073 // the types named in its generic association list."
2074 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2075 CompatIndices.size() == 0) {
2076 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2077 SourceRange SR = P.first;
2078 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
2079 return ExprError();
2080 }
2081
2082 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2083 // type name that is compatible with the type of the controlling expression,
2084 // then the result expression of the generic selection is the expression
2085 // in that generic association. Otherwise, the result expression of the
2086 // generic selection is the expression in the default generic association."
2087 unsigned ResultIndex =
2088 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2089
2090 if (ControllingExpr) {
2092 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
2093 ContainsUnexpandedParameterPack, ResultIndex);
2094 }
2096 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
2097 ContainsUnexpandedParameterPack, ResultIndex);
2098}
2099
2101 switch (Kind) {
2102 default:
2103 llvm_unreachable("unexpected TokenKind");
2104 case tok::kw___func__:
2105 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2106 case tok::kw___FUNCTION__:
2108 case tok::kw___FUNCDNAME__:
2109 return PredefinedIdentKind::FuncDName; // [MS]
2110 case tok::kw___FUNCSIG__:
2111 return PredefinedIdentKind::FuncSig; // [MS]
2112 case tok::kw_L__FUNCTION__:
2113 return PredefinedIdentKind::LFunction; // [MS]
2114 case tok::kw_L__FUNCSIG__:
2115 return PredefinedIdentKind::LFuncSig; // [MS]
2116 case tok::kw___PRETTY_FUNCTION__:
2118 }
2119}
2120
2121/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2122/// to determine the value of a PredefinedExpr. This can be either a
2123/// block, lambda, captured statement, function, otherwise a nullptr.
2125 auto LSI = S.FunctionScopes.rbegin();
2126
2127 auto tryAdjustLambdaContext = [&S, &LSI](DeclContext *&DC) {
2128 if (isLambdaCallOperator(DC)) {
2129 auto E = S.FunctionScopes.rend();
2130 while (LSI != E && !isa<LambdaScopeInfo>(*LSI))
2131 ++LSI;
2132 assert(LSI != E && "Should be in a lambda scope info");
2133 if (dyn_cast<LambdaScopeInfo>(*LSI)->BeforeCompoundStatement)
2134 DC = DC->getParent();
2135 ++LSI;
2136 }
2137 };
2138
2139 tryAdjustLambdaContext(DC);
2140 while (DC &&
2142 DC = DC->getParent();
2143 tryAdjustLambdaContext(DC);
2144 }
2145
2146 return cast_or_null<Decl>(DC);
2147}
2148
2149/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2150/// location of the token and the offset of the ud-suffix within it.
2152 unsigned Offset) {
2153 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2154 S.getLangOpts());
2155}
2156
2157/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2158/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2160 IdentifierInfo *UDSuffix,
2161 SourceLocation UDSuffixLoc,
2162 ArrayRef<Expr*> Args,
2163 SourceLocation LitEndLoc) {
2164 assert(Args.size() <= 2 && "too many arguments for literal operator");
2165
2166 QualType ArgTy[2];
2167 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2168 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2169 if (ArgTy[ArgIdx]->isArrayType())
2170 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2171 }
2172
2173 DeclarationName OpName =
2175 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2176 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2177
2178 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2179 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2180 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2181 /*AllowStringTemplatePack*/ false,
2182 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2183 return ExprError();
2184
2185 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2186}
2187
2189 // StringToks needs backing storage as it doesn't hold array elements itself
2190 std::vector<Token> ExpandedToks;
2191 if (getLangOpts().MicrosoftExt)
2192 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2193
2194 StringLiteralParser Literal(StringToks, PP,
2196 if (Literal.hadError)
2197 return ExprError();
2198
2199 SmallVector<SourceLocation, 4> StringTokLocs;
2200 for (const Token &Tok : StringToks)
2201 StringTokLocs.push_back(Tok.getLocation());
2202
2203 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2205 false, {}, StringTokLocs);
2206
2207 if (!Literal.getUDSuffix().empty()) {
2208 SourceLocation UDSuffixLoc =
2209 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2210 Literal.getUDSuffixOffset());
2211 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2212 }
2213
2214 return Lit;
2215}
2216
2217std::vector<Token>
2219 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2220 // local macros that expand to string literals that may be concatenated.
2221 // These macros are expanded here (in Sema), because StringLiteralParser
2222 // (in Lex) doesn't know the enclosing function (because it hasn't been
2223 // parsed yet).
2224 assert(getLangOpts().MicrosoftExt);
2225
2226 // Note: Although function local macros are defined only inside functions,
2227 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2228 // expansion of macros into empty string literals without additional checks.
2229 Decl *CurrentDecl = getPredefinedExprDecl(*this, CurContext);
2230 if (!CurrentDecl)
2231 CurrentDecl = Context.getTranslationUnitDecl();
2232
2233 std::vector<Token> ExpandedToks;
2234 ExpandedToks.reserve(Toks.size());
2235 for (const Token &Tok : Toks) {
2237 assert(tok::isStringLiteral(Tok.getKind()));
2238 ExpandedToks.emplace_back(Tok);
2239 continue;
2240 }
2241 if (isa<TranslationUnitDecl>(CurrentDecl))
2242 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2243 // Stringify predefined expression
2244 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2245 << Tok.getKind();
2246 SmallString<64> Str;
2247 llvm::raw_svector_ostream OS(Str);
2248 Token &Exp = ExpandedToks.emplace_back();
2249 Exp.startToken();
2250 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2251 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2252 OS << 'L';
2253 Exp.setKind(tok::wide_string_literal);
2254 } else {
2255 Exp.setKind(tok::string_literal);
2256 }
2257 OS << '"'
2259 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2260 << '"';
2261 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2262 }
2263 return ExpandedToks;
2264}
2265
2268 assert(!StringToks.empty() && "Must have at least one string!");
2269
2270 // StringToks needs backing storage as it doesn't hold array elements itself
2271 std::vector<Token> ExpandedToks;
2272 if (getLangOpts().MicrosoftExt)
2273 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2274
2275 StringLiteralParser Literal(
2277 if (Literal.hadError)
2278 return ExprError();
2279
2280 SmallVector<SourceLocation, 4> StringTokLocs;
2281 for (const Token &Tok : StringToks)
2282 StringTokLocs.push_back(Tok.getLocation());
2283
2284 QualType CharTy = Context.CharTy;
2286 if (Literal.isWide()) {
2287 CharTy = Context.getWideCharType();
2289 } else if (Literal.isUTF8()) {
2290 if (getLangOpts().Char8)
2291 CharTy = Context.Char8Ty;
2292 else if (getLangOpts().C23)
2293 CharTy = Context.UnsignedCharTy;
2295 } else if (Literal.isUTF16()) {
2296 CharTy = Context.Char16Ty;
2298 } else if (Literal.isUTF32()) {
2299 CharTy = Context.Char32Ty;
2301 } else if (Literal.isPascal()) {
2302 CharTy = Context.UnsignedCharTy;
2303 }
2304
2305 // Warn on u8 string literals before C++20 and C23, whose type
2306 // was an array of char before but becomes an array of char8_t.
2307 // In C++20, it cannot be used where a pointer to char is expected.
2308 // In C23, it might have an unexpected value if char was signed.
2309 if (Kind == StringLiteralKind::UTF8 &&
2311 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2312 : !getLangOpts().C23)) {
2313 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2314 ? diag::warn_cxx20_compat_utf8_string
2315 : diag::warn_c23_compat_utf8_string);
2316
2317 // Create removals for all 'u8' prefixes in the string literal(s). This
2318 // ensures C++20/C23 compatibility (but may change the program behavior when
2319 // built by non-Clang compilers for which the execution character set is
2320 // not always UTF-8).
2321 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2322 SourceLocation RemovalDiagLoc;
2323 for (const Token &Tok : StringToks) {
2324 if (Tok.getKind() == tok::utf8_string_literal) {
2325 if (RemovalDiagLoc.isInvalid())
2326 RemovalDiagLoc = Tok.getLocation();
2328 Tok.getLocation(),
2329 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2331 }
2332 }
2333 Diag(RemovalDiagLoc, RemovalDiag);
2334 }
2335
2336 QualType StrTy =
2337 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2338
2339 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2341 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2342 if (Literal.getUDSuffix().empty())
2343 return Lit;
2344
2345 // We're building a user-defined literal.
2346 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2347 SourceLocation UDSuffixLoc =
2348 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2349 Literal.getUDSuffixOffset());
2350
2351 // Make sure we're allowed user-defined literals here.
2352 if (!UDLScope)
2353 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2354
2355 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2356 // operator "" X (str, len)
2357 QualType SizeType = Context.getSizeType();
2358
2359 DeclarationName OpName =
2360 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2361 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2362 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2363
2364 QualType ArgTy[] = {
2365 Context.getArrayDecayedType(StrTy), SizeType
2366 };
2367
2368 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2369 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2370 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2371 /*AllowStringTemplatePack*/ true,
2372 /*DiagnoseMissing*/ true, Lit)) {
2373
2374 case LOLR_Cooked: {
2375 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2376 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2377 StringTokLocs[0]);
2378 Expr *Args[] = { Lit, LenArg };
2379
2380 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2381 }
2382
2383 case LOLR_Template: {
2384 TemplateArgumentListInfo ExplicitArgs;
2385 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2386 TemplateArgumentLocInfo ArgInfo(Lit);
2387 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2388 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2389 &ExplicitArgs);
2390 }
2391
2393 TemplateArgumentListInfo ExplicitArgs;
2394
2395 unsigned CharBits = Context.getIntWidth(CharTy);
2396 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2397 llvm::APSInt Value(CharBits, CharIsUnsigned);
2398
2399 TemplateArgument TypeArg(CharTy);
2400 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2401 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2402
2403 SourceLocation Loc = StringTokLocs.back();
2404 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2405 Value = Lit->getCodeUnit(I);
2406 TemplateArgument Arg(Context, Value, CharTy);
2408 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2409 }
2410 return BuildLiteralOperatorCall(R, OpNameInfo, {}, Loc, &ExplicitArgs);
2411 }
2412 case LOLR_Raw:
2414 llvm_unreachable("unexpected literal operator lookup result");
2415 case LOLR_Error:
2416 return ExprError();
2417 }
2418 llvm_unreachable("unexpected literal operator lookup result");
2419}
2420
2423 SourceLocation Loc,
2424 const CXXScopeSpec *SS) {
2425 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2426 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2427}
2428
2431 const DeclarationNameInfo &NameInfo,
2432 const CXXScopeSpec *SS, NamedDecl *FoundD,
2433 SourceLocation TemplateKWLoc,
2434 const TemplateArgumentListInfo *TemplateArgs) {
2437 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2438 TemplateArgs);
2439}
2440
2441// CUDA/HIP: Check whether a captured reference variable is referencing a
2442// host variable in a device or host device lambda.
2444 VarDecl *VD) {
2445 if (!S.getLangOpts().CUDA || !VD->hasInit())
2446 return false;
2447 assert(VD->getType()->isReferenceType());
2448
2449 // Check whether the reference variable is referencing a host variable.
2450 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2451 if (!DRE)
2452 return false;
2453 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2454 if (!Referee || !Referee->hasGlobalStorage() ||
2455 Referee->hasAttr<CUDADeviceAttr>())
2456 return false;
2457
2458 // Check whether the current function is a device or host device lambda.
2459 // Check whether the reference variable is a capture by getDeclContext()
2460 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2461 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2462 if (MD && MD->getParent()->isLambda() &&
2463 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2464 VD->getDeclContext() != MD)
2465 return true;
2466
2467 return false;
2468}
2469
2471 // A declaration named in an unevaluated operand never constitutes an odr-use.
2473 return NOUR_Unevaluated;
2474
2475 // C++2a [basic.def.odr]p4:
2476 // A variable x whose name appears as a potentially-evaluated expression e
2477 // is odr-used by e unless [...] x is a reference that is usable in
2478 // constant expressions.
2479 // CUDA/HIP:
2480 // If a reference variable referencing a host variable is captured in a
2481 // device or host device lambda, the value of the referee must be copied
2482 // to the capture and the reference variable must be treated as odr-use
2483 // since the value of the referee is not known at compile time and must
2484 // be loaded from the captured.
2485 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2486 if (VD->getType()->isReferenceType() &&
2487 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2489 VD->isUsableInConstantExpressions(Context))
2490 return NOUR_Constant;
2491 }
2492
2493 // All remaining non-variable cases constitute an odr-use. For variables, we
2494 // need to wait and see how the expression is used.
2495 return NOUR_None;
2496}
2497
2500 const DeclarationNameInfo &NameInfo,
2501 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2502 SourceLocation TemplateKWLoc,
2503 const TemplateArgumentListInfo *TemplateArgs) {
2504 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2505 NeedToCaptureVariable(D, NameInfo.getLoc());
2506
2508 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2509 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2511
2512 // C++ [except.spec]p17:
2513 // An exception-specification is considered to be needed when:
2514 // - in an expression, the function is the unique lookup result or
2515 // the selected member of a set of overloaded functions.
2516 //
2517 // We delay doing this until after we've built the function reference and
2518 // marked it as used so that:
2519 // a) if the function is defaulted, we get errors from defining it before /
2520 // instead of errors from computing its exception specification, and
2521 // b) if the function is a defaulted comparison, we can use the body we
2522 // build when defining it as input to the exception specification
2523 // computation rather than computing a new body.
2524 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2525 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2526 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2527 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2528 }
2529 }
2530
2531 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2533 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2535
2536 const auto *FD = dyn_cast<FieldDecl>(D);
2537 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2538 FD = IFD->getAnonField();
2539 if (FD) {
2540 UnusedPrivateFields.remove(FD);
2541 // Just in case we're building an illegal pointer-to-member.
2542 if (FD->isBitField())
2544 }
2545
2546 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2547 // designates a bit-field.
2548 if (const auto *BD = dyn_cast<BindingDecl>(D))
2549 if (const auto *BE = BD->getBinding())
2550 E->setObjectKind(BE->getObjectKind());
2551
2552 return E;
2553}
2554
2555// Diagnose when a macro cannot be expanded because it's a function-like macro
2556// being used as a function-like macro. Returns true if a diagnostic is emitted.
2558 SourceLocation TypoLoc) {
2559
2560 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
2561 if (II->hasMacroDefinition()) {
2562 MacroInfo *MI = SemaRef.PP.getMacroInfo(II);
2563 if (MI && MI->isFunctionLike()) {
2564 // If the identifier is immediately followed by '(', the user did
2565 // attempt to invoke it as a function-like macro; the failure is
2566 // for some other reason (e.g. wrong argument count), which the
2567 // preprocessor already diagnosed separately. Don't suggest adding
2568 // parens in that case, since they're already there.
2569 SourceManager &SM = SemaRef.getSourceManager();
2570 const LangOptions &LangOpts = SemaRef.getLangOpts();
2571 std::optional<Token> NextTok =
2572 Lexer::findNextToken(TypoLoc, SM, LangOpts);
2573 if (NextTok && NextTok->is(tok::l_paren))
2574 return false;
2575 SemaRef.Diag(TypoLoc,
2576 diag::err_undeclared_var_use_suggest_func_like_macro)
2577 << II->getName();
2578 SemaRef.Diag(MI->getDefinitionLoc(),
2579 diag::note_function_like_macro_requires_parens)
2580 << II->getName();
2581 return true;
2582 }
2583 }
2584 }
2585 return false;
2586}
2587
2588void
2591 DeclarationNameInfo &NameInfo,
2592 const TemplateArgumentListInfo *&TemplateArgs) {
2594 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2595 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2596
2597 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2598 Id.TemplateId->NumArgs);
2599 translateTemplateArguments(TemplateArgsPtr, Buffer);
2600
2601 TemplateName TName = Id.TemplateId->Template.get();
2603 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2604 TemplateArgs = &Buffer;
2605 } else {
2606 NameInfo = GetNameFromUnqualifiedId(Id);
2607 TemplateArgs = nullptr;
2608 }
2609}
2610
2612 // During a default argument instantiation the CurContext points
2613 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2614 // function parameter list, hence add an explicit check.
2615 bool isDefaultArgument =
2616 !CodeSynthesisContexts.empty() &&
2617 CodeSynthesisContexts.back().Kind ==
2619 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2620 bool isInstance = CurMethod && CurMethod->isInstance() &&
2621 R.getNamingClass() == CurMethod->getParent() &&
2622 !isDefaultArgument;
2623
2624 // There are two ways we can find a class-scope declaration during template
2625 // instantiation that we did not find in the template definition: if it is a
2626 // member of a dependent base class, or if it is declared after the point of
2627 // use in the same class. Distinguish these by comparing the class in which
2628 // the member was found to the naming class of the lookup.
2629 unsigned DiagID = diag::err_found_in_dependent_base;
2630 unsigned NoteID = diag::note_member_declared_at;
2631 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2632 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2633 : diag::err_found_later_in_class;
2634 } else if (getLangOpts().MSVCCompat) {
2635 DiagID = diag::ext_found_in_dependent_base;
2636 NoteID = diag::note_dependent_member_use;
2637 }
2638
2639 if (isInstance) {
2640 // Give a code modification hint to insert 'this->'.
2641 Diag(R.getNameLoc(), DiagID)
2642 << R.getLookupName()
2643 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2644 CheckCXXThisCapture(R.getNameLoc());
2645 } else {
2646 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2647 // they're not shadowed).
2648 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2649 }
2650
2651 for (const NamedDecl *D : R)
2652 Diag(D->getLocation(), NoteID);
2653
2654 // Return true if we are inside a default argument instantiation
2655 // and the found name refers to an instance member function, otherwise
2656 // the caller will try to create an implicit member call and this is wrong
2657 // for default arguments.
2658 //
2659 // FIXME: Is this special case necessary? We could allow the caller to
2660 // diagnose this.
2661 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2662 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2663 return true;
2664 }
2665
2666 // Tell the callee to try to recover.
2667 return false;
2668}
2669
2672 TemplateArgumentListInfo *ExplicitTemplateArgs,
2673 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2674 DeclarationName Name = R.getLookupName();
2675 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2676
2677 unsigned diagnostic = diag::err_undeclared_var_use;
2678 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2682 diagnostic = diag::err_undeclared_use;
2683 diagnostic_suggest = diag::err_undeclared_use_suggest;
2684 }
2685
2686 // If the original lookup was an unqualified lookup, fake an
2687 // unqualified lookup. This is useful when (for example) the
2688 // original lookup would not have found something because it was a
2689 // dependent name.
2690 DeclContext *DC =
2691 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2692 while (DC) {
2693 if (isa<CXXRecordDecl>(DC)) {
2694 if (ExplicitTemplateArgs) {
2696 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2697 /*EnteringContext*/ false, TemplateNameIsRequired,
2698 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2699 return true;
2700 } else {
2701 LookupQualifiedName(R, DC);
2702 }
2703
2704 if (!R.empty()) {
2705 // Don't give errors about ambiguities in this lookup.
2706 R.suppressDiagnostics();
2707
2708 // If there's a best viable function among the results, only mention
2709 // that one in the notes.
2710 OverloadCandidateSet Candidates(R.getNameLoc(),
2712 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2714 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2715 OR_Success) {
2716 R.clear();
2717 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2718 R.resolveKind();
2719 }
2720
2722 }
2723
2724 R.clear();
2725 }
2726
2727 DC = DC->getLookupParent();
2728 }
2729
2730 // We didn't find anything, so try to correct for a typo.
2731 TypoCorrection Corrected;
2732 if (S && (Corrected =
2733 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2734 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2735 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2736 bool DroppedSpecifier =
2737 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2738 R.setLookupName(Corrected.getCorrection());
2739
2740 bool AcceptableWithRecovery = false;
2741 bool AcceptableWithoutRecovery = false;
2742 NamedDecl *ND = Corrected.getFoundDecl();
2743 if (ND) {
2744 if (Corrected.isOverloaded()) {
2745 OverloadCandidateSet OCS(R.getNameLoc(),
2748 for (NamedDecl *CD : Corrected) {
2749 if (FunctionTemplateDecl *FTD =
2750 dyn_cast<FunctionTemplateDecl>(CD))
2752 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2753 Args, OCS);
2754 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2755 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2757 Args, OCS);
2758 }
2759 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2760 case OR_Success:
2761 ND = Best->FoundDecl;
2762 Corrected.setCorrectionDecl(ND);
2763 break;
2764 default:
2765 // FIXME: Arbitrarily pick the first declaration for the note.
2766 Corrected.setCorrectionDecl(ND);
2767 break;
2768 }
2769 }
2770 R.addDecl(ND);
2771 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2774 if (!Record)
2777 R.setNamingClass(Record);
2778 }
2779
2780 auto *UnderlyingND = ND->getUnderlyingDecl();
2781 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2782 isa<FunctionTemplateDecl>(UnderlyingND);
2783 // FIXME: If we ended up with a typo for a type name or
2784 // Objective-C class name, we're in trouble because the parser
2785 // is in the wrong place to recover. Suggest the typo
2786 // correction, but don't make it a fix-it since we're not going
2787 // to recover well anyway.
2788 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2789 getAsTypeTemplateDecl(UnderlyingND) ||
2790 isa<ObjCInterfaceDecl>(UnderlyingND);
2791 } else {
2792 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2793 // because we aren't able to recover.
2794 AcceptableWithoutRecovery = true;
2795 }
2796
2797 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2798 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2799 ? diag::note_implicit_param_decl
2800 : diag::note_previous_decl;
2801 if (SS.isEmpty())
2802 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2803 PDiag(NoteID), AcceptableWithRecovery);
2804 else
2805 diagnoseTypo(Corrected,
2806 PDiag(diag::err_no_member_suggest)
2807 << Name << computeDeclContext(SS, false)
2808 << DroppedSpecifier << NameRange,
2809 PDiag(NoteID), AcceptableWithRecovery);
2810
2811 if (Corrected.WillReplaceSpecifier()) {
2813 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2814 SS.MakeTrivial(Context, NNS,
2815 NNS ? NameRange.getBegin() : SourceRange());
2816 }
2817
2818 // Tell the callee whether to try to recover.
2819 return !AcceptableWithRecovery;
2820 }
2821 }
2822 R.clear();
2823
2824 if (diagnoseFunctionLikeMacro(SemaRef, Name, R.getNameLoc()))
2825 return true;
2826
2827 // Emit a special diagnostic for failed member lookups.
2828 // FIXME: computing the declaration context might fail here (?)
2829 if (!SS.isEmpty()) {
2830 Diag(R.getNameLoc(), diag::err_no_member)
2831 << Name << computeDeclContext(SS, false) << NameRange;
2832 return true;
2833 }
2834
2835 // Give up, we can't recover.
2836 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2837 return true;
2838}
2839
2840/// In Microsoft mode, if we are inside a template class whose parent class has
2841/// dependent base classes, and we can't resolve an unqualified identifier, then
2842/// assume the identifier is a member of a dependent base class. We can only
2843/// recover successfully in static methods, instance methods, and other contexts
2844/// where 'this' is available. This doesn't precisely match MSVC's
2845/// instantiation model, but it's close enough.
2846static Expr *
2848 DeclarationNameInfo &NameInfo,
2849 SourceLocation TemplateKWLoc,
2850 const TemplateArgumentListInfo *TemplateArgs) {
2851 // Only try to recover from lookup into dependent bases in static methods or
2852 // contexts where 'this' is available.
2853 QualType ThisType = S.getCurrentThisType();
2854 const CXXRecordDecl *RD = nullptr;
2855 if (!ThisType.isNull())
2856 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2857 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2858 RD = MD->getParent();
2859 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2860 return nullptr;
2861
2862 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2863 // is available, suggest inserting 'this->' as a fixit.
2864 SourceLocation Loc = NameInfo.getLoc();
2865 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2866 DB << NameInfo.getName() << RD;
2867
2868 if (!ThisType.isNull()) {
2869 DB << FixItHint::CreateInsertion(Loc, "this->");
2871 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2872 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2873 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2874 }
2875
2876 // Synthesize a fake NNS that points to the derived class. This will
2877 // perform name lookup during template instantiation.
2878 CXXScopeSpec SS;
2879 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2880 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2882 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2883 TemplateArgs);
2884}
2885
2887 SourceLocation TemplateKWLoc,
2888 UnqualifiedId &Id, bool HasTrailingLParen,
2889 bool IsAddressOfOperand,
2891 bool IsInlineAsmIdentifier) {
2892 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2893 "cannot be direct & operand and have a trailing lparen");
2894 if (SS.isInvalid())
2895 return ExprError();
2896
2897 TemplateArgumentListInfo TemplateArgsBuffer;
2898
2899 // Decompose the UnqualifiedId into the following data.
2900 DeclarationNameInfo NameInfo;
2901 const TemplateArgumentListInfo *TemplateArgs;
2902 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2903
2904 DeclarationName Name = NameInfo.getName();
2906 SourceLocation NameLoc = NameInfo.getLoc();
2907
2909 Id.TemplateId->Template)
2910 if (TemplateName TN = Id.TemplateId->Template.get();
2912 return CheckVarOrConceptTemplateTemplateId(NameInfo, TN, TemplateArgs);
2913
2914 if (II && II->isEditorPlaceholder()) {
2915 // FIXME: When typed placeholders are supported we can create a typed
2916 // placeholder expression node.
2917 return ExprError();
2918 }
2919
2920 // This specially handles arguments of attributes appertains to a type of C
2921 // struct field such that the name lookup within a struct finds the member
2922 // name, which is not the case for other contexts in C.
2923 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2924 // See if this is reference to a field of struct.
2925 LookupResult R(*this, NameInfo, LookupMemberName);
2926 // LookupName handles a name lookup from within anonymous struct.
2927 if (LookupName(R, S)) {
2928 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2929 QualType type = VD->getType().getNonReferenceType();
2930 // This will eventually be translated into MemberExpr upon
2931 // the use of instantiated struct fields.
2932 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2933 }
2934 }
2935 }
2936
2937 // Perform the required lookup.
2938 LookupResult R(*this, NameInfo,
2942 if (TemplateKWLoc.isValid() || TemplateArgs) {
2943 // Lookup the template name again to correctly establish the context in
2944 // which it was found. This is really unfortunate as we already did the
2945 // lookup to determine that it was a template name in the first place. If
2946 // this becomes a performance hit, we can work harder to preserve those
2947 // results until we get here but it's likely not worth it.
2948 AssumedTemplateKind AssumedTemplate;
2949 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2950 /*EnteringContext=*/false, TemplateKWLoc,
2951 &AssumedTemplate))
2952 return ExprError();
2953
2954 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2955 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2956 IsAddressOfOperand, TemplateArgs);
2957 } else {
2958 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2959 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2960 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2961
2962 // If the result might be in a dependent base class, this is a dependent
2963 // id-expression.
2964 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2965 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2966 IsAddressOfOperand, TemplateArgs);
2967
2968 // If this reference is in an Objective-C method, then we need to do
2969 // some special Objective-C lookup, too.
2970 if (IvarLookupFollowUp) {
2971 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2972 if (E.isInvalid())
2973 return ExprError();
2974
2975 if (Expr *Ex = E.getAs<Expr>())
2976 return Ex;
2977 }
2978 }
2979
2980 if (R.isAmbiguous())
2981 return ExprError();
2982
2983 // This could be an implicitly declared function reference if the language
2984 // mode allows it as a feature.
2985 if (R.empty() && HasTrailingLParen && II &&
2986 getLangOpts().implicitFunctionsAllowed()) {
2987 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2988 if (D) R.addDecl(D);
2989 }
2990
2991 // Determine whether this name might be a candidate for
2992 // argument-dependent lookup.
2993 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2994
2995 if (R.empty() && !ADL) {
2996 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2997 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2998 TemplateKWLoc, TemplateArgs))
2999 return E;
3000 }
3001
3002 // Don't diagnose an empty lookup for inline assembly.
3003 if (IsInlineAsmIdentifier)
3004 return ExprError();
3005
3006 // If this name wasn't predeclared and if this is not a function
3007 // call, diagnose the problem.
3008 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
3009 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
3010 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
3011 "Typo correction callback misconfigured");
3012 if (CCC) {
3013 // Make sure the callback knows what the typo being diagnosed is.
3014 CCC->setTypoName(II);
3015 if (SS.isValid())
3016 CCC->setTypoNNS(SS.getScopeRep());
3017 }
3018 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
3019 // a template name, but we happen to have always already looked up the name
3020 // before we get here if it must be a template name.
3021 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
3022 {}, nullptr))
3023 return ExprError();
3024
3025 assert(!R.empty() &&
3026 "DiagnoseEmptyLookup returned false but added no results");
3027
3028 // If we found an Objective-C instance variable, let
3029 // LookupInObjCMethod build the appropriate expression to
3030 // reference the ivar.
3031 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
3032 R.clear();
3033 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
3034 // In a hopelessly buggy code, Objective-C instance variable
3035 // lookup fails and no expression will be built to reference it.
3036 if (!E.isInvalid() && !E.get())
3037 return ExprError();
3038 return E;
3039 }
3040 }
3041
3042 // This is guaranteed from this point on.
3043 assert(!R.empty() || ADL);
3044
3045 // Check whether this might be a C++ implicit instance member access.
3046 // C++ [class.mfct.non-static]p3:
3047 // When an id-expression that is not part of a class member access
3048 // syntax and not used to form a pointer to member is used in the
3049 // body of a non-static member function of class X, if name lookup
3050 // resolves the name in the id-expression to a non-static non-type
3051 // member of some class C, the id-expression is transformed into a
3052 // class member access expression using (*this) as the
3053 // postfix-expression to the left of the . operator.
3054 //
3055 // But we don't actually need to do this for '&' operands if R
3056 // resolved to a function or overloaded function set, because the
3057 // expression is ill-formed if it actually works out to be a
3058 // non-static member function:
3059 //
3060 // C++ [expr.ref]p4:
3061 // Otherwise, if E1.E2 refers to a non-static member function. . .
3062 // [t]he expression can be used only as the left-hand operand of a
3063 // member function call.
3064 //
3065 // There are other safeguards against such uses, but it's important
3066 // to get this right here so that we don't end up making a
3067 // spuriously dependent expression if we're inside a dependent
3068 // instance method.
3069 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3070 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
3071 S);
3072
3073 if (TemplateArgs || TemplateKWLoc.isValid()) {
3074
3075 // In C++1y, if this is a variable template id, then check it
3076 // in BuildTemplateIdExpr().
3077 // The single lookup result must be a variable template declaration.
3081 assert(R.getAsSingle<TemplateDecl>() &&
3082 "There should only be one declaration found.");
3083 }
3084
3085 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
3086 }
3087
3088 return BuildDeclarationNameExpr(SS, R, ADL);
3089}
3090
3092 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3093 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3094 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3095 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
3096
3097 if (R.isAmbiguous())
3098 return ExprError();
3099
3100 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3101 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3102 NameInfo, /*TemplateArgs=*/nullptr);
3103
3104 if (R.empty()) {
3105 // Don't diagnose problems with invalid record decl, the secondary no_member
3106 // diagnostic during template instantiation is likely bogus, e.g. if a class
3107 // is invalid because it's derived from an invalid base class, then missing
3108 // members were likely supposed to be inherited.
3110 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
3111 if (CD->isInvalidDecl() || CD->isBeingDefined())
3112 return ExprError();
3113 Diag(NameInfo.getLoc(), diag::err_no_member)
3114 << NameInfo.getName() << DC << SS.getRange();
3115 return ExprError();
3116 }
3117
3118 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3119 QualType ET;
3120 TypeLocBuilder TLB;
3121 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
3122 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
3123 SS.getScopeRep(), TagD,
3124 /*OwnsTag=*/false);
3125 auto TL = TLB.push<TagTypeLoc>(ET);
3127 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3128 TL.setNameLoc(NameInfo.getLoc());
3129 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
3130 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
3131 SS.getScopeRep(), TypedefD);
3132 TLB.push<TypedefTypeLoc>(ET).set(
3133 /*ElaboratedKeywordLoc=*/SourceLocation(),
3134 SS.getWithLocInContext(Context), NameInfo.getLoc());
3135 } else {
3136 // FIXME: What else can appear here?
3137 ET = SemaRef.Context.getTypeDeclType(TD);
3138 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
3139 assert(SS.isEmpty());
3140 }
3141
3142 // Diagnose a missing typename if this resolved unambiguously to a type in
3143 // a dependent context. If we can recover with a type, downgrade this to
3144 // a warning in Microsoft compatibility mode.
3145 unsigned DiagID = diag::err_typename_missing;
3146 if (RecoveryTSI && getLangOpts().MSVCCompat)
3147 DiagID = diag::ext_typename_missing;
3148 SourceLocation Loc = SS.getBeginLoc();
3149 auto D = Diag(Loc, DiagID);
3150 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3151
3152 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3153 // context.
3154 if (!RecoveryTSI)
3155 return ExprError();
3156
3157 // Only issue the fixit if we're prepared to recover.
3158 D << FixItHint::CreateInsertion(Loc, "typename ");
3159
3160 // Recover by pretending this was an elaborated type.
3161 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3162
3163 return ExprEmpty();
3164 }
3165
3166 // If necessary, build an implicit class member access.
3167 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3169 /*TemplateKWLoc=*/SourceLocation(),
3170 R, /*TemplateArgs=*/nullptr,
3171 /*S=*/nullptr);
3172
3173 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3174}
3175
3177 NestedNameSpecifier Qualifier,
3178 NamedDecl *FoundDecl,
3179 NamedDecl *Member) {
3180 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3181 if (!RD)
3182 return From;
3183
3184 QualType DestRecordType;
3185 QualType DestType;
3186 QualType FromRecordType;
3187 QualType FromType = From->getType();
3188 bool PointerConversions = false;
3189 if (isa<FieldDecl>(Member)) {
3190 DestRecordType = Context.getCanonicalTagType(RD);
3191 auto FromPtrType = FromType->getAs<PointerType>();
3192 DestRecordType = Context.getAddrSpaceQualType(
3193 DestRecordType, FromPtrType
3194 ? FromType->getPointeeType().getAddressSpace()
3195 : FromType.getAddressSpace());
3196
3197 if (FromPtrType) {
3198 DestType = Context.getPointerType(DestRecordType);
3199 FromRecordType = FromPtrType->getPointeeType();
3200 PointerConversions = true;
3201 } else {
3202 DestType = DestRecordType;
3203 FromRecordType = FromType;
3204 }
3205 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3206 if (!Method->isImplicitObjectMemberFunction())
3207 return From;
3208
3209 DestType = Method->getThisType().getNonReferenceType();
3210 DestRecordType = Method->getFunctionObjectParameterType();
3211
3212 if (FromType->getAs<PointerType>()) {
3213 FromRecordType = FromType->getPointeeType();
3214 PointerConversions = true;
3215 } else {
3216 FromRecordType = FromType;
3217 DestType = DestRecordType;
3218 }
3219
3220 LangAS FromAS = FromRecordType.getAddressSpace();
3221 LangAS DestAS = DestRecordType.getAddressSpace();
3222 if (FromAS != DestAS) {
3223 QualType FromRecordTypeWithoutAS =
3224 Context.removeAddrSpaceQualType(FromRecordType);
3225 QualType FromTypeWithDestAS =
3226 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3227 if (PointerConversions)
3228 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3229 From = ImpCastExprToType(From, FromTypeWithDestAS,
3230 CK_AddressSpaceConversion, From->getValueKind())
3231 .get();
3232 }
3233 } else {
3234 // No conversion necessary.
3235 return From;
3236 }
3237
3238 if (DestType->isDependentType() || FromType->isDependentType())
3239 return From;
3240
3241 // If the unqualified types are the same, no conversion is necessary.
3242 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3243 return From;
3244
3245 SourceRange FromRange = From->getSourceRange();
3246 SourceLocation FromLoc = FromRange.getBegin();
3247
3248 ExprValueKind VK = From->getValueKind();
3249
3250 // C++ [class.member.lookup]p8:
3251 // [...] Ambiguities can often be resolved by qualifying a name with its
3252 // class name.
3253 //
3254 // If the member was a qualified name and the qualified referred to a
3255 // specific base subobject type, we'll cast to that intermediate type
3256 // first and then to the object in which the member is declared. That allows
3257 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3258 //
3259 // class Base { public: int x; };
3260 // class Derived1 : public Base { };
3261 // class Derived2 : public Base { };
3262 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3263 //
3264 // void VeryDerived::f() {
3265 // x = 17; // error: ambiguous base subobjects
3266 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3267 // }
3268 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3269 QualType QType = QualType(Qualifier.getAsType(), 0);
3270 assert(QType->isRecordType() && "lookup done with non-record type");
3271
3272 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3273
3274 // In C++98, the qualifier type doesn't actually have to be a base
3275 // type of the object type, in which case we just ignore it.
3276 // Otherwise build the appropriate casts.
3277 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3278 CXXCastPath BasePath;
3279 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3280 FromLoc, FromRange, &BasePath))
3281 return ExprError();
3282
3283 if (PointerConversions)
3284 QType = Context.getPointerType(QType);
3285 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3286 VK, &BasePath).get();
3287
3288 FromType = QType;
3289 FromRecordType = QRecordType;
3290
3291 // If the qualifier type was the same as the destination type,
3292 // we're done.
3293 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3294 return From;
3295 }
3296 }
3297
3298 CXXCastPath BasePath;
3299 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3300 FromLoc, FromRange, &BasePath,
3301 /*IgnoreAccess=*/true))
3302 return ExprError();
3303
3304 // Propagate qualifiers to base subobjects as per:
3305 // C++ [basic.type.qualifier]p1.2:
3306 // A volatile object is [...] a subobject of a volatile object.
3307 Qualifiers FromTypeQuals = FromType.getQualifiers();
3308 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3309 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3310
3311 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3312 &BasePath);
3313}
3314
3316 const LookupResult &R,
3317 bool HasTrailingLParen) {
3318 // Only when used directly as the postfix-expression of a call.
3319 if (!HasTrailingLParen)
3320 return false;
3321
3322 // Never if a scope specifier was provided.
3323 if (SS.isNotEmpty())
3324 return false;
3325
3326 // Only in C++ or ObjC++.
3327 if (!getLangOpts().CPlusPlus)
3328 return false;
3329
3330 // Turn off ADL when we find certain kinds of declarations during
3331 // normal lookup:
3332 for (const NamedDecl *D : R) {
3333 // C++0x [basic.lookup.argdep]p3:
3334 // -- a declaration of a class member
3335 // Since using decls preserve this property, we check this on the
3336 // original decl.
3337 if (D->isCXXClassMember())
3338 return false;
3339
3340 // C++0x [basic.lookup.argdep]p3:
3341 // -- a block-scope function declaration that is not a
3342 // using-declaration
3343 // NOTE: we also trigger this for function templates (in fact, we
3344 // don't check the decl type at all, since all other decl types
3345 // turn off ADL anyway).
3346 if (isa<UsingShadowDecl>(D))
3347 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3348 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3349 return false;
3350
3351 // C++0x [basic.lookup.argdep]p3:
3352 // -- a declaration that is neither a function or a function
3353 // template
3354 // And also for builtin functions.
3355 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3356 // But also builtin functions.
3357 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3358 return false;
3359 } else if (!isa<FunctionTemplateDecl>(D))
3360 return false;
3361 }
3362
3363 return true;
3364}
3365
3366
3367/// Diagnoses obvious problems with the use of the given declaration
3368/// as an expression. This is only actually called for lookups that
3369/// were not overloaded, and it doesn't promise that the declaration
3370/// will in fact be used.
3372 bool AcceptInvalid) {
3373 if (D->isInvalidDecl() && !AcceptInvalid)
3374 return true;
3375
3376 if (isa<TypedefNameDecl>(D)) {
3377 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3378 return true;
3379 }
3380
3381 if (isa<ObjCInterfaceDecl>(D)) {
3382 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3383 return true;
3384 }
3385
3386 if (isa<NamespaceDecl>(D)) {
3387 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3388 return true;
3389 }
3390
3391 return false;
3392}
3393
3394// Certain multiversion types should be treated as overloaded even when there is
3395// only one result.
3397 assert(R.isSingleResult() && "Expected only a single result");
3398 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3399 return FD &&
3400 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3401}
3402
3404 LookupResult &R, bool NeedsADL,
3405 bool AcceptInvalidDecl) {
3406 // If this is a single, fully-resolved result and we don't need ADL,
3407 // just build an ordinary singleton decl ref.
3408 if (!NeedsADL && R.isSingleResult() &&
3409 !R.getAsSingle<FunctionTemplateDecl>() &&
3411 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3412 R.getRepresentativeDecl(), nullptr,
3413 AcceptInvalidDecl);
3414
3415 // We only need to check the declaration if there's exactly one
3416 // result, because in the overloaded case the results can only be
3417 // functions and function templates.
3418 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3419 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3420 AcceptInvalidDecl))
3421 return ExprError();
3422
3423 // Otherwise, just build an unresolved lookup expression. Suppress
3424 // any lookup-related diagnostics; we'll hash these out later, when
3425 // we've picked a target.
3426 R.suppressDiagnostics();
3427
3429 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3430 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3431 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3432
3433 return ULE;
3434}
3435
3437 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3438 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3439 bool AcceptInvalidDecl) {
3440 assert(D && "Cannot refer to a NULL declaration");
3441 assert(!isa<FunctionTemplateDecl>(D) &&
3442 "Cannot refer unambiguously to a function template");
3443
3444 SourceLocation Loc = NameInfo.getLoc();
3445 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3446 // Recovery from invalid cases (e.g. D is an invalid Decl).
3447 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3448 // diagnostics, as invalid decls use int as a fallback type.
3449 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3450 }
3451
3452 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3453 // Specifically diagnose references to class templates that are missing
3454 // a template argument list.
3455 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3456 return ExprError();
3457 }
3458
3459 // Make sure that we're referring to a value.
3461 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3462 Diag(D->getLocation(), diag::note_declared_at);
3463 return ExprError();
3464 }
3465
3466 // Check whether this declaration can be used. Note that we suppress
3467 // this check when we're going to perform argument-dependent lookup
3468 // on this function name, because this might not be the function
3469 // that overload resolution actually selects.
3470 if (DiagnoseUseOfDecl(D, Loc))
3471 return ExprError();
3472
3473 auto *VD = cast<ValueDecl>(D);
3474
3475 // Only create DeclRefExpr's for valid Decl's.
3476 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3477 return ExprError();
3478
3479 // Handle members of anonymous structs and unions. If we got here,
3480 // and the reference is to a class member indirect field, then this
3481 // must be the subject of a pointer-to-member expression.
3482 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3483 IndirectField && !IndirectField->isCXXClassMember())
3485 IndirectField);
3486
3487 QualType type = VD->getType();
3488 if (type.isNull())
3489 return ExprError();
3490 ExprValueKind valueKind = VK_PRValue;
3491
3492 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3493 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3494 // is expanded by some outer '...' in the context of the use.
3495 type = type.getNonPackExpansionType();
3496
3497 switch (D->getKind()) {
3498 // Ignore all the non-ValueDecl kinds.
3499#define ABSTRACT_DECL(kind)
3500#define VALUE(type, base)
3501#define DECL(type, base) case Decl::type:
3502#include "clang/AST/DeclNodes.inc"
3503 llvm_unreachable("invalid value decl kind");
3504
3505 // These shouldn't make it here.
3506 case Decl::ObjCAtDefsField:
3507 llvm_unreachable("forming non-member reference to ivar?");
3508
3509 // Enum constants are always r-values and never references.
3510 // Unresolved using declarations are dependent.
3511 case Decl::EnumConstant:
3512 case Decl::UnresolvedUsingValue:
3513 case Decl::OMPDeclareReduction:
3514 case Decl::OMPDeclareMapper:
3515 valueKind = VK_PRValue;
3516 break;
3517
3518 // Fields and indirect fields that got here must be for
3519 // pointer-to-member expressions; we just call them l-values for
3520 // internal consistency, because this subexpression doesn't really
3521 // exist in the high-level semantics.
3522 case Decl::Field:
3523 case Decl::IndirectField:
3524 case Decl::ObjCIvar:
3525 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3526 "building reference to field in C?");
3527
3528 // These can't have reference type in well-formed programs, but
3529 // for internal consistency we do this anyway.
3530 type = type.getNonReferenceType();
3531 valueKind = VK_LValue;
3532 break;
3533
3534 // Non-type template parameters are either l-values or r-values
3535 // depending on the type.
3536 case Decl::NonTypeTemplateParm: {
3537 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3538 type = reftype->getPointeeType();
3539 valueKind = VK_LValue; // even if the parameter is an r-value reference
3540 break;
3541 }
3542
3543 // [expr.prim.id.unqual]p2:
3544 // If the entity is a template parameter object for a template
3545 // parameter of type T, the type of the expression is const T.
3546 // [...] The expression is an lvalue if the entity is a [...] template
3547 // parameter object.
3548 if (type->isRecordType()) {
3549 type = type.getUnqualifiedType().withConst();
3550 valueKind = VK_LValue;
3551 break;
3552 }
3553
3554 // For non-references, we need to strip qualifiers just in case
3555 // the template parameter was declared as 'const int' or whatever.
3556 valueKind = VK_PRValue;
3557 type = type.getUnqualifiedType();
3558 break;
3559 }
3560
3561 case Decl::Var:
3562 case Decl::VarTemplateSpecialization:
3563 case Decl::VarTemplatePartialSpecialization:
3564 case Decl::Decomposition:
3565 case Decl::Binding:
3566 case Decl::OMPCapturedExpr:
3567 // In C, "extern void blah;" is valid and is an r-value.
3568 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3569 type->isVoidType()) {
3570 valueKind = VK_PRValue;
3571 break;
3572 }
3573 [[fallthrough]];
3574
3575 case Decl::ImplicitParam:
3576 case Decl::ParmVar: {
3577 // These are always l-values.
3578 valueKind = VK_LValue;
3579 type = type.getNonReferenceType();
3580
3581 // FIXME: Does the addition of const really only apply in
3582 // potentially-evaluated contexts? Since the variable isn't actually
3583 // captured in an unevaluated context, it seems that the answer is no.
3584 if (!isUnevaluatedContext()) {
3585 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3586 if (!CapturedType.isNull())
3587 type = CapturedType;
3588 }
3589 break;
3590 }
3591
3592 case Decl::Function: {
3593 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3594 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3595 type = Context.BuiltinFnTy;
3596 valueKind = VK_PRValue;
3597 break;
3598 }
3599 }
3600
3601 const FunctionType *fty = type->castAs<FunctionType>();
3602
3603 // If we're referring to a function with an __unknown_anytype
3604 // result type, make the entire expression __unknown_anytype.
3605 if (fty->getReturnType() == Context.UnknownAnyTy) {
3606 type = Context.UnknownAnyTy;
3607 valueKind = VK_PRValue;
3608 break;
3609 }
3610
3611 // Functions are l-values in C++.
3612 if (getLangOpts().CPlusPlus) {
3613 valueKind = VK_LValue;
3614 break;
3615 }
3616
3617 // C99 DR 316 says that, if a function type comes from a
3618 // function definition (without a prototype), that type is only
3619 // used for checking compatibility. Therefore, when referencing
3620 // the function, we pretend that we don't have the full function
3621 // type.
3622 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3623 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3624 fty->getExtInfo());
3625
3626 // Functions are r-values in C.
3627 valueKind = VK_PRValue;
3628 break;
3629 }
3630
3631 case Decl::CXXDeductionGuide:
3632 llvm_unreachable("building reference to deduction guide");
3633
3634 case Decl::MSProperty:
3635 case Decl::MSGuid:
3636 case Decl::TemplateParamObject:
3637 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3638 // capture in OpenMP, or duplicated between host and device?
3639 valueKind = VK_LValue;
3640 break;
3641
3642 case Decl::UnnamedGlobalConstant:
3643 valueKind = VK_LValue;
3644 break;
3645
3646 case Decl::CXXMethod:
3647 // If we're referring to a method with an __unknown_anytype
3648 // result type, make the entire expression __unknown_anytype.
3649 // This should only be possible with a type written directly.
3650 if (const FunctionProtoType *proto =
3651 dyn_cast<FunctionProtoType>(VD->getType()))
3652 if (proto->getReturnType() == Context.UnknownAnyTy) {
3653 type = Context.UnknownAnyTy;
3654 valueKind = VK_PRValue;
3655 break;
3656 }
3657
3658 // C++ methods are l-values if static, r-values if non-static.
3659 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3660 valueKind = VK_LValue;
3661 break;
3662 }
3663 [[fallthrough]];
3664
3665 case Decl::CXXConversion:
3666 case Decl::CXXDestructor:
3667 case Decl::CXXConstructor:
3668 valueKind = VK_PRValue;
3669 break;
3670 }
3671
3672 auto *E =
3673 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3674 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3675 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3676 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3677 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3678 // diagnostics).
3679 if (VD->isInvalidDecl() && E)
3680 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3681 return E;
3682}
3683
3684static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3686 Target.resize(CharByteWidth * (Source.size() + 1));
3687 char *ResultPtr = &Target[0];
3688 const llvm::UTF8 *ErrorPtr;
3689 bool success =
3690 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3691 (void)success;
3692 assert(success);
3693 Target.resize(ResultPtr - &Target[0]);
3694}
3695
3698 Decl *currentDecl = getPredefinedExprDecl(*this, CurContext);
3699 if (!currentDecl) {
3700 Diag(Loc, diag::ext_predef_outside_function);
3701 currentDecl = Context.getTranslationUnitDecl();
3702 }
3703
3704 QualType ResTy;
3705 StringLiteral *SL = nullptr;
3706 if (cast<DeclContext>(currentDecl)->isDependentContext())
3707 ResTy = Context.DependentTy;
3708 else {
3709 // Pre-defined identifiers are of type char[x], where x is the length of
3710 // the string.
3711 bool ForceElaboratedPrinting =
3712 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3713 auto Str =
3714 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3715 unsigned Length = Str.length();
3716
3717 llvm::APInt LengthI(32, Length + 1);
3720 ResTy =
3721 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3722 SmallString<32> RawChars;
3723 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3724 Str, RawChars);
3725 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3727 /*IndexTypeQuals*/ 0);
3729 /*Pascal*/ false, ResTy, Loc);
3730 } else {
3731 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3732 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3734 /*IndexTypeQuals*/ 0);
3736 /*Pascal*/ false, ResTy, Loc);
3737 }
3738 }
3739
3740 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3741 SL);
3742}
3743
3747
3749 SmallString<16> CharBuffer;
3750 bool Invalid = false;
3751 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3752 if (Invalid)
3753 return ExprError();
3754
3755 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3756 PP, Tok.getKind());
3757 if (Literal.hadError())
3758 return ExprError();
3759
3760 QualType Ty;
3761 if (Literal.isWide())
3762 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3763 else if (Literal.isUTF8() && getLangOpts().C23)
3764 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3765 else if (Literal.isUTF8() && getLangOpts().Char8)
3766 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3767 else if (Literal.isUTF16())
3768 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3769 else if (Literal.isUTF32())
3770 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3771 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3772 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3773 else
3774 Ty = Context.CharTy; // 'x' -> char in C++;
3775 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3776
3778 if (Literal.isWide())
3780 else if (Literal.isUTF16())
3782 else if (Literal.isUTF32())
3784 else if (Literal.isUTF8())
3786
3787 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3788 Tok.getLocation());
3789
3790 if (Literal.getUDSuffix().empty())
3791 return Lit;
3792
3793 // We're building a user-defined literal.
3794 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3795 SourceLocation UDSuffixLoc =
3796 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3797
3798 // Make sure we're allowed user-defined literals here.
3799 if (!UDLScope)
3800 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3801
3802 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3803 // operator "" X (ch)
3804 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3805 Lit, Tok.getLocation());
3806}
3807
3809 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3811 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3812 Context.IntTy, Loc);
3813}
3814
3816 ExprResult Inner;
3817 if (getLangOpts().CPlusPlus) {
3818 Inner = ActOnCXXBoolLiteral(Loc, Value ? tok::kw_true : tok::kw_false);
3819 } else {
3820 // C doesn't actually have a way to represent literal values of type
3821 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3822 Inner = ActOnIntegerConstant(Loc, Value ? 1 : 0);
3823 Inner =
3824 ImpCastExprToType(Inner.get(), Context.BoolTy, CK_IntegralToBoolean);
3825 }
3826 return Inner;
3827}
3828
3830 QualType Ty, SourceLocation Loc) {
3831 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3832
3833 using llvm::APFloat;
3834 APFloat Val(Format);
3835
3836 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3837 if (RM == llvm::RoundingMode::Dynamic)
3838 RM = llvm::RoundingMode::NearestTiesToEven;
3839 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3840
3841 // Overflow is always an error, but underflow is only an error if
3842 // we underflowed to zero (APFloat reports denormals as underflow).
3843 if ((result & APFloat::opOverflow) ||
3844 ((result & APFloat::opUnderflow) && Val.isZero())) {
3845 unsigned diagnostic;
3846 SmallString<20> buffer;
3847 if (result & APFloat::opOverflow) {
3848 diagnostic = diag::warn_float_overflow;
3849 APFloat::getLargest(Format).toString(buffer);
3850 } else {
3851 diagnostic = diag::warn_float_underflow;
3852 APFloat::getSmallest(Format).toString(buffer);
3853 }
3854
3855 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3856 }
3857
3858 bool isExact = (result == APFloat::opOK);
3859 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3860}
3861
3862bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3863 assert(E && "Invalid expression");
3864
3865 if (E->isValueDependent())
3866 return false;
3867
3868 QualType QT = E->getType();
3869 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3870 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3871 return true;
3872 }
3873
3874 llvm::APSInt ValueAPS;
3876
3877 if (R.isInvalid())
3878 return true;
3879
3880 // GCC allows the value of unroll count to be 0.
3881 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3882 // "The values of 0 and 1 block any unrolling of the loop."
3883 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3884 // '#pragma unroll' cases.
3885 bool ValueIsPositive =
3886 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3887 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3888 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3889 << toString(ValueAPS, 10) << ValueIsPositive;
3890 return true;
3891 }
3892
3893 return false;
3894}
3895
3897 // Fast path for a single digit (which is quite common). A single digit
3898 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3899 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3900 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3901 return ActOnIntegerConstant(Tok.getLocation(), Val);
3902 }
3903
3904 SmallString<128> SpellingBuffer;
3905 // NumericLiteralParser wants to overread by one character. Add padding to
3906 // the buffer in case the token is copied to the buffer. If getSpelling()
3907 // returns a StringRef to the memory buffer, it should have a null char at
3908 // the EOF, so it is also safe.
3909 SpellingBuffer.resize(Tok.getLength() + 1);
3910
3911 // Get the spelling of the token, which eliminates trigraphs, etc.
3912 bool Invalid = false;
3913 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3914 if (Invalid)
3915 return ExprError();
3916
3917 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3918 PP.getSourceManager(), PP.getLangOpts(),
3919 PP.getTargetInfo(), PP.getDiagnostics());
3920 if (Literal.hadError)
3921 return ExprError();
3922
3923 if (Literal.hasUDSuffix()) {
3924 // We're building a user-defined literal.
3925 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3926 SourceLocation UDSuffixLoc =
3927 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3928
3929 // Make sure we're allowed user-defined literals here.
3930 if (!UDLScope)
3931 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3932
3933 QualType CookedTy;
3934 if (Literal.isFloatingLiteral()) {
3935 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3936 // long double, the literal is treated as a call of the form
3937 // operator "" X (f L)
3938 CookedTy = Context.LongDoubleTy;
3939 } else {
3940 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3941 // unsigned long long, the literal is treated as a call of the form
3942 // operator "" X (n ULL)
3943 CookedTy = Context.UnsignedLongLongTy;
3944 }
3945
3946 DeclarationName OpName =
3947 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3948 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3949 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3950
3951 SourceLocation TokLoc = Tok.getLocation();
3952
3953 // Perform literal operator lookup to determine if we're building a raw
3954 // literal or a cooked one.
3955 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3956 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3957 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3958 /*AllowStringTemplatePack*/ false,
3959 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3961 // Lookup failure for imaginary constants isn't fatal, there's still the
3962 // GNU extension producing _Complex types.
3963 break;
3964 case LOLR_Error:
3965 return ExprError();
3966 case LOLR_Cooked: {
3967 Expr *Lit;
3968 if (Literal.isFloatingLiteral()) {
3969 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3970 } else {
3971 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3972 if (Literal.GetIntegerValue(ResultVal))
3973 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3974 << /* Unsigned */ 1;
3975 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3976 Tok.getLocation());
3977 }
3978 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3979 }
3980
3981 case LOLR_Raw: {
3982 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3983 // literal is treated as a call of the form
3984 // operator "" X ("n")
3985 unsigned Length = Literal.getUDSuffixOffset();
3986 QualType StrTy = Context.getConstantArrayType(
3987 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3988 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3989 Expr *Lit =
3990 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3992 /*Pascal*/ false, StrTy, TokLoc);
3993 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3994 }
3995
3996 case LOLR_Template: {
3997 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3998 // template), L is treated as a call fo the form
3999 // operator "" X <'c1', 'c2', ... 'ck'>()
4000 // where n is the source character sequence c1 c2 ... ck.
4001 TemplateArgumentListInfo ExplicitArgs;
4002 unsigned CharBits = Context.getIntWidth(Context.CharTy);
4003 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4004 llvm::APSInt Value(CharBits, CharIsUnsigned);
4005 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4006 Value = TokSpelling[I];
4007 TemplateArgument Arg(Context, Value, Context.CharTy);
4009 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
4010 }
4011 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
4012 }
4014 llvm_unreachable("unexpected literal operator lookup result");
4015 }
4016 }
4017
4018 Expr *Res;
4019
4020 if (Literal.isFixedPointLiteral()) {
4021 QualType Ty;
4022
4023 if (Literal.isAccum) {
4024 if (Literal.isHalf) {
4025 Ty = Context.ShortAccumTy;
4026 } else if (Literal.isLong) {
4027 Ty = Context.LongAccumTy;
4028 } else {
4029 Ty = Context.AccumTy;
4030 }
4031 } else if (Literal.isFract) {
4032 if (Literal.isHalf) {
4033 Ty = Context.ShortFractTy;
4034 } else if (Literal.isLong) {
4035 Ty = Context.LongFractTy;
4036 } else {
4037 Ty = Context.FractTy;
4038 }
4039 }
4040
4041 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
4042
4043 bool isSigned = !Literal.isUnsigned;
4044 unsigned scale = Context.getFixedPointScale(Ty);
4045 unsigned bit_width = Context.getTypeInfo(Ty).Width;
4046
4047 llvm::APInt Val(bit_width, 0, isSigned);
4048 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
4049 bool ValIsZero = Val.isZero() && !Overflowed;
4050
4051 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4052 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4053 // Clause 6.4.4 - The value of a constant shall be in the range of
4054 // representable values for its type, with exception for constants of a
4055 // fract type with a value of exactly 1; such a constant shall denote
4056 // the maximal value for the type.
4057 --Val;
4058 else if (Val.ugt(MaxVal) || Overflowed)
4059 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4060
4062 Tok.getLocation(), scale);
4063 } else if (Literal.isFloatingLiteral()) {
4064 QualType Ty;
4065 if (Literal.isHalf){
4066 if (getLangOpts().HLSL ||
4067 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4068 Ty = Context.HalfTy;
4069 else {
4070 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4071 return ExprError();
4072 }
4073 } else if (Literal.isFloat)
4074 Ty = Context.FloatTy;
4075 else if (Literal.isLong)
4076 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4077 else if (Literal.isFloat16)
4078 Ty = Context.Float16Ty;
4079 else if (Literal.isFloat128)
4080 Ty = Context.Float128Ty;
4081 else if (getLangOpts().HLSL)
4082 Ty = Context.FloatTy;
4083 else
4084 Ty = Context.DoubleTy;
4085
4086 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4087
4088 if (Ty == Context.DoubleTy) {
4089 if (getLangOpts().SinglePrecisionConstants) {
4090 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4091 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4092 }
4093 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4094 "cl_khr_fp64", getLangOpts())) {
4095 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4096 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4098 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4099 }
4100 }
4101 } else if (!Literal.isIntegerLiteral()) {
4102 return ExprError();
4103 } else {
4104 QualType Ty;
4105
4106 // 'z/uz' literals are a C++23 feature.
4107 if (Literal.isSizeT) {
4108 if (getLangOpts().CPlusPlus)
4109 DiagCompat(Tok.getLocation(), diag_compat::size_t_suffix);
4110 else
4111 Diag(Tok.getLocation(), diag::err_cxx23_size_t_suffix);
4112 }
4113
4114 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4115 // but we do not currently support the suffix in C++ mode because it's not
4116 // entirely clear whether WG21 will prefer this suffix to return a library
4117 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4118 // literals are a C++ extension.
4119 if (Literal.isBitInt)
4120 PP.Diag(Tok.getLocation(),
4121 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4122 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4123 : diag::ext_c23_bitint_suffix);
4124
4125 // Get the value in the widest-possible width. What is "widest" depends on
4126 // whether the literal is a bit-precise integer or not. For a bit-precise
4127 // integer type, try to scan the source to determine how many bits are
4128 // needed to represent the value. This may seem a bit expensive, but trying
4129 // to get the integer value from an overly-wide APInt is *extremely*
4130 // expensive, so the naive approach of assuming
4131 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4132 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4133 if (Literal.isBitInt)
4134 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4135 Literal.getLiteralDigits(), Literal.getRadix());
4136 if (Literal.MicrosoftInteger) {
4137 if (Literal.MicrosoftInteger == 128 &&
4138 !Context.getTargetInfo().hasInt128Type())
4139 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4140 << Literal.isUnsigned;
4141 BitsNeeded = std::max<unsigned>(BitsNeeded, Literal.MicrosoftInteger);
4142 }
4143
4144 llvm::APInt ResultVal(BitsNeeded, 0);
4145
4146 if (Literal.GetIntegerValue(ResultVal)) {
4147 // If this value didn't fit into uintmax_t, error and force to ull.
4148 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4149 << /* Unsigned */ 1;
4150 Ty = Context.UnsignedLongLongTy;
4151 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4152 "long long is not intmax_t?");
4153 } else {
4154 // If this value fits into a ULL, try to figure out what else it fits into
4155 // according to the rules of C99 6.4.4.1p5.
4156
4157 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4158 // be an unsigned int.
4159 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4160
4161 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4162 // suffix for portability of code with C++, but both `l` and `ll` are
4163 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4164 // same.
4165 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4166 Literal.isLong = true;
4167 Literal.isLongLong = false;
4168 }
4169
4170 // Check from smallest to largest, picking the smallest type we can.
4171 unsigned Width = 0;
4172
4173 // Microsoft specific integer suffixes are explicitly sized.
4174 if (Literal.MicrosoftInteger) {
4175 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4176 Width = 8;
4177 Ty = Context.CharTy;
4178 } else {
4179 Width = Literal.MicrosoftInteger;
4180 Ty = Context.getIntTypeForBitwidth(Width,
4181 /*Signed=*/!Literal.isUnsigned);
4182 }
4183 // To maintain consistency with MSVC, we chose to truncate directly
4184 // without issuing any warnings.
4185 ResultVal = ResultVal.zextOrTrunc(Width);
4186 }
4187
4188 // Bit-precise integer literals are automagically-sized based on the
4189 // width required by the literal.
4190 if (Literal.isBitInt) {
4191 // The signed version has one more bit for the sign value. There are no
4192 // zero-width bit-precise integers, even if the literal value is 0.
4193 Width = std::max(ResultVal.getActiveBits(), 1u) +
4194 (Literal.isUnsigned ? 0u : 1u);
4195
4196 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4197 // and reset the type to the largest supported width.
4198 unsigned int MaxBitIntWidth =
4199 Context.getTargetInfo().getMaxBitIntWidth();
4200 if (Width > MaxBitIntWidth) {
4201 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4202 << Literal.isUnsigned;
4203 Width = MaxBitIntWidth;
4204 }
4205
4206 // Reset the result value to the smaller APInt and select the correct
4207 // type to be used. Note, we zext even for signed values because the
4208 // literal itself is always an unsigned value (a preceeding - is a
4209 // unary operator, not part of the literal).
4210 ResultVal = ResultVal.zextOrTrunc(Width);
4211 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4212 }
4213
4214 // Check C++23 size_t literals.
4215 if (Literal.isSizeT) {
4216 assert(!Literal.MicrosoftInteger &&
4217 "size_t literals can't be Microsoft literals");
4218 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4219 Context.getTargetInfo().getSizeType());
4220
4221 // Does it fit in size_t?
4222 if (ResultVal.isIntN(SizeTSize)) {
4223 // Does it fit in ssize_t?
4224 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4225 Ty = Context.getSignedSizeType();
4226 else if (AllowUnsigned)
4227 Ty = Context.getSizeType();
4228 Width = SizeTSize;
4229 }
4230 }
4231
4232 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4233 !Literal.isSizeT) {
4234 // Are int/unsigned possibilities?
4235 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4236
4237 // Does it fit in a unsigned int?
4238 if (ResultVal.isIntN(IntSize)) {
4239 // Does it fit in a signed int?
4240 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4241 Ty = Context.IntTy;
4242 else if (AllowUnsigned)
4243 Ty = Context.UnsignedIntTy;
4244 Width = IntSize;
4245 }
4246 }
4247
4248 // Are long/unsigned long possibilities?
4249 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4250 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4251
4252 // Does it fit in a unsigned long?
4253 if (ResultVal.isIntN(LongSize)) {
4254 // Does it fit in a signed long?
4255 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4256 Ty = Context.LongTy;
4257 else if (AllowUnsigned)
4258 Ty = Context.UnsignedLongTy;
4259 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4260 // is compatible.
4261 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4262 const unsigned LongLongSize =
4263 Context.getTargetInfo().getLongLongWidth();
4264 Diag(Tok.getLocation(),
4266 ? Literal.isLong
4267 ? diag::warn_old_implicitly_unsigned_long_cxx
4268 : /*C++98 UB*/ diag::
4269 ext_old_implicitly_unsigned_long_cxx
4270 : diag::warn_old_implicitly_unsigned_long)
4271 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4272 : /*will be ill-formed*/ 1);
4273 Ty = Context.UnsignedLongTy;
4274 }
4275 Width = LongSize;
4276 }
4277 }
4278
4279 // Check long long if needed.
4280 if (Ty.isNull() && !Literal.isSizeT) {
4281 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4282
4283 // Does it fit in a unsigned long long?
4284 if (ResultVal.isIntN(LongLongSize)) {
4285 // Does it fit in a signed long long?
4286 // To be compatible with MSVC, hex integer literals ending with the
4287 // LL or i64 suffix are always signed in Microsoft mode.
4288 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4289 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4290 Ty = Context.LongLongTy;
4291 else if (AllowUnsigned)
4292 Ty = Context.UnsignedLongLongTy;
4293 Width = LongLongSize;
4294
4295 // 'long long' is a C99 or C++11 feature, whether the literal
4296 // explicitly specified 'long long' or we needed the extra width.
4297 if (getLangOpts().CPlusPlus)
4298 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4299 ? diag::warn_cxx98_compat_longlong
4300 : diag::ext_cxx11_longlong);
4301 else if (!getLangOpts().C99)
4302 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4303 }
4304 }
4305
4306 // If we still couldn't decide a type, we either have 'size_t' literal
4307 // that is out of range, or a decimal literal that does not fit in a
4308 // signed long long and has no U suffix.
4309 if (Ty.isNull()) {
4310 if (Literal.isSizeT)
4311 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4312 << Literal.isUnsigned;
4313 else
4314 Diag(Tok.getLocation(),
4315 diag::ext_integer_literal_too_large_for_signed);
4316 Ty = Context.UnsignedLongLongTy;
4317 Width = Context.getTargetInfo().getLongLongWidth();
4318 }
4319
4320 if (ResultVal.getBitWidth() != Width)
4321 ResultVal = ResultVal.trunc(Width);
4322 }
4323 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4324 }
4325
4326 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4327 if (Literal.isImaginary) {
4328 Res = new (Context) ImaginaryLiteral(Res,
4329 Context.getComplexType(Res->getType()));
4330
4331 // In C++, this is a GNU extension. In C, it's a C2y extension.
4332 if (getLangOpts().CPlusPlus)
4333 Diag(Tok.getLocation(), diag::ext_gnu_imaginary_constant);
4334 else
4335 DiagCompat(Tok.getLocation(), diag_compat::imaginary_constant);
4336 }
4337 return Res;
4338}
4339
4341 assert(E && "ActOnParenExpr() missing expr");
4342 QualType ExprTy = E->getType();
4343 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4344 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4345 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4346 return new (Context) ParenExpr(L, R, E);
4347}
4348
4350 SourceLocation Loc,
4351 SourceRange ArgRange) {
4352 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4353 // scalar or vector data type argument..."
4354 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4355 // type (C99 6.2.5p18) or void.
4356 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4357 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4358 << T << ArgRange;
4359 return true;
4360 }
4361
4362 assert((T->isVoidType() || !T->isIncompleteType()) &&
4363 "Scalar types should always be complete");
4364 return false;
4365}
4366
4368 SourceLocation Loc,
4369 SourceRange ArgRange) {
4370 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4371 if (!T->isVectorType() && !T->isSizelessVectorType())
4372 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4373 << ""
4374 << "__builtin_vectorelements" << T << ArgRange;
4375
4376 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
4377 if (T->isSVESizelessBuiltinType()) {
4378 llvm::StringMap<bool> CallerFeatureMap;
4379 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
4380 return S.ARM().checkSVETypeSupport(T, Loc, FD, CallerFeatureMap);
4381 }
4382 }
4383
4384 return false;
4385}
4386
4388 SourceLocation Loc,
4389 SourceRange ArgRange) {
4390 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4391 return true;
4392
4393 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4394 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4395 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4396 return true;
4397 }
4398
4399 return false;
4400}
4401
4403 SourceLocation Loc,
4404 SourceRange ArgRange,
4405 UnaryExprOrTypeTrait TraitKind) {
4406 // Invalid types must be hard errors for SFINAE in C++.
4407 if (S.LangOpts.CPlusPlus)
4408 return true;
4409
4410 // C99 6.5.3.4p1:
4411 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4412 TraitKind == UETT_PreferredAlignOf) {
4413
4414 // sizeof(function)/alignof(function) is allowed as an extension.
4415 if (T->isFunctionType()) {
4416 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4417 << getTraitSpelling(TraitKind) << ArgRange;
4418 return false;
4419 }
4420
4421 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4422 // this is an error (OpenCL v1.1 s6.3.k)
4423 if (T->isVoidType()) {
4424 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4425 : diag::ext_sizeof_alignof_void_type;
4426 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4427 return false;
4428 }
4429 }
4430 return true;
4431}
4432
4434 SourceLocation Loc,
4435 SourceRange ArgRange,
4436 UnaryExprOrTypeTrait TraitKind) {
4437 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4438 // runtime doesn't allow it.
4439 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4440 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4441 << T << (TraitKind == UETT_SizeOf)
4442 << ArgRange;
4443 return true;
4444 }
4445
4446 return false;
4447}
4448
4449/// Check whether E is a pointer from a decayed array type (the decayed
4450/// pointer type is equal to T) and emit a warning if it is.
4452 const Expr *E) {
4453 // Don't warn if the operation changed the type.
4454 if (T != E->getType())
4455 return;
4456
4457 // Now look for array decays.
4458 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4459 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4460 return;
4461
4462 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4463 << ICE->getType()
4464 << ICE->getSubExpr()->getType();
4465}
4466
4468 UnaryExprOrTypeTrait ExprKind) {
4469 QualType ExprTy = E->getType();
4470 assert(!ExprTy->isReferenceType());
4471
4472 bool IsUnevaluatedOperand =
4473 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4474 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4475 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4476 if (IsUnevaluatedOperand) {
4478 if (Result.isInvalid())
4479 return true;
4480 E = Result.get();
4481 }
4482
4483 // The operand for sizeof and alignof is in an unevaluated expression context,
4484 // so side effects could result in unintended consequences.
4485 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4486 // used to build SFINAE gadgets.
4487 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4488 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4490 !E->getType()->isVariableArrayType() &&
4491 E->HasSideEffects(Context, false))
4492 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4493
4494 if (ExprKind == UETT_VecStep)
4495 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4496 E->getSourceRange());
4497
4498 if (ExprKind == UETT_VectorElements)
4499 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4500 E->getSourceRange());
4501
4502 // Explicitly list some types as extensions.
4503 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4504 E->getSourceRange(), ExprKind))
4505 return false;
4506
4507 // WebAssembly tables are always illegal operands to unary expressions and
4508 // type traits.
4509 if (Context.getTargetInfo().getTriple().isWasm() &&
4511 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4512 << getTraitSpelling(ExprKind);
4513 return true;
4514 }
4515
4516 // 'alignof' applied to an expression only requires the base element type of
4517 // the expression to be complete. 'sizeof' requires the expression's type to
4518 // be complete (and will attempt to complete it if it's an array of unknown
4519 // bound).
4520 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4522 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4523 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4524 getTraitSpelling(ExprKind), E->getSourceRange()))
4525 return true;
4526 } else {
4528 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4529 getTraitSpelling(ExprKind), E->getSourceRange()))
4530 return true;
4531 }
4532
4533 // Completing the expression's type may have changed it.
4534 ExprTy = E->getType();
4535 assert(!ExprTy->isReferenceType());
4536
4537 if (ExprTy->isFunctionType()) {
4538 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4539 << getTraitSpelling(ExprKind) << E->getSourceRange();
4540 return true;
4541 }
4542
4543 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4544 E->getSourceRange(), ExprKind))
4545 return true;
4546
4547 if (ExprKind == UETT_CountOf) {
4548 // The type has to be an array type. We already checked for incomplete
4549 // types above.
4550 QualType ExprType = E->IgnoreParens()->getType();
4551 if (!ExprType->isArrayType()) {
4552 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4553 return true;
4554 }
4555 // FIXME: warn on _Countof on an array parameter. Not warning on it
4556 // currently because there are papers in WG14 about array types which do
4557 // not decay that could impact this behavior, so we want to see if anything
4558 // changes here before coming up with a warning group for _Countof-related
4559 // diagnostics.
4560 }
4561
4562 if (ExprKind == UETT_SizeOf) {
4563 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4564 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4565 QualType OType = PVD->getOriginalType();
4566 QualType Type = PVD->getType();
4567 if (Type->isPointerType() && OType->isArrayType()) {
4568 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4569 << Type << OType;
4570 Diag(PVD->getLocation(), diag::note_declared_at);
4571 }
4572 }
4573 }
4574
4575 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4576 // decays into a pointer and returns an unintended result. This is most
4577 // likely a typo for "sizeof(array) op x".
4578 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4579 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4580 BO->getLHS());
4581 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4582 BO->getRHS());
4583 }
4584 }
4585
4586 return false;
4587}
4588
4589static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4590 // Cannot know anything else if the expression is dependent.
4591 if (E->isTypeDependent())
4592 return false;
4593
4594 if (E->getObjectKind() == OK_BitField) {
4595 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4596 << 1 << E->getSourceRange();
4597 return true;
4598 }
4599
4600 ValueDecl *D = nullptr;
4601 Expr *Inner = E->IgnoreParens();
4602 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4603 D = DRE->getDecl();
4604 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4605 D = ME->getMemberDecl();
4606 }
4607
4608 // If it's a field, require the containing struct to have a
4609 // complete definition so that we can compute the layout.
4610 //
4611 // This can happen in C++11 onwards, either by naming the member
4612 // in a way that is not transformed into a member access expression
4613 // (in an unevaluated operand, for instance), or by naming the member
4614 // in a trailing-return-type.
4615 //
4616 // For the record, since __alignof__ on expressions is a GCC
4617 // extension, GCC seems to permit this but always gives the
4618 // nonsensical answer 0.
4619 //
4620 // We don't really need the layout here --- we could instead just
4621 // directly check for all the appropriate alignment-lowing
4622 // attributes --- but that would require duplicating a lot of
4623 // logic that just isn't worth duplicating for such a marginal
4624 // use-case.
4625 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4626 // Fast path this check, since we at least know the record has a
4627 // definition if we can find a member of it.
4628 if (!FD->getParent()->isCompleteDefinition()) {
4629 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4630 << E->getSourceRange();
4631 return true;
4632 }
4633
4634 // Otherwise, if it's a field, and the field doesn't have
4635 // reference type, then it must have a complete type (or be a
4636 // flexible array member, which we explicitly want to
4637 // white-list anyway), which makes the following checks trivial.
4638 if (!FD->getType()->isReferenceType())
4639 return false;
4640 }
4641
4642 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4643}
4644
4646 E = E->IgnoreParens();
4647
4648 // Cannot know anything else if the expression is dependent.
4649 if (E->isTypeDependent())
4650 return false;
4651
4652 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4653}
4654
4656 CapturingScopeInfo *CSI) {
4657 assert(T->isVariablyModifiedType());
4658 assert(CSI != nullptr);
4659
4660 // We're going to walk down into the type and look for VLA expressions.
4661 do {
4662 const Type *Ty = T.getTypePtr();
4663 switch (Ty->getTypeClass()) {
4664#define TYPE(Class, Base)
4665#define ABSTRACT_TYPE(Class, Base)
4666#define NON_CANONICAL_TYPE(Class, Base)
4667#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4668#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4669#include "clang/AST/TypeNodes.inc"
4670 T = QualType();
4671 break;
4672 // These types are never variably-modified.
4673 case Type::Builtin:
4674 case Type::Complex:
4675 case Type::Vector:
4676 case Type::ExtVector:
4677 case Type::ConstantMatrix:
4678 case Type::Record:
4679 case Type::Enum:
4680 case Type::TemplateSpecialization:
4681 case Type::ObjCObject:
4682 case Type::ObjCInterface:
4683 case Type::ObjCObjectPointer:
4684 case Type::ObjCTypeParam:
4685 case Type::Pipe:
4686 case Type::BitInt:
4687 case Type::HLSLInlineSpirv:
4688 llvm_unreachable("type class is never variably-modified!");
4689 case Type::Adjusted:
4690 T = cast<AdjustedType>(Ty)->getOriginalType();
4691 break;
4692 case Type::Decayed:
4693 T = cast<DecayedType>(Ty)->getPointeeType();
4694 break;
4695 case Type::ArrayParameter:
4696 T = cast<ArrayParameterType>(Ty)->getElementType();
4697 break;
4698 case Type::Pointer:
4699 T = cast<PointerType>(Ty)->getPointeeType();
4700 break;
4701 case Type::BlockPointer:
4702 T = cast<BlockPointerType>(Ty)->getPointeeType();
4703 break;
4704 case Type::LValueReference:
4705 case Type::RValueReference:
4706 T = cast<ReferenceType>(Ty)->getPointeeType();
4707 break;
4708 case Type::MemberPointer:
4709 T = cast<MemberPointerType>(Ty)->getPointeeType();
4710 break;
4711 case Type::ConstantArray:
4712 case Type::IncompleteArray:
4713 // Losing element qualification here is fine.
4714 T = cast<ArrayType>(Ty)->getElementType();
4715 break;
4716 case Type::VariableArray: {
4717 // Losing element qualification here is fine.
4719
4720 // Unknown size indication requires no size computation.
4721 // Otherwise, evaluate and record it.
4722 auto Size = VAT->getSizeExpr();
4723 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4725 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4726
4727 T = VAT->getElementType();
4728 break;
4729 }
4730 case Type::FunctionProto:
4731 case Type::FunctionNoProto:
4732 T = cast<FunctionType>(Ty)->getReturnType();
4733 break;
4734 case Type::Paren:
4735 case Type::TypeOf:
4736 case Type::UnaryTransform:
4737 case Type::Attributed:
4738 case Type::BTFTagAttributed:
4739 case Type::OverflowBehavior:
4740 case Type::HLSLAttributedResource:
4741 case Type::SubstTemplateTypeParm:
4742 case Type::MacroQualified:
4743 case Type::CountAttributed:
4744 case Type::LateParsedAttr:
4745 // Keep walking after single level desugaring.
4746 T = T.getSingleStepDesugaredType(Context);
4747 break;
4748 case Type::Typedef:
4749 T = cast<TypedefType>(Ty)->desugar();
4750 break;
4751 case Type::Decltype:
4752 T = cast<DecltypeType>(Ty)->desugar();
4753 break;
4754 case Type::PackIndexing:
4755 T = cast<PackIndexingType>(Ty)->desugar();
4756 break;
4757 case Type::Using:
4758 T = cast<UsingType>(Ty)->desugar();
4759 break;
4760 case Type::Auto:
4761 case Type::DeducedTemplateSpecialization:
4762 T = cast<DeducedType>(Ty)->getDeducedType();
4763 break;
4764 case Type::TypeOfExpr:
4765 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4766 break;
4767 case Type::Atomic:
4768 T = cast<AtomicType>(Ty)->getValueType();
4769 break;
4770 case Type::PredefinedSugar:
4771 T = cast<PredefinedSugarType>(Ty)->desugar();
4772 break;
4773 }
4774 } while (!T.isNull() && T->isVariablyModifiedType());
4775}
4776
4778 SourceLocation OpLoc,
4779 SourceRange ExprRange,
4780 UnaryExprOrTypeTrait ExprKind,
4781 StringRef KWName) {
4782 if (ExprType->isDependentType())
4783 return false;
4784
4785 // These builtins evaluate with the operand type as written; a reference is
4786 // not looked through.
4787 if (ExprKind == UETT_VectorElements)
4788 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4789 ExprRange);
4790 if (ExprKind == UETT_VecStep)
4791 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4792 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4793 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4794 ExprRange);
4795
4796 // C++ [expr.sizeof]p2:
4797 // When applied to a reference or a reference type, the result
4798 // is the size of the referenced type.
4799 // C++11 [expr.alignof]p3:
4800 // When alignof is applied to a reference type, the result
4801 // shall be the alignment of the referenced type.
4802 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4803 ExprType = Ref->getPointeeType();
4804
4805 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4806 // When alignof or _Alignof is applied to an array type, the result
4807 // is the alignment of the element type.
4808 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4809 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4810 // If the trait is 'alignof' in C before C2y, the ability to apply the
4811 // trait to an incomplete array is an extension.
4812 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4813 ExprType->isIncompleteArrayType())
4814 DiagCompat(OpLoc, diag_compat::alignof_incomplete_array);
4815 ExprType = Context.getBaseElementType(ExprType);
4816 }
4817
4818 // Explicitly list some types as extensions.
4819 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4820 ExprKind))
4821 return false;
4822
4824 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4825 KWName, ExprRange))
4826 return true;
4827
4828 if (ExprType->isFunctionType()) {
4829 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4830 return true;
4831 }
4832
4833 if (ExprKind == UETT_CountOf) {
4834 // The type has to be an array type. We already checked for incomplete
4835 // types above.
4836 if (!ExprType->isArrayType()) {
4837 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4838 return true;
4839 }
4840 }
4841
4842 // WebAssembly tables are always illegal operands to unary expressions and
4843 // type traits.
4844 if (Context.getTargetInfo().getTriple().isWasm() &&
4845 ExprType->isWebAssemblyTableType()) {
4846 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4847 << getTraitSpelling(ExprKind);
4848 return true;
4849 }
4850
4851 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4852 ExprKind))
4853 return true;
4854
4855 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4856 if (auto *TT = ExprType->getAs<TypedefType>()) {
4857 for (auto I = FunctionScopes.rbegin(),
4858 E = std::prev(FunctionScopes.rend());
4859 I != E; ++I) {
4860 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4861 if (CSI == nullptr)
4862 break;
4863 DeclContext *DC = nullptr;
4864 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4865 DC = LSI->CallOperator;
4866 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4867 DC = CRSI->TheCapturedDecl;
4868 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4869 DC = BSI->TheDecl;
4870 if (DC) {
4871 if (DC->containsDecl(TT->getDecl()))
4872 break;
4873 captureVariablyModifiedType(Context, ExprType, CSI);
4874 }
4875 }
4876 }
4877 }
4878
4879 return false;
4880}
4881
4883 SourceLocation OpLoc,
4884 UnaryExprOrTypeTrait ExprKind,
4885 SourceRange R) {
4886 if (!TInfo)
4887 return ExprError();
4888
4889 QualType T = TInfo->getType();
4890
4891 if (!T->isDependentType() &&
4892 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4893 getTraitSpelling(ExprKind)))
4894 return ExprError();
4895
4896 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4897 // properly deal with VLAs in nested calls of sizeof and typeof.
4898 if (currentEvaluationContext().isUnevaluated() &&
4899 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4900 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4901 TInfo->getType()->isVariablyModifiedType())
4902 TInfo = TransformToPotentiallyEvaluated(TInfo);
4903
4904 // It's possible that the transformation above failed.
4905 if (!TInfo)
4906 return ExprError();
4907
4908 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4909 return new (Context) UnaryExprOrTypeTraitExpr(
4910 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4911}
4912
4915 UnaryExprOrTypeTrait ExprKind) {
4917 if (PE.isInvalid())
4918 return ExprError();
4919
4920 E = PE.get();
4921
4922 // Verify that the operand is valid.
4923 bool isInvalid = false;
4924 if (E->isTypeDependent()) {
4925 // Delay type-checking for type-dependent expressions.
4926 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4927 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4928 } else if (ExprKind == UETT_VecStep) {
4930 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4931 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4932 isInvalid = true;
4933 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4934 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4935 isInvalid = true;
4936 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4937 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4939 }
4940
4941 if (isInvalid)
4942 return ExprError();
4943
4944 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4945 E->getType()->isVariableArrayType()) {
4947 if (PE.isInvalid()) return ExprError();
4948 E = PE.get();
4949 }
4950
4951 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4952 return new (Context) UnaryExprOrTypeTraitExpr(
4953 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4954}
4955
4958 UnaryExprOrTypeTrait ExprKind, bool IsType,
4959 void *TyOrEx, SourceRange ArgRange) {
4960 // If error parsing type, ignore.
4961 if (!TyOrEx) return ExprError();
4962
4963 if (IsType) {
4964 TypeSourceInfo *TInfo;
4965 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4966 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4967 }
4968
4969 Expr *ArgEx = (Expr *)TyOrEx;
4970 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4971 return Result;
4972}
4973
4975 SourceLocation OpLoc, SourceRange R) {
4976 if (!TInfo)
4977 return true;
4978 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4979 UETT_AlignOf, KWName);
4980}
4981
4983 SourceLocation OpLoc, SourceRange R) {
4984 TypeSourceInfo *TInfo;
4986 &TInfo);
4987 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4988}
4989
4991 bool IsReal) {
4992 if (V.get()->isTypeDependent())
4993 return S.Context.DependentTy;
4994
4995 // _Real and _Imag are only l-values for normal l-values.
4996 if (V.get()->getObjectKind() != OK_Ordinary) {
4997 V = S.DefaultLvalueConversion(V.get());
4998 if (V.isInvalid())
4999 return QualType();
5000 }
5001
5002 // These operators return the element type of a complex type.
5003 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
5004 return CT->getElementType();
5005
5006 // Otherwise they pass through real integer and floating point types here.
5007 if (V.get()->getType()->isArithmeticType())
5008 return V.get()->getType();
5009
5010 // Test for placeholders.
5011 ExprResult PR = S.CheckPlaceholderExpr(V.get());
5012 if (PR.isInvalid()) return QualType();
5013 if (PR.get() != V.get()) {
5014 V = PR;
5015 return CheckRealImagOperand(S, V, Loc, IsReal);
5016 }
5017
5018 // Reject anything else.
5019 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
5020 << (IsReal ? "__real" : "__imag");
5021 return QualType();
5022}
5023
5024
5025
5028 tok::TokenKind Kind, Expr *Input) {
5030 switch (Kind) {
5031 default: llvm_unreachable("Unknown unary op!");
5032 case tok::plusplus: Opc = UO_PostInc; break;
5033 case tok::minusminus: Opc = UO_PostDec; break;
5034 }
5035
5036 // Since this might is a postfix expression, get rid of ParenListExprs.
5038 if (Result.isInvalid()) return ExprError();
5039 Input = Result.get();
5040
5041 return BuildUnaryOp(S, OpLoc, Opc, Input);
5042}
5043
5044/// Diagnose if arithmetic on the given ObjC pointer is illegal.
5045///
5046/// \return true on error
5048 SourceLocation opLoc,
5049 Expr *op) {
5050 assert(op->getType()->isObjCObjectPointerType());
5052 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5053 return false;
5054
5055 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
5057 << op->getSourceRange();
5058 return true;
5059}
5060
5062 auto *BaseNoParens = Base->IgnoreParens();
5063 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
5064 return MSProp->getPropertyDecl()->getType()->isArrayType();
5065 return isa<MSPropertySubscriptExpr>(BaseNoParens);
5066}
5067
5068// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5069// Typically this is DependentTy, but can sometimes be more precise.
5070//
5071// There are cases when we could determine a non-dependent type:
5072// - LHS and RHS may have non-dependent types despite being type-dependent
5073// (e.g. unbounded array static members of the current instantiation)
5074// - one may be a dependent-sized array with known element type
5075// - one may be a dependent-typed valid index (enum in current instantiation)
5076//
5077// We *always* return a dependent type, in such cases it is DependentTy.
5078// This avoids creating type-dependent expressions with non-dependent types.
5079// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5081 const ASTContext &Ctx) {
5082 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5083 QualType LTy = LHS->getType(), RTy = RHS->getType();
5085 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5086 if (const PointerType *PT = LTy->getAs<PointerType>())
5087 Result = PT->getPointeeType();
5088 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5089 Result = AT->getElementType();
5090 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5091 if (const PointerType *PT = RTy->getAs<PointerType>())
5092 Result = PT->getPointeeType();
5093 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5094 Result = AT->getElementType();
5095 }
5096 // Ensure we return a dependent type.
5097 return Result->isDependentType() ? Result : Ctx.DependentTy;
5098}
5099
5101 SourceLocation lbLoc,
5102 MultiExprArg ArgExprs,
5103 SourceLocation rbLoc) {
5104
5105 if (base && !base->getType().isNull() &&
5106 base->hasPlaceholderType(BuiltinType::ArraySection)) {
5107 auto *AS = cast<ArraySectionExpr>(base);
5108 if (AS->isOMPArraySection())
5110 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
5111 /*Length*/ nullptr,
5112 /*Stride=*/nullptr, rbLoc);
5113
5114 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
5115 SourceLocation(), /*Length*/ nullptr,
5116 rbLoc);
5117 }
5118
5119 // Since this might be a postfix expression, get rid of ParenListExprs.
5120 if (isa<ParenListExpr>(base)) {
5122 if (result.isInvalid())
5123 return ExprError();
5124 base = result.get();
5125 }
5126
5127 // Check if base and idx form a MatrixSubscriptExpr.
5128 //
5129 // Helper to check for comma expressions, which are not allowed as indices for
5130 // matrix subscript expressions.
5131 //
5132 // In C++23, we get multiple arguments instead of a comma expression.
5133 auto CheckAndReportCommaError = [&](Expr *E) {
5134 if (ArgExprs.size() > 1 ||
5135 (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp())) {
5136 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5137 << SourceRange(base->getBeginLoc(), rbLoc);
5138 return true;
5139 }
5140 return false;
5141 };
5142 // The matrix subscript operator ([][])is considered a single operator.
5143 // Separating the index expressions by parenthesis is not allowed.
5144 if (base && !base->getType().isNull() &&
5145 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5146 !isa<MatrixSubscriptExpr>(base)) {
5147 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5148 << SourceRange(base->getBeginLoc(), rbLoc);
5149 return ExprError();
5150 }
5151 // If the base is a MatrixSubscriptExpr, try to create a new
5152 // MatrixSubscriptExpr.
5153 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5154 if (matSubscriptE && matSubscriptE->isIncomplete()) {
5155 if (CheckAndReportCommaError(ArgExprs.front()))
5156 return ExprError();
5157
5158 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5159 matSubscriptE->getRowIdx(),
5160 ArgExprs.front(), rbLoc);
5161 }
5162 if (base->getType()->isWebAssemblyTableType()) {
5163 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5164 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5165 return ExprError();
5166 }
5167
5168 CheckInvalidBuiltinCountedByRef(base,
5170
5171 // Handle any non-overload placeholder types in the base and index
5172 // expressions. We can't handle overloads here because the other
5173 // operand might be an overloadable type, in which case the overload
5174 // resolution for the operator overload should get the first crack
5175 // at the overload.
5176 bool IsMSPropertySubscript = false;
5177 if (base->getType()->isNonOverloadPlaceholderType()) {
5178 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5179 if (!IsMSPropertySubscript) {
5180 ExprResult result = CheckPlaceholderExpr(base);
5181 if (result.isInvalid())
5182 return ExprError();
5183 base = result.get();
5184 }
5185 }
5186
5187 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5188 if (base->getType()->isMatrixType()) {
5189 if (CheckAndReportCommaError(ArgExprs.front()))
5190 return ExprError();
5191
5192 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5193 rbLoc);
5194 }
5195
5196 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5197 Expr *idx = ArgExprs[0];
5198 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5200 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5201 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5202 << SourceRange(base->getBeginLoc(), rbLoc);
5203 }
5204 }
5205
5206 if (ArgExprs.size() == 1 &&
5207 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5208 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5209 if (result.isInvalid())
5210 return ExprError();
5211 ArgExprs[0] = result.get();
5212 } else {
5213 if (CheckArgsForPlaceholders(ArgExprs))
5214 return ExprError();
5215 }
5216
5217 // Build an unanalyzed expression if either operand is type-dependent.
5218 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5219 (base->isTypeDependent() ||
5221 !isa<PackExpansionExpr>(ArgExprs[0])) {
5222 return new (Context) ArraySubscriptExpr(
5223 base, ArgExprs.front(),
5224 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5225 VK_LValue, OK_Ordinary, rbLoc);
5226 }
5227
5228 // MSDN, property (C++)
5229 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5230 // This attribute can also be used in the declaration of an empty array in a
5231 // class or structure definition. For example:
5232 // __declspec(property(get=GetX, put=PutX)) int x[];
5233 // The above statement indicates that x[] can be used with one or more array
5234 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5235 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5236 if (IsMSPropertySubscript) {
5237 if (ArgExprs.size() > 1) {
5238 Diag(base->getExprLoc(),
5239 diag::err_ms_property_subscript_expects_single_arg);
5240 return ExprError();
5241 }
5242
5243 // Build MS property subscript expression if base is MS property reference
5244 // or MS property subscript.
5245 return new (Context)
5246 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5247 VK_LValue, OK_Ordinary, rbLoc);
5248 }
5249
5250 // Use C++ overloaded-operator rules if either operand has record
5251 // type. The spec says to do this if either type is *overloadable*,
5252 // but enum types can't declare subscript operators or conversion
5253 // operators, so there's nothing interesting for overload resolution
5254 // to do if there aren't any record types involved.
5255 //
5256 // ObjC pointers have their own subscripting logic that is not tied
5257 // to overload resolution and so should not take this path.
5258 //
5259 // Issue a better diagnostic if we tried to pass multiple arguments to
5260 // a builtin subscript operator rather than diagnosing this as a generic
5261 // overload resolution failure.
5262 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5263 !base->getType()->isRecordType() &&
5264 !base->getType()->isObjCObjectPointerType()) {
5265 Diag(base->getExprLoc(), diag::err_ovl_builtin_subscript_expects_single_arg)
5266 << base->getType() << base->getSourceRange();
5267 return ExprError();
5268 }
5269
5271 ((base->getType()->isRecordType() ||
5272 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5273 ArgExprs[0]->getType()->isRecordType())))) {
5274 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5275 }
5276
5277 ExprResult Res =
5278 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5279
5280 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5281 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5282
5283 return Res;
5284}
5285
5288 InitializationKind Kind =
5290 InitializationSequence InitSeq(*this, Entity, Kind, E);
5291 return InitSeq.Perform(*this, Entity, Kind, E);
5292}
5293
5295 Expr *RowIdx,
5296 SourceLocation RBLoc) {
5298 if (BaseR.isInvalid())
5299 return BaseR;
5300 Base = BaseR.get();
5301
5302 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5303 if (RowR.isInvalid())
5304 return RowR;
5305 RowIdx = RowR.get();
5306
5307 // Build an unanalyzed expression if any of the operands is type-dependent.
5308 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5309 return new (Context)
5310 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5311
5312 // Check that IndexExpr is an integer expression. If it is a constant
5313 // expression, check that it is less than Dim (= the number of elements in the
5314 // corresponding dimension).
5315 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5316 bool IsColumnIdx) -> Expr * {
5317 if (!IndexExpr->getType()->isIntegerType() &&
5318 !IndexExpr->isTypeDependent()) {
5319 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5320 << IsColumnIdx;
5321 return nullptr;
5322 }
5323
5324 if (std::optional<llvm::APSInt> Idx =
5325 IndexExpr->getIntegerConstantExpr(Context)) {
5326 if ((*Idx < 0 || *Idx >= Dim)) {
5327 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5328 << IsColumnIdx << Dim;
5329 return nullptr;
5330 }
5331 }
5332
5333 ExprResult ConvExpr = IndexExpr;
5334 assert(!ConvExpr.isInvalid() &&
5335 "should be able to convert any integer type to size type");
5336 return ConvExpr.get();
5337 };
5338
5339 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5340 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5341 if (!RowIdx)
5342 return ExprError();
5343
5344 QualType RowVecQT =
5345 Context.getExtVectorType(MTy->getElementType(), MTy->getNumColumns());
5346
5347 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5348}
5349
5351 Expr *ColumnIdx,
5352 SourceLocation RBLoc) {
5354 if (BaseR.isInvalid())
5355 return BaseR;
5356 Base = BaseR.get();
5357
5358 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5359 if (RowR.isInvalid())
5360 return RowR;
5361 RowIdx = RowR.get();
5362
5363 if (!ColumnIdx)
5364 return new (Context) MatrixSubscriptExpr(
5365 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5366
5367 // Build an unanalyzed expression if any of the operands is type-dependent.
5368 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5369 ColumnIdx->isTypeDependent())
5370 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5371 Context.DependentTy, RBLoc);
5372
5373 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5374 if (ColumnR.isInvalid())
5375 return ColumnR;
5376 ColumnIdx = ColumnR.get();
5377
5378 // Check that IndexExpr is an integer expression. If it is a constant
5379 // expression, check that it is less than Dim (= the number of elements in the
5380 // corresponding dimension).
5381 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5382 bool IsColumnIdx) -> Expr * {
5383 if (!IndexExpr->getType()->isIntegerType() &&
5384 !IndexExpr->isTypeDependent()) {
5385 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5386 << IsColumnIdx;
5387 return nullptr;
5388 }
5389
5390 if (std::optional<llvm::APSInt> Idx =
5391 IndexExpr->getIntegerConstantExpr(Context)) {
5392 if ((*Idx < 0 || *Idx >= Dim)) {
5393 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5394 << IsColumnIdx << Dim;
5395 return nullptr;
5396 }
5397 }
5398
5399 ExprResult ConvExpr = IndexExpr;
5400 assert(!ConvExpr.isInvalid() &&
5401 "should be able to convert any integer type to size type");
5402 return ConvExpr.get();
5403 };
5404
5405 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5406 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5407 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5408 if (!RowIdx || !ColumnIdx)
5409 return ExprError();
5410
5411 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5412 MTy->getElementType(), RBLoc);
5413}
5414
5415void Sema::CheckAddressOfNoDeref(const Expr *E) {
5416 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5417 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5418
5419 // For expressions like `&(*s).b`, the base is recorded and what should be
5420 // checked.
5421 const MemberExpr *Member = nullptr;
5422 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5423 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5424
5425 LastRecord.PossibleDerefs.erase(StrippedExpr);
5426}
5427
5428void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5430 return;
5431
5432 QualType ResultTy = E->getType();
5433 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5434
5435 // Bail if the element is an array since it is not memory access.
5436 if (isa<ArrayType>(ResultTy))
5437 return;
5438
5439 if (ResultTy->hasAttr(attr::NoDeref)) {
5440 LastRecord.PossibleDerefs.insert(E);
5441 return;
5442 }
5443
5444 // Check if the base type is a pointer to a member access of a struct
5445 // marked with noderef.
5446 const Expr *Base = E->getBase();
5447 QualType BaseTy = Base->getType();
5448 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5449 // Not a pointer access
5450 return;
5451
5452 const MemberExpr *Member = nullptr;
5453 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5454 Member->isArrow())
5455 Base = Member->getBase();
5456
5457 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5458 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5459 LastRecord.PossibleDerefs.insert(E);
5460 }
5461}
5462
5465 Expr *Idx, SourceLocation RLoc) {
5466 Expr *LHSExp = Base;
5467 Expr *RHSExp = Idx;
5468
5471
5472 // Per C++ core issue 1213, the result is an xvalue if either operand is
5473 // a non-lvalue array, and an lvalue otherwise.
5474 if (getLangOpts().CPlusPlus11) {
5475 for (auto *Op : {LHSExp, RHSExp}) {
5476 Op = Op->IgnoreImplicit();
5477 if (Op->getType()->isArrayType() && !Op->isLValue())
5478 VK = VK_XValue;
5479 }
5480 }
5481
5482 // Perform default conversions.
5483 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5485 if (Result.isInvalid())
5486 return ExprError();
5487 LHSExp = Result.get();
5488 }
5490 if (Result.isInvalid())
5491 return ExprError();
5492 RHSExp = Result.get();
5493
5494 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5495
5496 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5497 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5498 // in the subscript position. As a result, we need to derive the array base
5499 // and index from the expression types.
5500 Expr *BaseExpr, *IndexExpr;
5501 QualType ResultType;
5502 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5503 BaseExpr = LHSExp;
5504 IndexExpr = RHSExp;
5505 ResultType =
5507 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5508 BaseExpr = LHSExp;
5509 IndexExpr = RHSExp;
5510 ResultType = PTy->getPointeeType();
5511 } else if (const ObjCObjectPointerType *PTy =
5512 LHSTy->getAs<ObjCObjectPointerType>()) {
5513 BaseExpr = LHSExp;
5514 IndexExpr = RHSExp;
5515
5516 // Use custom logic if this should be the pseudo-object subscript
5517 // expression.
5518 if (!LangOpts.isSubscriptPointerArithmetic())
5519 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5520 nullptr, nullptr);
5521
5522 ResultType = PTy->getPointeeType();
5523 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5524 // Handle the uncommon case of "123[Ptr]".
5525 BaseExpr = RHSExp;
5526 IndexExpr = LHSExp;
5527 ResultType = PTy->getPointeeType();
5528 } else if (const ObjCObjectPointerType *PTy =
5529 RHSTy->getAs<ObjCObjectPointerType>()) {
5530 // Handle the uncommon case of "123[Ptr]".
5531 BaseExpr = RHSExp;
5532 IndexExpr = LHSExp;
5533 ResultType = PTy->getPointeeType();
5534 if (!LangOpts.isSubscriptPointerArithmetic()) {
5535 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5536 << ResultType << BaseExpr->getSourceRange();
5537 return ExprError();
5538 }
5539 } else if (LHSTy->isSubscriptableVectorType()) {
5540 if (LHSTy->isBuiltinType() &&
5541 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5542 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5543 if (BTy->isSVEBool())
5544 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5545 << LHSExp->getSourceRange()
5546 << RHSExp->getSourceRange());
5547 ResultType = BTy->getSveEltType(Context);
5548 } else {
5549 const VectorType *VTy = LHSTy->getAs<VectorType>();
5550 ResultType = VTy->getElementType();
5551 }
5552 BaseExpr = LHSExp; // vectors: V[123]
5553 IndexExpr = RHSExp;
5554 // We apply C++ DR1213 to vector subscripting too.
5555 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5556 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5557 if (Materialized.isInvalid())
5558 return ExprError();
5559 LHSExp = Materialized.get();
5560 }
5561 VK = LHSExp->getValueKind();
5562 if (VK != VK_PRValue)
5563 OK = OK_VectorComponent;
5564
5565 QualType BaseType = BaseExpr->getType();
5566 Qualifiers BaseQuals = BaseType.getQualifiers();
5567 Qualifiers MemberQuals = ResultType.getQualifiers();
5568 Qualifiers Combined = BaseQuals + MemberQuals;
5569 if (Combined != MemberQuals)
5570 ResultType = Context.getQualifiedType(ResultType, Combined);
5571 } else if (LHSTy->isArrayType()) {
5572 // If we see an array that wasn't promoted by
5573 // DefaultFunctionArrayLvalueConversion, it must be an array that
5574 // wasn't promoted because of the C90 rule that doesn't
5575 // allow promoting non-lvalue arrays. Warn, then
5576 // force the promotion here.
5577 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5578 << LHSExp->getSourceRange();
5579 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5580 CK_ArrayToPointerDecay).get();
5581 LHSTy = LHSExp->getType();
5582
5583 BaseExpr = LHSExp;
5584 IndexExpr = RHSExp;
5585 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5586 } else if (RHSTy->isArrayType()) {
5587 // Same as previous, except for 123[f().a] case
5588 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5589 << RHSExp->getSourceRange();
5590 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5591 CK_ArrayToPointerDecay).get();
5592 RHSTy = RHSExp->getType();
5593
5594 BaseExpr = RHSExp;
5595 IndexExpr = LHSExp;
5596 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5597 } else {
5598 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5599 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5600 }
5601 // C99 6.5.2.1p1
5602 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5603 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5604 << IndexExpr->getSourceRange());
5605
5606 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5607 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5608 !IndexExpr->isTypeDependent()) {
5609 std::optional<llvm::APSInt> IntegerContantExpr =
5611 if (!IntegerContantExpr.has_value() ||
5612 IntegerContantExpr.value().isNegative())
5613 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5614 }
5615
5616 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5617 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5618 // type. Note that Functions are not objects, and that (in C99 parlance)
5619 // incomplete types are not object types.
5620 if (ResultType->isFunctionType()) {
5621 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5622 << ResultType << BaseExpr->getSourceRange();
5623 return ExprError();
5624 }
5625
5626 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5627 // GNU extension: subscripting on pointer to void
5628 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5629 << BaseExpr->getSourceRange();
5630
5631 // C forbids expressions of unqualified void type from being l-values.
5632 // See IsCForbiddenLValueType.
5633 if (!ResultType.hasQualifiers())
5634 VK = VK_PRValue;
5635 } else if (!ResultType->isDependentType() &&
5636 !ResultType.isWebAssemblyReferenceType() &&
5638 LLoc, ResultType,
5639 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5640 return ExprError();
5641
5642 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5643 !ResultType.isCForbiddenLValueType());
5644
5646 FunctionScopes.size() > 1) {
5647 if (auto *TT =
5648 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5649 for (auto I = FunctionScopes.rbegin(),
5650 E = std::prev(FunctionScopes.rend());
5651 I != E; ++I) {
5652 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5653 if (CSI == nullptr)
5654 break;
5655 DeclContext *DC = nullptr;
5656 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5657 DC = LSI->CallOperator;
5658 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5659 DC = CRSI->TheCapturedDecl;
5660 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5661 DC = BSI->TheDecl;
5662 if (DC) {
5663 if (DC->containsDecl(TT->getDecl()))
5664 break;
5666 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5667 }
5668 }
5669 }
5670 }
5671
5672 return new (Context)
5673 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5674}
5675
5677 ParmVarDecl *Param, Expr *RewrittenInit,
5678 bool SkipImmediateInvocations) {
5679 if (Param->hasUnparsedDefaultArg()) {
5680 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5681 // If we've already cleared out the location for the default argument,
5682 // that means we're parsing it right now.
5683 if (!UnparsedDefaultArgLocs.count(Param)) {
5684 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5685 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5686 Param->setInvalidDecl();
5687 return true;
5688 }
5689
5690 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5691 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5693 diag::note_default_argument_declared_here);
5694 return true;
5695 }
5696
5697 if (Param->hasUninstantiatedDefaultArg()) {
5698 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5699 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5700 return true;
5701 }
5702
5703 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5704 assert(Init && "default argument but no initializer?");
5705
5706 // If the default expression creates temporaries, we need to
5707 // push them to the current stack of expression temporaries so they'll
5708 // be properly destroyed.
5709 // FIXME: We should really be rebuilding the default argument with new
5710 // bound temporaries; see the comment in PR5810.
5711 // We don't need to do that with block decls, though, because
5712 // blocks in default argument expression can never capture anything.
5713 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5714 // Set the "needs cleanups" bit regardless of whether there are
5715 // any explicit objects.
5716 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5717 // Append all the objects to the cleanup list. Right now, this
5718 // should always be a no-op, because blocks in default argument
5719 // expressions should never be able to capture anything.
5720 assert(!InitWithCleanup->getNumObjects() &&
5721 "default argument expression has capturing blocks?");
5722 }
5723 // C++ [expr.const]p15.1:
5724 // An expression or conversion is in an immediate function context if it is
5725 // potentially evaluated and [...] its innermost enclosing non-block scope
5726 // is a function parameter scope of an immediate function.
5728 *this,
5732 Param);
5733 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5734 SkipImmediateInvocations;
5735 runWithSufficientStackSpace(CallLoc, [&] {
5736 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5737 });
5738 return false;
5739}
5740
5745 }
5746
5747 bool HasImmediateCalls = false;
5748
5749 bool VisitCallExpr(CallExpr *E) override {
5750 if (const FunctionDecl *FD = E->getDirectCallee())
5751 HasImmediateCalls |= FD->isImmediateFunction();
5753 }
5754
5756 if (const FunctionDecl *FD = E->getConstructor())
5757 HasImmediateCalls |= FD->isImmediateFunction();
5759 }
5760
5761 // SourceLocExpr are not immediate invocations
5762 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5763 // need to be rebuilt so that they refer to the correct SourceLocation and
5764 // DeclContext.
5766 HasImmediateCalls = true;
5768 }
5769
5770 // A nested lambda might have parameters with immediate invocations
5771 // in their default arguments.
5772 // The compound statement is not visited (as it does not constitute a
5773 // subexpression).
5774 // FIXME: We should consider visiting and transforming captures
5775 // with init expressions.
5776 bool VisitLambdaExpr(LambdaExpr *E) override {
5777 return VisitCXXMethodDecl(E->getCallOperator());
5778 }
5779
5781 return TraverseStmt(E->getExpr());
5782 }
5783
5785 return TraverseStmt(E->getExpr());
5786 }
5787};
5788
5790 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5793
5794 bool AlwaysRebuild() { return true; }
5795
5796 // Lambda can only have immediate invocations in the default
5797 // args of their parameters, which is transformed upon calling the closure.
5798 // The body is not a subexpression, so we have nothing to do.
5799 // FIXME: Immediate calls in capture initializers should be transformed.
5802
5803 // Make sure we don't rebuild the this pointer as it would
5804 // cause it to incorrectly point it to the outermost class
5805 // in the case of nested struct initialization.
5807
5808 // Rewrite to source location to refer to the context in which they are used.
5810 DeclContext *DC = E->getParentContext();
5811 if (DC == SemaRef.CurContext)
5812 return E;
5813
5814 // FIXME: During instantiation, because the rebuild of defaults arguments
5815 // is not always done in the context of the template instantiator,
5816 // we run the risk of producing a dependent source location
5817 // that would never be rebuilt.
5818 // This usually happens during overload resolution, or in contexts
5819 // where the value of the source location does not matter.
5820 // However, we should find a better way to deal with source location
5821 // of function templates.
5822 if (!SemaRef.CurrentInstantiationScope ||
5823 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5824 DC = SemaRef.CurContext;
5825
5826 return getDerived().RebuildSourceLocExpr(
5827 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5828 }
5829};
5830
5832 FunctionDecl *FD, ParmVarDecl *Param,
5833 Expr *Init) {
5834 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5835
5836 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5837 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5838 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5839 InitializationContext =
5841 if (!InitializationContext.has_value())
5842 InitializationContext.emplace(CallLoc, Param, CurContext);
5843
5844 if (!Init && !Param->hasUnparsedDefaultArg()) {
5845 // Mark that we are replacing a default argument first.
5846 // If we are instantiating a template we won't have to
5847 // retransform immediate calls.
5848 // C++ [expr.const]p15.1:
5849 // An expression or conversion is in an immediate function context if it
5850 // is potentially evaluated and [...] its innermost enclosing non-block
5851 // scope is a function parameter scope of an immediate function.
5853 *this,
5857 Param);
5858
5859 if (Param->hasUninstantiatedDefaultArg()) {
5860 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5861 return ExprError();
5862 }
5863 // CWG2631
5864 // An immediate invocation that is not evaluated where it appears is
5865 // evaluated and checked for whether it is a constant expression at the
5866 // point where the enclosing initializer is used in a function call.
5868 if (!NestedDefaultChecking)
5869 V.TraverseDecl(Param);
5870
5871 // Rewrite the call argument that was created from the corresponding
5872 // parameter's default argument.
5873 if (V.HasImmediateCalls ||
5874 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5875 if (V.HasImmediateCalls)
5876 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5877 CallLoc, Param, CurContext};
5878 // Pass down lifetime extending flag, and collect temporaries in
5879 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5883 ExprResult Res;
5884 runWithSufficientStackSpace(CallLoc, [&] {
5885 Res = Immediate.TransformInitializer(Param->getInit(),
5886 /*NotCopy=*/false);
5887 });
5888 if (Res.isInvalid())
5889 return ExprError();
5890 Res = ConvertParamDefaultArgument(Param, Res.get(),
5891 Res.get()->getBeginLoc());
5892 if (Res.isInvalid())
5893 return ExprError();
5894 Init = Res.get();
5895 }
5896 }
5897
5899 CallLoc, FD, Param, Init,
5900 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5901 return ExprError();
5902
5903 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5904 Init, InitializationContext->Context);
5905}
5906
5908 FieldDecl *Field) {
5909 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5910 return Pattern;
5911 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5912 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5914 ClassPattern->lookup(Field->getDeclName());
5915 auto Rng = llvm::make_filter_range(
5916 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5917 if (Rng.empty())
5918 return nullptr;
5919 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5920 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5921 // && "Duplicated instantiation pattern for field decl");
5922 return cast<FieldDecl>(*Rng.begin());
5923}
5924
5925ExprResult Sema::BuildCXXDefaultInitInternal(SourceLocation Loc,
5926 FieldDecl *Field,
5927 const InitializedEntity &Entity,
5928 bool NestedDefaultChecking,
5929 bool NeedRebuild) {
5930 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5931
5932 if (!Field->getInClassInitializer() &&
5933 isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5934 // Maybe we haven't instantiated the in-class initializer. Go check the
5935 // pattern FieldDecl to see if it has one.
5936 FieldDecl *Pattern =
5938 assert(Pattern && "We must have set the Pattern!");
5939 if (!Pattern->hasInClassInitializer() ||
5940 InstantiateInClassInitializer(Loc, Field, Pattern,
5942 return ExprError();
5943 }
5944
5945 Expr *InClassInit = Field->getInClassInitializer();
5946 if (!InClassInit) {
5947 // DR1351:
5948 // If the brace-or-equal-initializer of a non-static data member
5949 // invokes a defaulted default constructor of its class or of an
5950 // enclosing class in a potentially evaluated subexpression, the
5951 // program is ill-formed.
5952 //
5953 // This resolution is unworkable: the exception specification of the
5954 // default constructor can be needed in an unevaluated context, in
5955 // particular, in the operand of a noexcept-expression, and we can be
5956 // unable to compute an exception specification for an enclosed class.
5957 //
5958 // Any attempt to resolve the exception specification of a defaulted default
5959 // constructor before the initializer is lexically complete will ultimately
5960 // come here at which point we can diagnose it.
5961 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5962 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5963 << OutermostClass << Field;
5964 Diag(Field->getEndLoc(),
5965 diag::note_default_member_initializer_not_yet_parsed);
5966 // Recover by marking the field invalid, unless we're in a SFINAE context.
5967 if (!isSFINAEContext())
5968 Field->setInvalidDecl();
5969 return ExprError();
5970 }
5971
5972 // CWG2631
5973 // An immediate invocation that is not evaluated where it appears is
5974 // evaluated and checked for whether it is a constant expression at the
5975 // point where the enclosing initializer is used in a [...] a constructor
5976 // definition, or an aggregate initialization.
5977 ImmediateCallVisitor V(getASTContext());
5978 if (!NestedDefaultChecking)
5979 V.TraverseDecl(Field);
5980
5981 // CWG1815
5982 // Support lifetime extension of temporary created by aggregate
5983 // initialization using a default member initializer. We should rebuild
5984 // the initializer in a lifetime extension context if the initializer
5985 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5986 // extension code recurses into the default initializer and does lifetime
5987 // extension when warranted.
5988 bool ContainsAnyTemporaries = isa<ExprWithCleanups>(InClassInit);
5989 Expr *Init = InClassInit;
5990 if (!InClassInit->containsErrors() &&
5991 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5992 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5993 CurContext};
5994 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5995 NestedDefaultChecking;
5996 // Pass down lifetime extending flag, and collect temporaries in
5997 // CreateMaterializeTemporaryExpr when we rewrite the initializer.
6000
6001 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6002 ExprResult Res;
6004 Res = Immediate.TransformInitializer(InClassInit,
6005 /*CXXDirectInit=*/false);
6006 });
6007 if (!Res.isInvalid())
6008 Res = ConvertMemberDefaultInitExpression(Field, Entity, Res.get(), Loc);
6009 if (Res.isInvalid()) {
6010 Field->setInvalidDecl();
6011 return ExprError();
6012 }
6013 Init = Res.get();
6014 }
6015
6016 if (!NestedDefaultChecking)
6018 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/false);
6019 });
6020 return Init;
6021}
6022
6024 FieldDecl *Field) {
6025 assert(Field->hasInClassInitializer());
6026
6027 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6028
6029 // C++11 [class.base.init]p7:
6030 // The initialization of each base and member constitutes a
6031 // full-expression.
6032 // So this initializer gets an evaluation context of its own, and is finished
6033 // as a full-expression below.
6036 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6037
6039 if (!InitContext)
6040 InitContext.emplace(Loc, Field, CurContext);
6041
6042 // [class.temporary]/p7:
6043 // If such a temporary object would otherwise be destroyed at the end of the
6044 // for-range-initializer full-expression, the object persists for the lifetime
6045 // of the reference initialized by the for-range-initializer.
6046 //
6047 // A default member initializer used by a constructor is a separate
6048 // full-expression, we don't need extend temporaries lifetime in this
6049 // situation, the NeedRebuild will always false.
6050 ExprResult Init = BuildCXXDefaultInitInternal(
6051 Loc, Field,
6053 NestedDefaultChecking, /*NeedRebuild=*/false);
6054 if (Init.isInvalid())
6055 return ExprError();
6056
6057 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue=*/false);
6058 if (Init.isInvalid()) {
6059 Field->setInvalidDecl();
6060 return ExprError();
6061 }
6062
6064 Context, InitContext->Loc, Field, InitContext->Context,
6065 Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6066}
6067
6070 const InitializedEntity &MemberEntity) {
6071 assert(Field->hasInClassInitializer());
6072
6073 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6074
6075 // Unlike a mem-initializer, this initializer is a subexpression of the
6076 // full-expression containing the aggregate initialization. It is evaluated
6077 // exactly as that full-expression is, so inherit the enclosing context kind
6078 // rather than forcing a potentially evaluated one.
6080 *this, currentEvaluationContext().Context, Field);
6081 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6082
6084 if (!InitContext)
6085 InitContext.emplace(Loc, Field, CurContext);
6086
6087 // [class.temporary]/p7:
6088 // If such a temporary object would otherwise be destroyed at the end of the
6089 // for-range-initializer full-expression, the object persists for the lifetime
6090 // of the reference initialized by the for-range-initializer.
6091 //
6092 // A default member initializer used by an aggregate initialization belongs to
6093 // the full-expression containing the aggregate initialization. we need extend
6094 // temporaries lifetime in this situation, the NeedRebuild will always true.
6095
6096 // CWG1815: always rebuild, never share the AST built when the field was
6097 // declared. Only a copy rebuilt here has its MaterializeTemporaryExprs
6098 // collected in this context, which is what lets the aggregate initialization
6099 // lifetime-extend them; sharing one AST would also make several uses of the
6100 // same field fight over its extension. A mem-initializer has no such need,
6101 // as its temporaries die at the end of the initializer itself.
6102 ExprResult Init = BuildCXXDefaultInitInternal(
6103 Loc, Field, MemberEntity, NestedDefaultChecking, /*NeedRebuild=*/true);
6104 if (Init.isInvalid())
6105 return ExprError();
6106
6107 // Deliberately not finished as a full-expression: leaving the temporaries it
6108 // created on ExprCleanupObjects lets PopExpressionEvaluationContext merge
6109 // them into the enclosing context, which eventually wraps them all in a
6110 // single ExprWithCleanups. They are then destroyed at the end of the
6111 // containing full-expression, in reverse construction order.
6112
6114 Context, InitContext->Loc, Field, InitContext->Context,
6115 Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6116}
6117
6119 const FunctionProtoType *Proto,
6120 Expr *Fn) {
6121 if (Proto && Proto->isVariadic()) {
6122 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6124 else if (Fn && Fn->getType()->isBlockPointerType())
6126 else if (FDecl) {
6127 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6128 if (Method->isInstance())
6130 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6133 }
6135}
6136
6137namespace {
6138class FunctionCallCCC final : public FunctionCallFilterCCC {
6139public:
6140 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6141 unsigned NumArgs, MemberExpr *ME)
6142 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6143 FunctionName(FuncName) {}
6144
6145 bool ValidateCandidate(const TypoCorrection &candidate) override {
6146 if (!candidate.getCorrectionSpecifier() ||
6147 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6148 return false;
6149 }
6150
6152 }
6153
6154 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6155 return std::make_unique<FunctionCallCCC>(*this);
6156 }
6157
6158private:
6159 const IdentifierInfo *const FunctionName;
6160};
6161}
6162
6164 FunctionDecl *FDecl,
6165 ArrayRef<Expr *> Args) {
6166 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6167 DeclarationName FuncName = FDecl->getDeclName();
6168 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6169
6170 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6171 if (TypoCorrection Corrected = S.CorrectTypo(
6173 S.getScopeForContext(S.CurContext), nullptr, CCC,
6175 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6176 if (Corrected.isOverloaded()) {
6179 for (NamedDecl *CD : Corrected) {
6180 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6182 OCS);
6183 }
6184 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6185 case OR_Success:
6186 ND = Best->FoundDecl;
6187 Corrected.setCorrectionDecl(ND);
6188 break;
6189 default:
6190 break;
6191 }
6192 }
6193 ND = ND->getUnderlyingDecl();
6195 return Corrected;
6196 }
6197 }
6198 return TypoCorrection();
6199}
6200
6201// [C++26][[expr.unary.op]/p4
6202// A pointer to member is only formed when an explicit &
6203// is used and its operand is a qualified-id not enclosed in parentheses.
6205 if (!isa<ParenExpr>(Fn))
6206 return false;
6207
6208 Fn = Fn->IgnoreParens();
6209
6210 auto *UO = dyn_cast<UnaryOperator>(Fn);
6211 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6212 return false;
6213 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
6214 return DRE->hasQualifier();
6215 }
6216 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
6217 return bool(OVL->getQualifier());
6218 return false;
6219}
6220
6221bool
6223 FunctionDecl *FDecl,
6224 const FunctionProtoType *Proto,
6225 ArrayRef<Expr *> Args,
6226 SourceLocation RParenLoc,
6227 bool IsExecConfig) {
6228 // Bail out early if calling a builtin with custom typechecking.
6229 // For HLSL builtin aliases, argument conversion is still needed because
6230 // overload resolution may have selected a conversion sequence (e.g.,
6231 // vector-to-scalar truncation) that must be applied before the custom
6232 // type checker runs.
6233 if (FDecl)
6234 if (unsigned ID = FDecl->getBuiltinID())
6235 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6236 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6237 return false;
6238
6239 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6240 // assignment, to the types of the corresponding parameter, ...
6241
6242 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6243 bool HasExplicitObjectParameter =
6244 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6245 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6246 unsigned NumParams = Proto->getNumParams();
6247 bool Invalid = false;
6248 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6249 unsigned FnKind = Fn->getType()->isBlockPointerType()
6250 ? 1 /* block */
6251 : (IsExecConfig ? 3 /* kernel function (exec config) */
6252 : 0 /* function */);
6253
6254 // If too few arguments are available (and we don't have default
6255 // arguments for the remaining parameters), don't make the call.
6256 if (Args.size() < NumParams) {
6257 if (Args.size() < MinArgs) {
6258 TypoCorrection TC;
6259 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6260 unsigned diag_id =
6261 MinArgs == NumParams && !Proto->isVariadic()
6262 ? diag::err_typecheck_call_too_few_args_suggest
6263 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6265 TC, PDiag(diag_id)
6266 << FnKind << MinArgs - ExplicitObjectParameterOffset
6267 << static_cast<unsigned>(Args.size()) -
6268 ExplicitObjectParameterOffset
6269 << HasExplicitObjectParameter << TC.getCorrectionRange());
6270 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6271 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6272 ->getDeclName())
6273 Diag(RParenLoc,
6274 MinArgs == NumParams && !Proto->isVariadic()
6275 ? diag::err_typecheck_call_too_few_args_one
6276 : diag::err_typecheck_call_too_few_args_at_least_one)
6277 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6278 << HasExplicitObjectParameter << Fn->getSourceRange();
6279 else
6280 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6281 ? diag::err_typecheck_call_too_few_args
6282 : diag::err_typecheck_call_too_few_args_at_least)
6283 << FnKind << MinArgs - ExplicitObjectParameterOffset
6284 << static_cast<unsigned>(Args.size()) -
6285 ExplicitObjectParameterOffset
6286 << HasExplicitObjectParameter << Fn->getSourceRange();
6287
6288 // Emit the location of the prototype.
6289 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6290 Diag(FDecl->getLocation(), diag::note_callee_decl)
6291 << FDecl << FDecl->getParametersSourceRange();
6292
6293 return true;
6294 }
6295 // We reserve space for the default arguments when we create
6296 // the call expression, before calling ConvertArgumentsForCall.
6297 assert((Call->getNumArgs() == NumParams) &&
6298 "We should have reserved space for the default arguments before!");
6299 }
6300
6301 // If too many are passed and not variadic, error on the extras and drop
6302 // them.
6303 if (Args.size() > NumParams) {
6304 if (!Proto->isVariadic()) {
6305 TypoCorrection TC;
6306 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6307 unsigned diag_id =
6308 MinArgs == NumParams && !Proto->isVariadic()
6309 ? diag::err_typecheck_call_too_many_args_suggest
6310 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6312 TC, PDiag(diag_id)
6313 << FnKind << NumParams - ExplicitObjectParameterOffset
6314 << static_cast<unsigned>(Args.size()) -
6315 ExplicitObjectParameterOffset
6316 << HasExplicitObjectParameter << TC.getCorrectionRange());
6317 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6318 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6319 ->getDeclName())
6320 Diag(Args[NumParams]->getBeginLoc(),
6321 MinArgs == NumParams
6322 ? diag::err_typecheck_call_too_many_args_one
6323 : diag::err_typecheck_call_too_many_args_at_most_one)
6324 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6325 << static_cast<unsigned>(Args.size()) -
6326 ExplicitObjectParameterOffset
6327 << HasExplicitObjectParameter << Fn->getSourceRange()
6328 << SourceRange(Args[NumParams]->getBeginLoc(),
6329 Args.back()->getEndLoc());
6330 else
6331 Diag(Args[NumParams]->getBeginLoc(),
6332 MinArgs == NumParams
6333 ? diag::err_typecheck_call_too_many_args
6334 : diag::err_typecheck_call_too_many_args_at_most)
6335 << FnKind << NumParams - ExplicitObjectParameterOffset
6336 << static_cast<unsigned>(Args.size()) -
6337 ExplicitObjectParameterOffset
6338 << HasExplicitObjectParameter << Fn->getSourceRange()
6339 << SourceRange(Args[NumParams]->getBeginLoc(),
6340 Args.back()->getEndLoc());
6341
6342 // Emit the location of the prototype.
6343 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6344 Diag(FDecl->getLocation(), diag::note_callee_decl)
6345 << FDecl << FDecl->getParametersSourceRange();
6346
6347 // This deletes the extra arguments.
6348 Call->shrinkNumArgs(NumParams);
6349 return true;
6350 }
6351 }
6352 SmallVector<Expr *, 8> AllArgs;
6353 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6354
6355 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6356 AllArgs, CallType);
6357 if (Invalid)
6358 return true;
6359 unsigned TotalNumArgs = AllArgs.size();
6360 for (unsigned i = 0; i < TotalNumArgs; ++i)
6361 Call->setArg(i, AllArgs[i]);
6362
6363 Call->computeDependence();
6364 return false;
6365}
6366
6368 const FunctionProtoType *Proto,
6369 unsigned FirstParam, ArrayRef<Expr *> Args,
6370 SmallVectorImpl<Expr *> &AllArgs,
6371 VariadicCallType CallType, bool AllowExplicit,
6372 bool IsListInitialization) {
6373 unsigned NumParams = Proto->getNumParams();
6374 bool Invalid = false;
6375 size_t ArgIx = 0;
6376 // Continue to check argument types (even if we have too few/many args).
6377 for (unsigned i = FirstParam; i < NumParams; i++) {
6378 QualType ProtoArgType = Proto->getParamType(i);
6379
6380 Expr *Arg;
6381 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6382 if (ArgIx < Args.size()) {
6383 Arg = Args[ArgIx++];
6384
6385 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6386 diag::err_call_incomplete_argument, Arg))
6387 return true;
6388
6389 // Strip the unbridged-cast placeholder expression off, if applicable.
6390 bool CFAudited = false;
6391 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6392 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6393 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6394 Arg = ObjC().stripARCUnbridgedCast(Arg);
6395 else if (getLangOpts().ObjCAutoRefCount &&
6396 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6397 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6398 CFAudited = true;
6399
6400 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6401 ProtoArgType->isBlockPointerType())
6402 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6403 BE->getBlockDecl()->setDoesNotEscape();
6404 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6406 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6407 if (ArgExpr.isInvalid())
6408 return true;
6409 Arg = ArgExpr.getAs<Expr>();
6410 }
6411
6412 InitializedEntity Entity =
6414 ProtoArgType)
6416 Context, ProtoArgType, Proto->isParamConsumed(i));
6417
6418 // Remember that parameter belongs to a CF audited API.
6419 if (CFAudited)
6420 Entity.setParameterCFAudited();
6421
6422 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6423 // function boundaries is a common oversight.
6424 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6425 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6426 bool isPedantic =
6427 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6428 Diag(Arg->getExprLoc(),
6429 isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6430 : diag::warn_obt_discarded_at_function_boundary)
6431 << Arg->getType() << ProtoArgType;
6432 }
6433
6435 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6436 if (ArgE.isInvalid())
6437 return true;
6438
6439 Arg = ArgE.getAs<Expr>();
6440 } else {
6441 assert(Param && "can't use default arguments without a known callee");
6442
6443 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6444 if (ArgExpr.isInvalid())
6445 return true;
6446
6447 Arg = ArgExpr.getAs<Expr>();
6448 }
6449
6450 // Check for array bounds violations for each argument to the call. This
6451 // check only triggers warnings when the argument isn't a more complex Expr
6452 // with its own checking, such as a BinaryOperator.
6453 CheckArrayAccess(Arg);
6454
6455 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6456 CheckStaticArrayArgument(CallLoc, Param, Arg);
6457
6458 AllArgs.push_back(Arg);
6459 }
6460
6461 // If this is a variadic call, handle args passed through "...".
6462 if (CallType != VariadicCallType::DoesNotApply) {
6463 // Assume that extern "C" functions with variadic arguments that
6464 // return __unknown_anytype aren't *really* variadic.
6465 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6466 FDecl->isExternC()) {
6467 for (Expr *A : Args.slice(ArgIx)) {
6468 QualType paramType; // ignored
6469 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6470 Invalid |= arg.isInvalid();
6471 AllArgs.push_back(arg.get());
6472 }
6473
6474 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6475 } else {
6476 for (Expr *A : Args.slice(ArgIx)) {
6477 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6478 Invalid |= Arg.isInvalid();
6479 AllArgs.push_back(Arg.get());
6480 }
6481 }
6482
6483 // Check for array bounds violations.
6484 for (Expr *A : Args.slice(ArgIx))
6485 CheckArrayAccess(A);
6486 }
6487 return Invalid;
6488}
6489
6491 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6492 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6493 TL = DTL.getOriginalLoc();
6494 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6495 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6496 << ATL.getLocalSourceRange();
6497}
6498
6499void
6501 ParmVarDecl *Param,
6502 const Expr *ArgExpr) {
6503 // Static array parameters are not supported in C++.
6504 if (!Param || getLangOpts().CPlusPlus)
6505 return;
6506
6507 QualType OrigTy = Param->getOriginalType();
6508
6509 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6510 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6511 return;
6512
6513 if (ArgExpr->isNullPointerConstant(Context,
6515 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6516 DiagnoseCalleeStaticArrayParam(*this, Param);
6517 return;
6518 }
6519
6520 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6521 if (!CAT)
6522 return;
6523
6524 const ConstantArrayType *ArgCAT =
6525 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6526 if (!ArgCAT)
6527 return;
6528
6529 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6530 ArgCAT->getElementType())) {
6531 if (ArgCAT->getSize().ult(CAT->getSize())) {
6532 Diag(CallLoc, diag::warn_static_array_too_small)
6533 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6534 << (unsigned)CAT->getZExtSize() << 0;
6535 DiagnoseCalleeStaticArrayParam(*this, Param);
6536 }
6537 return;
6538 }
6539
6540 std::optional<CharUnits> ArgSize =
6542 std::optional<CharUnits> ParmSize =
6544 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6545 Diag(CallLoc, diag::warn_static_array_too_small)
6546 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6547 << (unsigned)ParmSize->getQuantity() << 1;
6548 DiagnoseCalleeStaticArrayParam(*this, Param);
6549 }
6550}
6551
6552/// Given a function expression of unknown-any type, try to rebuild it
6553/// to have a function type.
6555
6556/// Is the given type a placeholder that we need to lower out
6557/// immediately during argument processing?
6559 // Placeholders are never sugared.
6560 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6561 if (!placeholder) return false;
6562
6563 switch (placeholder->getKind()) {
6564 // Ignore all the non-placeholder types.
6565#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6566 case BuiltinType::Id:
6567#include "clang/Basic/OpenCLImageTypes.def"
6568#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6569 case BuiltinType::Id:
6570#include "clang/Basic/OpenCLExtensionTypes.def"
6571 // In practice we'll never use this, since all SVE types are sugared
6572 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6573#define SVE_TYPE(Name, Id, SingletonId) \
6574 case BuiltinType::Id:
6575#include "clang/Basic/AArch64ACLETypes.def"
6576#define PPC_VECTOR_TYPE(Name, Id, Size) \
6577 case BuiltinType::Id:
6578#include "clang/Basic/PPCTypes.def"
6579#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6580#include "clang/Basic/RISCVVTypes.def"
6581#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6582#include "clang/Basic/WebAssemblyReferenceTypes.def"
6583#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6584#include "clang/Basic/AMDGPUTypes.def"
6585#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6586#include "clang/Basic/HLSLIntangibleTypes.def"
6587#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6588#include "clang/Basic/HLSLPackedTypes.def"
6589#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6590#include "clang/Basic/SPIRVTypes.def"
6591#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6592#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6593#include "clang/AST/BuiltinTypes.def"
6594 return false;
6595
6596 case BuiltinType::UnresolvedTemplate:
6597 // We cannot lower out overload sets; they might validly be resolved
6598 // by the call machinery.
6599 case BuiltinType::Overload:
6600 return false;
6601
6602 // Unbridged casts in ARC can be handled in some call positions and
6603 // should be left in place.
6604 case BuiltinType::ARCUnbridgedCast:
6605 return false;
6606
6607 // Pseudo-objects should be converted as soon as possible.
6608 case BuiltinType::PseudoObject:
6609 return true;
6610
6611 // The debugger mode could theoretically but currently does not try
6612 // to resolve unknown-typed arguments based on known parameter types.
6613 case BuiltinType::UnknownAny:
6614 return true;
6615
6616 // These are always invalid as call arguments and should be reported.
6617 case BuiltinType::BoundMember:
6618 case BuiltinType::BuiltinFn:
6619 case BuiltinType::IncompleteMatrixIdx:
6620 case BuiltinType::ArraySection:
6621 case BuiltinType::OMPArrayShaping:
6622 case BuiltinType::OMPIterator:
6623 return true;
6624
6625 }
6626 llvm_unreachable("bad builtin type kind");
6627}
6628
6630 // Apply this processing to all the arguments at once instead of
6631 // dying at the first failure.
6632 bool hasInvalid = false;
6633 for (size_t i = 0, e = args.size(); i != e; i++) {
6634 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6635 ExprResult result = CheckPlaceholderExpr(args[i]);
6636 if (result.isInvalid()) hasInvalid = true;
6637 else args[i] = result.get();
6638 }
6639 }
6640 return hasInvalid;
6641}
6642
6643/// If a builtin function has a pointer argument with no explicit address
6644/// space, then it should be able to accept a pointer to any address
6645/// space as input. In order to do this, we need to replace the
6646/// standard builtin declaration with one that uses the same address space
6647/// as the call.
6648///
6649/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6650/// it does not contain any pointer arguments without
6651/// an address space qualifer. Otherwise the rewritten
6652/// FunctionDecl is returned.
6653/// TODO: Handle pointer return types.
6655 FunctionDecl *FDecl,
6656 MultiExprArg ArgExprs) {
6657
6658 QualType DeclType = FDecl->getType();
6659 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6660
6661 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6662 ArgExprs.size() < FT->getNumParams())
6663 return nullptr;
6664
6665 bool NeedsNewDecl = false;
6666 unsigned i = 0;
6667 SmallVector<QualType, 8> OverloadParams;
6668
6669 {
6670 // The lvalue conversions in this loop are only for type resolution and
6671 // don't actually occur.
6674 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6675
6676 for (QualType ParamType : FT->param_types()) {
6677
6678 // Convert array arguments to pointer to simplify type lookup.
6679 ExprResult ArgRes =
6681 if (ArgRes.isInvalid())
6682 return nullptr;
6683 Expr *Arg = ArgRes.get();
6684 QualType ArgType = Arg->getType();
6685 if (!ParamType->isPointerType() ||
6686 ParamType->getPointeeType().hasAddressSpace() ||
6687 !ArgType->isPointerType() ||
6688 !ArgType->getPointeeType().hasAddressSpace() ||
6689 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6690 OverloadParams.push_back(ParamType);
6691 continue;
6692 }
6693
6694 QualType PointeeType = ParamType->getPointeeType();
6695 NeedsNewDecl = true;
6696 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6697
6698 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6699 OverloadParams.push_back(Context.getPointerType(PointeeType));
6700 }
6701 }
6702
6703 if (!NeedsNewDecl)
6704 return nullptr;
6705
6707 EPI.Variadic = FT->isVariadic();
6708 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6709 OverloadParams, EPI);
6710 DeclContext *Parent = FDecl->getParent();
6711 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6712 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6713 FDecl->getIdentifier(), OverloadTy,
6714 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6715 false,
6716 /*hasPrototype=*/true);
6718 FT = cast<FunctionProtoType>(OverloadTy);
6719 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6720 QualType ParamType = FT->getParamType(i);
6721 ParmVarDecl *Parm =
6722 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6723 SourceLocation(), nullptr, ParamType,
6724 /*TInfo=*/nullptr, SC_None, nullptr);
6725 Parm->setScopeInfo(0, i);
6726 Params.push_back(Parm);
6727 }
6728 OverloadDecl->setParams(Params);
6729 // We cannot merge host/device attributes of redeclarations. They have to
6730 // be consistent when created.
6731 if (Sema->LangOpts.CUDA) {
6732 if (FDecl->hasAttr<CUDAHostAttr>())
6733 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6734 if (FDecl->hasAttr<CUDADeviceAttr>())
6735 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6736 }
6737 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6738 return OverloadDecl;
6739}
6740
6741static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6742 FunctionDecl *Callee,
6743 MultiExprArg ArgExprs) {
6744 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6745 // similar attributes) really don't like it when functions are called with an
6746 // invalid number of args.
6747 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6748 /*PartialOverloading=*/false) &&
6749 !Callee->isVariadic())
6750 return;
6751 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6752 return;
6753
6754 if (const EnableIfAttr *Attr =
6755 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6756 S.Diag(Fn->getBeginLoc(),
6757 isa<CXXMethodDecl>(Callee)
6758 ? diag::err_ovl_no_viable_member_function_in_call
6759 : diag::err_ovl_no_viable_function_in_call)
6760 << Callee << Callee->getSourceRange();
6761 S.Diag(Callee->getLocation(),
6762 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6763 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6764 return;
6765 }
6766}
6767
6769 const UnresolvedMemberExpr *const UME, Sema &S) {
6770
6771 const auto GetFunctionLevelDCIfCXXClass =
6772 [](Sema &S) -> const CXXRecordDecl * {
6773 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6774 if (!DC || !DC->getParent())
6775 return nullptr;
6776
6777 // If the call to some member function was made from within a member
6778 // function body 'M' return return 'M's parent.
6779 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6780 return MD->getParent()->getCanonicalDecl();
6781 // else the call was made from within a default member initializer of a
6782 // class, so return the class.
6783 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6784 return RD->getCanonicalDecl();
6785 return nullptr;
6786 };
6787 // If our DeclContext is neither a member function nor a class (in the
6788 // case of a lambda in a default member initializer), we can't have an
6789 // enclosing 'this'.
6790
6791 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6792 if (!CurParentClass)
6793 return false;
6794
6795 // The naming class for implicit member functions call is the class in which
6796 // name lookup starts.
6797 const CXXRecordDecl *const NamingClass =
6799 assert(NamingClass && "Must have naming class even for implicit access");
6800
6801 // If the unresolved member functions were found in a 'naming class' that is
6802 // related (either the same or derived from) to the class that contains the
6803 // member function that itself contained the implicit member access.
6804
6805 return CurParentClass == NamingClass ||
6806 CurParentClass->isDerivedFrom(NamingClass);
6807}
6808
6809static void
6811 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6812
6813 if (!UME)
6814 return;
6815
6816 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6817 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6818 // already been captured, or if this is an implicit member function call (if
6819 // it isn't, an attempt to capture 'this' should already have been made).
6820 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6821 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6822 return;
6823
6824 // Check if the naming class in which the unresolved members were found is
6825 // related (same as or is a base of) to the enclosing class.
6826
6828 return;
6829
6830
6831 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6832 // If the enclosing function is not dependent, then this lambda is
6833 // capture ready, so if we can capture this, do so.
6834 if (!EnclosingFunctionCtx->isDependentContext()) {
6835 // If the current lambda and all enclosing lambdas can capture 'this' -
6836 // then go ahead and capture 'this' (since our unresolved overload set
6837 // contains at least one non-static member function).
6838 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6839 S.CheckCXXThisCapture(CallLoc);
6840 } else if (S.CurContext->isDependentContext()) {
6841 // ... since this is an implicit member reference, that might potentially
6842 // involve a 'this' capture, mark 'this' for potential capture in
6843 // enclosing lambdas.
6844 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6845 CurLSI->addPotentialThisCapture(CallLoc);
6846 }
6847}
6848
6849// Once a call is fully resolved, warn for unqualified calls to specific
6850// C++ standard functions, like move and forward.
6852 const CallExpr *Call) {
6853 // We are only checking unary move and forward so exit early here.
6854 if (Call->getNumArgs() != 1)
6855 return;
6856
6857 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6858 if (!E || isa<UnresolvedLookupExpr>(E))
6859 return;
6860 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6861 if (!DRE || !DRE->getLocation().isValid())
6862 return;
6863
6864 if (DRE->getQualifier())
6865 return;
6866
6867 const FunctionDecl *FD = Call->getDirectCallee();
6868 if (!FD)
6869 return;
6870
6871 // Only warn for some functions deemed more frequent or problematic.
6872 unsigned BuiltinID = FD->getBuiltinID();
6873 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6874 return;
6875
6876 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6878 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6879}
6880
6882 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6883 Expr *ExecConfig) {
6885 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6886 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6887 if (Call.isInvalid())
6888 return Call;
6889
6890 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6891 // language modes.
6892 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6893 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6894 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6895 << ULE->getName();
6896 }
6897
6898 if (LangOpts.OpenMP)
6899 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6900 ExecConfig);
6901 if (LangOpts.CPlusPlus) {
6902 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6904
6905 // If we previously found that the id-expression of this call refers to a
6906 // consteval function but the call is dependent, we should not treat is an
6907 // an invalid immediate call.
6908 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6909 DRE && Call.get()->isValueDependent()) {
6911 }
6912 }
6913 return Call;
6914}
6915
6916// Any type that could be used to form a callable expression
6917static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6918 QualType T = E->getType();
6919 if (T->isDependentType())
6920 return true;
6921
6922 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6923 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6924 T->isFunctionType() || T->isFunctionReferenceType() ||
6925 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6926 T->isBlockPointerType() || T->isRecordType() || T->isUndeducedType())
6927 return true;
6928
6931}
6932
6934 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6935 Expr *ExecConfig, bool IsExecConfig,
6936 bool AllowRecovery) {
6937 // Since this might be a postfix expression, get rid of ParenListExprs.
6939 if (Result.isInvalid()) return ExprError();
6940 Fn = Result.get();
6941
6942 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6943 // later, when we check boolean conditions, for now we merely forward it
6944 // without any additional checking.
6945 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6946 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6947 const auto *FD = cast<FunctionDecl>(Fn->getReferencedDeclOfCallee());
6948
6949 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6950 QualType FnPtrTy = Context.getPointerType(FD->getType());
6951 Expr *R = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6952 return CallExpr::Create(
6953 Context, R, ArgExprs, Context.AMDGPUFeaturePredicateTy,
6955 }
6956 }
6957
6958 if (CheckArgsForPlaceholders(ArgExprs))
6959 return ExprError();
6960
6961 // The result of __builtin_counted_by_ref cannot be used as a function
6962 // argument. It allows leaking and modification of bounds safety information.
6963 for (const Expr *Arg : ArgExprs)
6964 if (CheckInvalidBuiltinCountedByRef(Arg,
6966 return ExprError();
6967
6968 if (getLangOpts().CPlusPlus) {
6969 // If this is a pseudo-destructor expression, build the call immediately.
6971 if (!ArgExprs.empty()) {
6972 // Pseudo-destructor calls should not have any arguments.
6973 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6975 SourceRange(ArgExprs.front()->getBeginLoc(),
6976 ArgExprs.back()->getEndLoc()));
6977 }
6978
6979 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6980 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6981 }
6982 if (Fn->getType() == Context.PseudoObjectTy) {
6983 ExprResult result = CheckPlaceholderExpr(Fn);
6984 if (result.isInvalid()) return ExprError();
6985 Fn = result.get();
6986 }
6987
6988 // Determine whether this is a dependent call inside a C++ template,
6989 // in which case we won't do any semantic analysis now.
6990 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6991 if (ExecConfig) {
6993 cast<CallExpr>(ExecConfig), ArgExprs,
6994 Context.DependentTy, VK_PRValue,
6995 RParenLoc, CurFPFeatureOverrides());
6996 } else {
6997
6999 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
7000 Fn->getBeginLoc());
7001
7002 // If the type of the function itself is not dependent
7003 // check that it is a reasonable as a function, as type deduction
7004 // later assume the CallExpr has a sensible TYPE.
7005 if (!MayBeFunctionType(Context, Fn))
7006 return ExprError(
7007 Diag(LParenLoc, diag::err_typecheck_call_not_function)
7008 << Fn->getType() << Fn->getSourceRange());
7009
7010 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7011 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7012 }
7013 }
7014
7015 // Determine whether this is a call to an object (C++ [over.call.object]).
7016 if (Fn->getType()->isRecordType())
7017 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
7018 RParenLoc);
7019
7020 if (Fn->getType() == Context.UnknownAnyTy) {
7021 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7022 if (result.isInvalid()) return ExprError();
7023 Fn = result.get();
7024 }
7025
7026 if (Fn->getType() == Context.BoundMemberTy) {
7027 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7028 RParenLoc, ExecConfig, IsExecConfig,
7029 AllowRecovery);
7030 }
7031 }
7032
7033 // Check for overloaded calls. This can happen even in C due to extensions.
7034 if (Fn->getType() == Context.OverloadTy) {
7036
7037 // We aren't supposed to apply this logic if there's an '&' involved.
7040 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7041 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7042 OverloadExpr *ovl = find.Expression;
7043 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
7045 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7046 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
7047 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7048 RParenLoc, ExecConfig, IsExecConfig,
7049 AllowRecovery);
7050 }
7051 }
7052
7053 // If we're directly calling a function, get the appropriate declaration.
7054 if (Fn->getType() == Context.UnknownAnyTy) {
7055 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7056 if (result.isInvalid()) return ExprError();
7057 Fn = result.get();
7058 }
7059
7060 Expr *NakedFn = Fn->IgnoreParens();
7061
7062 bool CallingNDeclIndirectly = false;
7063 NamedDecl *NDecl = nullptr;
7064 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
7065 if (UnOp->getOpcode() == UO_AddrOf) {
7066 CallingNDeclIndirectly = true;
7067 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7068 }
7069 }
7070
7071 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
7072 NDecl = DRE->getDecl();
7073
7074 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
7075 if (FDecl && FDecl->getBuiltinID()) {
7076 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
7077 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
7078 if (Context.BuiltinInfo.isTSBuiltin(FDecl->getBuiltinID()) &&
7079 !Context.BuiltinInfo.isAuxBuiltinID(FDecl->getBuiltinID())) {
7081 getFunctionLevelDeclContext(/*AllowLambda=*/true)));
7082 }
7083 }
7084
7085 // Rewrite the function decl for this builtin by replacing parameters
7086 // with no explicit address space with the address space of the arguments
7087 // in ArgExprs.
7088 if ((FDecl =
7089 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
7090 NDecl = FDecl;
7092 Context, DRE->getQualifierLoc(), SourceLocation(), FDecl, false,
7093 SourceLocation(), Fn->getType() /* BuiltinFnTy */,
7094 Fn->getValueKind(), FDecl, nullptr, DRE->isNonOdrUse());
7095 }
7096 }
7097 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
7098 NDecl = ME->getMemberDecl();
7099
7100 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
7101 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7102 FD, /*Complain=*/true, Fn->getBeginLoc()))
7103 return ExprError();
7104
7105 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
7106
7107 // If this expression is a call to a builtin function in HIP compilation,
7108 // allow a pointer-type argument to default address space to be passed as a
7109 // pointer-type parameter to a non-default address space. If Arg is declared
7110 // in the default address space and Param is declared in a non-default
7111 // address space, perform an implicit address space cast to the parameter
7112 // type.
7113 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
7114 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
7115 ++Idx) {
7116 ParmVarDecl *Param = FD->getParamDecl(Idx);
7117 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7118 !ArgExprs[Idx]->getType()->isPointerType())
7119 continue;
7120
7121 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7122 auto ArgTy = ArgExprs[Idx]->getType();
7123 auto ArgPtTy = ArgTy->getPointeeType();
7124 auto ArgAS = ArgPtTy.getAddressSpace();
7125
7126 // Add address space cast if target address spaces are different
7127 bool NeedImplicitASC =
7128 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7129 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7130 // or from specific AS which has target AS matching that of Param.
7132 if (!NeedImplicitASC)
7133 continue;
7134
7135 // First, ensure that the Arg is an RValue.
7136 if (ArgExprs[Idx]->isGLValue()) {
7137 ExprResult Res = DefaultLvalueConversion(ArgExprs[Idx]);
7138 if (Res.isInvalid())
7139 return ExprError();
7140 ArgExprs[Idx] = Res.get();
7141 }
7142
7143 // Construct a new arg type with address space of Param
7144 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7145 ArgPtQuals.setAddressSpace(ParamAS);
7146 auto NewArgPtTy =
7147 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7148 auto NewArgTy =
7149 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7150 ArgTy.getQualifiers());
7151
7152 // Finally perform an implicit address space cast
7153 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7154 CK_AddressSpaceConversion)
7155 .get();
7156 }
7157 }
7158 }
7159
7160 if (Context.isDependenceAllowed() &&
7161 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7162 assert(!getLangOpts().CPlusPlus);
7163 assert((Fn->containsErrors() ||
7164 llvm::any_of(ArgExprs,
7165 [](clang::Expr *E) { return E->containsErrors(); })) &&
7166 "should only occur in error-recovery path.");
7167 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7168 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7169 }
7170 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7171 ExecConfig, IsExecConfig);
7172}
7173
7175 MultiExprArg CallArgs) {
7176 std::string Name = Context.BuiltinInfo.getName(Id);
7177 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7179 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7180
7181 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7182 assert(BuiltInDecl && "failed to find builtin declaration");
7183
7184 ExprResult DeclRef =
7185 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7186 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7187
7189 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7190
7191 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7192 return Call.get();
7193}
7194
7196 SourceLocation BuiltinLoc,
7197 SourceLocation RParenLoc) {
7198 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7199 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7200}
7201
7203 SourceLocation BuiltinLoc,
7204 SourceLocation RParenLoc) {
7207 QualType SrcTy = E->getType();
7208 if (!SrcTy->isDependentType() &&
7209 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7210 return ExprError(
7211 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7212 << DestTy << SrcTy << E->getSourceRange());
7213 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7214}
7215
7217 SourceLocation BuiltinLoc,
7218 SourceLocation RParenLoc) {
7219 TypeSourceInfo *TInfo;
7220 GetTypeFromParser(ParsedDestTy, &TInfo);
7221 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7222}
7223
7225 SourceLocation LParenLoc,
7226 ArrayRef<Expr *> Args,
7227 SourceLocation RParenLoc, Expr *Config,
7228 bool IsExecConfig, ADLCallKind UsesADL) {
7229 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7230 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7231
7232 auto IsSJLJ = [&] {
7233 switch (BuiltinID) {
7234 case Builtin::BI__builtin_longjmp:
7235 case Builtin::BI__builtin_setjmp:
7236 case Builtin::BI__sigsetjmp:
7237 case Builtin::BI_longjmp:
7238 case Builtin::BI_setjmp:
7239 case Builtin::BIlongjmp:
7240 case Builtin::BIsetjmp:
7241 case Builtin::BIsiglongjmp:
7242 case Builtin::BIsigsetjmp:
7243 return true;
7244 default:
7245 return false;
7246 }
7247 };
7248
7249 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7250 if (!CurrentDefer.empty() && IsSJLJ()) {
7251 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7252 // for more than just blocks (e.g. lambdas, nested classes...).
7253 Scope *DeferParent = CurrentDefer.back().first;
7254 Scope *Block = CurScope->getBlockParent();
7255 if (DeferParent->Contains(*CurScope) &&
7256 (!Block || !DeferParent->Contains(*Block)))
7257 Diag(Fn->getExprLoc(), diag::err_defer_invalid_sjlj) << FDecl;
7258 }
7259
7260 // Functions with 'interrupt' attribute cannot be called directly.
7261 if (FDecl) {
7262 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7263 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7264 return ExprError();
7265 }
7266 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7267 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
7268 return ExprError();
7269 }
7270 }
7271
7272 // X86 interrupt handlers may only call routines with attribute
7273 // no_caller_saved_registers since there is no efficient way to
7274 // save and restore the non-GPR state.
7275 if (auto *Caller = getCurFunctionDecl()) {
7276 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7277 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7278 const TargetInfo &TI = Context.getTargetInfo();
7279 bool HasNonGPRRegisters =
7280 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
7281 if (HasNonGPRRegisters &&
7282 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7283 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
7284 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7285 if (FDecl)
7286 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7287 }
7288 }
7289 }
7290
7291 // Extract the return type from the builtin function pointer type.
7292 QualType ResultTy;
7293 if (BuiltinID)
7294 ResultTy = FDecl->getCallResultType();
7295 else
7296 ResultTy = Context.BoolTy;
7297
7298 // Promote the function operand.
7299 // We special-case function promotion here because we only allow promoting
7300 // builtin functions to function pointers in the callee of a call.
7302 if (BuiltinID &&
7303 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7304 // FIXME Several builtins still have setType in
7305 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7306 // Builtins.td to ensure they are correct before removing setType calls.
7307 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7308 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7309 } else
7311 if (Result.isInvalid())
7312 return ExprError();
7313 Fn = Result.get();
7314
7315 // Check for a valid function type, but only if it is not a builtin which
7316 // requires custom type checking. These will be handled by
7317 // CheckBuiltinFunctionCall below just after creation of the call expression.
7318 const FunctionType *FuncT = nullptr;
7319 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7320 retry:
7321 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7322 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7323 // have type pointer to function".
7324 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7325 if (!FuncT)
7326 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7327 << Fn->getType() << Fn->getSourceRange());
7328 } else if (const BlockPointerType *BPT =
7329 Fn->getType()->getAs<BlockPointerType>()) {
7330 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7331 } else {
7332 // Handle calls to expressions of unknown-any type.
7333 if (Fn->getType() == Context.UnknownAnyTy) {
7334 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7335 if (rewrite.isInvalid())
7336 return ExprError();
7337 Fn = rewrite.get();
7338 goto retry;
7339 }
7340
7341 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7342 << Fn->getType() << Fn->getSourceRange());
7343 }
7344 }
7345
7346 // Get the number of parameters in the function prototype, if any.
7347 // We will allocate space for max(Args.size(), NumParams) arguments
7348 // in the call expression.
7349 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7350 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7351
7352 CallExpr *TheCall;
7353 if (Config) {
7354 assert(UsesADL == ADLCallKind::NotADL &&
7355 "CUDAKernelCallExpr should not use ADL");
7356 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7357 Args, ResultTy, VK_PRValue, RParenLoc,
7358 CurFPFeatureOverrides(), NumParams);
7359 } else {
7360 TheCall =
7361 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7362 CurFPFeatureOverrides(), NumParams, UsesADL);
7363 }
7364
7365 // Bail out early if calling a builtin with custom type checking.
7366 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7367 // For HLSL builtin aliases, the call was resolved via overload resolution
7368 // which may have selected a conversion sequence (e.g., vector-to-scalar
7369 // truncation). Convert arguments to match the declared prototype before
7370 // the custom type checker runs, otherwise the builtin will operate on
7371 // the unconverted argument types.
7372 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7373 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7374 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, P, Args, RParenLoc,
7375 IsExecConfig))
7376 return ExprError();
7377 }
7378 }
7379 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7380 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
7381 E = CheckForImmediateInvocation(E, FDecl);
7382 return E;
7383 }
7384
7385 if (getLangOpts().CUDA) {
7386 if (Config) {
7387 // CUDA: Kernel calls must be to global functions
7388 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7389 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7390 << FDecl << Fn->getSourceRange());
7391
7392 // CUDA: Kernel function must have 'void' return type
7393 if (!FuncT->getReturnType()->isVoidType() &&
7394 !FuncT->getReturnType()->getAs<AutoType>() &&
7396 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7397 << Fn->getType() << Fn->getSourceRange());
7398 } else {
7399 // CUDA: Calls to global functions must be configured
7400 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7401 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7402 << FDecl << Fn->getSourceRange());
7403 }
7404 }
7405
7406 // Check for a valid return type
7407 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7408 FDecl))
7409 return ExprError();
7410
7411 // We know the result type of the call, set it.
7412 TheCall->setType(FuncT->getCallResultType(Context));
7414
7415 // WebAssembly tables can't be used as arguments.
7416 if (Context.getTargetInfo().getTriple().isWasm()) {
7417 for (const Expr *Arg : Args) {
7418 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7419 return ExprError(Diag(Arg->getExprLoc(),
7420 diag::err_wasm_table_as_function_parameter));
7421 }
7422 }
7423 }
7424
7425 // Check read_image{i|ui} sampler argument before ConvertArgumentsForCall
7426 // replaces sampler DeclRefExprs with their integer initializers.
7427 if (getLangOpts().OpenCL && FDecl) {
7428 OpenCL().checkBuiltinReadImage(FDecl, TheCall);
7429 }
7430
7431 if (Proto) {
7432 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7433 IsExecConfig))
7434 return ExprError();
7435 } else {
7436 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7437
7438 if (FDecl) {
7439 // Check if we have too few/too many template arguments, based
7440 // on our knowledge of the function definition.
7441 const FunctionDecl *Def = nullptr;
7442 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7443 Proto = Def->getType()->getAs<FunctionProtoType>();
7444 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7445 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7446 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7447 }
7448
7449 // If the function we're calling isn't a function prototype, but we have
7450 // a function prototype from a prior declaratiom, use that prototype.
7451 if (!FDecl->hasPrototype())
7452 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7453 }
7454
7455 // If we still haven't found a prototype to use but there are arguments to
7456 // the call, diagnose this as calling a function without a prototype.
7457 // However, if we found a function declaration, check to see if
7458 // -Wdeprecated-non-prototype was disabled where the function was declared.
7459 // If so, we will silence the diagnostic here on the assumption that this
7460 // interface is intentional and the user knows what they're doing. We will
7461 // also silence the diagnostic if there is a function declaration but it
7462 // was implicitly defined (the user already gets diagnostics about the
7463 // creation of the implicit function declaration, so the additional warning
7464 // is not helpful).
7465 if (!Proto && !Args.empty() &&
7466 (!FDecl || (!FDecl->isImplicit() &&
7467 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7468 FDecl->getLocation()))))
7469 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7470 << (FDecl != nullptr) << FDecl;
7471
7472 // Promote the arguments (C99 6.5.2.2p6).
7473 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7474 Expr *Arg = Args[i];
7475
7476 if (Proto && i < Proto->getNumParams()) {
7478 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7479 ExprResult ArgE =
7481 if (ArgE.isInvalid())
7482 return true;
7483
7484 Arg = ArgE.getAs<Expr>();
7485
7486 } else {
7488
7489 if (ArgE.isInvalid())
7490 return true;
7491
7492 Arg = ArgE.getAs<Expr>();
7493 }
7494
7495 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7496 diag::err_call_incomplete_argument, Arg))
7497 return ExprError();
7498
7499 TheCall->setArg(i, Arg);
7500 }
7501 TheCall->computeDependence();
7502 }
7503
7504 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7505 if (Method->isImplicitObjectMemberFunction())
7506 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7507 << Fn->getSourceRange() << 0);
7508
7509 // Check for sentinels
7510 if (NDecl)
7511 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7512
7513 // Warn for unions passing across security boundary (CMSE).
7514 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7515 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7516 if (const auto *RT =
7517 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7518 if (RT->getDecl()->isOrContainsUnion())
7519 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7520 << 0 << i;
7521 }
7522 }
7523 }
7524
7525 // Do special checking on direct calls to functions.
7526 if (FDecl) {
7527 if (CheckFunctionCall(FDecl, TheCall, Proto))
7528 return ExprError();
7529
7530 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7531 checkFortifiedLibcArgument(FDecl, TheCall);
7532
7533 if (BuiltinID)
7534 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7535 } else if (NDecl) {
7536 if (CheckPointerCall(NDecl, TheCall, Proto))
7537 return ExprError();
7538 } else {
7539 if (CheckOtherCall(TheCall, Proto))
7540 return ExprError();
7541 }
7542
7543 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7544}
7545
7548 SourceLocation RParenLoc, Expr *InitExpr) {
7549 assert(Ty && "ActOnCompoundLiteral(): missing type");
7550 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7551
7552 TypeSourceInfo *TInfo;
7553 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7554 if (!TInfo)
7555 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7556
7557 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7558}
7559
7562 SourceLocation RParenLoc, Expr *LiteralExpr) {
7563 QualType literalType = TInfo->getType();
7564
7565 if (literalType->isArrayType()) {
7567 LParenLoc, Context.getBaseElementType(literalType),
7568 diag::err_array_incomplete_or_sizeless_type,
7569 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7570 return ExprError();
7571 if (literalType->isVariableArrayType()) {
7572 // C23 6.7.10p4: An entity of variable length array type shall not be
7573 // initialized except by an empty initializer.
7574 //
7575 // The C extension warnings are issued from ParseBraceInitializer() and
7576 // do not need to be issued here. However, we continue to issue an error
7577 // in the case there are initializers or we are compiling C++. We allow
7578 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7579 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7580 // FIXME: should we allow this construct in C++ when it makes sense to do
7581 // so?
7582 //
7583 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7584 // shall specify an object type or an array of unknown size, but not a
7585 // variable length array type. This seems odd, as it allows 'int a[size] =
7586 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7587 // says, this is what's implemented here for C (except for the extension
7588 // that permits constant foldable size arrays)
7589
7590 auto diagID = LangOpts.CPlusPlus
7591 ? diag::err_variable_object_no_init
7592 : diag::err_compound_literal_with_vla_type;
7593 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7594 diagID))
7595 return ExprError();
7596 }
7597 } else if (!literalType->isDependentType() &&
7598 RequireCompleteType(LParenLoc, literalType,
7599 diag::err_typecheck_decl_incomplete_type,
7600 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7601 return ExprError();
7602
7603 InitializedEntity Entity
7607 SourceRange(LParenLoc, RParenLoc),
7608 /*InitList=*/true);
7609 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7610 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7611 &literalType);
7612 if (Result.isInvalid())
7613 return ExprError();
7614 LiteralExpr = Result.get();
7615
7616 // We treat the compound literal as being at file scope if it's not in a
7617 // function or method body, or within the function's prototype scope. This
7618 // means the following compound literal is not at file scope:
7619 // void func(char *para[(int [1]){ 0 }[0]);
7620 const Scope *S = getCurScope();
7621 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7622 !S->isInCFunctionScope() &&
7623 (!S || !S->isFunctionPrototypeScope());
7624
7625 // In C, compound literals are l-values for some reason.
7626 // For GCC compatibility, in C++, file-scope array compound literals with
7627 // constant initializers are also l-values, and compound literals are
7628 // otherwise prvalues.
7629 //
7630 // (GCC also treats C++ list-initialized file-scope array prvalues with
7631 // constant initializers as l-values, but that's non-conforming, so we don't
7632 // follow it there.)
7633 //
7634 // FIXME: It would be better to handle the lvalue cases as materializing and
7635 // lifetime-extending a temporary object, but our materialized temporaries
7636 // representation only supports lifetime extension from a variable, not "out
7637 // of thin air".
7638 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7639 // is bound to the result of applying array-to-pointer decay to the compound
7640 // literal.
7641 // FIXME: GCC supports compound literals of reference type, which should
7642 // obviously have a value kind derived from the kind of reference involved.
7644 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7645 ? VK_PRValue
7646 : VK_LValue;
7647
7648 // C99 6.5.2.5
7649 // "If the compound literal occurs outside the body of a function, the
7650 // initializer list shall consist of constant expressions."
7651 if (IsFileScope)
7652 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7653 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7654 Expr *Init = ILE->getInit(i);
7655 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7656 !Init->isConstantInitializer(Context)) {
7657 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7658 << Init->getSourceBitField();
7659 return ExprError();
7660 }
7661
7662 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7663 }
7664
7665 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7666 LiteralExpr, IsFileScope);
7667 if (IsFileScope) {
7668 if (!LiteralExpr->isTypeDependent() &&
7669 !LiteralExpr->isValueDependent() &&
7670 !literalType->isDependentType()) // C99 6.5.2.5p3
7671 if (CheckForConstantInitializer(LiteralExpr))
7672 return ExprError();
7673 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7674 literalType.getAddressSpace() != LangAS::Default) {
7675 // Embedded-C extensions to C99 6.5.2.5:
7676 // "If the compound literal occurs inside the body of a function, the
7677 // type name shall not be qualified by an address-space qualifier."
7678 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7679 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7680 return ExprError();
7681 }
7682
7683 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7684 // Compound literals that have automatic storage duration are destroyed at
7685 // the end of the scope in C; in C++, they're just temporaries.
7686
7687 // Emit diagnostics if it is or contains a C union type that is non-trivial
7688 // to destruct.
7693
7694 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7695 Cleanup.setExprNeedsCleanups(true);
7696 ExprCleanupObjects.push_back(E);
7697 if (literalType.isDestructedType()) {
7699 }
7700 }
7701
7704 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7705 E->getInitializer()->getExprLoc());
7706
7707 return MaybeBindToTemporary(E);
7708}
7709
7712 SourceLocation RBraceLoc) {
7713 // Only produce each kind of designated initialization diagnostic once.
7714 SourceLocation FirstDesignator;
7715 bool DiagnosedArrayDesignator = false;
7716 bool DiagnosedNestedDesignator = false;
7717 bool DiagnosedMixedDesignator = false;
7718
7719 // Check that any designated initializers are syntactically valid in the
7720 // current language mode.
7721 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7722 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7723 if (FirstDesignator.isInvalid())
7724 FirstDesignator = DIE->getBeginLoc();
7725
7726 if (!getLangOpts().CPlusPlus)
7727 break;
7728
7729 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7730 DiagnosedNestedDesignator = true;
7731 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7732 << DIE->getDesignatorsSourceRange();
7733 }
7734
7735 for (auto &Desig : DIE->designators()) {
7736 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7737 DiagnosedArrayDesignator = true;
7738 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7739 << Desig.getSourceRange();
7740 }
7741 }
7742
7743 if (!DiagnosedMixedDesignator &&
7744 !isa<DesignatedInitExpr>(InitArgList[0])) {
7745 DiagnosedMixedDesignator = true;
7746 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7747 << DIE->getSourceRange();
7748 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7749 << InitArgList[0]->getSourceRange();
7750 }
7751 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7752 isa<DesignatedInitExpr>(InitArgList[0])) {
7753 DiagnosedMixedDesignator = true;
7754 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7755 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7756 << DIE->getSourceRange();
7757 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7758 << InitArgList[I]->getSourceRange();
7759 }
7760 }
7761
7762 if (FirstDesignator.isValid()) {
7763 // Only diagnose designated initiaization as a C++20 extension if we didn't
7764 // already diagnose use of (non-C++20) C99 designator syntax.
7765 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7766 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7767 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7768 ? diag::warn_cxx17_compat_designated_init
7769 : diag::ext_cxx_designated_init);
7770 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7771 Diag(FirstDesignator, diag::ext_designated_init);
7772 }
7773 }
7774
7775 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7776}
7777
7779 MultiExprArg InitArgList,
7780 SourceLocation RBraceLoc, bool IsExplicit) {
7781 // Semantic analysis for initializers is done by ActOnDeclarator() and
7782 // CheckInitializer() - it requires knowledge of the object being initialized.
7783
7784 // Immediately handle non-overload placeholders. Overloads can be
7785 // resolved contextually, but everything else here can't.
7786 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7787 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7788 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7789
7790 // Ignore failures; dropping the entire initializer list because
7791 // of one failure would be terrible for indexing/etc.
7792 if (result.isInvalid()) continue;
7793
7794 InitArgList[I] = result.get();
7795 }
7796 }
7797
7798 InitListExpr *E = new (Context)
7799 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7800 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7801 return E;
7802}
7803
7805 assert(E.get()->getType()->isBlockPointerType());
7806 assert(E.get()->isPRValue());
7807
7808 // Only do this in an r-value context.
7809 if (!getLangOpts().ObjCAutoRefCount) return;
7810
7812 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7813 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7814 Cleanup.setExprNeedsCleanups(true);
7815}
7816
7818 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7819 // Also, callers should have filtered out the invalid cases with
7820 // pointers. Everything else should be possible.
7821
7822 QualType SrcTy = Src.get()->getType();
7823 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7824 return CK_NoOp;
7825
7826 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7828 llvm_unreachable("member pointer type in C");
7829
7830 case Type::STK_CPointer:
7833 switch (DestTy->getScalarTypeKind()) {
7834 case Type::STK_CPointer: {
7835 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7836 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7837 if (SrcAS != DestAS)
7838 return CK_AddressSpaceConversion;
7839 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7840 return CK_NoOp;
7841 return CK_BitCast;
7842 }
7844 return (SrcKind == Type::STK_BlockPointer
7845 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7847 if (SrcKind == Type::STK_ObjCObjectPointer)
7848 return CK_BitCast;
7849 if (SrcKind == Type::STK_CPointer)
7850 return CK_CPointerToObjCPointerCast;
7852 return CK_BlockPointerToObjCPointerCast;
7853 case Type::STK_Bool:
7854 return CK_PointerToBoolean;
7855 case Type::STK_Integral:
7856 return CK_PointerToIntegral;
7857 case Type::STK_Floating:
7862 llvm_unreachable("illegal cast from pointer");
7863 }
7864 llvm_unreachable("Should have returned before this");
7865
7867 switch (DestTy->getScalarTypeKind()) {
7869 return CK_FixedPointCast;
7870 case Type::STK_Bool:
7871 return CK_FixedPointToBoolean;
7872 case Type::STK_Integral:
7873 return CK_FixedPointToIntegral;
7874 case Type::STK_Floating:
7875 return CK_FixedPointToFloating;
7878 Diag(Src.get()->getExprLoc(),
7879 diag::err_unimplemented_conversion_with_fixed_point_type)
7880 << DestTy;
7881 return CK_IntegralCast;
7882 case Type::STK_CPointer:
7886 llvm_unreachable("illegal cast to pointer type");
7887 }
7888 llvm_unreachable("Should have returned before this");
7889
7890 case Type::STK_Bool: // casting from bool is like casting from an integer
7891 case Type::STK_Integral:
7892 switch (DestTy->getScalarTypeKind()) {
7893 case Type::STK_CPointer:
7898 return CK_NullToPointer;
7899 return CK_IntegralToPointer;
7900 case Type::STK_Bool:
7901 return CK_IntegralToBoolean;
7902 case Type::STK_Integral:
7903 return CK_IntegralCast;
7904 case Type::STK_Floating:
7905 return CK_IntegralToFloating;
7907 Src = ImpCastExprToType(Src.get(),
7908 DestTy->castAs<ComplexType>()->getElementType(),
7909 CK_IntegralCast);
7910 return CK_IntegralRealToComplex;
7912 Src = ImpCastExprToType(Src.get(),
7913 DestTy->castAs<ComplexType>()->getElementType(),
7914 CK_IntegralToFloating);
7915 return CK_FloatingRealToComplex;
7917 llvm_unreachable("member pointer type in C");
7919 return CK_IntegralToFixedPoint;
7920 }
7921 llvm_unreachable("Should have returned before this");
7922
7923 case Type::STK_Floating:
7924 switch (DestTy->getScalarTypeKind()) {
7925 case Type::STK_Floating:
7926 return CK_FloatingCast;
7927 case Type::STK_Bool:
7928 return CK_FloatingToBoolean;
7929 case Type::STK_Integral:
7930 return CK_FloatingToIntegral;
7932 Src = ImpCastExprToType(Src.get(),
7933 DestTy->castAs<ComplexType>()->getElementType(),
7934 CK_FloatingCast);
7935 return CK_FloatingRealToComplex;
7937 Src = ImpCastExprToType(Src.get(),
7938 DestTy->castAs<ComplexType>()->getElementType(),
7939 CK_FloatingToIntegral);
7940 return CK_IntegralRealToComplex;
7941 case Type::STK_CPointer:
7944 llvm_unreachable("valid float->pointer cast?");
7946 llvm_unreachable("member pointer type in C");
7948 return CK_FloatingToFixedPoint;
7949 }
7950 llvm_unreachable("Should have returned before this");
7951
7953 switch (DestTy->getScalarTypeKind()) {
7955 return CK_FloatingComplexCast;
7957 return CK_FloatingComplexToIntegralComplex;
7958 case Type::STK_Floating: {
7959 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7960 if (Context.hasSameType(ET, DestTy))
7961 return CK_FloatingComplexToReal;
7962 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7963 return CK_FloatingCast;
7964 }
7965 case Type::STK_Bool:
7966 return CK_FloatingComplexToBoolean;
7967 case Type::STK_Integral:
7968 Src = ImpCastExprToType(Src.get(),
7969 SrcTy->castAs<ComplexType>()->getElementType(),
7970 CK_FloatingComplexToReal);
7971 return CK_FloatingToIntegral;
7972 case Type::STK_CPointer:
7975 llvm_unreachable("valid complex float->pointer cast?");
7977 llvm_unreachable("member pointer type in C");
7979 Diag(Src.get()->getExprLoc(),
7980 diag::err_unimplemented_conversion_with_fixed_point_type)
7981 << SrcTy;
7982 return CK_IntegralCast;
7983 }
7984 llvm_unreachable("Should have returned before this");
7985
7987 switch (DestTy->getScalarTypeKind()) {
7989 return CK_IntegralComplexToFloatingComplex;
7991 return CK_IntegralComplexCast;
7992 case Type::STK_Integral: {
7993 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7994 if (Context.hasSameType(ET, DestTy))
7995 return CK_IntegralComplexToReal;
7996 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7997 return CK_IntegralCast;
7998 }
7999 case Type::STK_Bool:
8000 return CK_IntegralComplexToBoolean;
8001 case Type::STK_Floating:
8002 Src = ImpCastExprToType(Src.get(),
8003 SrcTy->castAs<ComplexType>()->getElementType(),
8004 CK_IntegralComplexToReal);
8005 return CK_IntegralToFloating;
8006 case Type::STK_CPointer:
8009 llvm_unreachable("valid complex int->pointer cast?");
8011 llvm_unreachable("member pointer type in C");
8013 Diag(Src.get()->getExprLoc(),
8014 diag::err_unimplemented_conversion_with_fixed_point_type)
8015 << SrcTy;
8016 return CK_IntegralCast;
8017 }
8018 llvm_unreachable("Should have returned before this");
8019 }
8020
8021 llvm_unreachable("Unhandled scalar cast");
8022}
8023
8024static bool breakDownVectorType(QualType type, uint64_t &len,
8025 QualType &eltType) {
8026 // Vectors are simple.
8027 if (const VectorType *vecType = type->getAs<VectorType>()) {
8028 len = vecType->getNumElements();
8029 eltType = vecType->getElementType();
8030 assert(eltType->isScalarType() || eltType->isMFloat8Type());
8031 return true;
8032 }
8033
8034 // We allow lax conversion to and from non-vector types, but only if
8035 // they're real types (i.e. non-complex, non-pointer scalar types).
8036 if (!type->isRealType()) return false;
8037
8038 len = 1;
8039 eltType = type;
8040 return true;
8041}
8042
8044 assert(srcTy->isVectorType() || destTy->isVectorType());
8045
8046 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8047 if (!FirstType->isSVESizelessBuiltinType())
8048 return false;
8049
8050 const auto *VecTy = SecondType->getAs<VectorType>();
8051 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
8052 };
8053
8054 return ValidScalableConversion(srcTy, destTy) ||
8055 ValidScalableConversion(destTy, srcTy);
8056}
8057
8059 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8060 return false;
8061
8062 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8063 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8064
8065 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8066 matSrcType->getNumColumns() == matDestType->getNumColumns();
8067}
8068
8070 assert(DestTy->isVectorType() || SrcTy->isVectorType());
8071
8072 uint64_t SrcLen, DestLen;
8073 QualType SrcEltTy, DestEltTy;
8074 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
8075 return false;
8076 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
8077 return false;
8078
8079 // ASTContext::getTypeSize will return the size rounded up to a
8080 // power of 2, so instead of using that, we need to use the raw
8081 // element size multiplied by the element count.
8082 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
8083 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
8084
8085 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8086}
8087
8089 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
8090 "expected at least one type to be a vector here");
8091
8092 bool IsSrcTyAltivec =
8093 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8095 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8097 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8099
8100 bool IsDestTyAltivec = DestTy->isVectorType() &&
8101 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8103 (DestTy->castAs<VectorType>()->getVectorKind() ==
8105 (DestTy->castAs<VectorType>()->getVectorKind() ==
8107
8108 return (IsSrcTyAltivec || IsDestTyAltivec);
8109}
8110
8112 assert(destTy->isVectorType() || srcTy->isVectorType());
8113
8114 // Disallow lax conversions between scalars and ExtVectors (these
8115 // conversions are allowed for other vector types because common headers
8116 // depend on them). Most scalar OP ExtVector cases are handled by the
8117 // splat path anyway, which does what we want (convert, not bitcast).
8118 // What this rules out for ExtVectors is crazy things like char4*float.
8119 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8120 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8121
8122 return areVectorTypesSameSize(srcTy, destTy);
8123}
8124
8126 assert(destTy->isVectorType() || srcTy->isVectorType());
8127
8128 switch (Context.getLangOpts().getLaxVectorConversions()) {
8130 return false;
8131
8133 if (!srcTy->isIntegralOrEnumerationType()) {
8134 auto *Vec = srcTy->getAs<VectorType>();
8135 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8136 return false;
8137 }
8138 if (!destTy->isIntegralOrEnumerationType()) {
8139 auto *Vec = destTy->getAs<VectorType>();
8140 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8141 return false;
8142 }
8143 // OK, integer (vector) -> integer (vector) bitcast.
8144 break;
8145
8147 break;
8148 }
8149
8150 return areLaxCompatibleVectorTypes(srcTy, destTy);
8151}
8152
8154 CastKind &Kind) {
8155 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8156 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8157 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8158 << DestTy << SrcTy << R;
8159 }
8160 } else if (SrcTy->isMatrixType()) {
8161 return Diag(R.getBegin(),
8162 diag::err_invalid_conversion_between_matrix_and_type)
8163 << SrcTy << DestTy << R;
8164 } else if (DestTy->isMatrixType()) {
8165 return Diag(R.getBegin(),
8166 diag::err_invalid_conversion_between_matrix_and_type)
8167 << DestTy << SrcTy << R;
8168 }
8169
8170 Kind = CK_MatrixCast;
8171 return false;
8172}
8173
8175 CastKind &Kind) {
8176 assert(VectorTy->isVectorType() && "Not a vector type!");
8177
8178 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8179 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8180 return Diag(R.getBegin(),
8181 Ty->isVectorType() ?
8182 diag::err_invalid_conversion_between_vectors :
8183 diag::err_invalid_conversion_between_vector_and_integer)
8184 << VectorTy << Ty << R;
8185 } else
8186 return Diag(R.getBegin(),
8187 diag::err_invalid_conversion_between_vector_and_scalar)
8188 << VectorTy << Ty << R;
8189
8190 Kind = CK_BitCast;
8191 return false;
8192}
8193
8195 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8196
8197 if (DestElemTy == SplattedExpr->getType())
8198 return SplattedExpr;
8199
8200 assert(DestElemTy->isFloatingType() ||
8201 DestElemTy->isIntegralOrEnumerationType());
8202
8203 CastKind CK;
8204 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8205 // OpenCL requires that we convert `true` boolean expressions to -1, but
8206 // only when splatting vectors.
8207 if (DestElemTy->isFloatingType()) {
8208 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8209 // in two steps: boolean to signed integral, then to floating.
8210 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8211 CK_BooleanToSignedIntegral);
8212 SplattedExpr = CastExprRes.get();
8213 CK = CK_IntegralToFloating;
8214 } else {
8215 CK = CK_BooleanToSignedIntegral;
8216 }
8217 } else {
8218 ExprResult CastExprRes = SplattedExpr;
8219 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8220 if (CastExprRes.isInvalid())
8221 return ExprError();
8222 SplattedExpr = CastExprRes.get();
8223 }
8224 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8225}
8226
8228 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8229
8230 if (DestElemTy == SplattedExpr->getType())
8231 return SplattedExpr;
8232
8233 assert(DestElemTy->isFloatingType() ||
8234 DestElemTy->isIntegralOrEnumerationType());
8235
8236 ExprResult CastExprRes = SplattedExpr;
8237 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
8238 if (CastExprRes.isInvalid())
8239 return ExprError();
8240 SplattedExpr = CastExprRes.get();
8241
8242 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8243}
8244
8246 Expr *CastExpr, CastKind &Kind) {
8247 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8248
8249 QualType SrcTy = CastExpr->getType();
8250
8251 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8252 // an ExtVectorType.
8253 // In OpenCL, casts between vectors of different types are not allowed.
8254 // (See OpenCL 6.2).
8255 if (SrcTy->isVectorType()) {
8256 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8257 (getLangOpts().OpenCL &&
8258 !Context.hasSameUnqualifiedType(DestTy, SrcTy) &&
8259 !Context.areCompatibleVectorTypes(DestTy, SrcTy))) {
8260 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8261 << DestTy << SrcTy << R;
8262 return ExprError();
8263 }
8264 Kind = CK_BitCast;
8265 return CastExpr;
8266 }
8267
8268 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8269 // conversion will take place first from scalar to elt type, and then
8270 // splat from elt type to vector.
8271 if (SrcTy->isPointerType())
8272 return Diag(R.getBegin(),
8273 diag::err_invalid_conversion_between_vector_and_scalar)
8274 << DestTy << SrcTy << R;
8275
8276 Kind = CK_VectorSplat;
8277 return prepareVectorSplat(DestTy, CastExpr);
8278}
8279
8280/// Check that a call to alloc_size function specifies sufficient space for the
8281/// destination type.
8282static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8283 const Expr *E) {
8284 QualType SourceType = E->getType();
8285 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8286 DestType == SourceType)
8287 return;
8288
8289 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
8290 if (!CE)
8291 return;
8292
8293 // Find the total size allocated by the function call.
8294 if (!CE->getCalleeAllocSizeAttr())
8295 return;
8296 std::optional<llvm::APInt> AllocSize =
8297 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
8298 // Allocations of size zero are permitted as a special case. They are usually
8299 // done intentionally.
8300 if (!AllocSize || AllocSize->isZero())
8301 return;
8302 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
8303
8304 QualType TargetType = DestType->getPointeeType();
8305 // Find the destination size. As a special case function types have size of
8306 // one byte to match the sizeof operator behavior.
8307 auto LhsSize = TargetType->isFunctionType()
8308 ? CharUnits::One()
8309 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
8310 if (LhsSize && Size < LhsSize)
8311 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
8312 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8313}
8314
8317 Declarator &D, ParsedType &Ty,
8318 SourceLocation RParenLoc, Expr *CastExpr) {
8319 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8320 "ActOnCastExpr(): missing type or expr");
8321
8323 if (D.isInvalidType())
8324 return ExprError();
8325
8326 if (getLangOpts().CPlusPlus) {
8327 // Check that there are no default arguments (C++ only).
8329 }
8330
8332
8333 QualType castType = castTInfo->getType();
8334 Ty = CreateParsedType(castType, castTInfo);
8335
8336 bool isVectorLiteral = false;
8337
8338 // Check for an altivec or OpenCL literal,
8339 // i.e. all the elements are integer constants.
8340 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8341 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8342 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8343 && castType->isVectorType() && (PE || PLE)) {
8344 if (PLE && PLE->getNumExprs() == 0) {
8345 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8346 return ExprError();
8347 }
8348 if (PE || PLE->getNumExprs() == 1) {
8349 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8350 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8351 isVectorLiteral = true;
8352 }
8353 else
8354 isVectorLiteral = true;
8355 }
8356
8357 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8358 // then handle it as such.
8359 if (isVectorLiteral)
8360 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8361
8362 // If the Expr being casted is a ParenListExpr, handle it specially.
8363 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8364 // sequence of BinOp comma operators.
8367 if (Result.isInvalid()) return ExprError();
8368 CastExpr = Result.get();
8369 }
8370
8371 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8372 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8373
8375
8377
8379
8380 CheckSufficientAllocSize(*this, castType, CastExpr);
8381
8382 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8383}
8384
8386 SourceLocation RParenLoc, Expr *E,
8387 TypeSourceInfo *TInfo) {
8388 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8389 "Expected paren or paren list expression");
8390
8391 Expr **exprs;
8392 unsigned numExprs;
8393 Expr *subExpr;
8394 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8395 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8396 LiteralLParenLoc = PE->getLParenLoc();
8397 LiteralRParenLoc = PE->getRParenLoc();
8398 exprs = PE->getExprs();
8399 numExprs = PE->getNumExprs();
8400 } else { // isa<ParenExpr> by assertion at function entrance
8401 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8402 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8403 subExpr = cast<ParenExpr>(E)->getSubExpr();
8404 exprs = &subExpr;
8405 numExprs = 1;
8406 }
8407
8408 QualType Ty = TInfo->getType();
8409 assert(Ty->isVectorType() && "Expected vector type");
8410
8411 SmallVector<Expr *, 8> initExprs;
8412 const VectorType *VTy = Ty->castAs<VectorType>();
8413 unsigned numElems = VTy->getNumElements();
8414
8415 // '(...)' form of vector initialization in AltiVec: the number of
8416 // initializers must be one or must match the size of the vector.
8417 // If a single value is specified in the initializer then it will be
8418 // replicated to all the components of the vector
8420 VTy->getElementType()))
8421 return ExprError();
8423 // The number of initializers must be one or must match the size of the
8424 // vector. If a single value is specified in the initializer then it will
8425 // be replicated to all the components of the vector
8426 if (numExprs == 1) {
8427 QualType ElemTy = VTy->getElementType();
8428 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8429 if (Literal.isInvalid())
8430 return ExprError();
8431 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8432 PrepareScalarCast(Literal, ElemTy));
8433 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8434 }
8435 else if (numExprs < numElems) {
8436 Diag(E->getExprLoc(),
8437 diag::err_incorrect_number_of_vector_initializers);
8438 return ExprError();
8439 }
8440 else
8441 initExprs.append(exprs, exprs + numExprs);
8442 }
8443 else {
8444 // For OpenCL, when the number of initializers is a single value,
8445 // it will be replicated to all components of the vector.
8447 numExprs == 1) {
8448 QualType SrcTy = exprs[0]->getType();
8449 if (!SrcTy->isArithmeticType()) {
8450 Diag(exprs[0]->getBeginLoc(), diag::err_typecheck_convert_incompatible)
8451 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8452 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8453 return ExprError();
8454 }
8455 QualType ElemTy = VTy->getElementType();
8456 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8457 if (Literal.isInvalid())
8458 return ExprError();
8459 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8460 PrepareScalarCast(Literal, ElemTy));
8461 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8462 }
8463
8464 initExprs.append(exprs, exprs + numExprs);
8465 }
8466 // FIXME: This means that pretty-printing the final AST will produce curly
8467 // braces instead of the original commas.
8468 InitListExpr *initE =
8469 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8470 LiteralRParenLoc, /*isExplicit=*/false);
8471 initE->setType(Ty);
8472 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8473}
8474
8477 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8478 if (!E)
8479 return OrigExpr;
8480
8481 ExprResult Result(E->getExpr(0));
8482
8483 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8484 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8485 E->getExpr(i));
8486
8487 if (Result.isInvalid()) return ExprError();
8488
8489 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8490}
8491
8497
8499 unsigned NumUserSpecifiedExprs,
8500 SourceLocation InitLoc,
8501 SourceLocation LParenLoc,
8502 SourceLocation RParenLoc) {
8503 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8504 InitLoc, LParenLoc, RParenLoc);
8505}
8506
8507bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8508 SourceLocation QuestionLoc) {
8509 const Expr *NullExpr = LHSExpr;
8510 const Expr *NonPointerExpr = RHSExpr;
8514
8515 if (NullKind == Expr::NPCK_NotNull) {
8516 NullExpr = RHSExpr;
8517 NonPointerExpr = LHSExpr;
8518 NullKind =
8521 }
8522
8523 if (NullKind == Expr::NPCK_NotNull)
8524 return false;
8525
8526 if (NullKind == Expr::NPCK_ZeroExpression)
8527 return false;
8528
8529 if (NullKind == Expr::NPCK_ZeroLiteral) {
8530 // In this case, check to make sure that we got here from a "NULL"
8531 // string in the source code.
8532 NullExpr = NullExpr->IgnoreParenImpCasts();
8533 SourceLocation loc = NullExpr->getExprLoc();
8534 if (!findMacroSpelling(loc, "NULL"))
8535 return false;
8536 }
8537
8538 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8539 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8540 << NonPointerExpr->getType() << DiagType
8541 << NonPointerExpr->getSourceRange();
8542 return true;
8543}
8544
8545/// Return false if the condition expression is valid, true otherwise.
8546static bool checkCondition(Sema &S, const Expr *Cond,
8547 SourceLocation QuestionLoc) {
8548 QualType CondTy = Cond->getType();
8549
8550 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8551 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8552 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8553 << CondTy << Cond->getSourceRange();
8554 return true;
8555 }
8556
8557 // C99 6.5.15p2
8558 if (CondTy->isScalarType()) return false;
8559
8560 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8561 << CondTy << Cond->getSourceRange();
8562 return true;
8563}
8564
8565/// Return false if the NullExpr can be promoted to PointerTy,
8566/// true otherwise.
8568 QualType PointerTy) {
8569 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8570 !NullExpr.get()->isNullPointerConstant(S.Context,
8572 return true;
8573
8574 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8575 return false;
8576}
8577
8578/// Checks compatibility between two pointers and return the resulting
8579/// type.
8581 ExprResult &RHS,
8582 SourceLocation Loc) {
8583 QualType LHSTy = LHS.get()->getType();
8584 QualType RHSTy = RHS.get()->getType();
8585
8586 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8587 // Two identical pointers types are always compatible.
8588 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8589 }
8590
8591 QualType lhptee, rhptee;
8592
8593 // Get the pointee types.
8594 bool IsBlockPointer = false;
8595 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8596 lhptee = LHSBTy->getPointeeType();
8597 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8598 IsBlockPointer = true;
8599 } else {
8600 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8601 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8602 }
8603
8604 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8605 // differently qualified versions of compatible types, the result type is
8606 // a pointer to an appropriately qualified version of the composite
8607 // type.
8608
8609 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8610 // clause doesn't make sense for our extensions. E.g. address space 2 should
8611 // be incompatible with address space 3: they may live on different devices or
8612 // anything.
8613 Qualifiers lhQual = lhptee.getQualifiers();
8614 Qualifiers rhQual = rhptee.getQualifiers();
8615
8616 LangAS ResultAddrSpace = LangAS::Default;
8617 LangAS LAddrSpace = lhQual.getAddressSpace();
8618 LangAS RAddrSpace = rhQual.getAddressSpace();
8619
8620 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8621 // spaces is disallowed.
8622 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8623 ResultAddrSpace = LAddrSpace;
8624 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8625 ResultAddrSpace = RAddrSpace;
8626 else {
8627 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8628 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8629 << RHS.get()->getSourceRange();
8630 return QualType();
8631 }
8632
8633 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8634 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8635 lhQual.removeCVRQualifiers();
8636 rhQual.removeCVRQualifiers();
8637
8638 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8639 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8640 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8641 << RHS.get()->getSourceRange();
8642 return QualType();
8643 }
8644
8645 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8646 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8647 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8648 // qual types are compatible iff
8649 // * corresponded types are compatible
8650 // * CVR qualifiers are equal
8651 // * address spaces are equal
8652 // Thus for conditional operator we merge CVR and address space unqualified
8653 // pointees and if there is a composite type we return a pointer to it with
8654 // merged qualifiers.
8655 LHSCastKind =
8656 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8657 RHSCastKind =
8658 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8659 lhQual.removeAddressSpace();
8660 rhQual.removeAddressSpace();
8661
8662 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8663 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8664
8665 QualType CompositeTy = S.Context.mergeTypes(
8666 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8667 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8668
8669 if (CompositeTy.isNull()) {
8670 // In this situation, we assume void* type. No especially good
8671 // reason, but this is what gcc does, and we do have to pick
8672 // to get a consistent AST.
8673 QualType incompatTy;
8674 incompatTy = S.Context.getPointerType(
8675 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8676 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8677 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8678
8679 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8680 // for casts between types with incompatible address space qualifiers.
8681 // For the following code the compiler produces casts between global and
8682 // local address spaces of the corresponded innermost pointees:
8683 // local int *global *a;
8684 // global int *global *b;
8685 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8686 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8687 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8688 << RHS.get()->getSourceRange();
8689
8690 return incompatTy;
8691 }
8692
8693 // The pointer types are compatible.
8694 // In case of OpenCL ResultTy should have the address space qualifier
8695 // which is a superset of address spaces of both the 2nd and the 3rd
8696 // operands of the conditional operator.
8697 QualType ResultTy = [&, ResultAddrSpace]() {
8698 if (S.getLangOpts().OpenCL) {
8699 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8700 CompositeQuals.setAddressSpace(ResultAddrSpace);
8701 return S.Context
8702 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8703 .withCVRQualifiers(MergedCVRQual);
8704 }
8705 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8706 }();
8707 if (IsBlockPointer)
8708 ResultTy = S.Context.getBlockPointerType(ResultTy);
8709 else
8710 ResultTy = S.Context.getPointerType(ResultTy);
8711
8712 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8713 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8714 return ResultTy;
8715}
8716
8717/// Return the resulting type when the operands are both block pointers.
8719 ExprResult &LHS,
8720 ExprResult &RHS,
8721 SourceLocation Loc) {
8722 QualType LHSTy = LHS.get()->getType();
8723 QualType RHSTy = RHS.get()->getType();
8724
8725 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8726 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8728 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8729 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8730 return destType;
8731 }
8732 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8733 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8734 << RHS.get()->getSourceRange();
8735 return QualType();
8736 }
8737
8738 // We have 2 block pointer types.
8739 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8740}
8741
8742/// Return the resulting type when the operands are both pointers.
8743static QualType
8745 ExprResult &RHS,
8746 SourceLocation Loc) {
8747 // get the pointer types
8748 QualType LHSTy = LHS.get()->getType();
8749 QualType RHSTy = RHS.get()->getType();
8750
8751 // get the "pointed to" types
8752 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8753 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8754
8755 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8756 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8757 // Figure out necessary qualifiers (C99 6.5.15p6)
8758 QualType destPointee
8759 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8760 QualType destType = S.Context.getPointerType(destPointee);
8761 // Add qualifiers if necessary.
8762 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8763 // Promote to void*.
8764 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8765 return destType;
8766 }
8767 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8768 QualType destPointee
8769 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8770 QualType destType = S.Context.getPointerType(destPointee);
8771 // Add qualifiers if necessary.
8772 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8773 // Promote to void*.
8774 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8775 return destType;
8776 }
8777
8778 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8779}
8780
8781/// Return false if the first expression is not an integer and the second
8782/// expression is not a pointer, true otherwise.
8784 Expr* PointerExpr, SourceLocation Loc,
8785 bool IsIntFirstExpr) {
8786 if (!PointerExpr->getType()->isPointerType() ||
8787 !Int.get()->getType()->isIntegerType())
8788 return false;
8789
8790 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8791 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8792
8793 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8794 << Expr1->getType() << Expr2->getType()
8795 << Expr1->getSourceRange() << Expr2->getSourceRange();
8796 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8797 CK_IntegralToPointer);
8798 return true;
8799}
8800
8801/// Simple conversion between integer and floating point types.
8802///
8803/// Used when handling the OpenCL conditional operator where the
8804/// condition is a vector while the other operands are scalar.
8805///
8806/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8807/// types are either integer or floating type. Between the two
8808/// operands, the type with the higher rank is defined as the "result
8809/// type". The other operand needs to be promoted to the same type. No
8810/// other type promotion is allowed. We cannot use
8811/// UsualArithmeticConversions() for this purpose, since it always
8812/// promotes promotable types.
8814 ExprResult &RHS,
8815 SourceLocation QuestionLoc) {
8817 if (LHS.isInvalid())
8818 return QualType();
8820 if (RHS.isInvalid())
8821 return QualType();
8822
8823 // For conversion purposes, we ignore any qualifiers.
8824 // For example, "const float" and "float" are equivalent.
8825 QualType LHSType =
8827 QualType RHSType =
8829
8830 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8831 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8832 << LHSType << LHS.get()->getSourceRange();
8833 return QualType();
8834 }
8835
8836 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8837 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8838 << RHSType << RHS.get()->getSourceRange();
8839 return QualType();
8840 }
8841
8842 // If both types are identical, no conversion is needed.
8843 if (LHSType == RHSType)
8844 return LHSType;
8845
8846 // Now handle "real" floating types (i.e. float, double, long double).
8847 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8848 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8849 /*IsCompAssign = */ false);
8850
8851 // Finally, we have two differing integer types.
8853 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8854}
8855
8856/// Convert scalar operands to a vector that matches the
8857/// condition in length.
8858///
8859/// Used when handling the OpenCL conditional operator where the
8860/// condition is a vector while the other operands are scalar.
8861///
8862/// We first compute the "result type" for the scalar operands
8863/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8864/// into a vector of that type where the length matches the condition
8865/// vector type. s6.11.6 requires that the element types of the result
8866/// and the condition must have the same number of bits.
8867static QualType
8869 QualType CondTy, SourceLocation QuestionLoc) {
8870 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8871 if (ResTy.isNull()) return QualType();
8872
8873 const VectorType *CV = CondTy->getAs<VectorType>();
8874 assert(CV);
8875
8876 // Determine the vector result type
8877 unsigned NumElements = CV->getNumElements();
8878 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8879
8880 // Ensure that all types have the same number of bits
8882 != S.Context.getTypeSize(ResTy)) {
8883 // Since VectorTy is created internally, it does not pretty print
8884 // with an OpenCL name. Instead, we just print a description.
8885 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8886 SmallString<64> Str;
8887 llvm::raw_svector_ostream OS(Str);
8888 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8889 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8890 << CondTy << OS.str();
8891 return QualType();
8892 }
8893
8894 // Convert operands to the vector result type
8895 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8896 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8897
8898 return VectorTy;
8899}
8900
8901/// Return false if this is a valid OpenCL condition vector
8903 SourceLocation QuestionLoc) {
8904 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8905 // integral type.
8906 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8907 assert(CondTy);
8908 QualType EleTy = CondTy->getElementType();
8909 if (EleTy->isIntegerType()) return false;
8910
8911 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8912 << Cond->getType() << Cond->getSourceRange();
8913 return true;
8914}
8915
8916/// Return false if the vector condition type and the vector
8917/// result type are compatible.
8918///
8919/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8920/// number of elements, and their element types have the same number
8921/// of bits.
8922static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8923 SourceLocation QuestionLoc) {
8924 const VectorType *CV = CondTy->getAs<VectorType>();
8925 const VectorType *RV = VecResTy->getAs<VectorType>();
8926 assert(CV && RV);
8927
8928 if (CV->getNumElements() != RV->getNumElements()) {
8929 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8930 << CondTy << VecResTy;
8931 return true;
8932 }
8933
8934 QualType CVE = CV->getElementType();
8935 QualType RVE = RV->getElementType();
8936
8937 // Boolean vectors are permitted outside of OpenCL mode.
8938 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8939 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8940 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8941 << CondTy << VecResTy;
8942 return true;
8943 }
8944
8945 return false;
8946}
8947
8948/// Return the resulting type for the conditional operator in
8949/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8950/// s6.3.i) when the condition is a vector type.
8951static QualType
8953 ExprResult &LHS, ExprResult &RHS,
8954 SourceLocation QuestionLoc) {
8956 if (Cond.isInvalid())
8957 return QualType();
8958 QualType CondTy = Cond.get()->getType();
8959
8960 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8961 return QualType();
8962
8963 // If either operand is a vector then find the vector type of the
8964 // result as specified in OpenCL v1.1 s6.3.i.
8965 if (LHS.get()->getType()->isVectorType() ||
8966 RHS.get()->getType()->isVectorType()) {
8967 bool IsBoolVecLang =
8968 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8969 QualType VecResTy =
8970 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8971 /*isCompAssign*/ false,
8972 /*AllowBothBool*/ true,
8973 /*AllowBoolConversions*/ false,
8974 /*AllowBooleanOperation*/ IsBoolVecLang);
8975 if (VecResTy.isNull())
8976 return QualType();
8977 // The result type must match the condition type as specified in
8978 // OpenCL v1.1 s6.11.6.
8979 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8980 return QualType();
8981 return VecResTy;
8982 }
8983
8984 // Both operands are scalar.
8985 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8986}
8987
8988/// Return true if the Expr is block type
8989static bool checkBlockType(Sema &S, const Expr *E) {
8990 if (E->getType()->isBlockPointerType()) {
8991 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8992 return true;
8993 }
8994
8995 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8996 QualType Ty = CE->getCallee()->getType();
8997 if (Ty->isBlockPointerType()) {
8998 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8999 return true;
9000 }
9001 }
9002 return false;
9003}
9004
9005/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9006/// In that case, LHS = cond.
9007/// C99 6.5.15
9010 ExprObjectKind &OK,
9011 SourceLocation QuestionLoc) {
9012
9013 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
9014 if (!LHSResult.isUsable()) return QualType();
9015 LHS = LHSResult;
9016
9017 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
9018 if (!RHSResult.isUsable()) return QualType();
9019 RHS = RHSResult;
9020
9021 // C++ is sufficiently different to merit its own checker.
9022 if (getLangOpts().CPlusPlus)
9023 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
9024
9025 VK = VK_PRValue;
9026 OK = OK_Ordinary;
9027
9028 if (Context.isDependenceAllowed() &&
9029 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
9030 RHS.get()->isTypeDependent())) {
9031 assert(!getLangOpts().CPlusPlus);
9032 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
9033 RHS.get()->containsErrors()) &&
9034 "should only occur in error-recovery path.");
9035 return Context.DependentTy;
9036 }
9037
9038 // The OpenCL operator with a vector condition is sufficiently
9039 // different to merit its own checker.
9040 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
9041 Cond.get()->getType()->isExtVectorType())
9042 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
9043
9044 // First, check the condition.
9045 Cond = UsualUnaryConversions(Cond.get());
9046 if (Cond.isInvalid())
9047 return QualType();
9048 if (checkCondition(*this, Cond.get(), QuestionLoc))
9049 return QualType();
9050
9051 // Handle vectors.
9052 if (LHS.get()->getType()->isVectorType() ||
9053 RHS.get()->getType()->isVectorType())
9054 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
9055 /*AllowBothBool*/ true,
9056 /*AllowBoolConversions*/ false,
9057 /*AllowBooleanOperation*/ false);
9058
9059 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
9061 if (LHS.isInvalid() || RHS.isInvalid())
9062 return QualType();
9063
9064 // WebAssembly tables are not allowed as conditional LHS or RHS.
9065 QualType LHSTy = LHS.get()->getType();
9066 QualType RHSTy = RHS.get()->getType();
9067 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
9068 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
9069 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9070 return QualType();
9071 }
9072
9073 // Diagnose attempts to convert between __ibm128, __float128 and long double
9074 // where such conversions currently can't be handled.
9075 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
9076 Diag(QuestionLoc,
9077 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
9078 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9079 return QualType();
9080 }
9081
9082 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9083 // selection operator (?:).
9084 if (getLangOpts().OpenCL &&
9085 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
9086 return QualType();
9087 }
9088
9089 // If both operands have arithmetic type, do the usual arithmetic conversions
9090 // to find a common type: C99 6.5.15p3,5.
9091 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
9092 // Disallow invalid arithmetic conversions, such as those between bit-
9093 // precise integers types of different sizes, or between a bit-precise
9094 // integer and another type.
9095 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9096 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9097 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9098 << RHS.get()->getSourceRange();
9099 return QualType();
9100 }
9101
9102 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
9103 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
9104
9105 return ResTy;
9106 }
9107
9108 // If both operands are the same structure or union type, the result is that
9109 // type.
9110 // FIXME: Type of conditional expression must be complete in C mode.
9111 if (LHSTy->isRecordType() &&
9112 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
9113 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
9114 RHSTy.getUnqualifiedType());
9115
9116 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9117 // The following || allows only one side to be void (a GCC-ism).
9118 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9119 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9120 // UsualArithmeticConversions already handled the case where both sides
9121 // are the same type.
9122 } else if (RHSTy->isVoidType()) {
9123 ResTy = RHSTy;
9124 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9125 << RHS.get()->getSourceRange();
9126 } else {
9127 ResTy = LHSTy;
9128 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9129 << LHS.get()->getSourceRange();
9130 }
9131 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
9132 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
9133 return ResTy;
9134 }
9135
9136 // C23 6.5.15p7:
9137 // ... if both the second and third operands have nullptr_t type, the
9138 // result also has that type.
9139 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
9140 return ResTy;
9141
9142 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9143 // the type of the other operand."
9144 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
9145 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
9146
9147 // All objective-c pointer type analysis is done here.
9148 QualType compositeType =
9149 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9150 if (LHS.isInvalid() || RHS.isInvalid())
9151 return QualType();
9152 if (!compositeType.isNull())
9153 return compositeType;
9154
9155
9156 // Handle block pointer types.
9157 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9158 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9159 QuestionLoc);
9160
9161 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9162 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9163 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9164 QuestionLoc);
9165
9166 // GCC compatibility: soften pointer/integer mismatch. Note that
9167 // null pointers have been filtered out by this point.
9168 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9169 /*IsIntFirstExpr=*/true))
9170 return RHSTy;
9171 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9172 /*IsIntFirstExpr=*/false))
9173 return LHSTy;
9174
9175 // Emit a better diagnostic if one of the expressions is a null pointer
9176 // constant and the other is not a pointer type. In this case, the user most
9177 // likely forgot to take the address of the other expression.
9178 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9179 return QualType();
9180
9181 // Finally, if the LHS and RHS types are canonically the same type, we can
9182 // use the common sugared type.
9183 if (Context.hasSameType(LHSTy, RHSTy))
9184 return Context.getCommonSugaredType(LHSTy, RHSTy);
9185
9186 // Otherwise, the operands are not compatible.
9187 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9188 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9189 << RHS.get()->getSourceRange();
9190 return QualType();
9191}
9192
9193/// SuggestParentheses - Emit a note with a fixit hint that wraps
9194/// ParenRange in parentheses.
9196 const PartialDiagnostic &Note,
9197 SourceRange ParenRange) {
9198 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9199 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9200 EndLoc.isValid()) {
9201 Self.Diag(Loc, Note)
9202 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9203 << FixItHint::CreateInsertion(EndLoc, ")");
9204 } else {
9205 // We can't display the parentheses, so just show the bare note.
9206 Self.Diag(Loc, Note) << ParenRange;
9207 }
9208}
9209
9211 return BinaryOperator::isAdditiveOp(Opc) ||
9213 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9214 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9215 // not any of the logical operators. Bitwise-xor is commonly used as a
9216 // logical-xor because there is no logical-xor operator. The logical
9217 // operators, including uses of xor, have a high false positive rate for
9218 // precedence warnings.
9219}
9220
9221/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9222/// expression, either using a built-in or overloaded operator,
9223/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9224/// expression.
9225static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9226 const Expr **RHSExprs) {
9227 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9228 E = E->IgnoreImpCasts();
9230 E = E->IgnoreImpCasts();
9231 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9232 E = MTE->getSubExpr();
9233 E = E->IgnoreImpCasts();
9234 }
9235
9236 // Built-in binary operator.
9237 if (const auto *OP = dyn_cast<BinaryOperator>(E);
9238 OP && IsArithmeticOp(OP->getOpcode())) {
9239 *Opcode = OP->getOpcode();
9240 *RHSExprs = OP->getRHS();
9241 return true;
9242 }
9243
9244 // Overloaded operator.
9245 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9246 if (Call->getNumArgs() != 2)
9247 return false;
9248
9249 // Make sure this is really a binary operator that is safe to pass into
9250 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9251 OverloadedOperatorKind OO = Call->getOperator();
9252 if (OO < OO_Plus || OO > OO_Arrow ||
9253 OO == OO_PlusPlus || OO == OO_MinusMinus)
9254 return false;
9255
9257 if (IsArithmeticOp(OpKind)) {
9258 *Opcode = OpKind;
9259 *RHSExprs = Call->getArg(1);
9260 return true;
9261 }
9262 }
9263
9264 return false;
9265}
9266
9267/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9268/// or is a logical expression such as (x==y) which has int type, but is
9269/// commonly interpreted as boolean.
9270static bool ExprLooksBoolean(const Expr *E) {
9271 E = E->IgnoreParenImpCasts();
9272
9273 if (E->getType()->isBooleanType())
9274 return true;
9275 if (const auto *OP = dyn_cast<BinaryOperator>(E))
9276 return OP->isComparisonOp() || OP->isLogicalOp();
9277 if (const auto *OP = dyn_cast<UnaryOperator>(E))
9278 return OP->getOpcode() == UO_LNot;
9279 if (E->getType()->isPointerType())
9280 return true;
9281 // FIXME: What about overloaded operator calls returning "unspecified boolean
9282 // type"s (commonly pointer-to-members)?
9283
9284 return false;
9285}
9286
9287/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9288/// and binary operator are mixed in a way that suggests the programmer assumed
9289/// the conditional operator has higher precedence, for example:
9290/// "int x = a + someBinaryCondition ? 1 : 2".
9292 Expr *Condition, const Expr *LHSExpr,
9293 const Expr *RHSExpr) {
9294 BinaryOperatorKind CondOpcode;
9295 const Expr *CondRHS;
9296
9297 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9298 return;
9299 if (!ExprLooksBoolean(CondRHS))
9300 return;
9301
9302 // The condition is an arithmetic binary expression, with a right-
9303 // hand side that looks boolean, so warn.
9304
9305 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9306 ? diag::warn_precedence_bitwise_conditional
9307 : diag::warn_precedence_conditional;
9308
9309 Self.Diag(OpLoc, DiagID)
9310 << Condition->getSourceRange()
9311 << BinaryOperator::getOpcodeStr(CondOpcode);
9312
9314 Self, OpLoc,
9315 Self.PDiag(diag::note_precedence_silence)
9316 << BinaryOperator::getOpcodeStr(CondOpcode),
9317 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9318
9319 SuggestParentheses(Self, OpLoc,
9320 Self.PDiag(diag::note_precedence_conditional_first),
9321 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9322}
9323
9324/// Compute the nullability of a conditional expression.
9326 QualType LHSTy, QualType RHSTy,
9327 ASTContext &Ctx) {
9328 if (!ResTy->isAnyPointerType())
9329 return ResTy;
9330
9331 auto GetNullability = [](QualType Ty) {
9332 NullabilityKindOrNone Kind = Ty->getNullability();
9333 if (Kind) {
9334 // For our purposes, treat _Nullable_result as _Nullable.
9337 return *Kind;
9338 }
9340 };
9341
9342 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9343 NullabilityKind MergedKind;
9344
9345 // Compute nullability of a binary conditional expression.
9346 if (IsBin) {
9347 if (LHSKind == NullabilityKind::NonNull)
9348 MergedKind = NullabilityKind::NonNull;
9349 else
9350 MergedKind = RHSKind;
9351 // Compute nullability of a normal conditional expression.
9352 } else {
9353 if (LHSKind == NullabilityKind::Nullable ||
9354 RHSKind == NullabilityKind::Nullable)
9355 MergedKind = NullabilityKind::Nullable;
9356 else if (LHSKind == NullabilityKind::NonNull)
9357 MergedKind = RHSKind;
9358 else if (RHSKind == NullabilityKind::NonNull)
9359 MergedKind = LHSKind;
9360 else
9361 MergedKind = NullabilityKind::Unspecified;
9362 }
9363
9364 // Return if ResTy already has the correct nullability.
9365 if (GetNullability(ResTy) == MergedKind)
9366 return ResTy;
9367
9368 // Strip all nullability from ResTy.
9369 while (ResTy->getNullability())
9370 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9371
9372 // Create a new AttributedType with the new nullability kind.
9373 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
9374}
9375
9377 SourceLocation ColonLoc,
9378 Expr *CondExpr, Expr *LHSExpr,
9379 Expr *RHSExpr) {
9380 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9381 // was the condition.
9382 OpaqueValueExpr *opaqueValue = nullptr;
9383 Expr *commonExpr = nullptr;
9384 if (!LHSExpr) {
9385 commonExpr = CondExpr;
9386 // Lower out placeholder types first. This is important so that we don't
9387 // try to capture a placeholder. This happens in few cases in C++; such
9388 // as Objective-C++'s dictionary subscripting syntax.
9389 if (commonExpr->hasPlaceholderType()) {
9390 ExprResult result = CheckPlaceholderExpr(commonExpr);
9391 if (!result.isUsable()) return ExprError();
9392 commonExpr = result.get();
9393 }
9394 // We usually want to apply unary conversions *before* saving, except
9395 // in the special case of a C++ l-value conditional.
9396 if (!(getLangOpts().CPlusPlus
9397 && !commonExpr->isTypeDependent()
9398 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9399 && commonExpr->isGLValue()
9400 && commonExpr->isOrdinaryOrBitFieldObject()
9401 && RHSExpr->isOrdinaryOrBitFieldObject()
9402 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9403 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9404 if (commonRes.isInvalid())
9405 return ExprError();
9406 commonExpr = commonRes.get();
9407 }
9408
9409 // If the common expression is a class or array prvalue, materialize it
9410 // so that we can safely refer to it multiple times.
9411 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9412 commonExpr->getType()->isArrayType())) {
9413 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9414 if (MatExpr.isInvalid())
9415 return ExprError();
9416 commonExpr = MatExpr.get();
9417 }
9418
9419 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9420 commonExpr->getType(),
9421 commonExpr->getValueKind(),
9422 commonExpr->getObjectKind(),
9423 commonExpr);
9424 LHSExpr = CondExpr = opaqueValue;
9425 }
9426
9427 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9430 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9431 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9432 VK, OK, QuestionLoc);
9433 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9434 RHS.isInvalid())
9435 return ExprError();
9436
9437 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9438 RHS.get());
9439
9440 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9441
9442 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9443 Context);
9444
9445 if (!commonExpr)
9446 return new (Context)
9447 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9448 RHS.get(), result, VK, OK);
9449
9451 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9452 ColonLoc, result, VK, OK);
9453}
9454
9456 unsigned FromAttributes = 0, ToAttributes = 0;
9457 if (const auto *FromFn =
9458 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9459 FromAttributes =
9460 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9461 if (const auto *ToFn =
9462 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9463 ToAttributes =
9464 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9465
9466 return FromAttributes != ToAttributes;
9467}
9468
9469// checkPointerTypesForAssignment - This is a very tricky routine (despite
9470// being closely modeled after the C99 spec:-). The odd characteristic of this
9471// routine is it effectively iqnores the qualifiers on the top level pointee.
9472// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9473// FIXME: add a couple examples in this comment.
9475 QualType LHSType,
9476 QualType RHSType,
9477 SourceLocation Loc) {
9478 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9479 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9480
9481 // get the "pointed to" type (ignoring qualifiers at the top level)
9482 const Type *lhptee, *rhptee;
9483 Qualifiers lhq, rhq;
9484 std::tie(lhptee, lhq) =
9485 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9486 std::tie(rhptee, rhq) =
9487 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9488
9490
9491 // C99 6.5.16.1p1: This following citation is common to constraints
9492 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9493 // qualifiers of the type *pointed to* by the right;
9494
9495 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9496 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9498 // Ignore lifetime for further calculation.
9499 lhq.removeObjCLifetime();
9500 rhq.removeObjCLifetime();
9501 }
9502
9503 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9504 // Treat address-space mismatches as fatal.
9505 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9507
9508 // It's okay to add or remove GC or lifetime qualifiers when converting to
9509 // and from void*.
9512 S.getASTContext()) &&
9513 (lhptee->isVoidType() || rhptee->isVoidType()))
9514 ; // keep old
9515
9516 // Treat lifetime mismatches as fatal.
9517 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9519
9520 // Treat pointer-auth mismatches as fatal.
9521 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9523
9524 // For GCC/MS compatibility, other qualifier mismatches are treated
9525 // as still compatible in C.
9526 else
9528 }
9529
9530 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9531 // incomplete type and the other is a pointer to a qualified or unqualified
9532 // version of void...
9533 if (lhptee->isVoidType()) {
9534 if (rhptee->isIncompleteOrObjectType())
9535 return ConvTy;
9536
9537 // As an extension, we allow cast to/from void* to function pointer.
9538 assert(rhptee->isFunctionType());
9540 }
9541
9542 if (rhptee->isVoidType()) {
9543 // In C, void * to another pointer type is compatible, but we want to note
9544 // that there will be an implicit conversion happening here.
9545 if (lhptee->isIncompleteOrObjectType())
9546 return ConvTy == AssignConvertType::Compatible &&
9547 !S.getLangOpts().CPlusPlus
9549 : ConvTy;
9550
9551 // As an extension, we allow cast to/from void* to function pointer.
9552 assert(lhptee->isFunctionType());
9554 }
9555
9556 if (!S.Diags.isIgnored(
9557 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9558 Loc) &&
9559 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9560 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9562
9563 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9564 // unqualified versions of compatible types, ...
9565 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9566
9567 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9568 if (!S.Context.hasSameType(ltrans, rtrans)) {
9569 QualType LUnderlying =
9570 ltrans->isOverflowBehaviorType()
9571 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9572 : ltrans;
9573 QualType RUnderlying =
9574 rtrans->isOverflowBehaviorType()
9575 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9576 : rtrans;
9577
9578 if (S.Context.hasSameType(LUnderlying, RUnderlying))
9580
9581 ltrans = LUnderlying;
9582 rtrans = RUnderlying;
9583 }
9584 }
9585
9586 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9587 // Check if the pointee types are compatible ignoring the sign.
9588 // We explicitly check for char so that we catch "char" vs
9589 // "unsigned char" on systems where "char" is unsigned.
9590 if (lhptee->isCharType())
9591 ltrans = S.Context.UnsignedCharTy;
9592 else if (lhptee->hasSignedIntegerRepresentation())
9593 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9594
9595 if (rhptee->isCharType())
9596 rtrans = S.Context.UnsignedCharTy;
9597 else if (rhptee->hasSignedIntegerRepresentation())
9598 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9599
9600 if (ltrans == rtrans) {
9601 // Types are compatible ignoring the sign. Qualifier incompatibility
9602 // takes priority over sign incompatibility because the sign
9603 // warning can be disabled.
9604 if (!S.IsAssignConvertCompatible(ConvTy))
9605 return ConvTy;
9606
9608 }
9609
9610 // If we are a multi-level pointer, it's possible that our issue is simply
9611 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9612 // the eventual target type is the same and the pointers have the same
9613 // level of indirection, this must be the issue.
9614 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9615 do {
9616 std::tie(lhptee, lhq) =
9617 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9618 std::tie(rhptee, rhq) =
9619 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9620
9621 // Inconsistent address spaces at this point is invalid, even if the
9622 // address spaces would be compatible.
9623 // FIXME: This doesn't catch address space mismatches for pointers of
9624 // different nesting levels, like:
9625 // __local int *** a;
9626 // int ** b = a;
9627 // It's not clear how to actually determine when such pointers are
9628 // invalidly incompatible.
9629 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9630 return AssignConvertType::
9631 IncompatibleNestedPointerAddressSpaceMismatch;
9632
9633 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9634
9635 if (lhptee == rhptee)
9637 }
9638
9639 // General pointer incompatibility takes priority over qualifiers.
9640 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9643 }
9644 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9645 // hasSameType, so we can skip further checks.
9646 const auto *LFT = ltrans->getAs<FunctionType>();
9647 const auto *RFT = rtrans->getAs<FunctionType>();
9648 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9649 // The invocation of IsFunctionConversion below will try to transform rtrans
9650 // to obtain an exact match for ltrans. This should not fail because of
9651 // mismatches in result type and parameter types, they were already checked
9652 // by typesAreCompatible above. So we will recreate rtrans (or where
9653 // appropriate ltrans) using the result type and parameter types from ltrans
9654 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9655 const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);
9656 const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);
9657 if (LFPT && RFPT) {
9658 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9659 LFPT->getParamTypes(),
9660 RFPT->getExtProtoInfo());
9661 } else if (LFPT) {
9663 EPI.ExtInfo = RFT->getExtInfo();
9664 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9665 LFPT->getParamTypes(), EPI);
9666 } else if (RFPT) {
9667 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9668 // all of its ExtProtoInfo. Transform ltrans instead.
9670 EPI.ExtInfo = LFT->getExtInfo();
9671 ltrans = S.Context.getFunctionType(RFPT->getReturnType(),
9672 RFPT->getParamTypes(), EPI);
9673 } else {
9674 rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),
9675 RFT->getExtInfo());
9676 }
9677 if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&
9678 !S.IsFunctionConversion(rtrans, ltrans))
9680 }
9681 return ConvTy;
9682}
9683
9684/// checkBlockPointerTypesForAssignment - This routine determines whether two
9685/// block pointer types are compatible or whether a block and normal pointer
9686/// are compatible. It is more restrict than comparing two function pointer
9687// types.
9689 QualType LHSType,
9690 QualType RHSType) {
9691 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9692 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9693
9694 QualType lhptee, rhptee;
9695
9696 // get the "pointed to" type (ignoring qualifiers at the top level)
9697 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9698 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9699
9700 // In C++, the types have to match exactly.
9701 if (S.getLangOpts().CPlusPlus)
9703
9705
9706 // For blocks we enforce that qualifiers are identical.
9707 Qualifiers LQuals = lhptee.getLocalQualifiers();
9708 Qualifiers RQuals = rhptee.getLocalQualifiers();
9709 if (S.getLangOpts().OpenCL) {
9710 LQuals.removeAddressSpace();
9711 RQuals.removeAddressSpace();
9712 }
9713 if (LQuals != RQuals)
9715
9716 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9717 // assignment.
9718 // The current behavior is similar to C++ lambdas. A block might be
9719 // assigned to a variable iff its return type and parameters are compatible
9720 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9721 // an assignment. Presumably it should behave in way that a function pointer
9722 // assignment does in C, so for each parameter and return type:
9723 // * CVR and address space of LHS should be a superset of CVR and address
9724 // space of RHS.
9725 // * unqualified types should be compatible.
9726 if (S.getLangOpts().OpenCL) {
9728 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9729 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9731 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9733
9734 return ConvTy;
9735}
9736
9737/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9738/// for assignment compatibility.
9740 QualType LHSType,
9741 QualType RHSType) {
9742 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9743 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9744
9745 if (LHSType->isObjCBuiltinType()) {
9746 // Class is not compatible with ObjC object pointers.
9747 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9748 !RHSType->isObjCQualifiedClassType())
9751 }
9752 if (RHSType->isObjCBuiltinType()) {
9753 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9754 !LHSType->isObjCQualifiedClassType())
9757 }
9758 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9759 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9760
9761 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9762 // make an exception for id<P>
9763 !LHSType->isObjCQualifiedIdType())
9765
9766 if (S.Context.typesAreCompatible(LHSType, RHSType))
9768 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9771}
9772
9774 QualType LHSType,
9775 QualType RHSType) {
9776 // Fake up an opaque expression. We don't actually care about what
9777 // cast operations are required, so if CheckAssignmentConstraints
9778 // adds casts to this they'll be wasted, but fortunately that doesn't
9779 // usually happen on valid code.
9780 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9781 ExprResult RHSPtr = &RHSExpr;
9782 CastKind K;
9783
9784 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9785}
9786
9787/// This helper function returns true if QT is a vector type that has element
9788/// type ElementType.
9789static bool isVector(QualType QT, QualType ElementType) {
9790 if (const VectorType *VT = QT->getAs<VectorType>())
9791 return VT->getElementType().getCanonicalType() == ElementType;
9792 return false;
9793}
9794
9795/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9796/// has code to accommodate several GCC extensions when type checking
9797/// pointers. Here are some objectionable examples that GCC considers warnings:
9798///
9799/// int a, *pint;
9800/// short *pshort;
9801/// struct foo *pfoo;
9802///
9803/// pint = pshort; // warning: assignment from incompatible pointer type
9804/// a = pint; // warning: assignment makes integer from pointer without a cast
9805/// pint = a; // warning: assignment makes pointer from integer without a cast
9806/// pint = pfoo; // warning: assignment from incompatible pointer type
9807///
9808/// As a result, the code for dealing with pointers is more complex than the
9809/// C99 spec dictates.
9810///
9811/// Sets 'Kind' for any result kind except Incompatible.
9813 ExprResult &RHS,
9814 CastKind &Kind,
9815 bool ConvertRHS) {
9816 QualType RHSType = RHS.get()->getType();
9817 QualType OrigLHSType = LHSType;
9818
9819 // Get canonical types. We're not formatting these types, just comparing
9820 // them.
9821 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9822 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9823
9824 // Common case: no conversion required.
9825 if (LHSType == RHSType) {
9826 Kind = CK_NoOp;
9828 }
9829
9830 // If the LHS has an __auto_type, there are no additional type constraints
9831 // to be worried about.
9832 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9833 if (AT->isGNUAutoType()) {
9834 Kind = CK_NoOp;
9836 }
9837 }
9838
9839 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHSType, RHSType);
9840 switch (OBTResult) {
9842 Kind = CK_NoOp;
9845 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9849 break;
9850 }
9851
9852 // Check for incompatible OBT types in pointer pointee types
9853 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9854 QualType LHSPointee = LHSType->getPointeeType();
9855 QualType RHSPointee = RHSType->getPointeeType();
9856 if ((LHSPointee->isOverflowBehaviorType() ||
9857 RHSPointee->isOverflowBehaviorType()) &&
9858 !Context.areCompatibleOverflowBehaviorTypes(LHSPointee, RHSPointee)) {
9859 Kind = CK_NoOp;
9861 }
9862 }
9863
9864 // If we have an atomic type, try a non-atomic assignment, then just add an
9865 // atomic qualification step.
9866 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9868 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9870 return Result;
9871 if (Kind != CK_NoOp && ConvertRHS)
9872 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9873 Kind = CK_NonAtomicToAtomic;
9874 return Result;
9875 }
9876
9877 // If the left-hand side is a reference type, then we are in a
9878 // (rare!) case where we've allowed the use of references in C,
9879 // e.g., as a parameter type in a built-in function. In this case,
9880 // just make sure that the type referenced is compatible with the
9881 // right-hand side type. The caller is responsible for adjusting
9882 // LHSType so that the resulting expression does not have reference
9883 // type.
9884 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9885 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9886 Kind = CK_LValueBitCast;
9888 }
9890 }
9891
9892 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9893 // of an ExtVector type to the same ExtVector type.
9894 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9895 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9896 // Implicit conversions require the same number of elements.
9897 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9899
9900 if (LHSType->isExtVectorBoolType() &&
9901 RHSExtType->getElementType()->isIntegerType()) {
9902 Kind = CK_IntegralToBoolean;
9904 }
9905 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9906 if (Context.getLangOpts().OpenCL &&
9907 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9908 Kind = CK_BitCast;
9910 }
9912 }
9913 if (RHSType->isArithmeticType()) {
9914 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9915 if (ConvertRHS)
9916 RHS = prepareVectorSplat(LHSType, RHS.get());
9917 Kind = CK_VectorSplat;
9919 }
9920 }
9921
9922 // Conversions to or from vector type.
9923 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9924 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9925 // Allow assignments of an AltiVec vector type to an equivalent GCC
9926 // vector type and vice versa
9927 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9928 Kind = CK_BitCast;
9930 }
9931
9932 // If we are allowing lax vector conversions, and LHS and RHS are both
9933 // vectors, the total size only needs to be the same. This is a bitcast;
9934 // no bits are changed but the result type is different.
9935 if (isLaxVectorConversion(RHSType, LHSType)) {
9936 // The default for lax vector conversions with Altivec vectors will
9937 // change, so if we are converting between vector types where
9938 // at least one is an Altivec vector, emit a warning.
9939 if (Context.getTargetInfo().getTriple().isPPC() &&
9940 anyAltivecTypes(RHSType, LHSType) &&
9941 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9942 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9943 << RHSType << LHSType;
9944 Kind = CK_BitCast;
9946 }
9947 }
9948
9949 // When the RHS comes from another lax conversion (e.g. binops between
9950 // scalars and vectors) the result is canonicalized as a vector. When the
9951 // LHS is also a vector, the lax is allowed by the condition above. Handle
9952 // the case where LHS is a scalar.
9953 if (LHSType->isScalarType()) {
9954 const VectorType *VecType = RHSType->getAs<VectorType>();
9955 if (VecType && VecType->getNumElements() == 1 &&
9956 isLaxVectorConversion(RHSType, LHSType)) {
9957 if (Context.getTargetInfo().getTriple().isPPC() &&
9959 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9961 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9962 << RHSType << LHSType;
9963 ExprResult *VecExpr = &RHS;
9964 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9965 Kind = CK_BitCast;
9967 }
9968 }
9969
9970 // Allow assignments between fixed-length and sizeless SVE vectors.
9971 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9972 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9973 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9974 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9975 Kind = CK_BitCast;
9977 }
9978
9979 // Allow assignments between fixed-length and sizeless RVV vectors.
9980 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9981 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9982 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9983 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9984 Kind = CK_BitCast;
9986 }
9987 }
9988
9990 }
9991
9992 // Diagnose attempts to convert between __ibm128, __float128 and long double
9993 // where such conversions currently can't be handled.
9994 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9996
9997 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9998 // discards the imaginary part.
9999 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
10000 !LHSType->getAs<ComplexType>())
10002
10003 // Arithmetic conversions.
10004 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
10005 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
10006 if (ConvertRHS)
10007 Kind = PrepareScalarCast(RHS, LHSType);
10009 }
10010
10011 // Conversions to normal pointers.
10012 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
10013 // U* -> T*
10014 if (isa<PointerType>(RHSType)) {
10015 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10016 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
10017 if (AddrSpaceL != AddrSpaceR)
10018 Kind = CK_AddressSpaceConversion;
10019 else if (Context.hasCvrSimilarType(RHSType, LHSType))
10020 Kind = CK_NoOp;
10021 else
10022 Kind = CK_BitCast;
10023 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
10024 RHS.get()->getBeginLoc());
10025 }
10026
10027 // int -> T*
10028 if (RHSType->isIntegerType()) {
10029 Kind = CK_IntegralToPointer; // FIXME: null?
10031 }
10032
10033 // C pointers are not compatible with ObjC object pointers,
10034 // with two exceptions:
10035 if (isa<ObjCObjectPointerType>(RHSType)) {
10036 // - conversions to void*
10037 if (LHSPointer->getPointeeType()->isVoidType()) {
10038 Kind = CK_BitCast;
10040 }
10041
10042 // - conversions from 'Class' to the redefinition type
10043 if (RHSType->isObjCClassType() &&
10044 Context.hasSameType(LHSType,
10045 Context.getObjCClassRedefinitionType())) {
10046 Kind = CK_BitCast;
10048 }
10049
10050 Kind = CK_BitCast;
10052 }
10053
10054 // U^ -> void*
10055 if (RHSType->getAs<BlockPointerType>()) {
10056 if (LHSPointer->getPointeeType()->isVoidType()) {
10057 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10058 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10059 ->getPointeeType()
10060 .getAddressSpace();
10061 Kind =
10062 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10064 }
10065 }
10066
10068 }
10069
10070 // Conversions to block pointers.
10071 if (isa<BlockPointerType>(LHSType)) {
10072 // U^ -> T^
10073 if (RHSType->isBlockPointerType()) {
10074 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10075 ->getPointeeType()
10076 .getAddressSpace();
10077 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10078 ->getPointeeType()
10079 .getAddressSpace();
10080 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10081 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
10082 }
10083
10084 // int or null -> T^
10085 if (RHSType->isIntegerType()) {
10086 Kind = CK_IntegralToPointer; // FIXME: null
10088 }
10089
10090 // id -> T^
10091 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10092 Kind = CK_AnyPointerToBlockPointerCast;
10094 }
10095
10096 // void* -> T^
10097 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10098 if (RHSPT->getPointeeType()->isVoidType()) {
10099 Kind = CK_AnyPointerToBlockPointerCast;
10101 }
10102
10104 }
10105
10106 // Conversions to Objective-C pointers.
10107 if (isa<ObjCObjectPointerType>(LHSType)) {
10108 // A* -> B*
10109 if (RHSType->isObjCObjectPointerType()) {
10110 Kind = CK_BitCast;
10111 AssignConvertType result =
10112 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
10113 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10115 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10117 return result;
10118 }
10119
10120 // int or null -> A*
10121 if (RHSType->isIntegerType()) {
10122 Kind = CK_IntegralToPointer; // FIXME: null
10124 }
10125
10126 // In general, C pointers are not compatible with ObjC object pointers,
10127 // with two exceptions:
10128 if (isa<PointerType>(RHSType)) {
10129 Kind = CK_CPointerToObjCPointerCast;
10130
10131 // - conversions from 'void*'
10132 if (RHSType->isVoidPointerType()) {
10134 }
10135
10136 // - conversions to 'Class' from its redefinition type
10137 if (LHSType->isObjCClassType() &&
10138 Context.hasSameType(RHSType,
10139 Context.getObjCClassRedefinitionType())) {
10141 }
10142
10144 }
10145
10146 // Only under strict condition T^ is compatible with an Objective-C pointer.
10147 if (RHSType->isBlockPointerType() &&
10149 if (ConvertRHS)
10151 Kind = CK_BlockPointerToObjCPointerCast;
10153 }
10154
10156 }
10157
10158 // Conversion to nullptr_t (C23 only)
10159 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10162 // null -> nullptr_t
10163 Kind = CK_NullToPointer;
10165 }
10166
10167 // Conversions from pointers that are not covered by the above.
10168 if (isa<PointerType>(RHSType)) {
10169 // T* -> _Bool
10170 if (LHSType == Context.BoolTy) {
10171 Kind = CK_PointerToBoolean;
10173 }
10174
10175 // T* -> int
10176 if (LHSType->isIntegerType()) {
10177 Kind = CK_PointerToIntegral;
10179 }
10180
10182 }
10183
10184 // Conversions from Objective-C pointers that are not covered by the above.
10185 if (isa<ObjCObjectPointerType>(RHSType)) {
10186 // T* -> _Bool
10187 if (LHSType == Context.BoolTy) {
10188 Kind = CK_PointerToBoolean;
10190 }
10191
10192 // T* -> int
10193 if (LHSType->isIntegerType()) {
10194 Kind = CK_PointerToIntegral;
10196 }
10197
10199 }
10200
10201 // struct A -> struct B
10202 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10203 if (Context.typesAreCompatible(LHSType, RHSType)) {
10204 Kind = CK_NoOp;
10206 }
10207 }
10208
10209 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10210 Kind = CK_IntToOCLSampler;
10212 }
10213
10215}
10216
10217/// Constructs a transparent union from an expression that is
10218/// used to initialize the transparent union.
10220 ExprResult &EResult, QualType UnionType,
10221 FieldDecl *Field) {
10222 // Build an initializer list that designates the appropriate member
10223 // of the transparent union.
10224 Expr *E = EResult.get();
10226 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10227 Initializer->setType(UnionType);
10228 Initializer->setInitializedFieldInUnion(Field);
10229
10230 // Build a compound literal constructing a value of the transparent
10231 // union type from this initializer list.
10232 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10233 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10234 VK_PRValue, Initializer, false);
10235}
10236
10239 ExprResult &RHS) {
10240 QualType RHSType = RHS.get()->getType();
10241
10242 // If the ArgType is a Union type, we want to handle a potential
10243 // transparent_union GCC extension.
10244 const RecordType *UT = ArgType->getAsUnionType();
10245 if (!UT)
10247
10248 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10249 if (!UD->hasAttr<TransparentUnionAttr>())
10251
10252 // The field to initialize within the transparent union.
10253 FieldDecl *InitField = nullptr;
10254 // It's compatible if the expression matches any of the fields.
10255 for (auto *it : UD->fields()) {
10256 if (it->getType()->isPointerType()) {
10257 // If the transparent union contains a pointer type, we allow:
10258 // 1) void pointer
10259 // 2) null pointer constant
10260 if (RHSType->isPointerType())
10261 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10262 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10263 InitField = it;
10264 break;
10265 }
10266
10269 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10270 CK_NullToPointer);
10271 InitField = it;
10272 break;
10273 }
10274 }
10275
10276 CastKind Kind;
10277 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
10279 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10280 InitField = it;
10281 break;
10282 }
10283 }
10284
10285 if (!InitField)
10287
10288 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10290}
10291
10293 ExprResult &CallerRHS,
10294 bool Diagnose,
10295 bool DiagnoseCFAudited,
10296 bool ConvertRHS) {
10297 // We need to be able to tell the caller whether we diagnosed a problem, if
10298 // they ask us to issue diagnostics.
10299 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10300
10301 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10302 // we can't avoid *all* modifications at the moment, so we need some somewhere
10303 // to put the updated value.
10304 ExprResult LocalRHS = CallerRHS;
10305 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10306
10307 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10308 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10309 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10310 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10311 Diag(RHS.get()->getExprLoc(),
10312 diag::warn_noderef_to_dereferenceable_pointer)
10313 << RHS.get()->getSourceRange();
10314 }
10315 }
10316 }
10317
10318 if (getLangOpts().CPlusPlus) {
10319 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10320 // C++ 5.17p3: If the left operand is not of class type, the
10321 // expression is implicitly converted (C++ 4) to the
10322 // cv-unqualified type of the left operand.
10323 QualType RHSType = RHS.get()->getType();
10324 if (Diagnose) {
10325 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10327 } else {
10330 /*SuppressUserConversions=*/false,
10331 AllowedExplicit::None,
10332 /*InOverloadResolution=*/false,
10333 /*CStyle=*/false,
10334 /*AllowObjCWritebackConversion=*/false);
10335 if (ICS.isFailure())
10337 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10339 }
10340 if (RHS.isInvalid())
10343 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10344 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10346
10347 // Check if OBT is being discarded during assignment
10348 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10349 if (RHSType->isOverflowBehaviorType() &&
10350 !LHSType->isOverflowBehaviorType()) {
10352 }
10353
10354 return result;
10355 }
10356
10357 // FIXME: Currently, we fall through and treat C++ classes like C
10358 // structures.
10359 // FIXME: We also fall through for atomics; not sure what should
10360 // happen there, though.
10361 } else if (RHS.get()->getType() == Context.OverloadTy) {
10362 // As a set of extensions to C, we support overloading on functions. These
10363 // functions need to be resolved here.
10364 DeclAccessPair DAP;
10366 RHS.get(), LHSType, /*Complain=*/false, DAP))
10367 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10368 else
10370 }
10371
10372 // For HLSL records, insert derived-to-base conversion if needed.
10373 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10374 QualType RHSType = RHS.get()->getType();
10375 if (!Context.hasSameUnqualifiedType(RHSType, LHSType)) {
10376 CXXBasePaths Paths;
10377 if (IsDerivedFrom(RHS.get()->getBeginLoc(), RHSType, LHSType, Paths)) {
10378 CXXCastPath CastPath;
10379 BuildBasePathArray(Paths, CastPath);
10380 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_DerivedToBase, VK_LValue,
10381 &CastPath);
10382 }
10383 }
10384 }
10385
10386 // This check seems unnatural, however it is necessary to ensure the proper
10387 // conversion of functions/arrays. If the conversion were done for all
10388 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10389 // expressions that suppress this implicit conversion (&, sizeof). This needs
10390 // to happen before we check for null pointer conversions because C does not
10391 // undergo the same implicit conversions as C++ does above (by the calls to
10392 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10393 // lvalue to rvalue cast before checking for null pointer constraints. This
10394 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10395 //
10396 // Suppress this for references: C++ 8.5.3p5.
10397 if (!LHSType->isReferenceType()) {
10398 // FIXME: We potentially allocate here even if ConvertRHS is false.
10400 if (RHS.isInvalid())
10402 }
10403
10404 // The constraints are expressed in terms of the atomic, qualified, or
10405 // unqualified type of the LHS.
10406 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10407
10408 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10409 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10410 if ((LHSTypeAfterConversion->isPointerType() ||
10411 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10412 LHSTypeAfterConversion->isBlockPointerType()) &&
10413 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10417 if (Diagnose || ConvertRHS) {
10418 CastKind Kind;
10419 CXXCastPath Path;
10420 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10421 /*IgnoreBaseAccess=*/false, Diagnose);
10422
10423 // If there is a conversion of some kind, check to see what kind of
10424 // pointer conversion happened so we can diagnose a C++ compatibility
10425 // diagnostic if the conversion is invalid. This only matters if the RHS
10426 // is some kind of void pointer. We have a carve-out when the RHS is from
10427 // a macro expansion because the use of a macro may indicate different
10428 // code between C and C++. Consider: char *s = NULL; where NULL is
10429 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10430 // C++, which is valid in C++.
10431 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10432 !RHS.get()->getBeginLoc().isMacroID()) {
10433 QualType CanRHS =
10435 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10436 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10437 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
10438 RHS.get()->getExprLoc());
10439 // Anything that's not considered perfectly compatible would be
10440 // incompatible in C++.
10443 }
10444 }
10445
10446 if (ConvertRHS)
10447 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10448 }
10449 return Ret;
10450 }
10451 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10452 // unqualified bool, and the right operand is a pointer or its type is
10453 // nullptr_t.
10454 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10455 RHS.get()->getType()->isNullPtrType()) {
10456 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10457 // only handles nullptr -> _Bool due to needing an extra conversion
10458 // step.
10459 // We model this by converting from nullptr -> void * and then let the
10460 // conversion from void * -> _Bool happen naturally.
10461 if (Diagnose || ConvertRHS) {
10462 CastKind Kind;
10463 CXXCastPath Path;
10464 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10465 /*IgnoreBaseAccess=*/false, Diagnose);
10466 if (ConvertRHS)
10467 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10468 &Path);
10469 }
10470 }
10471
10472 // OpenCL queue_t type assignment.
10473 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10475 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10477 }
10478
10479 CastKind Kind;
10480 AssignConvertType result =
10481 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10482
10483 // If assigning a void * created by an allocation function call to some other
10484 // type, check that the allocated size is sufficient for that type.
10485 if (result != AssignConvertType::Incompatible &&
10486 RHS.get()->getType()->isVoidPointerType())
10487 CheckSufficientAllocSize(*this, LHSType, RHS.get());
10488
10489 // C99 6.5.16.1p2: The value of the right operand is converted to the
10490 // type of the assignment expression.
10491 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10492 // so that we can use references in built-in functions even in C.
10493 // The getNonReferenceType() call makes sure that the resulting expression
10494 // does not have reference type.
10495 if (result != AssignConvertType::Incompatible &&
10496 RHS.get()->getType() != LHSType) {
10498 Expr *E = RHS.get();
10499
10500 // Check for various Objective-C errors. If we are not reporting
10501 // diagnostics and just checking for errors, e.g., during overload
10502 // resolution, return Incompatible to indicate the failure.
10503 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10504 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
10506 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10507 if (!Diagnose)
10509 }
10510 if (getLangOpts().ObjC &&
10511 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10512 E->getType(), E, Diagnose) ||
10513 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10514 if (!Diagnose)
10516 // Replace the expression with a corrected version and continue so we
10517 // can find further errors.
10518 RHS = E;
10520 }
10521
10522 if (ConvertRHS)
10523 RHS = ImpCastExprToType(E, Ty, Kind);
10524 }
10525
10526 return result;
10527}
10528
10529namespace {
10530/// The original operand to an operator, prior to the application of the usual
10531/// arithmetic conversions and converting the arguments of a builtin operator
10532/// candidate.
10533struct OriginalOperand {
10534 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10535 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10536 Op = MTE->getSubExpr();
10537 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10538 Op = BTE->getSubExpr();
10539 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10540 Orig = ICE->getSubExprAsWritten();
10541 Conversion = ICE->getConversionFunction();
10542 }
10543 }
10544
10545 QualType getType() const { return Orig->getType(); }
10546
10547 Expr *Orig;
10548 NamedDecl *Conversion;
10549};
10550}
10551
10553 ExprResult &RHS) {
10554 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10555
10556 Diag(Loc, diag::err_typecheck_invalid_operands)
10557 << OrigLHS.getType() << OrigRHS.getType()
10558 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10559
10560 // If a user-defined conversion was applied to either of the operands prior
10561 // to applying the built-in operator rules, tell the user about it.
10562 if (OrigLHS.Conversion) {
10563 Diag(OrigLHS.Conversion->getLocation(),
10564 diag::note_typecheck_invalid_operands_converted)
10565 << 0 << LHS.get()->getType();
10566 }
10567 if (OrigRHS.Conversion) {
10568 Diag(OrigRHS.Conversion->getLocation(),
10569 diag::note_typecheck_invalid_operands_converted)
10570 << 1 << RHS.get()->getType();
10571 }
10572
10573 return QualType();
10574}
10575
10577 ExprResult &RHS) {
10578 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10579 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10580
10581 bool LHSNatVec = LHSType->isVectorType();
10582 bool RHSNatVec = RHSType->isVectorType();
10583
10584 if (!(LHSNatVec && RHSNatVec)) {
10585 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10586 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10587 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10588 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10589 << Vector->getSourceRange();
10590 return QualType();
10591 }
10592
10593 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10594 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10595 << RHS.get()->getSourceRange();
10596
10597 return QualType();
10598}
10599
10600/// Try to convert a value of non-vector type to a vector type by converting
10601/// the type to the element type of the vector and then performing a splat.
10602/// If the language is OpenCL, we only use conversions that promote scalar
10603/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10604/// for float->int.
10605///
10606/// OpenCL V2.0 6.2.6.p2:
10607/// An error shall occur if any scalar operand type has greater rank
10608/// than the type of the vector element.
10609///
10610/// \param scalar - if non-null, actually perform the conversions
10611/// \return true if the operation fails (but without diagnosing the failure)
10613 QualType scalarTy,
10614 QualType vectorEltTy,
10615 QualType vectorTy,
10616 unsigned &DiagID) {
10617 // The conversion to apply to the scalar before splatting it,
10618 // if necessary.
10619 CastKind scalarCast = CK_NoOp;
10620
10621 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10622 scalarCast = CK_IntegralToBoolean;
10623 } else if (vectorEltTy->isIntegralType(S.Context)) {
10624 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10625 (scalarTy->isIntegerType() &&
10626 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10627 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10628 return true;
10629 }
10630 if (!scalarTy->isIntegralType(S.Context))
10631 return true;
10632 scalarCast = CK_IntegralCast;
10633 } else if (vectorEltTy->isRealFloatingType()) {
10634 if (scalarTy->isRealFloatingType()) {
10635 if (S.getLangOpts().OpenCL &&
10636 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10637 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10638 return true;
10639 }
10640 scalarCast = CK_FloatingCast;
10641 }
10642 else if (scalarTy->isIntegralType(S.Context))
10643 scalarCast = CK_IntegralToFloating;
10644 else
10645 return true;
10646 } else {
10647 return true;
10648 }
10649
10650 // Adjust scalar if desired.
10651 if (scalar) {
10652 if (scalarCast != CK_NoOp)
10653 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10654 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10655 }
10656 return false;
10657}
10658
10659/// Convert vector E to a vector with the same number of elements but different
10660/// element type.
10661static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10662 const auto *VecTy = E->getType()->getAs<VectorType>();
10663 assert(VecTy && "Expression E must be a vector");
10664 QualType NewVecTy =
10665 VecTy->isExtVectorType()
10666 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10667 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10668 VecTy->getVectorKind());
10669
10670 // Look through the implicit cast. Return the subexpression if its type is
10671 // NewVecTy.
10672 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10673 if (ICE->getSubExpr()->getType() == NewVecTy)
10674 return ICE->getSubExpr();
10675
10676 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10677 return S.ImpCastExprToType(E, NewVecTy, Cast);
10678}
10679
10680/// Test if a (constant) integer Int can be casted to another integer type
10681/// IntTy without losing precision.
10683 QualType OtherIntTy) {
10684 Expr *E = Int->get();
10686 return false;
10687
10688 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10689
10690 // Reject cases where the value of the Int is unknown as that would
10691 // possibly cause truncation, but accept cases where the scalar can be
10692 // demoted without loss of precision.
10693 Expr::EvalResult EVResult;
10694 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10695 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10696 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10697 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10698
10699 if (CstInt) {
10700 // If the scalar is constant and is of a higher order and has more active
10701 // bits that the vector element type, reject it.
10702 llvm::APSInt Result = EVResult.Val.getInt();
10703 unsigned NumBits = IntSigned
10704 ? (Result.isNegative() ? Result.getSignificantBits()
10705 : Result.getActiveBits())
10706 : Result.getActiveBits();
10707 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10708 return true;
10709
10710 // If the signedness of the scalar type and the vector element type
10711 // differs and the number of bits is greater than that of the vector
10712 // element reject it.
10713 return (IntSigned != OtherIntSigned &&
10714 NumBits > S.Context.getIntWidth(OtherIntTy));
10715 }
10716
10717 // Reject cases where the value of the scalar is not constant and it's
10718 // order is greater than that of the vector element type.
10719 return (Order < 0);
10720}
10721
10722/// Test if a (constant) integer Int can be casted to floating point type
10723/// FloatTy without losing precision.
10725 QualType FloatTy) {
10726 if (Int->get()->containsErrors())
10727 return false;
10728
10729 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10730
10731 // Determine if the integer constant can be expressed as a floating point
10732 // number of the appropriate type.
10733 Expr::EvalResult EVResult;
10734 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10735
10736 uint64_t Bits = 0;
10737 if (CstInt) {
10738 // Reject constants that would be truncated if they were converted to
10739 // the floating point type. Test by simple to/from conversion.
10740 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10741 // could be avoided if there was a convertFromAPInt method
10742 // which could signal back if implicit truncation occurred.
10743 llvm::APSInt Result = EVResult.Val.getInt();
10744 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10745 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10746 llvm::APFloat::rmTowardZero);
10747 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10749 bool Ignored = false;
10750 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10751 &Ignored);
10752 if (Result != ConvertBack)
10753 return true;
10754 } else {
10755 // Reject types that cannot be fully encoded into the mantissa of
10756 // the float.
10757 Bits = S.Context.getTypeSize(IntTy);
10758 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10759 S.Context.getFloatTypeSemantics(FloatTy));
10760 if (Bits > FloatPrec)
10761 return true;
10762 }
10763
10764 return false;
10765}
10766
10767/// Attempt to convert and splat Scalar into a vector whose types matches
10768/// Vector following GCC conversion rules. The rule is that implicit
10769/// conversion can occur when Scalar can be casted to match Vector's element
10770/// type without causing truncation of Scalar.
10772 ExprResult *Vector) {
10773 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10774 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10775 QualType VectorEltTy;
10776
10777 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10778 assert(!isa<ExtVectorType>(VT) &&
10779 "ExtVectorTypes should not be handled here!");
10780 VectorEltTy = VT->getElementType();
10781 } else if (VectorTy->isSveVLSBuiltinType()) {
10782 VectorEltTy =
10783 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10784 } else {
10785 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10786 }
10787
10788 // Reject cases where the vector element type or the scalar element type are
10789 // not integral or floating point types.
10790 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10791 return true;
10792
10793 // The conversion to apply to the scalar before splatting it,
10794 // if necessary.
10795 CastKind ScalarCast = CK_NoOp;
10796
10797 // Accept cases where the vector elements are integers and the scalar is
10798 // an integer.
10799 // FIXME: Notionally if the scalar was a floating point value with a precise
10800 // integral representation, we could cast it to an appropriate integer
10801 // type and then perform the rest of the checks here. GCC will perform
10802 // this conversion in some cases as determined by the input language.
10803 // We should accept it on a language independent basis.
10804 if (VectorEltTy->isIntegralType(S.Context) &&
10805 ScalarTy->isIntegralType(S.Context) &&
10806 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10807
10808 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10809 return true;
10810
10811 ScalarCast = CK_IntegralCast;
10812 } else if (VectorEltTy->isIntegralType(S.Context) &&
10813 ScalarTy->isRealFloatingType()) {
10814 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10815 ScalarCast = CK_FloatingToIntegral;
10816 else
10817 return true;
10818 } else if (VectorEltTy->isRealFloatingType()) {
10819 if (ScalarTy->isRealFloatingType()) {
10820
10821 // Reject cases where the scalar type is not a constant and has a higher
10822 // Order than the vector element type.
10823 llvm::APFloat Result(0.0);
10824
10825 // Determine whether this is a constant scalar. In the event that the
10826 // value is dependent (and thus cannot be evaluated by the constant
10827 // evaluator), skip the evaluation. This will then diagnose once the
10828 // expression is instantiated.
10829 bool CstScalar = Scalar->get()->isValueDependent() ||
10830 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10831 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10832 if (!CstScalar && Order < 0)
10833 return true;
10834
10835 // If the scalar cannot be safely casted to the vector element type,
10836 // reject it.
10837 if (CstScalar) {
10838 bool Truncated = false;
10839 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10840 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10841 if (Truncated)
10842 return true;
10843 }
10844
10845 ScalarCast = CK_FloatingCast;
10846 } else if (ScalarTy->isIntegralType(S.Context)) {
10847 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10848 return true;
10849
10850 ScalarCast = CK_IntegralToFloating;
10851 } else
10852 return true;
10853 } else if (ScalarTy->isEnumeralType())
10854 return true;
10855
10856 // Adjust scalar if desired.
10857 if (ScalarCast != CK_NoOp)
10858 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10859 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10860 return false;
10861}
10862
10864 SourceLocation Loc, bool IsCompAssign,
10865 bool AllowBothBool,
10866 bool AllowBoolConversions,
10867 bool AllowBoolOperation) {
10868 if (!IsCompAssign) {
10870 if (LHS.isInvalid())
10871 return QualType();
10872 }
10874 if (RHS.isInvalid())
10875 return QualType();
10876
10877 // For conversion purposes, we ignore any qualifiers.
10878 // For example, "const float" and "float" are equivalent.
10879 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10880 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10881
10882 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10883 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10884 assert(LHSVecType || RHSVecType);
10885
10886 if (getLangOpts().HLSL)
10887 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10888 IsCompAssign);
10889
10890 // Any operation with MFloat8 type is only possible with C intrinsics
10891 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10892 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10893 return InvalidOperands(Loc, LHS, RHS);
10894
10895 // AltiVec-style "vector bool op vector bool" combinations are allowed
10896 // for some operators but not others.
10897 if (!AllowBothBool && LHSVecType &&
10898 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10899 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10900 return InvalidOperands(Loc, LHS, RHS);
10901
10902 // This operation may not be performed on boolean vectors.
10903 if (!AllowBoolOperation &&
10904 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10905 return InvalidOperands(Loc, LHS, RHS);
10906
10907 // If the vector types are identical, return.
10908 if (Context.hasSameType(LHSType, RHSType))
10909 return Context.getCommonSugaredType(LHSType, RHSType);
10910
10911 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10912 if (LHSVecType && RHSVecType &&
10913 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10914 if (isa<ExtVectorType>(LHSVecType)) {
10915 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10916 return LHSType;
10917 }
10918
10919 if (!IsCompAssign)
10920 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10921 return RHSType;
10922 }
10923
10924 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10925 // can be mixed, with the result being the non-bool type. The non-bool
10926 // operand must have integer element type.
10927 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10928 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10929 (Context.getTypeSize(LHSVecType->getElementType()) ==
10930 Context.getTypeSize(RHSVecType->getElementType()))) {
10931 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10932 LHSVecType->getElementType()->isIntegerType() &&
10933 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10934 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10935 return LHSType;
10936 }
10937 if (!IsCompAssign &&
10938 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10939 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10940 RHSVecType->getElementType()->isIntegerType()) {
10941 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10942 return RHSType;
10943 }
10944 }
10945
10946 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10947 // invalid since the ambiguity can affect the ABI.
10948 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10949 unsigned &SVEorRVV) {
10950 const VectorType *VecType = SecondType->getAs<VectorType>();
10951 SVEorRVV = 0;
10952 if (FirstType->isSizelessBuiltinType() && VecType) {
10955 return true;
10961 SVEorRVV = 1;
10962 return true;
10963 }
10964 }
10965
10966 return false;
10967 };
10968
10969 unsigned SVEorRVV;
10970 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10971 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10972 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10973 << SVEorRVV << LHSType << RHSType;
10974 return QualType();
10975 }
10976
10977 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10978 // invalid since the ambiguity can affect the ABI.
10979 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10980 unsigned &SVEorRVV) {
10981 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10982 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10983
10984 SVEorRVV = 0;
10985 if (FirstVecType && SecondVecType) {
10986 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10987 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10988 SecondVecType->getVectorKind() ==
10990 return true;
10991 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10992 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10993 SecondVecType->getVectorKind() ==
10995 SecondVecType->getVectorKind() ==
10997 SecondVecType->getVectorKind() ==
10999 SVEorRVV = 1;
11000 return true;
11001 }
11002 }
11003 return false;
11004 }
11005
11006 if (SecondVecType &&
11007 SecondVecType->getVectorKind() == VectorKind::Generic) {
11008 if (FirstType->isSVESizelessBuiltinType())
11009 return true;
11010 if (FirstType->isRVVSizelessBuiltinType()) {
11011 SVEorRVV = 1;
11012 return true;
11013 }
11014 }
11015
11016 return false;
11017 };
11018
11019 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
11020 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
11021 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
11022 << SVEorRVV << LHSType << RHSType;
11023 return QualType();
11024 }
11025
11026 // If there's a vector type and a scalar, try to convert the scalar to
11027 // the vector element type and splat.
11028 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
11029 if (!RHSVecType) {
11030 if (isa<ExtVectorType>(LHSVecType)) {
11031 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
11032 LHSVecType->getElementType(), LHSType,
11033 DiagID))
11034 return LHSType;
11035 } else {
11036 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11037 return LHSType;
11038 }
11039 }
11040 if (!LHSVecType) {
11041 if (isa<ExtVectorType>(RHSVecType)) {
11042 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
11043 LHSType, RHSVecType->getElementType(),
11044 RHSType, DiagID))
11045 return RHSType;
11046 } else {
11047 if (LHS.get()->isLValue() ||
11048 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11049 return RHSType;
11050 }
11051 }
11052
11053 // FIXME: The code below also handles conversion between vectors and
11054 // non-scalars, we should break this down into fine grained specific checks
11055 // and emit proper diagnostics.
11056 QualType VecType = LHSVecType ? LHSType : RHSType;
11057 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
11058 QualType OtherType = LHSVecType ? RHSType : LHSType;
11059 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
11060 if (isLaxVectorConversion(OtherType, VecType)) {
11061 if (Context.getTargetInfo().getTriple().isPPC() &&
11062 anyAltivecTypes(RHSType, LHSType) &&
11063 !Context.areCompatibleVectorTypes(RHSType, LHSType))
11064 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
11065 // If we're allowing lax vector conversions, only the total (data) size
11066 // needs to be the same. For non compound assignment, if one of the types is
11067 // scalar, the result is always the vector type.
11068 if (!IsCompAssign) {
11069 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
11070 return VecType;
11071 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11072 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11073 // type. Note that this is already done by non-compound assignments in
11074 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11075 // <1 x T> -> T. The result is also a vector type.
11076 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
11077 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
11078 ExprResult *RHSExpr = &RHS;
11079 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
11080 return VecType;
11081 }
11082 }
11083
11084 // Okay, the expression is invalid.
11085
11086 // If there's a non-vector, non-real operand, diagnose that.
11087 if ((!RHSVecType && !RHSType->isRealType()) ||
11088 (!LHSVecType && !LHSType->isRealType())) {
11089 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11090 << LHSType << RHSType
11091 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11092 return QualType();
11093 }
11094
11095 // OpenCL V1.1 6.2.6.p1:
11096 // If the operands are of more than one vector type, then an error shall
11097 // occur. Implicit conversions between vector types are not permitted, per
11098 // section 6.2.1.
11099 if (getLangOpts().OpenCL &&
11100 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
11101 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
11102 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
11103 << RHSType;
11104 return QualType();
11105 }
11106
11107
11108 // If there is a vector type that is not a ExtVector and a scalar, we reach
11109 // this point if scalar could not be converted to the vector's element type
11110 // without truncation.
11111 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
11112 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
11113 QualType Scalar = LHSVecType ? RHSType : LHSType;
11114 QualType Vector = LHSVecType ? LHSType : RHSType;
11115 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11116 Diag(Loc,
11117 diag::err_typecheck_vector_not_convertable_implict_truncation)
11118 << ScalarOrVector << Scalar << Vector;
11119
11120 return QualType();
11121 }
11122
11123 // Otherwise, use the generic diagnostic.
11124 Diag(Loc, DiagID)
11125 << LHSType << RHSType
11126 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11127 return QualType();
11128}
11129
11131 SourceLocation Loc,
11132 bool IsCompAssign,
11133 ArithConvKind OperationKind) {
11134 if (!IsCompAssign) {
11136 if (LHS.isInvalid())
11137 return QualType();
11138 }
11140 if (RHS.isInvalid())
11141 return QualType();
11142
11143 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11144 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11145
11146 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11147 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11148
11149 unsigned DiagID = diag::err_typecheck_invalid_operands;
11150 if ((OperationKind == ArithConvKind::Arithmetic) &&
11151 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11152 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11153 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11154 << RHS.get()->getSourceRange();
11155 return QualType();
11156 }
11157
11158 if (Context.hasSameType(LHSType, RHSType))
11159 return LHSType;
11160
11161 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11162 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11163 return LHSType;
11164 }
11165 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11166 if (LHS.get()->isLValue() ||
11167 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11168 return RHSType;
11169 }
11170
11171 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11172 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11173 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11174 << LHSType << RHSType << LHS.get()->getSourceRange()
11175 << RHS.get()->getSourceRange();
11176 return QualType();
11177 }
11178
11179 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11180 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11181 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11182 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11183 << LHSType << RHSType << LHS.get()->getSourceRange()
11184 << RHS.get()->getSourceRange();
11185 return QualType();
11186 }
11187
11188 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11189 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11190 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11191 bool ScalarOrVector =
11192 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11193
11194 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11195 << ScalarOrVector << Scalar << Vector;
11196
11197 return QualType();
11198 }
11199
11200 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11201 << RHS.get()->getSourceRange();
11202 return QualType();
11203}
11204
11205// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11206// expression. These are mainly cases where the null pointer is used as an
11207// integer instead of a pointer.
11209 SourceLocation Loc, bool IsCompare) {
11210 // The canonical way to check for a GNU null is with isNullPointerConstant,
11211 // but we use a bit of a hack here for speed; this is a relatively
11212 // hot path, and isNullPointerConstant is slow.
11213 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11214 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11215
11216 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11217
11218 // Avoid analyzing cases where the result will either be invalid (and
11219 // diagnosed as such) or entirely valid and not something to warn about.
11220 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11221 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11222 return;
11223
11224 // Comparison operations would not make sense with a null pointer no matter
11225 // what the other expression is.
11226 if (!IsCompare) {
11227 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11228 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11229 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11230 return;
11231 }
11232
11233 // The rest of the operations only make sense with a null pointer
11234 // if the other expression is a pointer.
11235 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11236 NonNullType->canDecayToPointerType())
11237 return;
11238
11239 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11240 << LHSNull /* LHS is NULL */ << NonNullType
11241 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11242}
11243
11245 SourceLocation OpLoc) {
11246 // If the divisor is real, then this is real/real or complex/real division.
11247 // Either way there can be no precision loss.
11248 auto *CT = DivisorTy->getAs<ComplexType>();
11249 if (!CT)
11250 return;
11251
11252 QualType ElementType = CT->getElementType().getCanonicalType();
11253 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11255 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11256 return;
11257
11258 ASTContext &Ctx = S.getASTContext();
11259 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11260 const llvm::fltSemantics &ElementTypeSemantics =
11261 Ctx.getFloatTypeSemantics(ElementType);
11262 const llvm::fltSemantics &HigherElementTypeSemantics =
11263 Ctx.getFloatTypeSemantics(HigherElementType);
11264
11265 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11266 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11267 (HigherElementType == Ctx.LongDoubleTy &&
11268 !Ctx.getTargetInfo().hasLongDoubleType())) {
11269 // Retain the location of the first use of higher precision type.
11272 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11273 if (Type == HigherElementType) {
11274 Num++;
11275 return;
11276 }
11277 }
11278 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
11279 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
11280 }
11281}
11282
11284 SourceLocation Loc) {
11285 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11286 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11287 if (!LUE || !RUE)
11288 return;
11289 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11290 RUE->getKind() != UETT_SizeOf)
11291 return;
11292
11293 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11294 QualType LHSTy = LHSArg->getType();
11295 QualType RHSTy;
11296
11297 if (RUE->isArgumentType())
11298 RHSTy = RUE->getArgumentType().getNonReferenceType();
11299 else
11300 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11301
11302 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11303 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11304 return;
11305
11306 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11307 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11308 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11309 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11310 << LHSArgDecl;
11311 }
11312 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11313 QualType ArrayElemTy = ArrayTy->getElementType();
11314 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11315 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11316 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11317 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11318 return;
11319 S.Diag(Loc, diag::warn_division_sizeof_array)
11320 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11321 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11322 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11323 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11324 << LHSArgDecl;
11325 }
11326
11327 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11328 }
11329}
11330
11332 ExprResult &RHS,
11333 SourceLocation Loc, bool IsDiv) {
11334 // Check for division/remainder by zero.
11335 Expr::EvalResult RHSValue;
11336 if (!RHS.get()->isValueDependent() &&
11337 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11338 RHSValue.Val.getInt() == 0)
11339 S.DiagRuntimeBehavior(Loc, RHS.get(),
11340 S.PDiag(diag::warn_remainder_division_by_zero)
11341 << IsDiv << RHS.get()->getSourceRange());
11342}
11343
11344static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11345 const ExprResult &LHS, const ExprResult &RHS,
11346 BinaryOperatorKind Opc) {
11347 if (!LHS.isUsable() || !RHS.isUsable())
11348 return;
11349 const Expr *LHSExpr = LHS.get();
11350 const Expr *RHSExpr = RHS.get();
11351 const QualType LHSType = LHSExpr->getType();
11352 const QualType RHSType = RHSExpr->getType();
11353 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11354 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11355 if (!LHSIsScoped && !RHSIsScoped)
11356 return;
11357 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11358 return;
11359 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11360 return;
11361 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11362 return;
11363 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11364 SourceLocation BeginLoc = expr->getBeginLoc();
11365 QualType IntType = type->castAs<EnumType>()
11366 ->getDecl()
11367 ->getDefinitionOrSelf()
11368 ->getIntegerType();
11369 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11370 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
11371 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
11372 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
11373 };
11374 if (LHSIsScoped) {
11375 DiagnosticHelper(LHSExpr, LHSType);
11376 }
11377 if (RHSIsScoped) {
11378 DiagnosticHelper(RHSExpr, RHSType);
11379 }
11380}
11381
11383 SourceLocation Loc,
11384 BinaryOperatorKind Opc) {
11385 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11386 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11387
11388 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11389
11390 QualType LHSTy = LHS.get()->getType();
11391 QualType RHSTy = RHS.get()->getType();
11392 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11393 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11394 /*AllowBothBool*/ getLangOpts().AltiVec,
11395 /*AllowBoolConversions*/ false,
11396 /*AllowBooleanOperation*/ false);
11397 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11398 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11400 if (!IsDiv &&
11401 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11402 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11403 // For division, only matrix-by-scalar is supported. Other combinations with
11404 // matrix types are invalid.
11405 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11406 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11407
11409 LHS, RHS, Loc,
11411 if (LHS.isInvalid() || RHS.isInvalid())
11412 return QualType();
11413
11414 if (compType.isNull() || !compType->isArithmeticType()) {
11415 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11416 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11417 return ResultTy;
11418 }
11419 if (IsDiv) {
11420 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
11421 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11422 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11423 }
11424 return compType;
11425}
11426
11428 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11429 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11430
11431 // Note: This check is here to simplify the double exclusions of
11432 // scalar and vector HLSL checks. No getLangOpts().HLSL
11433 // is needed since all languages exlcude doubles.
11434 if (LHS.get()->getType()->isDoubleType() ||
11435 RHS.get()->getType()->isDoubleType() ||
11436 (LHS.get()->getType()->isVectorType() && LHS.get()
11437 ->getType()
11438 ->getAs<VectorType>()
11439 ->getElementType()
11440 ->isDoubleType()) ||
11441 (RHS.get()->getType()->isVectorType() && RHS.get()
11442 ->getType()
11443 ->getAs<VectorType>()
11444 ->getElementType()
11445 ->isDoubleType()))
11446 return InvalidOperands(Loc, LHS, RHS);
11447
11448 if (LHS.get()->getType()->isVectorType() ||
11449 RHS.get()->getType()->isVectorType()) {
11450 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11451 RHS.get()->getType()->hasIntegerRepresentation()) ||
11452 (getLangOpts().HLSL &&
11453 (LHS.get()->getType()->hasFloatingRepresentation() ||
11455 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11456 /*AllowBothBool*/ getLangOpts().AltiVec,
11457 /*AllowBoolConversions*/ false,
11458 /*AllowBooleanOperation*/ false);
11459 return InvalidOperands(Loc, LHS, RHS);
11460 }
11461
11462 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11463 RHS.get()->getType()->isSveVLSBuiltinType()) {
11464 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11466 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11468
11469 return InvalidOperands(Loc, LHS, RHS);
11470 }
11471
11473 LHS, RHS, Loc,
11475 if (LHS.isInvalid() || RHS.isInvalid())
11476 return QualType();
11477
11478 if (compType.isNull() ||
11479 (!compType->isIntegerType() &&
11480 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11481 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11482 diagnoseScopedEnums(*this, Loc, LHS, RHS,
11483 IsCompAssign ? BO_RemAssign : BO_Rem);
11484 return ResultTy;
11485 }
11486 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11487 return compType;
11488}
11489
11490/// Diagnose invalid arithmetic on two void pointers.
11492 Expr *LHSExpr, Expr *RHSExpr) {
11493 S.Diag(Loc, S.getLangOpts().CPlusPlus
11494 ? diag::err_typecheck_pointer_arith_void_type
11495 : diag::ext_gnu_void_ptr)
11496 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11497 << RHSExpr->getSourceRange();
11498}
11499
11500/// Diagnose invalid arithmetic on a void pointer.
11502 Expr *Pointer) {
11503 S.Diag(Loc, S.getLangOpts().CPlusPlus
11504 ? diag::err_typecheck_pointer_arith_void_type
11505 : diag::ext_gnu_void_ptr)
11506 << 0 /* one pointer */ << Pointer->getSourceRange();
11507}
11508
11509/// Diagnose invalid arithmetic on a null pointer.
11510///
11511/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11512/// idiom, which we recognize as a GNU extension.
11513///
11515 Expr *Pointer, bool IsGNUIdiom) {
11516 if (IsGNUIdiom)
11517 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11518 << Pointer->getSourceRange();
11519 else
11520 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11521 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11522}
11523
11524/// Diagnose invalid subraction on a null pointer.
11525///
11527 Expr *Pointer, bool BothNull) {
11528 // Null - null is valid in C++ [expr.add]p7
11529 if (BothNull && S.getLangOpts().CPlusPlus)
11530 return;
11531
11532 // Is this s a macro from a system header?
11534 return;
11535
11537 S.PDiag(diag::warn_pointer_sub_null_ptr)
11538 << S.getLangOpts().CPlusPlus
11539 << Pointer->getSourceRange());
11540}
11541
11542/// Diagnose invalid arithmetic on two function pointers.
11544 Expr *LHS, Expr *RHS) {
11545 assert(LHS->getType()->isAnyPointerType());
11546 assert(RHS->getType()->isAnyPointerType());
11547 S.Diag(Loc, S.getLangOpts().CPlusPlus
11548 ? diag::err_typecheck_pointer_arith_function_type
11549 : diag::ext_gnu_ptr_func_arith)
11550 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11551 // We only show the second type if it differs from the first.
11553 RHS->getType())
11554 << RHS->getType()->getPointeeType()
11555 << LHS->getSourceRange() << RHS->getSourceRange();
11556}
11557
11558/// Diagnose invalid arithmetic on a function pointer.
11560 Expr *Pointer) {
11561 assert(Pointer->getType()->isAnyPointerType());
11562 S.Diag(Loc, S.getLangOpts().CPlusPlus
11563 ? diag::err_typecheck_pointer_arith_function_type
11564 : diag::ext_gnu_ptr_func_arith)
11565 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11566 << 0 /* one pointer, so only one type */
11567 << Pointer->getSourceRange();
11568}
11569
11570/// Emit error if Operand is incomplete pointer type
11571///
11572/// \returns True if pointer has incomplete type
11574 Expr *Operand) {
11575 QualType ResType = Operand->getType();
11576 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11577 ResType = ResAtomicType->getValueType();
11578
11579 assert(ResType->isAnyPointerType());
11580 QualType PointeeTy = ResType->getPointeeType();
11581 return S.RequireCompleteSizedType(
11582 Loc, PointeeTy,
11583 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11584 Operand->getSourceRange());
11585}
11586
11587/// Check the validity of an arithmetic pointer operand.
11588///
11589/// If the operand has pointer type, this code will check for pointer types
11590/// which are invalid in arithmetic operations. These will be diagnosed
11591/// appropriately, including whether or not the use is supported as an
11592/// extension.
11593///
11594/// \returns True when the operand is valid to use (even if as an extension).
11596 Expr *Operand) {
11597 QualType ResType = Operand->getType();
11598 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11599 ResType = ResAtomicType->getValueType();
11600
11601 if (!ResType->isAnyPointerType()) return true;
11602
11603 QualType PointeeTy = ResType->getPointeeType();
11604 if (PointeeTy->isVoidType()) {
11605 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11606 return !S.getLangOpts().CPlusPlus;
11607 }
11608 if (PointeeTy->isFunctionType()) {
11609 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11610 return !S.getLangOpts().CPlusPlus;
11611 }
11612
11613 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11614
11615 return true;
11616}
11617
11618/// Check the validity of a binary arithmetic operation w.r.t. pointer
11619/// operands.
11620///
11621/// This routine will diagnose any invalid arithmetic on pointer operands much
11622/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11623/// for emitting a single diagnostic even for operations where both LHS and RHS
11624/// are (potentially problematic) pointers.
11625///
11626/// \returns True when the operand is valid to use (even if as an extension).
11628 Expr *LHSExpr, Expr *RHSExpr) {
11629 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11630 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11631 if (!isLHSPointer && !isRHSPointer) return true;
11632
11633 QualType LHSPointeeTy, RHSPointeeTy;
11634 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11635 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11636
11637 // if both are pointers check if operation is valid wrt address spaces
11638 if (isLHSPointer && isRHSPointer) {
11639 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11640 S.getASTContext())) {
11641 S.Diag(Loc,
11642 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11643 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11644 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11645 return false;
11646 }
11647 }
11648
11649 // Check for arithmetic on pointers to incomplete types.
11650 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11651 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11652 if (isLHSVoidPtr || isRHSVoidPtr) {
11653 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11654 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11655 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11656
11657 return !S.getLangOpts().CPlusPlus;
11658 }
11659
11660 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11661 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11662 if (isLHSFuncPtr || isRHSFuncPtr) {
11663 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11664 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11665 RHSExpr);
11666 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11667
11668 return !S.getLangOpts().CPlusPlus;
11669 }
11670
11671 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11672 return false;
11673 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11674 return false;
11675
11676 return true;
11677}
11678
11679/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11680/// literal.
11682 Expr *LHSExpr, Expr *RHSExpr) {
11683 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11684 Expr* IndexExpr = RHSExpr;
11685 if (!StrExpr) {
11686 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11687 IndexExpr = LHSExpr;
11688 }
11689
11690 bool IsStringPlusInt = StrExpr &&
11692 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11693 return;
11694
11695 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11696 Self.Diag(OpLoc, diag::warn_string_plus_int)
11697 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11698
11699 // Only print a fixit for "str" + int, not for int + "str".
11700 if (IndexExpr == RHSExpr) {
11701 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11702 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11703 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11705 << FixItHint::CreateInsertion(EndLoc, "]");
11706 } else
11707 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11708}
11709
11710/// Emit a warning when adding a char literal to a string.
11712 Expr *LHSExpr, Expr *RHSExpr) {
11713 const Expr *StringRefExpr = LHSExpr;
11714 const CharacterLiteral *CharExpr =
11715 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11716
11717 if (!CharExpr) {
11718 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11719 StringRefExpr = RHSExpr;
11720 }
11721
11722 if (!CharExpr || !StringRefExpr)
11723 return;
11724
11725 const QualType StringType = StringRefExpr->getType();
11726
11727 // Return if not a PointerType.
11728 if (!StringType->isAnyPointerType())
11729 return;
11730
11731 // Return if not a CharacterType.
11732 if (!StringType->getPointeeType()->isAnyCharacterType())
11733 return;
11734
11735 ASTContext &Ctx = Self.getASTContext();
11736 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11737
11738 const QualType CharType = CharExpr->getType();
11739 if (!CharType->isAnyCharacterType() &&
11740 CharType->isIntegerType() &&
11741 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11742 Self.Diag(OpLoc, diag::warn_string_plus_char)
11743 << DiagRange << Ctx.CharTy;
11744 } else {
11745 Self.Diag(OpLoc, diag::warn_string_plus_char)
11746 << DiagRange << CharExpr->getType();
11747 }
11748
11749 // Only print a fixit for str + char, not for char + str.
11750 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11751 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11752 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11753 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11755 << FixItHint::CreateInsertion(EndLoc, "]");
11756 } else {
11757 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11758 }
11759}
11760
11761/// Emit error when two pointers are incompatible.
11763 Expr *LHSExpr, Expr *RHSExpr) {
11764 assert(LHSExpr->getType()->isAnyPointerType());
11765 assert(RHSExpr->getType()->isAnyPointerType());
11766 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11767 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11768 << RHSExpr->getSourceRange();
11769}
11770
11771// C99 6.5.6
11774 QualType* CompLHSTy) {
11775 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11776
11777 if (LHS.get()->getType()->isVectorType() ||
11778 RHS.get()->getType()->isVectorType()) {
11779 QualType compType =
11780 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11781 /*AllowBothBool*/ getLangOpts().AltiVec,
11782 /*AllowBoolConversions*/ getLangOpts().ZVector,
11783 /*AllowBooleanOperation*/ false);
11784 if (CompLHSTy) *CompLHSTy = compType;
11785 return compType;
11786 }
11787
11788 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11789 RHS.get()->getType()->isSveVLSBuiltinType()) {
11790 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11792 if (CompLHSTy)
11793 *CompLHSTy = compType;
11794 return compType;
11795 }
11796
11797 if (LHS.get()->getType()->isConstantMatrixType() ||
11798 RHS.get()->getType()->isConstantMatrixType()) {
11799 QualType compType =
11800 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11801 if (CompLHSTy)
11802 *CompLHSTy = compType;
11803 return compType;
11804 }
11805
11807 LHS, RHS, Loc,
11809 if (LHS.isInvalid() || RHS.isInvalid())
11810 return QualType();
11811
11812 // Diagnose "string literal" '+' int and string '+' "char literal".
11813 if (Opc == BO_Add) {
11814 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11815 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11816 }
11817
11818 // handle the common case first (both operands are arithmetic).
11819 if (!compType.isNull() && compType->isArithmeticType()) {
11820 if (CompLHSTy) *CompLHSTy = compType;
11821 return compType;
11822 }
11823
11824 // Type-checking. Ultimately the pointer's going to be in PExp;
11825 // note that we bias towards the LHS being the pointer.
11826 Expr *PExp = LHS.get(), *IExp = RHS.get();
11827
11828 bool isObjCPointer;
11829 if (PExp->getType()->isPointerType()) {
11830 isObjCPointer = false;
11831 } else if (PExp->getType()->isObjCObjectPointerType()) {
11832 isObjCPointer = true;
11833 } else {
11834 std::swap(PExp, IExp);
11835 if (PExp->getType()->isPointerType()) {
11836 isObjCPointer = false;
11837 } else if (PExp->getType()->isObjCObjectPointerType()) {
11838 isObjCPointer = true;
11839 } else {
11840 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11841 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11842 return ResultTy;
11843 }
11844 }
11845 assert(PExp->getType()->isAnyPointerType());
11846
11847 if (!IExp->getType()->isIntegerType())
11848 return InvalidOperands(Loc, LHS, RHS);
11849
11850 // Adding to a null pointer results in undefined behavior.
11853 // In C++ adding zero to a null pointer is defined.
11854 Expr::EvalResult KnownVal;
11855 if (!getLangOpts().CPlusPlus ||
11856 (!IExp->isValueDependent() &&
11857 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11858 KnownVal.Val.getInt() != 0))) {
11859 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11861 Context, BO_Add, PExp, IExp);
11862 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11863 }
11864 }
11865
11866 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11867 return QualType();
11868
11869 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11870 return QualType();
11871
11872 // Arithmetic on label addresses is normally allowed, except when we add
11873 // a ptrauth signature to the addresses.
11874 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11875 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11876 << /*addition*/ 1;
11877 return QualType();
11878 }
11879
11880 // Check array bounds for pointer arithemtic
11881 CheckArrayAccess(PExp, IExp);
11882
11883 if (CompLHSTy) {
11884 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11885 if (LHSTy.isNull()) {
11886 LHSTy = LHS.get()->getType();
11887 if (Context.isPromotableIntegerType(LHSTy))
11888 LHSTy = Context.getPromotedIntegerType(LHSTy);
11889 }
11890 *CompLHSTy = LHSTy;
11891 }
11892
11893 return PExp->getType();
11894}
11895
11896/// Determine whether the size of \p T is provably zero: some array dimension
11897/// is provably zero or the base element type has zero size. A variable
11898/// dimension that does not fold to an integer constant is assumed nonzero.
11899static bool isProvablyZeroSize(const ASTContext &Ctx, QualType T) {
11900 while (const ArrayType *AT = Ctx.getAsArrayType(T)) {
11901 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
11902 if (CAT->isZeroSize())
11903 return true;
11904 } else if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
11905 if (const Expr *Bound = VAT->getSizeExpr())
11906 if (std::optional<llvm::APSInt> Size =
11907 Bound->getIntegerConstantExpr(Ctx))
11908 if (*Size == 0)
11909 return true;
11910 }
11911 T = AT->getElementType();
11912 }
11913 return !T->isIncompleteType() && Ctx.getTypeSizeInChars(T).isZero();
11914}
11915
11916// C99 6.5.6
11918 SourceLocation Loc,
11920 QualType *CompLHSTy) {
11921 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11922
11923 if (LHS.get()->getType()->isVectorType() ||
11924 RHS.get()->getType()->isVectorType()) {
11925 QualType compType =
11926 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11927 /*AllowBothBool*/ getLangOpts().AltiVec,
11928 /*AllowBoolConversions*/ getLangOpts().ZVector,
11929 /*AllowBooleanOperation*/ false);
11930 if (CompLHSTy) *CompLHSTy = compType;
11931 return compType;
11932 }
11933
11934 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11935 RHS.get()->getType()->isSveVLSBuiltinType()) {
11936 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11938 if (CompLHSTy)
11939 *CompLHSTy = compType;
11940 return compType;
11941 }
11942
11943 if (LHS.get()->getType()->isConstantMatrixType() ||
11944 RHS.get()->getType()->isConstantMatrixType()) {
11945 QualType compType =
11946 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11947 if (CompLHSTy)
11948 *CompLHSTy = compType;
11949 return compType;
11950 }
11951
11953 LHS, RHS, Loc,
11955 if (LHS.isInvalid() || RHS.isInvalid())
11956 return QualType();
11957
11958 // Enforce type constraints: C99 6.5.6p3.
11959
11960 // Handle the common case first (both operands are arithmetic).
11961 if (!compType.isNull() && compType->isArithmeticType()) {
11962 if (CompLHSTy) *CompLHSTy = compType;
11963 return compType;
11964 }
11965
11966 // Either ptr - int or ptr - ptr.
11967 if (LHS.get()->getType()->isAnyPointerType()) {
11968 QualType lpointee = LHS.get()->getType()->getPointeeType();
11969
11970 // Diagnose bad cases where we step over interface counts.
11971 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11972 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11973 return QualType();
11974
11975 // Arithmetic on label addresses is normally allowed, except when we add
11976 // a ptrauth signature to the addresses.
11977 if (isa<AddrLabelExpr>(LHS.get()) &&
11978 getLangOpts().PointerAuthIndirectGotos) {
11979 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11980 << /*subtraction*/ 0;
11981 return QualType();
11982 }
11983
11984 // The result type of a pointer-int computation is the pointer type.
11985 if (RHS.get()->getType()->isIntegerType()) {
11986 // Subtracting from a null pointer should produce a warning.
11987 // The last argument to the diagnose call says this doesn't match the
11988 // GNU int-to-pointer idiom.
11991 // In C++ adding zero to a null pointer is defined.
11992 Expr::EvalResult KnownVal;
11993 if (!getLangOpts().CPlusPlus ||
11994 (!RHS.get()->isValueDependent() &&
11995 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11996 KnownVal.Val.getInt() != 0))) {
11997 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11998 }
11999 }
12000
12001 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
12002 return QualType();
12003
12004 // Check array bounds for pointer arithemtic
12005 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
12006 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
12007
12008 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12009 return LHS.get()->getType();
12010 }
12011
12012 // Handle pointer-pointer subtractions.
12013 if (const PointerType *RHSPTy
12014 = RHS.get()->getType()->getAs<PointerType>()) {
12015 QualType rpointee = RHSPTy->getPointeeType();
12016
12017 if (getLangOpts().CPlusPlus) {
12018 // Pointee types must be the same: C++ [expr.add]
12019 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
12020 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
12021 }
12022 } else {
12023 // Pointee types must be compatible C99 6.5.6p3
12024 if (!Context.typesAreCompatible(
12025 Context.getCanonicalType(lpointee).getUnqualifiedType(),
12026 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
12027 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
12028 return QualType();
12029 }
12030 }
12031
12033 LHS.get(), RHS.get()))
12034 return QualType();
12035
12036 // For pointer subtraction, if the address spaces differ but overlap,
12037 // convert both pointers to the composite (superset) address space.
12038 // This is needed because address spaces may use different
12039 // representations, such as a private offset vs a flat address.
12040 LangAS LAddrSpace = lpointee.getAddressSpace();
12041 LangAS RAddrSpace = rpointee.getAddressSpace();
12042 if (LAddrSpace != RAddrSpace) {
12043 Qualifiers LQual = lpointee.getQualifiers();
12044 Qualifiers RQual = rpointee.getQualifiers();
12045 LangAS ResultAddrSpace = LQual.isAddressSpaceSupersetOf(RQual, Context)
12046 ? LAddrSpace
12047 : RAddrSpace;
12048
12049 if (LAddrSpace != ResultAddrSpace) {
12050 QualType NewPteTy = Context.getAddrSpaceQualType(
12051 lpointee.getUnqualifiedType(), ResultAddrSpace);
12052 QualType NewPtrTy = Context.getPointerType(NewPteTy);
12053 LHS =
12054 ImpCastExprToType(LHS.get(), NewPtrTy, CK_AddressSpaceConversion);
12055 }
12056 if (RAddrSpace != ResultAddrSpace) {
12057 QualType NewPteTy = Context.getAddrSpaceQualType(
12058 rpointee.getUnqualifiedType(), ResultAddrSpace);
12059 QualType NewPtrTy = Context.getPointerType(NewPteTy);
12060 RHS =
12061 ImpCastExprToType(RHS.get(), NewPtrTy, CK_AddressSpaceConversion);
12062 }
12063 }
12064
12065 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12067 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12069
12070 // Subtracting nullptr or from nullptr is suspect
12071 if (LHSIsNullPtr)
12072 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
12073 if (RHSIsNullPtr)
12074 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
12075
12076 // The pointee type may have zero size. As an extension, a structure or
12077 // union may have zero size or an array may have zero length. In this
12078 // case subtraction does not make sense. For a variably modified type,
12079 // warn only when the size is provably zero.
12080 if (!rpointee->isVoidType() && !rpointee->isFunctionType() &&
12081 isProvablyZeroSize(Context, rpointee))
12082 Diag(Loc, diag::warn_sub_ptr_zero_size_types)
12083 << rpointee.getUnqualifiedType() << LHS.get()->getSourceRange()
12084 << RHS.get()->getSourceRange();
12085
12086 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12087 return Context.getPointerDiffType();
12088 }
12089 }
12090
12091 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12092 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12093 return ResultTy;
12094}
12095
12097 if (const EnumType *ET = T->getAsCanonical<EnumType>())
12098 return ET->getDecl()->isScoped();
12099 return false;
12100}
12101
12104 QualType LHSType) {
12105 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
12106 // so skip remaining warnings as we don't want to modify values within Sema.
12107 if (S.getLangOpts().OpenCL)
12108 return;
12109
12110 if (Opc == BO_Shr &&
12112 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
12113
12114 // Check right/shifter operand
12115 Expr::EvalResult RHSResult;
12116 if (RHS.get()->isValueDependent() ||
12117 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
12118 return;
12119 llvm::APSInt Right = RHSResult.Val.getInt();
12120
12121 if (Right.isNegative()) {
12122 S.DiagRuntimeBehavior(Loc, RHS.get(),
12123 S.PDiag(diag::warn_shift_negative)
12124 << RHS.get()->getSourceRange());
12125 return;
12126 }
12127
12128 QualType LHSExprType = LHS.get()->getType();
12129 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
12130 if (LHSExprType->isBitIntType())
12131 LeftSize = S.Context.getIntWidth(LHSExprType);
12132 else if (LHSExprType->isFixedPointType()) {
12133 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
12134 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
12135 }
12136 if (Right.uge(LeftSize)) {
12137 S.DiagRuntimeBehavior(Loc, RHS.get(),
12138 S.PDiag(diag::warn_shift_gt_typewidth)
12139 << RHS.get()->getSourceRange());
12140 return;
12141 }
12142
12143 // FIXME: We probably need to handle fixed point types specially here.
12144 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12145 return;
12146
12147 // When left shifting an ICE which is signed, we can check for overflow which
12148 // according to C++ standards prior to C++2a has undefined behavior
12149 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12150 // more than the maximum value representable in the result type, so never
12151 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12152 // expression is still probably a bug.)
12153 Expr::EvalResult LHSResult;
12154 if (LHS.get()->isValueDependent() ||
12156 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
12157 return;
12158 llvm::APSInt Left = LHSResult.Val.getInt();
12159
12160 // Don't warn if signed overflow is defined, then all the rest of the
12161 // diagnostics will not be triggered because the behavior is defined.
12162 // Also don't warn in C++20 mode (and newer), as signed left shifts
12163 // always wrap and never overflow.
12164 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12165 return;
12166
12167 // If LHS does not have a non-negative value then, the
12168 // behavior is undefined before C++2a. Warn about it.
12169 if (Left.isNegative()) {
12170 S.DiagRuntimeBehavior(Loc, LHS.get(),
12171 S.PDiag(diag::warn_shift_lhs_negative)
12172 << LHS.get()->getSourceRange());
12173 return;
12174 }
12175
12176 llvm::APInt ResultBits =
12177 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12178 if (ResultBits.ule(LeftSize))
12179 return;
12180 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
12181 Result = Result.shl(Right);
12182
12183 // Print the bit representation of the signed integer as an unsigned
12184 // hexadecimal number.
12185 SmallString<40> HexResult;
12186 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
12187
12188 // If we are only missing a sign bit, this is less likely to result in actual
12189 // bugs -- if the result is cast back to an unsigned type, it will have the
12190 // expected value. Thus we place this behind a different warning that can be
12191 // turned off separately if needed.
12192 if (ResultBits - 1 == LeftSize) {
12193 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
12194 << HexResult << LHSType
12195 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12196 return;
12197 }
12198
12199 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
12200 << HexResult.str() << Result.getSignificantBits() << LHSType
12201 << Left.getBitWidth() << LHS.get()->getSourceRange()
12202 << RHS.get()->getSourceRange();
12203}
12204
12205/// Return the resulting type when a vector is shifted
12206/// by a scalar or vector shift amount.
12208 SourceLocation Loc, bool IsCompAssign) {
12209 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12210 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12211 !LHS.get()->getType()->isVectorType()) {
12212 S.Diag(Loc, diag::err_shift_rhs_only_vector)
12213 << RHS.get()->getType() << LHS.get()->getType()
12214 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12215 return QualType();
12216 }
12217
12218 if (!IsCompAssign) {
12219 LHS = S.UsualUnaryConversions(LHS.get());
12220 if (LHS.isInvalid()) return QualType();
12221 }
12222
12223 RHS = S.UsualUnaryConversions(RHS.get());
12224 if (RHS.isInvalid()) return QualType();
12225
12226 QualType LHSType = LHS.get()->getType();
12227 // Note that LHS might be a scalar because the routine calls not only in
12228 // OpenCL case.
12229 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12230 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12231
12232 // Note that RHS might not be a vector.
12233 QualType RHSType = RHS.get()->getType();
12234 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12235 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12236
12237 // Do not allow shifts for boolean vectors.
12238 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12239 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12240 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12241 << LHS.get()->getType() << RHS.get()->getType()
12242 << LHS.get()->getSourceRange();
12243 return QualType();
12244 }
12245
12246 // The operands need to be integers.
12247 if (!LHSEleType->isIntegerType()) {
12248 S.Diag(Loc, diag::err_typecheck_expect_int)
12249 << LHS.get()->getType() << LHS.get()->getSourceRange();
12250 return QualType();
12251 }
12252
12253 if (!RHSEleType->isIntegerType()) {
12254 S.Diag(Loc, diag::err_typecheck_expect_int)
12255 << RHS.get()->getType() << RHS.get()->getSourceRange();
12256 return QualType();
12257 }
12258
12259 if (!LHSVecTy) {
12260 assert(RHSVecTy);
12261 if (IsCompAssign)
12262 return RHSType;
12263 if (LHSEleType != RHSEleType) {
12264 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
12265 LHSEleType = RHSEleType;
12266 }
12267 QualType VecTy =
12268 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
12269 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
12270 LHSType = VecTy;
12271 } else if (RHSVecTy) {
12272 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12273 // are applied component-wise. So if RHS is a vector, then ensure
12274 // that the number of elements is the same as LHS...
12275 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12276 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12277 << LHS.get()->getType() << RHS.get()->getType()
12278 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12279 return QualType();
12280 }
12281 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12282 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12283 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12284 if (LHSBT != RHSBT &&
12285 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12286 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12287 << LHS.get()->getType() << RHS.get()->getType()
12288 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12289 }
12290 }
12291 } else {
12292 // ...else expand RHS to match the number of elements in LHS.
12293 QualType VecTy =
12294 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12295 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12296 }
12297
12298 return LHSType;
12299}
12300
12302 ExprResult &RHS, SourceLocation Loc,
12303 bool IsCompAssign) {
12304 if (!IsCompAssign) {
12305 LHS = S.UsualUnaryConversions(LHS.get());
12306 if (LHS.isInvalid())
12307 return QualType();
12308 }
12309
12310 RHS = S.UsualUnaryConversions(RHS.get());
12311 if (RHS.isInvalid())
12312 return QualType();
12313
12314 QualType LHSType = LHS.get()->getType();
12315 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12316 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12317 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12318 : LHSType;
12319
12320 // Note that RHS might not be a vector
12321 QualType RHSType = RHS.get()->getType();
12322 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12323 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12324 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12325 : RHSType;
12326
12327 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12328 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12329 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12330 << LHSType << RHSType << LHS.get()->getSourceRange();
12331 return QualType();
12332 }
12333
12334 if (!LHSEleType->isIntegerType()) {
12335 S.Diag(Loc, diag::err_typecheck_expect_int)
12336 << LHS.get()->getType() << LHS.get()->getSourceRange();
12337 return QualType();
12338 }
12339
12340 if (!RHSEleType->isIntegerType()) {
12341 S.Diag(Loc, diag::err_typecheck_expect_int)
12342 << RHS.get()->getType() << RHS.get()->getSourceRange();
12343 return QualType();
12344 }
12345
12346 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12347 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12348 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12349 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12350 << LHSType << RHSType << LHS.get()->getSourceRange()
12351 << RHS.get()->getSourceRange();
12352 return QualType();
12353 }
12354
12355 if (!LHSType->isSveVLSBuiltinType()) {
12356 assert(RHSType->isSveVLSBuiltinType());
12357 if (IsCompAssign)
12358 return RHSType;
12359 if (LHSEleType != RHSEleType) {
12360 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12361 LHSEleType = RHSEleType;
12362 }
12363 const llvm::ElementCount VecSize =
12364 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12365 QualType VecTy =
12366 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12367 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12368 LHSType = VecTy;
12369 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12370 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12371 S.Context.getTypeSize(LHSBuiltinTy)) {
12372 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12373 << LHSType << RHSType << LHS.get()->getSourceRange()
12374 << RHS.get()->getSourceRange();
12375 return QualType();
12376 }
12377 } else {
12378 const llvm::ElementCount VecSize =
12379 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12380 if (LHSEleType != RHSEleType) {
12381 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12382 RHSEleType = LHSEleType;
12383 }
12384 QualType VecTy =
12385 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12386 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12387 }
12388
12389 return LHSType;
12390}
12391
12392// C99 6.5.7
12395 bool IsCompAssign) {
12396 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12397
12398 // Vector shifts promote their scalar inputs to vector type.
12399 if (LHS.get()->getType()->isVectorType() ||
12400 RHS.get()->getType()->isVectorType()) {
12401 if (LangOpts.ZVector) {
12402 // The shift operators for the z vector extensions work basically
12403 // like general shifts, except that neither the LHS nor the RHS is
12404 // allowed to be a "vector bool".
12405 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12406 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12407 return InvalidOperands(Loc, LHS, RHS);
12408 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12409 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12410 return InvalidOperands(Loc, LHS, RHS);
12411 }
12412 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12413 }
12414
12415 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12416 RHS.get()->getType()->isSveVLSBuiltinType())
12417 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12418
12419 // Shifts don't perform usual arithmetic conversions, they just do integer
12420 // promotions on each operand. C99 6.5.7p3
12421
12422 // For the LHS, do usual unary conversions, but then reset them away
12423 // if this is a compound assignment.
12424 ExprResult OldLHS = LHS;
12425 LHS = UsualUnaryConversions(LHS.get());
12426 if (LHS.isInvalid())
12427 return QualType();
12428 QualType LHSType = LHS.get()->getType();
12429 if (IsCompAssign) LHS = OldLHS;
12430
12431 // The RHS is simpler.
12432 RHS = UsualUnaryConversions(RHS.get());
12433 if (RHS.isInvalid())
12434 return QualType();
12435 QualType RHSType = RHS.get()->getType();
12436
12437 // C99 6.5.7p2: Each of the operands shall have integer type.
12438 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12439 if ((!LHSType->isFixedPointOrIntegerType() &&
12440 !LHSType->hasIntegerRepresentation()) ||
12441 !RHSType->hasIntegerRepresentation()) {
12442 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12443 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12444 return ResultTy;
12445 }
12446
12447 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12448
12449 // "The type of the result is that of the promoted left operand."
12450 return LHSType;
12451}
12452
12453/// Diagnose bad pointer comparisons.
12455 ExprResult &LHS, ExprResult &RHS,
12456 bool IsError) {
12457 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12458 : diag::ext_typecheck_comparison_of_distinct_pointers)
12459 << LHS.get()->getType() << RHS.get()->getType()
12460 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12461}
12462
12463/// Returns false if the pointers are converted to a composite type,
12464/// true otherwise.
12466 ExprResult &LHS, ExprResult &RHS) {
12467 // C++ [expr.rel]p2:
12468 // [...] Pointer conversions (4.10) and qualification
12469 // conversions (4.4) are performed on pointer operands (or on
12470 // a pointer operand and a null pointer constant) to bring
12471 // them to their composite pointer type. [...]
12472 //
12473 // C++ [expr.eq]p1 uses the same notion for (in)equality
12474 // comparisons of pointers.
12475
12476 QualType LHSType = LHS.get()->getType();
12477 QualType RHSType = RHS.get()->getType();
12478 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12479 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12480
12481 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12482 if (T.isNull()) {
12483 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12484 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12485 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12486 else
12487 S.InvalidOperands(Loc, LHS, RHS);
12488 return true;
12489 }
12490
12491 return false;
12492}
12493
12495 ExprResult &LHS,
12496 ExprResult &RHS,
12497 bool IsError) {
12498 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12499 : diag::ext_typecheck_comparison_of_fptr_to_void)
12500 << LHS.get()->getType() << RHS.get()->getType()
12501 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12502}
12503
12505 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12506 case Stmt::ObjCArrayLiteralClass:
12507 case Stmt::ObjCDictionaryLiteralClass:
12508 case Stmt::ObjCStringLiteralClass:
12509 case Stmt::ObjCBoxedExprClass:
12510 return true;
12511 default:
12512 // Note that ObjCBoolLiteral is NOT an object literal!
12513 return false;
12514 }
12515}
12516
12517static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12520
12521 // If this is not actually an Objective-C object, bail out.
12522 if (!Type)
12523 return false;
12524
12525 // Get the LHS object's interface type.
12526 QualType InterfaceType = Type->getPointeeType();
12527
12528 // If the RHS isn't an Objective-C object, bail out.
12529 if (!RHS->getType()->isObjCObjectPointerType())
12530 return false;
12531
12532 // Try to find the -isEqual: method.
12533 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12534 ObjCMethodDecl *Method =
12535 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
12536 /*IsInstance=*/true);
12537 if (!Method) {
12538 if (Type->isObjCIdType()) {
12539 // For 'id', just check the global pool.
12540 Method =
12542 /*receiverId=*/true);
12543 } else {
12544 // Check protocols.
12545 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
12546 /*IsInstance=*/true);
12547 }
12548 }
12549
12550 if (!Method)
12551 return false;
12552
12553 QualType T = Method->parameters()[0]->getType();
12554 if (!T->isObjCObjectPointerType())
12555 return false;
12556
12557 QualType R = Method->getReturnType();
12558 if (!R->isScalarType())
12559 return false;
12560
12561 return true;
12562}
12563
12565 ExprResult &LHS, ExprResult &RHS,
12567 Expr *Literal;
12568 Expr *Other;
12569 if (isObjCObjectLiteral(LHS)) {
12570 Literal = LHS.get();
12571 Other = RHS.get();
12572 } else {
12573 Literal = RHS.get();
12574 Other = LHS.get();
12575 }
12576
12577 // Don't warn on comparisons against nil.
12578 Other = Other->IgnoreParenCasts();
12579 if (Other->isNullPointerConstant(S.getASTContext(),
12581 return;
12582
12583 // This should be kept in sync with warn_objc_literal_comparison.
12584 // LK_String should always be after the other literals, since it has its own
12585 // warning flag.
12586 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12587 assert(LiteralKind != SemaObjC::LK_Block);
12588 if (LiteralKind == SemaObjC::LK_None) {
12589 llvm_unreachable("Unknown Objective-C object literal kind");
12590 }
12591
12592 if (LiteralKind == SemaObjC::LK_String)
12593 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12594 << Literal->getSourceRange();
12595 else
12596 S.Diag(Loc, diag::warn_objc_literal_comparison)
12597 << LiteralKind << Literal->getSourceRange();
12598
12600 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12601 SourceLocation Start = LHS.get()->getBeginLoc();
12603 CharSourceRange OpRange =
12605
12606 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12607 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12608 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12609 << FixItHint::CreateInsertion(End, "]");
12610 }
12611}
12612
12613/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12615 ExprResult &RHS, SourceLocation Loc,
12616 BinaryOperatorKind Opc) {
12617 // Check that left hand side is !something.
12618 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12619 if (!UO || UO->getOpcode() != UO_LNot) return;
12620
12621 // Only check if the right hand side is non-bool arithmetic type.
12622 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12623
12624 // Make sure that the something in !something is not bool.
12625 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12626 if (SubExpr->isKnownToHaveBooleanValue()) return;
12627
12628 // Emit warning.
12629 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12630 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12631 << Loc << IsBitwiseOp;
12632
12633 // First note suggest !(x < y)
12634 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12635 SourceLocation FirstClose = RHS.get()->getEndLoc();
12636 FirstClose = S.getLocForEndOfToken(FirstClose);
12637 if (FirstClose.isInvalid())
12638 FirstOpen = SourceLocation();
12639 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12640 << IsBitwiseOp
12641 << FixItHint::CreateInsertion(FirstOpen, "(")
12642 << FixItHint::CreateInsertion(FirstClose, ")");
12643
12644 // Second note suggests (!x) < y
12645 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12646 SourceLocation SecondClose = LHS.get()->getEndLoc();
12647 SecondClose = S.getLocForEndOfToken(SecondClose);
12648 if (SecondClose.isInvalid())
12649 SecondOpen = SourceLocation();
12650 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12651 << FixItHint::CreateInsertion(SecondOpen, "(")
12652 << FixItHint::CreateInsertion(SecondClose, ")");
12653}
12654
12655// Returns true if E refers to a non-weak array.
12656static bool checkForArray(const Expr *E) {
12657 const ValueDecl *D = nullptr;
12658 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12659 D = DR->getDecl();
12660 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12661 if (Mem->isImplicitAccess())
12662 D = Mem->getMemberDecl();
12663 }
12664 if (!D)
12665 return false;
12666 return D->getType()->isArrayType() && !D->isWeak();
12667}
12668
12669/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12670/// pointer and size is an unsigned integer. Return whether the result is
12671/// always true/false.
12672static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12673 const Expr *RHS,
12674 BinaryOperatorKind Opc) {
12675 if (!LHS->getType()->isPointerType() ||
12676 S.getLangOpts().PointerOverflowDefined)
12677 return std::nullopt;
12678
12679 // Canonicalize to >= or < predicate.
12680 switch (Opc) {
12681 case BO_GE:
12682 case BO_LT:
12683 break;
12684 case BO_GT:
12685 std::swap(LHS, RHS);
12686 Opc = BO_LT;
12687 break;
12688 case BO_LE:
12689 std::swap(LHS, RHS);
12690 Opc = BO_GE;
12691 break;
12692 default:
12693 return std::nullopt;
12694 }
12695
12696 auto *BO = dyn_cast<BinaryOperator>(LHS);
12697 if (!BO || BO->getOpcode() != BO_Add)
12698 return std::nullopt;
12699
12700 Expr *Other;
12701 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12702 Other = BO->getRHS();
12703 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12704 Other = BO->getLHS();
12705 else
12706 return std::nullopt;
12707
12708 if (!Other->getType()->isUnsignedIntegerType())
12709 return std::nullopt;
12710
12711 return Opc == BO_GE;
12712}
12713
12714/// Diagnose some forms of syntactically-obvious tautological comparison.
12716 Expr *LHS, Expr *RHS,
12717 BinaryOperatorKind Opc) {
12718 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12719 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12720
12721 QualType LHSType = LHS->getType();
12722 QualType RHSType = RHS->getType();
12723 if (LHSType->hasFloatingRepresentation() ||
12724 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12726 return;
12727
12728 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12729 // Tautological diagnostics.
12730 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12731 return;
12732
12733 // Comparisons between two array types are ill-formed for operator<=>, so
12734 // we shouldn't emit any additional warnings about it.
12735 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12736 return;
12737
12738 // For non-floating point types, check for self-comparisons of the form
12739 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12740 // often indicate logic errors in the program.
12741 //
12742 // NOTE: Don't warn about comparison expressions resulting from macro
12743 // expansion. Also don't warn about comparisons which are only self
12744 // comparisons within a template instantiation. The warnings should catch
12745 // obvious cases in the definition of the template anyways. The idea is to
12746 // warn when the typed comparison operator will always evaluate to the same
12747 // result.
12748
12749 // Used for indexing into %select in warn_comparison_always
12750 enum {
12751 AlwaysConstant,
12752 AlwaysTrue,
12753 AlwaysFalse,
12754 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12755 };
12756
12757 // C++1a [array.comp]:
12758 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12759 // operands of array type.
12760 // C++2a [depr.array.comp]:
12761 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12762 // operands of array type are deprecated.
12763 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12764 RHSStripped->getType()->isArrayType()) {
12765 auto IsDeprArrayComparionIgnored =
12766 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12767 auto DiagID = S.getLangOpts().CPlusPlus26
12768 ? diag::warn_array_comparison_cxx26
12769 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12770 ? diag::warn_array_comparison
12771 : diag::warn_depr_array_comparison;
12772 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12773 << LHSStripped->getType() << RHSStripped->getType();
12774 // Carry on to produce the tautological comparison warning, if this
12775 // expression is potentially-evaluated, we can resolve the array to a
12776 // non-weak declaration, and so on.
12777 }
12778
12779 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12780 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12781 unsigned Result;
12782 switch (Opc) {
12783 case BO_EQ:
12784 case BO_LE:
12785 case BO_GE:
12786 Result = AlwaysTrue;
12787 break;
12788 case BO_NE:
12789 case BO_LT:
12790 case BO_GT:
12791 Result = AlwaysFalse;
12792 break;
12793 case BO_Cmp:
12794 Result = AlwaysEqual;
12795 break;
12796 default:
12797 Result = AlwaysConstant;
12798 break;
12799 }
12800 S.DiagRuntimeBehavior(Loc, nullptr,
12801 S.PDiag(diag::warn_comparison_always)
12802 << 0 /*self-comparison*/
12803 << Result);
12804 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12805 // What is it always going to evaluate to?
12806 unsigned Result;
12807 switch (Opc) {
12808 case BO_EQ: // e.g. array1 == array2
12809 Result = AlwaysFalse;
12810 break;
12811 case BO_NE: // e.g. array1 != array2
12812 Result = AlwaysTrue;
12813 break;
12814 default: // e.g. array1 <= array2
12815 // The best we can say is 'a constant'
12816 Result = AlwaysConstant;
12817 break;
12818 }
12819 S.DiagRuntimeBehavior(Loc, nullptr,
12820 S.PDiag(diag::warn_comparison_always)
12821 << 1 /*array comparison*/
12822 << Result);
12823 } else if (std::optional<bool> Res =
12824 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12825 S.DiagRuntimeBehavior(Loc, nullptr,
12826 S.PDiag(diag::warn_comparison_always)
12827 << 2 /*pointer comparison*/
12828 << (*Res ? AlwaysTrue : AlwaysFalse));
12829 }
12830 }
12831
12832 if (isa<CastExpr>(LHSStripped))
12833 LHSStripped = LHSStripped->IgnoreParenCasts();
12834 if (isa<CastExpr>(RHSStripped))
12835 RHSStripped = RHSStripped->IgnoreParenCasts();
12836
12837 // Warn about comparisons against a string constant (unless the other
12838 // operand is null); the user probably wants string comparison function.
12839 Expr *LiteralString = nullptr;
12840 Expr *LiteralStringStripped = nullptr;
12841 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12842 !RHSStripped->isNullPointerConstant(S.Context,
12844 LiteralString = LHS;
12845 LiteralStringStripped = LHSStripped;
12846 } else if ((isa<StringLiteral>(RHSStripped) ||
12847 isa<ObjCEncodeExpr>(RHSStripped)) &&
12848 !LHSStripped->isNullPointerConstant(S.Context,
12850 LiteralString = RHS;
12851 LiteralStringStripped = RHSStripped;
12852 }
12853
12854 if (LiteralString) {
12855 S.DiagRuntimeBehavior(Loc, nullptr,
12856 S.PDiag(diag::warn_stringcompare)
12857 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12858 << LiteralString->getSourceRange());
12859 }
12860}
12861
12863 switch (CK) {
12864 default: {
12865#ifndef NDEBUG
12866 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12867 << "\n";
12868#endif
12869 llvm_unreachable("unhandled cast kind");
12870 }
12871 case CK_UserDefinedConversion:
12872 return ICK_Identity;
12873 case CK_LValueToRValue:
12874 return ICK_Lvalue_To_Rvalue;
12875 case CK_ArrayToPointerDecay:
12876 return ICK_Array_To_Pointer;
12877 case CK_FunctionToPointerDecay:
12879 case CK_IntegralCast:
12881 case CK_FloatingCast:
12883 case CK_IntegralToFloating:
12884 case CK_FloatingToIntegral:
12885 return ICK_Floating_Integral;
12886 case CK_IntegralComplexCast:
12887 case CK_FloatingComplexCast:
12888 case CK_FloatingComplexToIntegralComplex:
12889 case CK_IntegralComplexToFloatingComplex:
12891 case CK_FloatingComplexToReal:
12892 case CK_FloatingRealToComplex:
12893 case CK_IntegralComplexToReal:
12894 case CK_IntegralRealToComplex:
12895 return ICK_Complex_Real;
12896 case CK_HLSLArrayRValue:
12897 return ICK_HLSL_Array_RValue;
12898 }
12899}
12900
12902 QualType FromType,
12903 SourceLocation Loc) {
12904 // Check for a narrowing implicit conversion.
12907 SCS.setToType(0, FromType);
12908 SCS.setToType(1, ToType);
12909 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12910 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12911
12912 APValue PreNarrowingValue;
12913 QualType PreNarrowingType;
12914 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12915 PreNarrowingType,
12916 /*IgnoreFloatToIntegralConversion*/ true)) {
12918 // Implicit conversion to a narrower type, but the expression is
12919 // value-dependent so we can't tell whether it's actually narrowing.
12920 case NK_Not_Narrowing:
12921 return false;
12922
12924 // Implicit conversion to a narrower type, and the value is not a constant
12925 // expression.
12926 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12927 << /*Constant*/ 1
12928 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12929 return true;
12930
12932 // Implicit conversion to a narrower type, and the value is not a constant
12933 // expression.
12934 case NK_Type_Narrowing:
12935 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12936 << /*Constant*/ 0 << FromType << ToType;
12937 // TODO: It's not a constant expression, but what if the user intended it
12938 // to be? Can we produce notes to help them figure out why it isn't?
12939 return true;
12940 }
12941 llvm_unreachable("unhandled case in switch");
12942}
12943
12945 ExprResult &LHS,
12946 ExprResult &RHS,
12947 SourceLocation Loc) {
12948 QualType LHSType = LHS.get()->getType();
12949 QualType RHSType = RHS.get()->getType();
12950 // Dig out the original argument type and expression before implicit casts
12951 // were applied. These are the types/expressions we need to check the
12952 // [expr.spaceship] requirements against.
12953 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12954 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12955 QualType LHSStrippedType = LHSStripped.get()->getType();
12956 QualType RHSStrippedType = RHSStripped.get()->getType();
12957
12958 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12959 // other is not, the program is ill-formed.
12960 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12961 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12962 return QualType();
12963 }
12964
12965 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12966 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12967 RHSStrippedType->isEnumeralType();
12968 if (NumEnumArgs == 1) {
12969 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12970 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12971 if (OtherTy->hasFloatingRepresentation()) {
12972 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12973 return QualType();
12974 }
12975 }
12976 if (NumEnumArgs == 2) {
12977 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12978 // type E, the operator yields the result of converting the operands
12979 // to the underlying type of E and applying <=> to the converted operands.
12980 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12981 S.InvalidOperands(Loc, LHS, RHS);
12982 return QualType();
12983 }
12984 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12985 assert(IntType->isArithmeticType());
12986
12987 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12988 // promote the boolean type, and all other promotable integer types, to
12989 // avoid this.
12990 if (S.Context.isPromotableIntegerType(IntType))
12991 IntType = S.Context.getPromotedIntegerType(IntType);
12992
12993 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12994 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12995 LHSType = RHSType = IntType;
12996 }
12997
12998 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12999 // usual arithmetic conversions are applied to the operands.
13000 QualType Type =
13002 if (LHS.isInvalid() || RHS.isInvalid())
13003 return QualType();
13004 if (Type.isNull()) {
13005 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13006 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
13007 return ResultTy;
13008 }
13009
13010 std::optional<ComparisonCategoryType> CCT =
13012 if (!CCT)
13013 return S.InvalidOperands(Loc, LHS, RHS);
13014
13015 bool HasNarrowing = checkThreeWayNarrowingConversion(
13016 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
13017 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
13018 RHS.get()->getBeginLoc());
13019 if (HasNarrowing)
13020 return QualType();
13021
13022 assert(!Type.isNull() && "composite type for <=> has not been set");
13023
13026}
13027
13029 ExprResult &RHS,
13030 SourceLocation Loc,
13031 BinaryOperatorKind Opc) {
13032 if (Opc == BO_Cmp)
13033 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
13034
13035 // C99 6.5.8p3 / C99 6.5.9p4
13036 QualType Type =
13038 if (LHS.isInvalid() || RHS.isInvalid())
13039 return QualType();
13040 if (Type.isNull()) {
13041 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13042 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
13043 return ResultTy;
13044 }
13045 assert(Type->isArithmeticType() || Type->isEnumeralType());
13046
13048 return S.InvalidOperands(Loc, LHS, RHS);
13049
13050 // Check for comparisons of floating point operands using != and ==.
13052 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13053
13054 // The result of comparisons is 'bool' in C++, 'int' in C.
13056}
13057
13059 if (!NullE.get()->getType()->isAnyPointerType())
13060 return;
13061 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
13062 if (!E.get()->getType()->isAnyPointerType() &&
13066 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
13067 if (CL->getValue() == 0)
13068 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13069 << NullValue
13071 NullValue ? "NULL" : "(void *)0");
13072 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
13073 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
13074 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
13075 if (T == Context.CharTy)
13076 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13077 << NullValue
13079 NullValue ? "NULL" : "(void *)0");
13080 }
13081 }
13082}
13083
13084// C99 6.5.8, C++ [expr.rel]
13086 SourceLocation Loc,
13087 BinaryOperatorKind Opc) {
13088 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
13089 bool IsThreeWay = Opc == BO_Cmp;
13090 bool IsOrdered = IsRelational || IsThreeWay;
13091 auto IsAnyPointerType = [](ExprResult E) {
13092 QualType Ty = E.get()->getType();
13093 return Ty->isPointerType() || Ty->isMemberPointerType();
13094 };
13095
13096 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
13097 // type, array-to-pointer, ..., conversions are performed on both operands to
13098 // bring them to their composite type.
13099 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
13100 // any type-related checks.
13101 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
13103 if (LHS.isInvalid())
13104 return QualType();
13106 if (RHS.isInvalid())
13107 return QualType();
13108 } else {
13109 LHS = DefaultLvalueConversion(LHS.get());
13110 if (LHS.isInvalid())
13111 return QualType();
13112 RHS = DefaultLvalueConversion(RHS.get());
13113 if (RHS.isInvalid())
13114 return QualType();
13115 }
13116
13117 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
13121 }
13122
13123 if (getLangOpts().HLSL && (LHS.get()->getType()->isConstantMatrixType() ||
13124 RHS.get()->getType()->isConstantMatrixType()))
13125 return CheckMatrixCompareOperands(LHS, RHS, Loc, Opc);
13126
13127 // Handle vector comparisons separately.
13128 if (LHS.get()->getType()->isVectorType() ||
13129 RHS.get()->getType()->isVectorType())
13130 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
13131
13132 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13133 RHS.get()->getType()->isSveVLSBuiltinType())
13134 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
13135
13136 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13137 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13138
13139 QualType LHSType = LHS.get()->getType();
13140 QualType RHSType = RHS.get()->getType();
13141 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
13142 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13143 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
13144
13145 if ((LHSType->isPointerType() &&
13147 (RHSType->isPointerType() &&
13149 return InvalidOperands(Loc, LHS, RHS);
13150
13151 const Expr::NullPointerConstantKind LHSNullKind =
13153 const Expr::NullPointerConstantKind RHSNullKind =
13155 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13156 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13157
13158 auto computeResultTy = [&]() {
13159 if (Opc != BO_Cmp)
13160 return QualType(Context.getLogicalOperationType());
13161 assert(getLangOpts().CPlusPlus);
13162 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13163
13164 QualType CompositeTy = LHS.get()->getType();
13165 assert(!CompositeTy->isReferenceType());
13166
13167 std::optional<ComparisonCategoryType> CCT =
13169 if (!CCT)
13170 return InvalidOperands(Loc, LHS, RHS);
13171
13172 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13173 // P0946R0: Comparisons between a null pointer constant and an object
13174 // pointer result in std::strong_equality, which is ill-formed under
13175 // P1959R0.
13176 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13177 << (LHSIsNull ? LHS.get()->getSourceRange()
13178 : RHS.get()->getSourceRange());
13179 return QualType();
13180 }
13181
13184 };
13185
13186 if (LHSType->isMetaInfoType() && RHSType->isMetaInfoType()) {
13187 if (!BinaryOperator::isEqualityOp(Opc)) {
13188 return InvalidOperands(Loc, LHS, RHS);
13189 }
13190 return computeResultTy();
13191 }
13192
13193 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13194 bool IsEquality = Opc == BO_EQ;
13195 if (RHSIsNull)
13196 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
13197 RHS.get()->getSourceRange());
13198 else
13199 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
13200 LHS.get()->getSourceRange());
13201 }
13202
13203 if (IsOrdered && LHSType->isFunctionPointerType() &&
13204 RHSType->isFunctionPointerType()) {
13205 // Valid unless a relational comparison of function pointers
13206 bool IsError = Opc == BO_Cmp;
13207 auto DiagID =
13208 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13209 : getLangOpts().CPlusPlus
13210 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13211 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13212 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13213 << RHS.get()->getSourceRange();
13214 if (IsError)
13215 return QualType();
13216 }
13217
13218 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13219 (RHSType->isIntegerType() && !RHSIsNull)) {
13220 // Skip normal pointer conversion checks in this case; we have better
13221 // diagnostics for this below.
13222 } else if (getLangOpts().CPlusPlus) {
13223 // Equality comparison of a function pointer to a void pointer is invalid,
13224 // but we allow it as an extension.
13225 // FIXME: If we really want to allow this, should it be part of composite
13226 // pointer type computation so it works in conditionals too?
13227 if (!IsOrdered &&
13228 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13229 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13230 // This is a gcc extension compatibility comparison.
13231 // In a SFINAE context, we treat this as a hard error to maintain
13232 // conformance with the C++ standard.
13233 bool IsError = isSFINAEContext();
13234 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError);
13235
13236 if (IsError)
13237 return QualType();
13238
13239 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13240 return computeResultTy();
13241 }
13242
13243 // C++ [expr.eq]p2:
13244 // If at least one operand is a pointer [...] bring them to their
13245 // composite pointer type.
13246 // C++ [expr.spaceship]p6
13247 // If at least one of the operands is of pointer type, [...] bring them
13248 // to their composite pointer type.
13249 // C++ [expr.rel]p2:
13250 // If both operands are pointers, [...] bring them to their composite
13251 // pointer type.
13252 // For <=>, the only valid non-pointer types are arrays and functions, and
13253 // we already decayed those, so this is really the same as the relational
13254 // comparison rule.
13255 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13256 (IsOrdered ? 2 : 1) &&
13257 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13258 RHSType->isObjCObjectPointerType()))) {
13259 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13260 return QualType();
13261 return computeResultTy();
13262 }
13263 } else if (LHSType->isPointerType() &&
13264 RHSType->isPointerType()) { // C99 6.5.8p2
13265 // All of the following pointer-related warnings are GCC extensions, except
13266 // when handling null pointer constants.
13267 QualType LCanPointeeTy =
13269 QualType RCanPointeeTy =
13271
13272 // C99 6.5.9p2 and C99 6.5.8p2
13273 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
13274 RCanPointeeTy.getUnqualifiedType())) {
13275 if (IsRelational) {
13276 // Pointers both need to point to complete or incomplete types
13277 if ((LCanPointeeTy->isIncompleteType() !=
13278 RCanPointeeTy->isIncompleteType()) &&
13279 !getLangOpts().C11) {
13280 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13281 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13282 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13283 << RCanPointeeTy->isIncompleteType();
13284 }
13285 }
13286 } else if (!IsRelational &&
13287 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13288 // Valid unless comparison between non-null pointer and function pointer
13289 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13290 && !LHSIsNull && !RHSIsNull)
13291 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13292 /*isError*/false);
13293 } else {
13294 // Invalid
13295 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13296 }
13297 if (LCanPointeeTy != RCanPointeeTy) {
13298 // Treat NULL constant as a special case in OpenCL.
13299 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13300 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
13301 getASTContext())) {
13302 Diag(Loc,
13303 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13304 << LHSType << RHSType << 0 /* comparison */
13305 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13306 }
13307 }
13308 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13309 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13310 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13311 : CK_BitCast;
13312
13313 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13314 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13315 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13316 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13317 bool ChangingCFIUncheckedCallee =
13318 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13319
13320 if (LHSIsNull && !RHSIsNull)
13321 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13322 else if (!ChangingCFIUncheckedCallee)
13323 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13324 }
13325 return computeResultTy();
13326 }
13327
13328
13329 // C++ [expr.eq]p4:
13330 // Two operands of type std::nullptr_t or one operand of type
13331 // std::nullptr_t and the other a null pointer constant compare
13332 // equal.
13333 // C23 6.5.9p5:
13334 // If both operands have type nullptr_t or one operand has type nullptr_t
13335 // and the other is a null pointer constant, they compare equal if the
13336 // former is a null pointer.
13337 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13338 if (LHSType->isNullPtrType()) {
13339 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13340 return computeResultTy();
13341 }
13342 if (RHSType->isNullPtrType()) {
13343 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13344 return computeResultTy();
13345 }
13346 }
13347
13348 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13349 // C23 6.5.9p6:
13350 // Otherwise, at least one operand is a pointer. If one is a pointer and
13351 // the other is a null pointer constant or has type nullptr_t, they
13352 // compare equal
13353 if (LHSIsNull && RHSType->isPointerType()) {
13354 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13355 return computeResultTy();
13356 }
13357 if (RHSIsNull && LHSType->isPointerType()) {
13358 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13359 return computeResultTy();
13360 }
13361 }
13362
13363 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13364 // These aren't covered by the composite pointer type rules.
13365 if (!IsOrdered && RHSType->isNullPtrType() &&
13366 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13367 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13368 return computeResultTy();
13369 }
13370 if (!IsOrdered && LHSType->isNullPtrType() &&
13371 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13372 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13373 return computeResultTy();
13374 }
13375
13376 if (getLangOpts().CPlusPlus) {
13377 if (IsRelational &&
13378 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13379 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13380 // HACK: Relational comparison of nullptr_t against a pointer type is
13381 // invalid per DR583, but we allow it within std::less<> and friends,
13382 // since otherwise common uses of it break.
13383 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13384 // friends to have std::nullptr_t overload candidates.
13385 DeclContext *DC = CurContext;
13386 if (isa<FunctionDecl>(DC))
13387 DC = DC->getParent();
13388 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13389 if (CTSD->isInStdNamespace() &&
13390 llvm::StringSwitch<bool>(CTSD->getName())
13391 .Cases({"less", "less_equal", "greater", "greater_equal"}, true)
13392 .Default(false)) {
13393 if (RHSType->isNullPtrType())
13394 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13395 else
13396 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13397 return computeResultTy();
13398 }
13399 }
13400 }
13401
13402 // C++ [expr.eq]p2:
13403 // If at least one operand is a pointer to member, [...] bring them to
13404 // their composite pointer type.
13405 if (!IsOrdered &&
13406 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13407 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13408 return QualType();
13409 else
13410 return computeResultTy();
13411 }
13412 }
13413
13414 // Handle block pointer types.
13415 if (!IsOrdered && LHSType->isBlockPointerType() &&
13416 RHSType->isBlockPointerType()) {
13417 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13418 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13419
13420 if (!LHSIsNull && !RHSIsNull &&
13421 !Context.typesAreCompatible(lpointee, rpointee)) {
13422 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13423 << LHSType << RHSType << LHS.get()->getSourceRange()
13424 << RHS.get()->getSourceRange();
13425 }
13426 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13427 return computeResultTy();
13428 }
13429
13430 // Allow block pointers to be compared with null pointer constants.
13431 if (!IsOrdered
13432 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13433 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13434 if (!LHSIsNull && !RHSIsNull) {
13435 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13437 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13438 ->getPointeeType()->isVoidType())))
13439 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13440 << LHSType << RHSType << LHS.get()->getSourceRange()
13441 << RHS.get()->getSourceRange();
13442 }
13443 if (LHSIsNull && !RHSIsNull)
13444 LHS = ImpCastExprToType(LHS.get(), RHSType,
13445 RHSType->isPointerType() ? CK_BitCast
13446 : CK_AnyPointerToBlockPointerCast);
13447 else
13448 RHS = ImpCastExprToType(RHS.get(), LHSType,
13449 LHSType->isPointerType() ? CK_BitCast
13450 : CK_AnyPointerToBlockPointerCast);
13451 return computeResultTy();
13452 }
13453
13454 if (LHSType->isObjCObjectPointerType() ||
13455 RHSType->isObjCObjectPointerType()) {
13456 const PointerType *LPT = LHSType->getAs<PointerType>();
13457 const PointerType *RPT = RHSType->getAs<PointerType>();
13458 if (LPT || RPT) {
13459 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13460 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13461
13462 if (!LPtrToVoid && !RPtrToVoid &&
13463 !Context.typesAreCompatible(LHSType, RHSType)) {
13464 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13465 /*isError*/false);
13466 }
13467 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13468 // the RHS, but we have test coverage for this behavior.
13469 // FIXME: Consider using convertPointersToCompositeType in C++.
13470 if (LHSIsNull && !RHSIsNull) {
13471 Expr *E = LHS.get();
13472 if (getLangOpts().ObjCAutoRefCount)
13473 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
13475 LHS = ImpCastExprToType(E, RHSType,
13476 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13477 }
13478 else {
13479 Expr *E = RHS.get();
13480 if (getLangOpts().ObjCAutoRefCount)
13481 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
13483 /*Diagnose=*/true,
13484 /*DiagnoseCFAudited=*/false, Opc);
13485 RHS = ImpCastExprToType(E, LHSType,
13486 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13487 }
13488 return computeResultTy();
13489 }
13490 if (LHSType->isObjCObjectPointerType() &&
13491 RHSType->isObjCObjectPointerType()) {
13492 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13493 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13494 /*isError*/false);
13496 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13497
13498 if (LHSIsNull && !RHSIsNull)
13499 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13500 else
13501 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13502 return computeResultTy();
13503 }
13504
13505 if (!IsOrdered && LHSType->isBlockPointerType() &&
13507 LHS = ImpCastExprToType(LHS.get(), RHSType,
13508 CK_BlockPointerToObjCPointerCast);
13509 return computeResultTy();
13510 } else if (!IsOrdered &&
13512 RHSType->isBlockPointerType()) {
13513 RHS = ImpCastExprToType(RHS.get(), LHSType,
13514 CK_BlockPointerToObjCPointerCast);
13515 return computeResultTy();
13516 }
13517 }
13518 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13519 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13520 unsigned DiagID = 0;
13521 bool isError = false;
13522 if (LangOpts.DebuggerSupport) {
13523 // Under a debugger, allow the comparison of pointers to integers,
13524 // since users tend to want to compare addresses.
13525 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13526 (RHSIsNull && RHSType->isIntegerType())) {
13527 if (IsOrdered) {
13528 isError = getLangOpts().CPlusPlus;
13529 DiagID =
13530 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13531 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13532 }
13533 } else if (getLangOpts().CPlusPlus) {
13534 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13535 isError = true;
13536 } else if (IsOrdered)
13537 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13538 else
13539 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13540
13541 if (DiagID) {
13542 Diag(Loc, DiagID)
13543 << LHSType << RHSType << LHS.get()->getSourceRange()
13544 << RHS.get()->getSourceRange();
13545 if (isError)
13546 return QualType();
13547 }
13548
13549 if (LHSType->isIntegerType())
13550 LHS = ImpCastExprToType(LHS.get(), RHSType,
13551 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13552 else
13553 RHS = ImpCastExprToType(RHS.get(), LHSType,
13554 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13555 return computeResultTy();
13556 }
13557
13558 // Handle block pointers.
13559 if (!IsOrdered && RHSIsNull
13560 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13561 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13562 return computeResultTy();
13563 }
13564 if (!IsOrdered && LHSIsNull
13565 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13566 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13567 return computeResultTy();
13568 }
13569
13570 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13571 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13572 return computeResultTy();
13573 }
13574
13575 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13576 return computeResultTy();
13577 }
13578
13579 if (LHSIsNull && RHSType->isQueueT()) {
13580 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13581 return computeResultTy();
13582 }
13583
13584 if (LHSType->isQueueT() && RHSIsNull) {
13585 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13586 return computeResultTy();
13587 }
13588 }
13589
13590 return InvalidOperands(Loc, LHS, RHS);
13591}
13592
13594 const VectorType *VTy = V->castAs<VectorType>();
13595 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13596
13597 if (isa<ExtVectorType>(VTy)) {
13598 if (VTy->isExtVectorBoolType())
13599 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13600 if (TypeSize == Context.getTypeSize(Context.CharTy))
13601 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13602 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13603 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13604 if (TypeSize == Context.getTypeSize(Context.IntTy))
13605 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13606 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13607 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13608 if (TypeSize == Context.getTypeSize(Context.LongTy))
13609 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13610 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13611 "Unhandled vector element size in vector compare");
13612 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13613 }
13614
13615 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13616 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13618 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13619 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13621 if (TypeSize == Context.getTypeSize(Context.LongTy))
13622 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13624 if (TypeSize == Context.getTypeSize(Context.IntTy))
13625 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13627 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13628 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13630 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13631 "Unhandled vector element size in vector compare");
13632 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13634}
13635
13637 const BuiltinType *VTy = V->castAs<BuiltinType>();
13638 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13639
13640 const QualType ETy = V->getSveEltType(Context);
13641 const auto TypeSize = Context.getTypeSize(ETy);
13642
13643 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13644 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13645 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13646}
13647
13649 SourceLocation Loc,
13650 BinaryOperatorKind Opc) {
13651 if (Opc == BO_Cmp) {
13652 Diag(Loc, diag::err_three_way_vector_comparison);
13653 return QualType();
13654 }
13655
13656 // Check to make sure we're operating on vectors of the same type and width,
13657 // Allowing one side to be a scalar of element type.
13658 QualType vType =
13659 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13660 /*AllowBothBool*/ true,
13661 /*AllowBoolConversions*/ getLangOpts().ZVector,
13662 /*AllowBooleanOperation*/ true);
13663 if (vType.isNull())
13664 return vType;
13665
13666 QualType LHSType = LHS.get()->getType();
13667
13668 // Determine the return type of a vector compare. By default clang will return
13669 // a scalar for all vector compares except vector bool and vector pixel.
13670 // With the gcc compiler we will always return a vector type and with the xl
13671 // compiler we will always return a scalar type. This switch allows choosing
13672 // which behavior is prefered.
13673 if (getLangOpts().AltiVec) {
13674 switch (getLangOpts().getAltivecSrcCompat()) {
13676 // If AltiVec, the comparison results in a numeric type, i.e.
13677 // bool for C++, int for C
13678 if (vType->castAs<VectorType>()->getVectorKind() ==
13680 return Context.getLogicalOperationType();
13681 else
13682 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13683 break;
13685 // For GCC we always return the vector type.
13686 break;
13688 return Context.getLogicalOperationType();
13689 break;
13690 }
13691 }
13692
13693 // For non-floating point types, check for self-comparisons of the form
13694 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13695 // often indicate logic errors in the program.
13696 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13697
13698 // Check for comparisons of floating point operands using != and ==.
13699 if (LHSType->hasFloatingRepresentation()) {
13700 assert(RHS.get()->getType()->hasFloatingRepresentation());
13701 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13702 }
13703
13704 // Return a signed type for the vector.
13705 return GetSignedVectorType(vType);
13706}
13707
13709 SourceLocation Loc,
13710 BinaryOperatorKind Opc) {
13711 assert(getLangOpts().HLSL && "matrix comparisons are only supported in HLSL");
13712 assert(Opc != BO_Cmp && "three-way comparisons are not supported in HLSL");
13713
13714 QualType MatrixTy =
13715 CheckMatrixElementwiseOperands(LHS, RHS, Loc, /*IsCompAssign=*/false);
13716 if (MatrixTy.isNull())
13717 return QualType();
13718
13719 if (!LHS.get()->getType()->isMatrixType()) {
13720 LHS = prepareMatrixSplat(MatrixTy, LHS.get());
13721 if (LHS.isInvalid())
13722 return QualType();
13723 LHS = ImpCastExprToType(LHS.get(), MatrixTy, CK_HLSLAggregateSplatCast);
13724 }
13725 if (!RHS.get()->getType()->isMatrixType()) {
13726 RHS = prepareMatrixSplat(MatrixTy, RHS.get());
13727 if (RHS.isInvalid())
13728 return QualType();
13729 RHS = ImpCastExprToType(RHS.get(), MatrixTy, CK_HLSLAggregateSplatCast);
13730 }
13731
13732 const auto *MT = MatrixTy->castAs<ConstantMatrixType>();
13733 return Context.getConstantMatrixType(Context.BoolTy, MT->getNumRows(),
13734 MT->getNumColumns());
13735}
13736
13738 ExprResult &RHS,
13739 SourceLocation Loc,
13740 BinaryOperatorKind Opc) {
13741 if (Opc == BO_Cmp) {
13742 Diag(Loc, diag::err_three_way_vector_comparison);
13743 return QualType();
13744 }
13745
13746 // Check to make sure we're operating on vectors of the same type and width,
13747 // Allowing one side to be a scalar of element type.
13749 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13750
13751 if (vType.isNull())
13752 return vType;
13753
13754 QualType LHSType = LHS.get()->getType();
13755
13756 // For non-floating point types, check for self-comparisons of the form
13757 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13758 // often indicate logic errors in the program.
13759 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13760
13761 // Check for comparisons of floating point operands using != and ==.
13762 if (LHSType->hasFloatingRepresentation()) {
13763 assert(RHS.get()->getType()->hasFloatingRepresentation());
13764 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13765 }
13766
13767 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13768 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13769
13770 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13771 RHSBuiltinTy->isSVEBool())
13772 return LHSType;
13773
13774 // Return a signed type for the vector.
13775 return GetSignedSizelessVectorType(vType);
13776}
13777
13778static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13779 const ExprResult &XorRHS,
13780 const SourceLocation Loc) {
13781 // Do not diagnose macros.
13782 if (Loc.isMacroID())
13783 return;
13784
13785 // Do not diagnose if both LHS and RHS are macros.
13786 if (XorLHS.get()->getExprLoc().isMacroID() &&
13787 XorRHS.get()->getExprLoc().isMacroID())
13788 return;
13789
13790 bool Negative = false;
13791 bool ExplicitPlus = false;
13792 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13793 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13794
13795 if (!LHSInt)
13796 return;
13797 if (!RHSInt) {
13798 // Check negative literals.
13799 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13800 UnaryOperatorKind Opc = UO->getOpcode();
13801 if (Opc != UO_Minus && Opc != UO_Plus)
13802 return;
13803 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13804 if (!RHSInt)
13805 return;
13806 Negative = (Opc == UO_Minus);
13807 ExplicitPlus = !Negative;
13808 } else {
13809 return;
13810 }
13811 }
13812
13813 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13814 llvm::APInt RightSideValue = RHSInt->getValue();
13815 if (LeftSideValue != 2 && LeftSideValue != 10)
13816 return;
13817
13818 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13819 return;
13820
13822 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13823 llvm::StringRef ExprStr =
13825
13826 CharSourceRange XorRange =
13828 llvm::StringRef XorStr =
13830 // Do not diagnose if xor keyword/macro is used.
13831 if (XorStr == "xor")
13832 return;
13833
13834 std::string LHSStr = std::string(Lexer::getSourceText(
13835 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13836 S.getSourceManager(), S.getLangOpts()));
13837 std::string RHSStr = std::string(Lexer::getSourceText(
13838 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13839 S.getSourceManager(), S.getLangOpts()));
13840
13841 if (Negative) {
13842 RightSideValue = -RightSideValue;
13843 RHSStr = "-" + RHSStr;
13844 } else if (ExplicitPlus) {
13845 RHSStr = "+" + RHSStr;
13846 }
13847
13848 StringRef LHSStrRef = LHSStr;
13849 StringRef RHSStrRef = RHSStr;
13850 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13851 // literals.
13852 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13853 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13854 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13855 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13856 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13857 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13858 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13859 return;
13860
13861 bool SuggestXor =
13862 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13863 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13864 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13865 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13866 std::string SuggestedExpr = "1 << " + RHSStr;
13867 bool Overflow = false;
13868 llvm::APInt One = (LeftSideValue - 1);
13869 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13870 if (Overflow) {
13871 if (RightSideIntValue < 64)
13872 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13873 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13874 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13875 else if (RightSideIntValue == 64)
13876 S.Diag(Loc, diag::warn_xor_used_as_pow)
13877 << ExprStr << toString(XorValue, 10, true);
13878 else
13879 return;
13880 } else {
13881 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13882 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13883 << toString(PowValue, 10, true)
13885 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13886 }
13887
13888 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13889 << ("0x2 ^ " + RHSStr) << SuggestXor;
13890 } else if (LeftSideValue == 10) {
13891 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13892 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13893 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13894 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13895 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13896 << ("0xA ^ " + RHSStr) << SuggestXor;
13897 }
13898}
13899
13901 SourceLocation Loc,
13902 BinaryOperatorKind Opc) {
13903 // Ensure that either both operands are of the same vector type, or
13904 // one operand is of a vector type and the other is of its element type.
13905 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13906 /*AllowBothBool*/ true,
13907 /*AllowBoolConversions*/ false,
13908 /*AllowBooleanOperation*/ false);
13909 if (vType.isNull())
13910 return QualType();
13911 if (getLangOpts().OpenCL &&
13912 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13914 return InvalidOperands(Loc, LHS, RHS);
13915 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13916 // usage of the logical operators && and || with vectors in C. This
13917 // check could be notionally dropped.
13918 if (!getLangOpts().CPlusPlus &&
13919 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13920 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13921 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13922 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13923 // `select` functions.
13924 if (getLangOpts().HLSL &&
13925 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13926 (void)InvalidOperands(Loc, LHS, RHS);
13927 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13928 return QualType();
13929 }
13930
13931 return GetSignedVectorType(LHS.get()->getType());
13932}
13933
13935 SourceLocation Loc,
13936 BinaryOperatorKind Opc) {
13937
13938 if (!getLangOpts().HLSL) {
13939 SemaRef.Diag(Loc, diag::err_matrix_logical_operations_supported_for_hlsl);
13940 return QualType();
13941 }
13942
13943 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13944 (void)InvalidOperands(Loc, LHS, RHS);
13945 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13946 return QualType();
13947 }
13948 SemaRef.Diag(LHS.get()->getBeginLoc(), diag::err_hlsl_langstd_unimplemented)
13949 << getLangOpts().getHLSLVersion();
13950 return QualType();
13951}
13952
13954 SourceLocation Loc,
13955 bool IsCompAssign) {
13956 if (!IsCompAssign) {
13958 if (LHS.isInvalid())
13959 return QualType();
13960 }
13962 if (RHS.isInvalid())
13963 return QualType();
13964
13965 // For conversion purposes, we ignore any qualifiers.
13966 // For example, "const float" and "float" are equivalent.
13967 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13968 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13969
13970 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13971 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13972 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13973
13974 if (Context.hasSameType(LHSType, RHSType))
13975 return Context.getCommonSugaredType(LHSType, RHSType);
13976
13977 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13978 // case we have to return InvalidOperands.
13979 ExprResult OriginalLHS = LHS;
13980 ExprResult OriginalRHS = RHS;
13981 if (LHSMatType && !RHSMatType) {
13982 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13983 if (!RHS.isInvalid())
13984 return LHSType;
13985
13986 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13987 }
13988
13989 if (!LHSMatType && RHSMatType) {
13990 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13991 if (!LHS.isInvalid())
13992 return RHSType;
13993 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13994 }
13995
13996 return InvalidOperands(Loc, LHS, RHS);
13997}
13998
14000 SourceLocation Loc,
14001 bool IsCompAssign) {
14002 if (!IsCompAssign) {
14004 if (LHS.isInvalid())
14005 return QualType();
14006 }
14008 if (RHS.isInvalid())
14009 return QualType();
14010
14011 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
14012 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
14013 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
14014
14015 if (LHSMatType && RHSMatType) {
14016 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
14017 return InvalidOperands(Loc, LHS, RHS);
14018
14019 if (Context.hasSameType(LHSMatType, RHSMatType))
14020 return Context.getCommonSugaredType(
14021 LHS.get()->getType().getUnqualifiedType(),
14022 RHS.get()->getType().getUnqualifiedType());
14023
14024 QualType LHSELTy = LHSMatType->getElementType(),
14025 RHSELTy = RHSMatType->getElementType();
14026 if (!Context.hasSameType(LHSELTy, RHSELTy))
14027 return InvalidOperands(Loc, LHS, RHS);
14028
14029 return Context.getConstantMatrixType(
14030 Context.getCommonSugaredType(LHSELTy, RHSELTy),
14031 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
14032 }
14033 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
14034}
14035
14037 switch (Opc) {
14038 default:
14039 return false;
14040 case BO_And:
14041 case BO_AndAssign:
14042 case BO_Or:
14043 case BO_OrAssign:
14044 case BO_Xor:
14045 case BO_XorAssign:
14046 return true;
14047 }
14048}
14049
14051 SourceLocation Loc,
14052 BinaryOperatorKind Opc) {
14053 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
14054
14055 bool IsCompAssign =
14056 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
14057
14058 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
14059
14060 if (LHS.get()->getType()->isVectorType() ||
14061 RHS.get()->getType()->isVectorType()) {
14062 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14064 return CheckVectorOperands(
14065 LHS, RHS, Loc, IsCompAssign,
14066 /*AllowBothBool*/ true,
14067 /*AllowBoolConversions*/ getLangOpts().ZVector,
14068 /*AllowBooleanOperation*/ LegalBoolVecOperator);
14069 return InvalidOperands(Loc, LHS, RHS);
14070 }
14071
14072 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14073 RHS.get()->getType()->isSveVLSBuiltinType()) {
14074 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14076 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14078 return InvalidOperands(Loc, LHS, RHS);
14079 }
14080
14081 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14082 RHS.get()->getType()->isSveVLSBuiltinType()) {
14083 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14085 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14087 return InvalidOperands(Loc, LHS, RHS);
14088 }
14089
14090 if (Opc == BO_And)
14091 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
14092
14093 if (LHS.get()->getType()->hasFloatingRepresentation() ||
14095 return InvalidOperands(Loc, LHS, RHS);
14096
14097 ExprResult LHSResult = LHS, RHSResult = RHS;
14099 LHSResult, RHSResult, Loc,
14101 if (LHSResult.isInvalid() || RHSResult.isInvalid())
14102 return QualType();
14103 LHS = LHSResult.get();
14104 RHS = RHSResult.get();
14105
14106 if (Opc == BO_Xor)
14107 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
14108
14109 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
14110 return compType;
14111 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14112 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14113 return ResultTy;
14114}
14115
14116// C99 6.5.[13,14]
14118 SourceLocation Loc,
14119 BinaryOperatorKind Opc) {
14120 // Check vector operands differently.
14121 if (LHS.get()->getType()->isVectorType() ||
14122 RHS.get()->getType()->isVectorType())
14123 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
14124
14125 if (LHS.get()->getType()->isConstantMatrixType() ||
14126 RHS.get()->getType()->isConstantMatrixType())
14127 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
14128
14129 bool EnumConstantInBoolContext = false;
14130 for (const ExprResult &HS : {LHS, RHS}) {
14131 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
14132 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
14133 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
14134 EnumConstantInBoolContext = true;
14135 }
14136 }
14137
14138 if (EnumConstantInBoolContext)
14139 Diag(Loc, diag::warn_enum_constant_in_bool_context);
14140
14141 // WebAssembly tables can't be used with logical operators.
14142 QualType LHSTy = LHS.get()->getType();
14143 QualType RHSTy = RHS.get()->getType();
14144 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
14145 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
14146 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
14147 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
14148 return InvalidOperands(Loc, LHS, RHS);
14149 }
14150
14151 // Diagnose cases where the user write a logical and/or but probably meant a
14152 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
14153 // is a constant.
14154 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
14155 !LHS.get()->getType()->isBooleanType() &&
14156 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
14157 // Don't warn in macros or template instantiations.
14158 !Loc.isMacroID() && !inTemplateInstantiation()) {
14159 // If the RHS can be constant folded, and if it constant folds to something
14160 // that isn't 0 or 1 (which indicate a potential logical operation that
14161 // happened to fold to true/false) then warn.
14162 // Parens on the RHS are ignored.
14163 Expr::EvalResult EVResult;
14164 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
14165 llvm::APSInt Result = EVResult.Val.getInt();
14166 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
14167 !RHS.get()->getExprLoc().isMacroID()) ||
14168 (Result != 0 && Result != 1)) {
14169 Diag(Loc, diag::warn_logical_instead_of_bitwise)
14170 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
14171 // Suggest replacing the logical operator with the bitwise version
14172 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
14173 << (Opc == BO_LAnd ? "&" : "|")
14176 Opc == BO_LAnd ? "&" : "|");
14177 if (Opc == BO_LAnd)
14178 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14179 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
14182 RHS.get()->getEndLoc()));
14183 }
14184 }
14185 }
14186
14187 if (!Context.getLangOpts().CPlusPlus) {
14188 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14189 // not operate on the built-in scalar and vector float types.
14190 if (Context.getLangOpts().OpenCL &&
14191 Context.getLangOpts().OpenCLVersion < 120) {
14192 if (LHS.get()->getType()->isFloatingType() ||
14193 RHS.get()->getType()->isFloatingType())
14194 return InvalidOperands(Loc, LHS, RHS);
14195 }
14196
14197 LHS = UsualUnaryConversions(LHS.get());
14198 if (LHS.isInvalid())
14199 return QualType();
14200
14201 RHS = UsualUnaryConversions(RHS.get());
14202 if (RHS.isInvalid())
14203 return QualType();
14204
14205 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14207 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14209
14210 if (!LHS.get()->getType()->isScalarType() ||
14211 !RHS.get()->getType()->isScalarType())
14212 return InvalidOperands(Loc, LHS, RHS);
14213
14214 return Context.IntTy;
14215 }
14216
14217 // The following is safe because we only use this method for
14218 // non-overloadable operands.
14219
14220 // C++ [expr.log.and]p1
14221 // C++ [expr.log.or]p1
14222 // The operands are both contextually converted to type bool.
14224 if (LHSRes.isInvalid()) {
14225 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14226 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14227 return ResultTy;
14228 }
14229 LHS = LHSRes;
14230
14232 if (RHSRes.isInvalid()) {
14233 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14234 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14235 return ResultTy;
14236 }
14237 RHS = RHSRes;
14238
14239 // C++ [expr.log.and]p2
14240 // C++ [expr.log.or]p2
14241 // The result is a bool.
14242 return Context.BoolTy;
14243}
14244
14245static bool IsReadonlyMessage(Expr *E, Sema &S) {
14246 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14247 if (!ME) return false;
14248 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
14249 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14251 if (!Base) return false;
14252 return Base->getMethodDecl() != nullptr;
14253}
14254
14255/// Is the given expression (which must be 'const') a reference to a
14256/// variable which was originally non-const, but which has become
14257/// 'const' due to being captured within a block?
14260 assert(E->isLValue() && E->getType().isConstQualified());
14261 E = E->IgnoreParens();
14262
14263 // Must be a reference to a declaration from an enclosing scope.
14264 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14265 if (!DRE) return NCCK_None;
14267
14268 ValueDecl *Value = DRE->getDecl();
14269
14270 // The declaration must be a value which is not declared 'const'.
14272 return NCCK_None;
14273
14274 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
14275 if (Binding) {
14276 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14277 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14278 return NCCK_Lambda;
14279 }
14280
14281 VarDecl *Var = dyn_cast<VarDecl>(Value);
14282 if (!Var)
14283 return NCCK_None;
14284 if (Var->getType()->isReferenceType())
14285 return NCCK_None;
14286
14287 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14288
14289 // Decide whether the first capture was for a block or a lambda.
14290 DeclContext *DC = S.CurContext, *Prev = nullptr;
14291 // Decide whether the first capture was for a block or a lambda.
14292 while (DC) {
14293 // For init-capture, it is possible that the variable belongs to the
14294 // template pattern of the current context.
14295 if (auto *FD = dyn_cast<FunctionDecl>(DC))
14296 if (Var->isInitCapture() &&
14297 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14298 break;
14299 if (DC == Var->getDeclContext())
14300 break;
14301 Prev = DC;
14302 DC = DC->getParent();
14303 }
14304 // Unless we have an init-capture, we've gone one step too far.
14305 if (!Var->isInitCapture())
14306 DC = Prev;
14307 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
14308}
14309
14310static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14311 Ty = Ty.getNonReferenceType();
14312 if (IsDereference && Ty->isPointerType())
14313 Ty = Ty->getPointeeType();
14314 return !Ty.isConstQualified();
14315}
14316
14317// Update err_typecheck_assign_const and note_typecheck_assign_const
14318// when this enum is changed.
14319enum {
14324 ConstUnknown, // Keep as last element
14325};
14326
14327/// Emit the "read-only variable not assignable" error and print notes to give
14328/// more information about why the variable is not assignable, such as pointing
14329/// to the declaration of a const variable, showing that a method is const, or
14330/// that the function is returning a const reference.
14331static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14332 SourceLocation Loc) {
14333 SourceRange ExprRange = E->getSourceRange();
14334
14335 // Only emit one error on the first const found. All other consts will emit
14336 // a note to the error.
14337 bool DiagnosticEmitted = false;
14338
14339 // Track if the current expression is the result of a dereference, and if the
14340 // next checked expression is the result of a dereference.
14341 bool IsDereference = false;
14342 bool NextIsDereference = false;
14343
14344 // Loop to process MemberExpr chains.
14345 while (true) {
14346 IsDereference = NextIsDereference;
14347
14349 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14350 NextIsDereference = ME->isArrow();
14351 const ValueDecl *VD = ME->getMemberDecl();
14352 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14353 // Mutable fields can be modified even if the class is const.
14354 if (Field->isMutable()) {
14355 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14356 break;
14357 }
14358
14359 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14360 if (!DiagnosticEmitted) {
14361 S.Diag(Loc, diag::err_typecheck_assign_const)
14362 << ExprRange << ConstMember << false /*static*/ << Field
14363 << Field->getType();
14364 DiagnosticEmitted = true;
14365 }
14366 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14367 << ConstMember << false /*static*/ << Field << Field->getType()
14368 << Field->getSourceRange();
14369 }
14370 E = ME->getBase();
14371 continue;
14372 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14373 if (VDecl->getType().isConstQualified()) {
14374 if (!DiagnosticEmitted) {
14375 S.Diag(Loc, diag::err_typecheck_assign_const)
14376 << ExprRange << ConstMember << true /*static*/ << VDecl
14377 << VDecl->getType();
14378 DiagnosticEmitted = true;
14379 }
14380 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14381 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14382 << VDecl->getSourceRange();
14383 }
14384 // Static fields do not inherit constness from parents.
14385 break;
14386 }
14387 break; // End MemberExpr
14388 } else if (const ArraySubscriptExpr *ASE =
14389 dyn_cast<ArraySubscriptExpr>(E)) {
14390 E = ASE->getBase()->IgnoreParenImpCasts();
14391 continue;
14392 } else if (const ExtVectorElementExpr *EVE =
14393 dyn_cast<ExtVectorElementExpr>(E)) {
14394 E = EVE->getBase()->IgnoreParenImpCasts();
14395 continue;
14396 }
14397 break;
14398 }
14399
14400 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14401 // Function calls
14402 const FunctionDecl *FD = CE->getDirectCallee();
14403 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14404 if (!DiagnosticEmitted) {
14405 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14406 << ConstFunction << FD;
14407 DiagnosticEmitted = true;
14408 }
14410 diag::note_typecheck_assign_const)
14411 << ConstFunction << FD << FD->getReturnType()
14412 << FD->getReturnTypeSourceRange();
14413 }
14414 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14415 // Point to variable declaration.
14416 if (const ValueDecl *VD = DRE->getDecl()) {
14417 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14418 if (!DiagnosticEmitted) {
14419 S.Diag(Loc, diag::err_typecheck_assign_const)
14420 << ExprRange << ConstVariable << VD << VD->getType();
14421 DiagnosticEmitted = true;
14422 }
14423 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14424 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14425 }
14426 }
14427 } else if (isa<CXXThisExpr>(E)) {
14428 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14429 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14430 if (MD->isConst()) {
14431 if (!DiagnosticEmitted) {
14432 S.Diag(Loc, diag::err_typecheck_assign_const_method)
14433 << ExprRange << MD;
14434 DiagnosticEmitted = true;
14435 }
14436 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const_method)
14437 << MD << MD->getSourceRange();
14438 }
14439 }
14440 }
14441 }
14442
14443 if (DiagnosticEmitted)
14444 return;
14445
14446 // Can't determine a more specific message, so display the generic error.
14447 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14448}
14449
14455
14457 const RecordType *Ty,
14458 SourceLocation Loc, SourceRange Range,
14459 OriginalExprKind OEK,
14460 bool &DiagnosticEmitted) {
14461 std::vector<const RecordType *> RecordTypeList;
14462 RecordTypeList.push_back(Ty);
14463 unsigned NextToCheckIndex = 0;
14464 // We walk the record hierarchy breadth-first to ensure that we print
14465 // diagnostics in field nesting order.
14466 while (RecordTypeList.size() > NextToCheckIndex) {
14467 bool IsNested = NextToCheckIndex > 0;
14468 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14469 ->getDecl()
14470 ->getDefinitionOrSelf()
14471 ->fields()) {
14472 // First, check every field for constness.
14473 QualType FieldTy = Field->getType();
14474 if (FieldTy.isConstQualified()) {
14475 if (!DiagnosticEmitted) {
14476 S.Diag(Loc, diag::err_typecheck_assign_const)
14477 << Range << NestedConstMember << OEK << VD
14478 << IsNested << Field;
14479 DiagnosticEmitted = true;
14480 }
14481 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14482 << NestedConstMember << IsNested << Field
14483 << FieldTy << Field->getSourceRange();
14484 }
14485
14486 // Then we append it to the list to check next in order.
14487 FieldTy = FieldTy.getCanonicalType();
14488 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14489 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14490 RecordTypeList.push_back(FieldRecTy);
14491 }
14492 }
14493 ++NextToCheckIndex;
14494 }
14495}
14496
14497/// Emit an error for the case where a record we are trying to assign to has a
14498/// const-qualified field somewhere in its hierarchy.
14499static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14500 SourceLocation Loc) {
14501 QualType Ty = E->getType();
14502 assert(Ty->isRecordType() && "lvalue was not record?");
14503 SourceRange Range = E->getSourceRange();
14504 const auto *RTy = Ty->getAsCanonical<RecordType>();
14505 bool DiagEmitted = false;
14506
14507 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14508 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14509 Range, OEK_Member, DiagEmitted);
14510 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14511 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14512 Range, OEK_Variable, DiagEmitted);
14513 else
14514 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14515 Range, OEK_LValue, DiagEmitted);
14516 if (!DiagEmitted)
14517 DiagnoseConstAssignment(S, E, Loc);
14518}
14519
14520/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14521/// emit an error and return true. If so, return false.
14523 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14524
14526
14527 SourceLocation OrigLoc = Loc;
14529 &Loc);
14530 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14532 if (IsLV == Expr::MLV_Valid)
14533 return false;
14534
14535 unsigned DiagID = 0;
14536 bool NeedType = false;
14537 switch (IsLV) { // C99 6.5.16p2
14539 // Use a specialized diagnostic when we're assigning to an object
14540 // from an enclosing function or block.
14542 if (NCCK == NCCK_Block)
14543 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14544 else
14545 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14546 break;
14547 }
14548
14549 // In ARC, use some specialized diagnostics for occasions where we
14550 // infer 'const'. These are always pseudo-strong variables.
14551 if (S.getLangOpts().ObjCAutoRefCount) {
14552 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14553 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14554 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14555
14556 // Use the normal diagnostic if it's pseudo-__strong but the
14557 // user actually wrote 'const'.
14558 if (var->isARCPseudoStrong() &&
14559 (!var->getTypeSourceInfo() ||
14560 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14561 // There are three pseudo-strong cases:
14562 // - self
14563 ObjCMethodDecl *method = S.getCurMethodDecl();
14564 if (method && var == method->getSelfDecl()) {
14565 DiagID = method->isClassMethod()
14566 ? diag::err_typecheck_arc_assign_self_class_method
14567 : diag::err_typecheck_arc_assign_self;
14568
14569 // - Objective-C externally_retained attribute.
14570 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14571 isa<ParmVarDecl>(var)) {
14572 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14573
14574 // - fast enumeration variables
14575 } else {
14576 DiagID = diag::err_typecheck_arr_assign_enumeration;
14577 }
14578
14579 SourceRange Assign;
14580 if (Loc != OrigLoc)
14581 Assign = SourceRange(OrigLoc, OrigLoc);
14582 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14583 // We need to preserve the AST regardless, so migration tool
14584 // can do its job.
14585 return false;
14586 }
14587 }
14588 }
14589
14590 // If none of the special cases above are triggered, then this is a
14591 // simple const assignment.
14592 if (DiagID == 0) {
14593 DiagnoseConstAssignment(S, E, Loc);
14594 return true;
14595 }
14596
14597 break;
14599 DiagnoseConstAssignment(S, E, Loc);
14600 return true;
14603 return true;
14606 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14607 NeedType = true;
14608 break;
14610 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14611 NeedType = true;
14612 break;
14614 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14615 break;
14616 case Expr::MLV_Valid:
14617 llvm_unreachable("did not take early return for MLV_Valid");
14621 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E)) {
14622 const Expr *Op = UnaryOp->getSubExpr()->IgnoreParens();
14623 if (UnaryOp->getOpcode() == UO_Imag &&
14624 !Op->getType()->isAnyComplexType()) {
14625 DiagID = diag::err_typecheck_lvalue_imag_not_modifiable_lvalue;
14626 NeedType = true;
14627 break;
14628 }
14629 }
14630
14631 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14632 break;
14633 }
14636 return S.RequireCompleteType(Loc, E->getType(),
14637 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14639 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14640 break;
14642 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14643 break;
14645 llvm_unreachable("readonly properties should be processed differently");
14647 DiagID = diag::err_readonly_message_assignment;
14648 break;
14650 DiagID = diag::err_no_subobject_property_setting;
14651 break;
14652 }
14653
14654 SourceRange Assign;
14655 if (Loc != OrigLoc)
14656 Assign = SourceRange(OrigLoc, OrigLoc);
14657 if (NeedType)
14658 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14659 else
14660 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14661 return true;
14662}
14663
14664static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14665 SourceLocation Loc,
14666 Sema &Sema) {
14668 return;
14670 return;
14671 if (Loc.isInvalid() || Loc.isMacroID())
14672 return;
14673 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14674 return;
14675
14676 // C / C++ fields
14677 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14678 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14679 if (ML && MR) {
14680 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14681 return;
14682 const ValueDecl *LHSDecl =
14684 const ValueDecl *RHSDecl =
14686 if (LHSDecl != RHSDecl)
14687 return;
14688 if (LHSDecl->getType().isVolatileQualified())
14689 return;
14690 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14691 if (RefTy->getPointeeType().isVolatileQualified())
14692 return;
14693
14694 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14695 }
14696
14697 // Objective-C instance variables
14698 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14699 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14700 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14701 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14702 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14703 if (RL && RR && RL->getDecl() == RR->getDecl())
14704 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14705 }
14706}
14707
14708// C99 6.5.16.1
14710 SourceLocation Loc,
14711 QualType CompoundType,
14712 BinaryOperatorKind Opc) {
14713 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14714
14715 // Verify that LHS is a modifiable lvalue, and emit error if not.
14716 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14717 return QualType();
14718
14719 QualType LHSType = LHSExpr->getType();
14720 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14721 CompoundType;
14722
14723 if (RHS.isUsable()) {
14724 // Even if this check fails don't return early to allow the best
14725 // possible error recovery and to allow any subsequent diagnostics to
14726 // work.
14727 const ValueDecl *Assignee = nullptr;
14728 bool ShowFullyQualifiedAssigneeName = false;
14729 // In simple cases describe what is being assigned to
14730 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14731 Assignee = DR->getDecl();
14732 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14733 Assignee = ME->getMemberDecl();
14734 ShowFullyQualifiedAssigneeName = true;
14735 }
14736
14738 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14739 ShowFullyQualifiedAssigneeName);
14740 }
14741
14742 // OpenCL v1.2 s6.1.1.1 p2:
14743 // The half data type can only be used to declare a pointer to a buffer that
14744 // contains half values
14745 if (getLangOpts().OpenCL &&
14746 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14747 LHSType->isHalfType()) {
14748 Diag(Loc, diag::err_opencl_half_load_store) << 1
14749 << LHSType.getUnqualifiedType();
14750 return QualType();
14751 }
14752
14753 // WebAssembly tables can't be used on RHS of an assignment expression.
14754 if (RHSType->isWebAssemblyTableType()) {
14755 Diag(Loc, diag::err_wasm_table_art) << 0;
14756 return QualType();
14757 }
14758
14759 AssignConvertType ConvTy;
14760 if (CompoundType.isNull()) {
14761 Expr *RHSCheck = RHS.get();
14762
14763 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14764
14765 QualType LHSTy(LHSType);
14766 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14767 if (RHS.isInvalid())
14768 return QualType();
14769 // Special case of NSObject attributes on c-style pointer types.
14771 ((Context.isObjCNSObjectType(LHSType) &&
14772 RHSType->isObjCObjectPointerType()) ||
14773 (Context.isObjCNSObjectType(RHSType) &&
14774 LHSType->isObjCObjectPointerType())))
14776
14777 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14778 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14779
14780 // If the RHS is a unary plus or minus, check to see if they = and + are
14781 // right next to each other. If so, the user may have typo'd "x =+ 4"
14782 // instead of "x += 4".
14783 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14784 RHSCheck = ICE->getSubExpr();
14785 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14786 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14787 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14788 // Only if the two operators are exactly adjacent.
14789 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14790 // And there is a space or other character before the subexpr of the
14791 // unary +/-. We don't want to warn on "x=-1".
14792 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14793 UO->getSubExpr()->getBeginLoc().isFileID()) {
14794 Diag(Loc, diag::warn_not_compound_assign)
14795 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14796 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14797 }
14798 }
14799
14800 if (IsAssignConvertCompatible(ConvTy)) {
14801 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14802 // Warn about retain cycles where a block captures the LHS, but
14803 // not if the LHS is a simple variable into which the block is
14804 // being stored...unless that variable can be captured by reference!
14805 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14806 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14807 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14808 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14809 }
14810
14811 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14813 // It is safe to assign a weak reference into a strong variable.
14814 // Although this code can still have problems:
14815 // id x = self.weakProp;
14816 // id y = self.weakProp;
14817 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14818 // paths through the function. This should be revisited if
14819 // -Wrepeated-use-of-weak is made flow-sensitive.
14820 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14821 // variable, which will be valid for the current autorelease scope.
14822 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14823 RHS.get()->getBeginLoc()))
14825
14826 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14827 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14828 }
14829 }
14830 } else {
14831 // Compound assignment "x += y"
14832 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14833 }
14834
14835 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14837 return QualType();
14838
14839 CheckForNullPointerDereference(*this, LHSExpr);
14840
14841 AssignedEntity AE{LHSExpr};
14842 checkAssignmentLifetime(*this, AE, RHS.get());
14843
14844 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14845 if (CompoundType.isNull()) {
14846 // C++2a [expr.ass]p5:
14847 // A simple-assignment whose left operand is of a volatile-qualified
14848 // type is deprecated unless the assignment is either a discarded-value
14849 // expression or an unevaluated operand
14850 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14851 }
14852 }
14853
14854 // C11 6.5.16p3: The type of an assignment expression is the type of the
14855 // left operand would have after lvalue conversion.
14856 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14857 // qualified type, the value has the unqualified version of the type of the
14858 // lvalue; additionally, if the lvalue has atomic type, the value has the
14859 // non-atomic version of the type of the lvalue.
14860 // C++ 5.17p1: the type of the assignment expression is that of its left
14861 // operand.
14862 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14863}
14864
14865// Scenarios to ignore if expression E is:
14866// 1. an explicit cast expression into void
14867// 2. a function call expression that returns void
14868static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14869 E = E->IgnoreParens();
14870
14871 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14872 if (CE->getCastKind() == CK_ToVoid) {
14873 return true;
14874 }
14875
14876 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14877 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14878 CE->getSubExpr()->getType()->isDependentType()) {
14879 return true;
14880 }
14881 }
14882
14883 if (const auto *CE = dyn_cast<CallExpr>(E))
14884 return CE->getCallReturnType(Context)->isVoidType();
14885 return false;
14886}
14887
14889 // No warnings in macros
14890 if (Loc.isMacroID())
14891 return;
14892
14893 // Don't warn in template instantiations.
14895 return;
14896
14897 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14898 // instead, skip more than needed, then call back into here with the
14899 // CommaVisitor in SemaStmt.cpp.
14900 // The listed locations are the initialization and increment portions
14901 // of a for loop. The additional checks are on the condition of
14902 // if statements, do/while loops, and for loops.
14903 if (getCurScope()->isControlScope())
14904 return;
14905
14906 // If there are multiple comma operators used together, get the RHS of the
14907 // of the comma operator as the LHS.
14908 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14909 if (BO->getOpcode() != BO_Comma)
14910 break;
14911 LHS = BO->getRHS();
14912 }
14913
14914 // Only allow some expressions on LHS to not warn.
14915 if (IgnoreCommaOperand(LHS, Context))
14916 return;
14917
14918 Diag(Loc, diag::warn_comma_operator);
14919 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14920 << LHS->getSourceRange()
14922 LangOpts.CPlusPlus ? "static_cast<void>("
14923 : "(void)(")
14924 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14925 ")");
14926}
14927
14928// C99 6.5.17
14930 SourceLocation Loc) {
14931 LHS = S.CheckPlaceholderExpr(LHS.get());
14932 RHS = S.CheckPlaceholderExpr(RHS.get());
14933 if (LHS.isInvalid() || RHS.isInvalid())
14934 return QualType();
14935
14936 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14937 // operands, but not unary promotions.
14938 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14939
14940 // So we treat the LHS as a ignored value, and in C++ we allow the
14941 // containing site to determine what should be done with the RHS.
14942 LHS = S.IgnoredValueConversions(LHS.get());
14943 if (LHS.isInvalid())
14944 return QualType();
14945
14946 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14947
14948 if (!S.getLangOpts().CPlusPlus) {
14950 if (RHS.isInvalid())
14951 return QualType();
14952 if (!RHS.get()->getType()->isVoidType())
14953 S.RequireCompleteType(Loc, RHS.get()->getType(),
14954 diag::err_incomplete_type);
14955 }
14956
14957 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14958 S.DiagnoseCommaOperator(LHS.get(), Loc);
14959
14960 return RHS.get()->getType();
14961}
14962
14963/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14964/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14967 ExprObjectKind &OK,
14968 SourceLocation OpLoc, bool IsInc,
14969 bool IsPrefix) {
14970 QualType ResType = Op->getType();
14971 // Atomic types can be used for increment / decrement where the non-atomic
14972 // versions can, so ignore the _Atomic() specifier for the purpose of
14973 // checking.
14974 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14975 ResType = ResAtomicType->getValueType();
14976
14977 assert(!ResType.isNull() && "no type for increment/decrement expression");
14978
14979 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14980 // Decrement of bool is not allowed.
14981 if (!IsInc) {
14982 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14983 return QualType();
14984 }
14985 // Increment of bool sets it to true, but is deprecated.
14986 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14987 : diag::warn_increment_bool)
14988 << Op->getSourceRange();
14989 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14990 // Error on enum increments and decrements in C++ mode
14991 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14992 return QualType();
14993 } else if (ResType->isRealType()) {
14994 // OK!
14995 } else if (ResType->isPointerType()) {
14996 // C99 6.5.2.4p2, 6.5.6p2
14997 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14998 return QualType();
14999 } else if (ResType->isOverflowBehaviorType()) {
15000 // OK!
15001 } else if (ResType->isObjCObjectPointerType()) {
15002 // On modern runtimes, ObjC pointer arithmetic is forbidden.
15003 // Otherwise, we just need a complete type.
15004 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
15005 checkArithmeticOnObjCPointer(S, OpLoc, Op))
15006 return QualType();
15007 } else if (ResType->isAnyComplexType()) {
15008 // C99 does not support ++/-- on complex types, we allow as an extension.
15009 S.DiagCompat(OpLoc, diag_compat::increment_complex)
15010 << IsInc << Op->getSourceRange();
15011 } else if (ResType->isPlaceholderType()) {
15013 if (PR.isInvalid()) return QualType();
15014 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
15015 IsInc, IsPrefix);
15016 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
15017 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
15018 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
15019 (ResType->castAs<VectorType>()->getVectorKind() !=
15021 // The z vector extensions allow ++ and -- for non-bool vectors.
15022 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
15023 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
15024 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
15025 } else {
15026 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
15027 << ResType << int(IsInc) << Op->getSourceRange();
15028 return QualType();
15029 }
15030 // At this point, we know we have a real, complex or pointer type.
15031 // Now make sure the operand is a modifiable lvalue.
15032 if (CheckForModifiableLvalue(Op, OpLoc, S))
15033 return QualType();
15034 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
15035 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
15036 // An operand with volatile-qualified type is deprecated
15037 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
15038 << IsInc << ResType;
15039 }
15040 // In C++, a prefix increment is the same type as the operand. Otherwise
15041 // (in C or with postfix), the increment is the unqualified type of the
15042 // operand.
15043 if (IsPrefix && S.getLangOpts().CPlusPlus) {
15044 VK = VK_LValue;
15045 OK = Op->getObjectKind();
15046 return ResType;
15047 } else {
15048 VK = VK_PRValue;
15049 return ResType.getUnqualifiedType();
15050 }
15051}
15052
15053/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
15054/// This routine allows us to typecheck complex/recursive expressions
15055/// where the declaration is needed for type checking. We only need to
15056/// handle cases when the expression references a function designator
15057/// or is an lvalue. Here are some examples:
15058/// - &(x) => x
15059/// - &*****f => f for f a function designator.
15060/// - &s.xx => s
15061/// - &s.zz[1].yy -> s, if zz is an array
15062/// - *(x + 1) -> x, if x is an array
15063/// - &"123"[2] -> 0
15064/// - & __real__ x -> x
15065///
15066/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
15067/// members.
15069 switch (E->getStmtClass()) {
15070 case Stmt::DeclRefExprClass:
15071 return cast<DeclRefExpr>(E)->getDecl();
15072 case Stmt::MemberExprClass:
15073 // If this is an arrow operator, the address is an offset from
15074 // the base's value, so the object the base refers to is
15075 // irrelevant.
15076 if (cast<MemberExpr>(E)->isArrow())
15077 return nullptr;
15078 // Otherwise, the expression refers to a part of the base
15079 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
15080 case Stmt::ArraySubscriptExprClass: {
15081 // FIXME: This code shouldn't be necessary! We should catch the implicit
15082 // promotion of register arrays earlier.
15083 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
15084 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
15085 if (ICE->getSubExpr()->getType()->isArrayType())
15086 return getPrimaryDecl(ICE->getSubExpr());
15087 }
15088 return nullptr;
15089 }
15090 case Stmt::UnaryOperatorClass: {
15092
15093 switch(UO->getOpcode()) {
15094 case UO_Real:
15095 case UO_Imag:
15096 case UO_Extension:
15097 return getPrimaryDecl(UO->getSubExpr());
15098 default:
15099 return nullptr;
15100 }
15101 }
15102 case Stmt::ParenExprClass:
15103 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
15104 case Stmt::ImplicitCastExprClass:
15105 // If the result of an implicit cast is an l-value, we care about
15106 // the sub-expression; otherwise, the result here doesn't matter.
15107 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
15108 case Stmt::CXXUuidofExprClass:
15109 return cast<CXXUuidofExpr>(E)->getGuidDecl();
15110 default:
15111 return nullptr;
15112 }
15113}
15114
15115namespace {
15116enum {
15117 AO_Bit_Field = 0,
15118 AO_Vector_Element = 1,
15119 AO_Property_Expansion = 2,
15120 AO_Register_Variable = 3,
15121 AO_Matrix_Element = 4,
15122 AO_No_Error = 5
15123};
15124}
15125/// Diagnose invalid operand for address of operations.
15126///
15127/// \param Type The type of operand which cannot have its address taken.
15129 Expr *E, unsigned Type) {
15130 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
15131}
15132
15134 const Expr *Op,
15135 const CXXMethodDecl *MD) {
15136 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
15137
15138 if (Op != DRE)
15139 return Diag(OpLoc, diag::err_parens_pointer_member_function)
15140 << Op->getSourceRange();
15141
15142 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
15143 if (isa<CXXDestructorDecl>(MD))
15144 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
15145 << DRE->getSourceRange();
15146
15147 if (DRE->getQualifier())
15148 return false;
15149
15150 if (MD->getParent()->getName().empty())
15151 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15152 << DRE->getSourceRange();
15153
15154 SmallString<32> Str;
15155 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
15156 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15157 << DRE->getSourceRange()
15158 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
15159}
15160
15162 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
15163 if (PTy->getKind() == BuiltinType::Overload) {
15164 Expr *E = OrigOp.get()->IgnoreParens();
15165 if (!isa<OverloadExpr>(E)) {
15166 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
15167 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
15168 << OrigOp.get()->getSourceRange();
15169 return QualType();
15170 }
15171
15175 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15176 << OrigOp.get()->getSourceRange();
15177 return QualType();
15178 }
15179
15180 return Context.OverloadTy;
15181 }
15182
15183 if (PTy->getKind() == BuiltinType::UnknownAny)
15184 return Context.UnknownAnyTy;
15185
15186 if (PTy->getKind() == BuiltinType::BoundMember) {
15187 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15188 << OrigOp.get()->getSourceRange();
15189 return QualType();
15190 }
15191
15192 OrigOp = CheckPlaceholderExpr(OrigOp.get());
15193 if (OrigOp.isInvalid()) return QualType();
15194 }
15195
15196 if (OrigOp.get()->isTypeDependent())
15197 return Context.DependentTy;
15198
15199 assert(!OrigOp.get()->hasPlaceholderType());
15200
15201 // Make sure to ignore parentheses in subsequent checks
15202 Expr *op = OrigOp.get()->IgnoreParens();
15203
15204 // In OpenCL captures for blocks called as lambda functions
15205 // are located in the private address space. Blocks used in
15206 // enqueue_kernel can be located in a different address space
15207 // depending on a vendor implementation. Thus preventing
15208 // taking an address of the capture to avoid invalid AS casts.
15209 if (LangOpts.OpenCL) {
15210 auto* VarRef = dyn_cast<DeclRefExpr>(op);
15211 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15212 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
15213 return QualType();
15214 }
15215 }
15216
15217 if (getLangOpts().C99) {
15218 // Implement C99-only parts of addressof rules.
15219 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
15220 if (uOp->getOpcode() == UO_Deref)
15221 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15222 // (assuming the deref expression is valid).
15223 return uOp->getSubExpr()->getType();
15224 }
15225 // Technically, there should be a check for array subscript
15226 // expressions here, but the result of one is always an lvalue anyway.
15227 }
15228 ValueDecl *dcl = getPrimaryDecl(op);
15229
15230 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
15231 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15232 op->getBeginLoc()))
15233 return QualType();
15234
15236 unsigned AddressOfError = AO_No_Error;
15237
15238 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15239 bool IsError = isSFINAEContext();
15240 Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary
15241 : diag::ext_typecheck_addrof_temporary)
15242 << op->getType() << op->getSourceRange();
15243 if (IsError)
15244 return QualType();
15245 // Materialize the temporary as an lvalue so that we can take its address.
15246 OrigOp = op =
15247 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
15248 } else if (isa<ObjCSelectorExpr>(op)) {
15249 return Context.getPointerType(op->getType());
15250 } else if (lval == Expr::LV_MemberFunction) {
15251 // If it's an instance method, make a member pointer.
15252 // The expression must have exactly the form &A::foo.
15253
15254 // If the underlying expression isn't a decl ref, give up.
15255 if (!isa<DeclRefExpr>(op)) {
15256 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15257 << OrigOp.get()->getSourceRange();
15258 return QualType();
15259 }
15260 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
15262
15263 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15264 QualType MPTy = Context.getMemberPointerType(
15265 op->getType(), DRE->getQualifier(), MD->getParent());
15266
15267 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15268 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15269 // When pointer authentication is enabled, argument and return types of
15270 // vitual member functions must be complete. This is because vitrual
15271 // member function pointers are implemented using virtual dispatch
15272 // thunks and the thunks cannot be emitted if the argument or return
15273 // types are incomplete.
15274 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15275 SourceLocation DeclRefLoc,
15276 SourceLocation RetArgTypeLoc) {
15277 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
15278 Diag(DeclRefLoc,
15279 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15280 Diag(RetArgTypeLoc,
15281 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15282 << T;
15283 return true;
15284 }
15285 return false;
15286 };
15287 QualType RetTy = MD->getReturnType();
15288 bool IsIncomplete =
15289 !RetTy->isVoidType() &&
15290 ReturnOrParamTypeIsIncomplete(
15291 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15292 for (auto *PVD : MD->parameters())
15293 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15294 PVD->getBeginLoc());
15295 if (IsIncomplete)
15296 return QualType();
15297 }
15298
15299 // Under the MS ABI, lock down the inheritance model now.
15300 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15301 (void)isCompleteType(OpLoc, MPTy);
15302 return MPTy;
15303 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15304 // C99 6.5.3.2p1
15305 // The operand must be either an l-value or a function designator
15306 if (!op->getType()->isFunctionType()) {
15307 // Use a special diagnostic for loads from property references.
15308 if (isa<PseudoObjectExpr>(op)) {
15309 AddressOfError = AO_Property_Expansion;
15310 } else {
15311 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15312 << op->getType() << op->getSourceRange();
15313 return QualType();
15314 }
15315 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
15316 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
15317 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15318 }
15319
15320 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15321 // The operand cannot be a bit-field
15322 AddressOfError = AO_Bit_Field;
15323 } else if (op->getObjectKind() == OK_VectorComponent) {
15324 // The operand cannot be an element of a vector
15325 AddressOfError = AO_Vector_Element;
15326 } else if (op->getObjectKind() == OK_MatrixComponent) {
15327 // The operand cannot be an element of a matrix.
15328 AddressOfError = AO_Matrix_Element;
15329 } else if (dcl) { // C99 6.5.3.2p1
15330 // We have an lvalue with a decl. Make sure the decl is not declared
15331 // with the register storage-class specifier.
15332 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15333 // in C++ it is not error to take address of a register
15334 // variable (c++03 7.1.1P3)
15335 if (vd->getStorageClass() == SC_Register &&
15337 AddressOfError = AO_Register_Variable;
15338 }
15339 } else if (isa<MSPropertyDecl>(dcl)) {
15340 AddressOfError = AO_Property_Expansion;
15341 } else if (isa<FunctionTemplateDecl>(dcl)) {
15342 return Context.OverloadTy;
15343 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15344 // Okay: we can take the address of a field.
15345 // Could be a pointer to member, though, if there is an explicit
15346 // scope qualifier for the class.
15347
15348 // [C++26] [expr.prim.id.general]
15349 // If an id-expression E denotes a non-static non-type member
15350 // of some class C [...] and if E is a qualified-id, E is
15351 // not the un-parenthesized operand of the unary & operator [...]
15352 // the id-expression is transformed into a class member access expression.
15353 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
15354 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
15355 DeclContext *Ctx = dcl->getDeclContext();
15356 if (Ctx && Ctx->isRecord()) {
15357 if (dcl->getType()->isReferenceType()) {
15358 Diag(OpLoc,
15359 diag::err_cannot_form_pointer_to_member_of_reference_type)
15360 << dcl->getDeclName() << dcl->getType();
15361 return QualType();
15362 }
15363
15364 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15365 Ctx = Ctx->getParent();
15366
15367 QualType MPTy = Context.getMemberPointerType(
15368 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
15369 // Under the MS ABI, lock down the inheritance model now.
15370 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15371 (void)isCompleteType(OpLoc, MPTy);
15372 return MPTy;
15373 }
15374 }
15378 llvm_unreachable("Unknown/unexpected decl type");
15379 }
15380
15381 if (AddressOfError != AO_No_Error) {
15382 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15383 return QualType();
15384 }
15385
15386 if (lval == Expr::LV_IncompleteVoidType) {
15387 // Taking the address of a void variable is technically illegal, but we
15388 // allow it in cases which are otherwise valid.
15389 // Example: "extern void x; void* y = &x;".
15390 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15391 }
15392
15393 // If the operand has type "type", the result has type "pointer to type".
15394 if (op->getType()->isObjCObjectType())
15395 return Context.getObjCObjectPointerType(op->getType());
15396
15397 // Cannot take the address of WebAssembly references or tables.
15398 if (Context.getTargetInfo().getTriple().isWasm()) {
15399 QualType OpTy = op->getType();
15400 if (OpTy.isWebAssemblyReferenceType()) {
15401 Diag(OpLoc, diag::err_wasm_ca_reference)
15402 << 1 << OrigOp.get()->getSourceRange();
15403 return QualType();
15404 }
15405 if (OpTy->isWebAssemblyTableType()) {
15406 Diag(OpLoc, diag::err_wasm_table_pr)
15407 << 1 << OrigOp.get()->getSourceRange();
15408 return QualType();
15409 }
15410 }
15411
15412 CheckAddressOfPackedMember(op);
15413
15414 return Context.getPointerType(op->getType());
15415}
15416
15417static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15418 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15419 if (!DRE)
15420 return;
15421 const Decl *D = DRE->getDecl();
15422 if (!D)
15423 return;
15424 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15425 if (!Param)
15426 return;
15427 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15428 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15429 return;
15430 if (FunctionScopeInfo *FD = S.getCurFunction())
15431 FD->ModifiedNonNullParams.insert(Param);
15432}
15433
15434/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15436 SourceLocation OpLoc,
15437 bool IsAfterAmp = false) {
15438 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15439 if (ConvResult.isInvalid())
15440 return QualType();
15441 Op = ConvResult.get();
15442 QualType OpTy = Op->getType();
15444
15446 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15447 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15448 Op->getSourceRange());
15449 }
15450
15451 if (const PointerType *PT = OpTy->getAs<PointerType>())
15452 {
15453 Result = PT->getPointeeType();
15454 }
15455 else if (const ObjCObjectPointerType *OPT =
15457 Result = OPT->getPointeeType();
15458 else {
15460 if (PR.isInvalid()) return QualType();
15461 if (PR.get() != Op)
15462 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15463 }
15464
15465 if (Result.isNull()) {
15466 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15467 << OpTy << Op->getSourceRange();
15468 return QualType();
15469 }
15470
15471 if (Result->isVoidType()) {
15472 // C++ [expr.unary.op]p1:
15473 // [...] the expression to which [the unary * operator] is applied shall
15474 // be a pointer to an object type, or a pointer to a function type
15475 LangOptions LO = S.getLangOpts();
15476 if (LO.CPlusPlus)
15477 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15478 << OpTy << Op->getSourceRange();
15479 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15480 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15481 << OpTy << Op->getSourceRange();
15482 }
15483
15484 // Dereferences are usually l-values...
15485 VK = VK_LValue;
15486
15487 // ...except that certain expressions are never l-values in C.
15488 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15489 VK = VK_PRValue;
15490
15491 return Result;
15492}
15493
15494BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15496 switch (Kind) {
15497 default: llvm_unreachable("Unknown binop!");
15498 case tok::periodstar: Opc = BO_PtrMemD; break;
15499 case tok::arrowstar: Opc = BO_PtrMemI; break;
15500 case tok::star: Opc = BO_Mul; break;
15501 case tok::slash: Opc = BO_Div; break;
15502 case tok::percent: Opc = BO_Rem; break;
15503 case tok::plus: Opc = BO_Add; break;
15504 case tok::minus: Opc = BO_Sub; break;
15505 case tok::lessless: Opc = BO_Shl; break;
15506 case tok::greatergreater: Opc = BO_Shr; break;
15507 case tok::lessequal: Opc = BO_LE; break;
15508 case tok::less: Opc = BO_LT; break;
15509 case tok::greaterequal: Opc = BO_GE; break;
15510 case tok::greater: Opc = BO_GT; break;
15511 case tok::exclaimequal: Opc = BO_NE; break;
15512 case tok::equalequal: Opc = BO_EQ; break;
15513 case tok::spaceship: Opc = BO_Cmp; break;
15514 case tok::amp: Opc = BO_And; break;
15515 case tok::caret: Opc = BO_Xor; break;
15516 case tok::pipe: Opc = BO_Or; break;
15517 case tok::ampamp: Opc = BO_LAnd; break;
15518 case tok::pipepipe: Opc = BO_LOr; break;
15519 case tok::equal: Opc = BO_Assign; break;
15520 case tok::starequal: Opc = BO_MulAssign; break;
15521 case tok::slashequal: Opc = BO_DivAssign; break;
15522 case tok::percentequal: Opc = BO_RemAssign; break;
15523 case tok::plusequal: Opc = BO_AddAssign; break;
15524 case tok::minusequal: Opc = BO_SubAssign; break;
15525 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15526 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15527 case tok::ampequal: Opc = BO_AndAssign; break;
15528 case tok::caretequal: Opc = BO_XorAssign; break;
15529 case tok::pipeequal: Opc = BO_OrAssign; break;
15530 case tok::comma: Opc = BO_Comma; break;
15531 }
15532 return Opc;
15533}
15534
15536 tok::TokenKind Kind) {
15538 switch (Kind) {
15539 default: llvm_unreachable("Unknown unary op!");
15540 case tok::plusplus: Opc = UO_PreInc; break;
15541 case tok::minusminus: Opc = UO_PreDec; break;
15542 case tok::amp: Opc = UO_AddrOf; break;
15543 case tok::star: Opc = UO_Deref; break;
15544 case tok::plus: Opc = UO_Plus; break;
15545 case tok::minus: Opc = UO_Minus; break;
15546 case tok::tilde: Opc = UO_Not; break;
15547 case tok::exclaim: Opc = UO_LNot; break;
15548 case tok::kw___real: Opc = UO_Real; break;
15549 case tok::kw___imag: Opc = UO_Imag; break;
15550 case tok::kw___extension__: Opc = UO_Extension; break;
15551 }
15552 return Opc;
15553}
15554
15555const FieldDecl *
15557 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15558 // common for setters.
15559 // struct A {
15560 // int X;
15561 // -void setX(int X) { X = X; }
15562 // +void setX(int X) { this->X = X; }
15563 // };
15564
15565 // Only consider parameters for self assignment fixes.
15566 if (!isa<ParmVarDecl>(SelfAssigned))
15567 return nullptr;
15568 const auto *Method =
15569 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15570 if (!Method)
15571 return nullptr;
15572
15573 const CXXRecordDecl *Parent = Method->getParent();
15574 // In theory this is fixable if the lambda explicitly captures this, but
15575 // that's added complexity that's rarely going to be used.
15576 if (Parent->isLambda())
15577 return nullptr;
15578
15579 // FIXME: Use an actual Lookup operation instead of just traversing fields
15580 // in order to get base class fields.
15581 auto Field =
15582 llvm::find_if(Parent->fields(),
15583 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15584 return F->getDeclName() == Name;
15585 });
15586 return (Field != Parent->field_end()) ? *Field : nullptr;
15587}
15588
15589/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15590/// This warning suppressed in the event of macro expansions.
15591static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15592 SourceLocation OpLoc, bool IsBuiltin) {
15594 return;
15595 if (S.isUnevaluatedContext())
15596 return;
15597 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15598 return;
15599 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15600 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15601 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15602 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15603 if (!LHSDeclRef || !RHSDeclRef ||
15604 LHSDeclRef->getLocation().isMacroID() ||
15605 RHSDeclRef->getLocation().isMacroID())
15606 return;
15607 const ValueDecl *LHSDecl =
15608 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15609 const ValueDecl *RHSDecl =
15610 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15611 if (LHSDecl != RHSDecl)
15612 return;
15613 if (LHSDecl->getType().isVolatileQualified())
15614 return;
15615 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15616 if (RefTy->getPointeeType().isVolatileQualified())
15617 return;
15618
15619 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15620 : diag::warn_self_assignment_overloaded)
15621 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15622 << RHSExpr->getSourceRange();
15623 if (const FieldDecl *SelfAssignField =
15625 Diag << 1 << SelfAssignField
15626 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15627 else
15628 Diag << 0;
15629}
15630
15631/// Check if a bitwise-& is performed on an Objective-C pointer. This
15632/// is usually indicative of introspection within the Objective-C pointer.
15634 SourceLocation OpLoc) {
15635 if (!S.getLangOpts().ObjC)
15636 return;
15637
15638 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15639 const Expr *LHS = L.get();
15640 const Expr *RHS = R.get();
15641
15643 ObjCPointerExpr = LHS;
15644 OtherExpr = RHS;
15645 }
15646 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15647 ObjCPointerExpr = RHS;
15648 OtherExpr = LHS;
15649 }
15650
15651 // This warning is deliberately made very specific to reduce false
15652 // positives with logic that uses '&' for hashing. This logic mainly
15653 // looks for code trying to introspect into tagged pointers, which
15654 // code should generally never do.
15655 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15656 unsigned Diag = diag::warn_objc_pointer_masking;
15657 // Determine if we are introspecting the result of performSelectorXXX.
15658 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15659 // Special case messages to -performSelector and friends, which
15660 // can return non-pointer values boxed in a pointer value.
15661 // Some clients may wish to silence warnings in this subcase.
15662 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15663 Selector S = ME->getSelector();
15664 StringRef SelArg0 = S.getNameForSlot(0);
15665 if (SelArg0.starts_with("performSelector"))
15666 Diag = diag::warn_objc_pointer_masking_performSelector;
15667 }
15668
15669 S.Diag(OpLoc, Diag)
15670 << ObjCPointerExpr->getSourceRange();
15671 }
15672}
15673
15674// This helper function promotes a binary operator's operands (which are of a
15675// half vector type) to a vector of floats and then truncates the result to
15676// a vector of either half or short.
15678 BinaryOperatorKind Opc, QualType ResultTy,
15680 bool IsCompAssign, SourceLocation OpLoc,
15681 FPOptionsOverride FPFeatures) {
15682 auto &Context = S.getASTContext();
15683 assert((isVector(ResultTy, Context.HalfTy) ||
15684 isVector(ResultTy, Context.ShortTy)) &&
15685 "Result must be a vector of half or short");
15686 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15687 isVector(RHS.get()->getType(), Context.HalfTy) &&
15688 "both operands expected to be a half vector");
15689
15690 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15691 QualType BinOpResTy = RHS.get()->getType();
15692
15693 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15694 // change BinOpResTy to a vector of ints.
15695 if (isVector(ResultTy, Context.ShortTy))
15696 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15697
15698 if (IsCompAssign)
15699 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15700 ResultTy, VK, OK, OpLoc, FPFeatures,
15701 BinOpResTy, BinOpResTy);
15702
15703 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15704 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15705 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15706 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15707}
15708
15709/// Returns true if conversion between vectors of halfs and vectors of floats
15710/// is needed.
15711static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15712 QualType ResultTy, Expr *E0,
15713 Expr *E1 = nullptr) {
15714 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType)
15715 return false;
15716
15717 // The conversion truncates the result to a half/short vector, so it shouldn't
15718 // apply when the result is not that type (e.g. HLSL comparisons).
15719 if (ResultTy->isVectorType() && !isVector(ResultTy, Ctx.HalfTy) &&
15720 !isVector(ResultTy, Ctx.ShortTy))
15721 return false;
15722
15723 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15724 QualType Ty = E->IgnoreImplicit()->getType();
15725
15726 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15727 // to vectors of floats. Although the element type of the vectors is __fp16,
15728 // the vectors shouldn't be treated as storage-only types. See the
15729 // discussion here: https://reviews.llvm.org/rG825235c140e7
15730 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15731 if (VT->getVectorKind() == VectorKind::Neon)
15732 return false;
15733 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15734 }
15735 return false;
15736 };
15737
15738 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15739}
15740
15742 BinaryOperatorKind Opc, Expr *LHSExpr,
15743 Expr *RHSExpr, bool ForFoldExpression) {
15744 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15745 // The syntax only allows initializer lists on the RHS of assignment,
15746 // so we don't need to worry about accepting invalid code for
15747 // non-assignment operators.
15748 // C++11 5.17p9:
15749 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15750 // of x = {} is x = T().
15752 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15753 InitializedEntity Entity =
15755 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15756 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15757 if (Init.isInvalid())
15758 return Init;
15759 RHSExpr = Init.get();
15760 }
15761
15762 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15763 QualType ResultTy; // Result type of the binary operator.
15764 // The following two variables are used for compound assignment operators
15765 QualType CompLHSTy; // Type of LHS after promotions for computation
15766 QualType CompResultTy; // Type of computation result
15769 bool ConvertHalfVec = false;
15770
15771 if (!LHS.isUsable() || !RHS.isUsable())
15772 return ExprError();
15773
15774 if (getLangOpts().OpenCL) {
15775 QualType LHSTy = LHSExpr->getType();
15776 QualType RHSTy = RHSExpr->getType();
15777 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15778 // the ATOMIC_VAR_INIT macro.
15779 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15780 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15781 if (BO_Assign == Opc)
15782 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15783 else
15784 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15785 return ExprError();
15786 }
15787
15788 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15789 // only with a builtin functions and therefore should be disallowed here.
15790 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15791 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15792 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15793 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15794 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15795 return ExprError();
15796 }
15797 }
15798
15799 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15800 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15801
15802 switch (Opc) {
15803 case BO_Assign:
15804 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15805 if (getLangOpts().CPlusPlus &&
15806 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15807 VK = LHS.get()->getValueKind();
15808 OK = LHS.get()->getObjectKind();
15809 }
15810 if (!ResultTy.isNull()) {
15811 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15812 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15813
15814 // Avoid copying a block to the heap if the block is assigned to a local
15815 // auto variable that is declared in the same scope as the block. This
15816 // optimization is unsafe if the local variable is declared in an outer
15817 // scope. For example:
15818 //
15819 // BlockTy b;
15820 // {
15821 // b = ^{...};
15822 // }
15823 // // It is unsafe to invoke the block here if it wasn't copied to the
15824 // // heap.
15825 // b();
15826
15827 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15828 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15829 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15830 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15831 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15832
15834 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15836 }
15837 RecordModifiableNonNullParam(*this, LHS.get());
15838 break;
15839 case BO_PtrMemD:
15840 case BO_PtrMemI:
15841 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15842 Opc == BO_PtrMemI);
15843 break;
15844 case BO_Mul:
15845 case BO_Div:
15846 ConvertHalfVec = true;
15847 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15848 break;
15849 case BO_Rem:
15850 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15851 break;
15852 case BO_Add:
15853 ConvertHalfVec = true;
15854 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15855 break;
15856 case BO_Sub:
15857 ConvertHalfVec = true;
15858 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15859 break;
15860 case BO_Shl:
15861 case BO_Shr:
15862 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15863 break;
15864 case BO_LE:
15865 case BO_LT:
15866 case BO_GE:
15867 case BO_GT:
15868 ConvertHalfVec = true;
15869 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15870
15871 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15872 !ForFoldExpression && BI && BI->isComparisonOp())
15873 Diag(OpLoc, diag::warn_consecutive_comparison)
15874 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15875
15876 break;
15877 case BO_EQ:
15878 case BO_NE:
15879 ConvertHalfVec = true;
15880 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15881 break;
15882 case BO_Cmp:
15883 ConvertHalfVec = true;
15884 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15885 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15886 break;
15887 case BO_And:
15888 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15889 [[fallthrough]];
15890 case BO_Xor:
15891 case BO_Or:
15892 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15893 break;
15894 case BO_LAnd:
15895 case BO_LOr:
15896 ConvertHalfVec = true;
15897 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15898 break;
15899 case BO_MulAssign:
15900 case BO_DivAssign:
15901 ConvertHalfVec = true;
15902 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15903 CompLHSTy = CompResultTy;
15904 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15905 ResultTy =
15906 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15907 break;
15908 case BO_RemAssign:
15909 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15910 CompLHSTy = CompResultTy;
15911 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15912 ResultTy =
15913 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15914 break;
15915 case BO_AddAssign:
15916 ConvertHalfVec = true;
15917 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15918 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15919 ResultTy =
15920 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15921 break;
15922 case BO_SubAssign:
15923 ConvertHalfVec = true;
15924 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15925 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15926 ResultTy =
15927 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15928 break;
15929 case BO_ShlAssign:
15930 case BO_ShrAssign:
15931 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15932 CompLHSTy = CompResultTy;
15933 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15934 ResultTy =
15935 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15936 break;
15937 case BO_AndAssign:
15938 case BO_OrAssign: // fallthrough
15939 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15940 [[fallthrough]];
15941 case BO_XorAssign:
15942 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15943 CompLHSTy = CompResultTy;
15944 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15945 ResultTy =
15946 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15947 break;
15948 case BO_Comma:
15949 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15950 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15951 VK = RHS.get()->getValueKind();
15952 OK = RHS.get()->getObjectKind();
15953 }
15954 break;
15955 }
15956 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15957 return ExprError();
15958
15959 // Some of the binary operations require promoting operands of half vector to
15960 // float vectors and truncating the result back to half vector. For now, we do
15961 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15962 // arm64).
15963 assert(
15964 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15965 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15966 "both sides are half vectors or neither sides are");
15967 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, ResultTy,
15968 LHS.get(), RHS.get());
15969
15970 // Check for array bounds violations for both sides of the BinaryOperator
15971 CheckArrayAccess(LHS.get());
15972 CheckArrayAccess(RHS.get());
15973
15974 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15975 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15976 &Context.Idents.get("object_setClass"),
15978 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15979 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15980 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15982 "object_setClass(")
15983 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15984 ",")
15985 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15986 }
15987 else
15988 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15989 }
15990 else if (const ObjCIvarRefExpr *OIRE =
15991 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15992 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15993
15994 // Opc is not a compound assignment if CompResultTy is null.
15995 if (CompResultTy.isNull()) {
15996 if (ConvertHalfVec)
15997 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15998 OpLoc, CurFPFeatureOverrides());
15999 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
16000 VK, OK, OpLoc, CurFPFeatureOverrides());
16001 }
16002
16003 // Handle compound assignments.
16004 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
16006 VK = VK_LValue;
16007 OK = LHS.get()->getObjectKind();
16008 }
16009
16010 // The LHS is not converted to the result type for fixed-point compound
16011 // assignment as the common type is computed on demand. Reset the CompLHSTy
16012 // to the LHS type we would have gotten after unary conversions.
16013 if (CompResultTy->isFixedPointType())
16014 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
16015
16016 if (ConvertHalfVec)
16017 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
16018 OpLoc, CurFPFeatureOverrides());
16019
16021 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
16022 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
16023}
16024
16025/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
16026/// operators are mixed in a way that suggests that the programmer forgot that
16027/// comparison operators have higher precedence. The most typical example of
16028/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
16030 SourceLocation OpLoc, Expr *LHSExpr,
16031 Expr *RHSExpr) {
16032 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
16033 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
16034
16035 // Check that one of the sides is a comparison operator and the other isn't.
16036 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
16037 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
16038 if (isLeftComp == isRightComp)
16039 return;
16040
16041 // Bitwise operations are sometimes used as eager logical ops.
16042 // Don't diagnose this.
16043 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
16044 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
16045 if (isLeftBitwise || isRightBitwise)
16046 return;
16047
16048 SourceRange DiagRange = isLeftComp
16049 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
16050 : SourceRange(OpLoc, RHSExpr->getEndLoc());
16051 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
16052 SourceRange ParensRange =
16053 isLeftComp
16054 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
16055 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
16056
16057 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
16058 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
16059 SuggestParentheses(Self, OpLoc,
16060 Self.PDiag(diag::note_precedence_silence) << OpStr,
16061 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
16062 SuggestParentheses(Self, OpLoc,
16063 Self.PDiag(diag::note_precedence_bitwise_first)
16065 ParensRange);
16066}
16067
16068/// It accepts a '&&' expr that is inside a '||' one.
16069/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
16070/// in parentheses.
16071static void
16073 BinaryOperator *Bop) {
16074 assert(Bop->getOpcode() == BO_LAnd);
16075 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
16076 << Bop->getSourceRange() << OpLoc;
16078 Self.PDiag(diag::note_precedence_silence)
16079 << Bop->getOpcodeStr(),
16080 Bop->getSourceRange());
16081}
16082
16083/// Look for '&&' in the left hand of a '||' expr.
16085 Expr *LHSExpr, Expr *RHSExpr) {
16086 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
16087 if (Bop->getOpcode() == BO_LAnd) {
16088 // If it's "string_literal && a || b" don't warn since the precedence
16089 // doesn't matter.
16090 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
16091 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
16092 } else if (Bop->getOpcode() == BO_LOr) {
16093 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
16094 // If it's "a || b && string_literal || c" we didn't warn earlier for
16095 // "a || b && string_literal", but warn now.
16096 if (RBop->getOpcode() == BO_LAnd &&
16097 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
16098 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
16099 }
16100 }
16101 }
16102}
16103
16104/// Look for '&&' in the right hand of a '||' expr.
16106 Expr *LHSExpr, Expr *RHSExpr) {
16107 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
16108 if (Bop->getOpcode() == BO_LAnd) {
16109 // If it's "a || b && string_literal" don't warn since the precedence
16110 // doesn't matter.
16111 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
16112 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
16113 }
16114 }
16115}
16116
16117/// Look for bitwise op in the left or right hand of a bitwise op with
16118/// lower precedence and emit a diagnostic together with a fixit hint that wraps
16119/// the '&' expression in parentheses.
16121 SourceLocation OpLoc, Expr *SubExpr) {
16122 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
16123 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
16124 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
16125 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
16126 << Bop->getSourceRange() << OpLoc;
16127 SuggestParentheses(S, Bop->getOperatorLoc(),
16128 S.PDiag(diag::note_precedence_silence)
16129 << Bop->getOpcodeStr(),
16130 Bop->getSourceRange());
16131 }
16132 }
16133}
16134
16136 Expr *SubExpr, StringRef Shift) {
16137 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
16138 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
16139 StringRef Op = Bop->getOpcodeStr();
16140 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
16141 << Bop->getSourceRange() << OpLoc << Shift << Op;
16142 SuggestParentheses(S, Bop->getOperatorLoc(),
16143 S.PDiag(diag::note_precedence_silence) << Op,
16144 Bop->getSourceRange());
16145 }
16146 }
16147}
16148
16150 Expr *LHSExpr, Expr *RHSExpr) {
16151 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
16152 if (!OCE)
16153 return;
16154
16155 FunctionDecl *FD = OCE->getDirectCallee();
16156 if (!FD || !FD->isOverloadedOperator())
16157 return;
16158
16160 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
16161 return;
16162
16163 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
16164 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
16165 << (Kind == OO_LessLess);
16167 S.PDiag(diag::note_precedence_silence)
16168 << (Kind == OO_LessLess ? "<<" : ">>"),
16169 OCE->getSourceRange());
16171 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
16172 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
16173}
16174
16175/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
16176/// precedence.
16178 SourceLocation OpLoc, Expr *LHSExpr,
16179 Expr *RHSExpr){
16180 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
16182 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
16183
16184 // Diagnose "arg1 & arg2 | arg3"
16185 if ((Opc == BO_Or || Opc == BO_Xor) &&
16186 !OpLoc.isMacroID()/* Don't warn in macros. */) {
16187 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
16188 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
16189 }
16190
16191 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16192 // We don't warn for 'assert(a || b && "bad")' since this is safe.
16193 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
16194 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
16195 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
16196 }
16197
16198 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
16199 || Opc == BO_Shr) {
16200 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
16201 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
16202 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
16203 }
16204
16205 // Warn on overloaded shift operators and comparisons, such as:
16206 // cout << 5 == 4;
16208 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
16209}
16210
16212 tok::TokenKind Kind,
16213 Expr *LHSExpr, Expr *RHSExpr) {
16214 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16215 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16216 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16217
16218 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16219 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
16220
16224
16225 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
16226 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
16227
16228 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
16229}
16230
16232 UnresolvedSetImpl &Functions) {
16234 if (OverOp != OO_None && OverOp != OO_Equal)
16235 LookupOverloadedOperatorName(OverOp, S, Functions);
16236
16237 // In C++20 onwards, we may have a second operator to look up.
16238 if (getLangOpts().CPlusPlus20) {
16240 LookupOverloadedOperatorName(ExtraOp, S, Functions);
16241 }
16242}
16243
16244/// Build an overloaded binary operator expression in the given scope.
16247 Expr *LHS, Expr *RHS) {
16248 switch (Opc) {
16249 case BO_Assign:
16250 // In the non-overloaded case, we warn about self-assignment (x = x) for
16251 // both simple assignment and certain compound assignments where algebra
16252 // tells us the operation yields a constant result. When the operator is
16253 // overloaded, we can't do the latter because we don't want to assume that
16254 // those algebraic identities still apply; for example, a path-building
16255 // library might use operator/= to append paths. But it's still reasonable
16256 // to assume that simple assignment is just moving/copying values around
16257 // and so self-assignment is likely a bug.
16258 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
16259 [[fallthrough]];
16260 case BO_DivAssign:
16261 case BO_RemAssign:
16262 case BO_SubAssign:
16263 case BO_AndAssign:
16264 case BO_OrAssign:
16265 case BO_XorAssign:
16266 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
16267 break;
16268 default:
16269 break;
16270 }
16271
16272 // Find all of the overloaded operators visible from this point.
16273 UnresolvedSet<16> Functions;
16274 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
16275
16276 // Build the (potentially-overloaded, potentially-dependent)
16277 // binary operation.
16278 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16279}
16280
16282 BinaryOperatorKind Opc, Expr *LHSExpr,
16283 Expr *RHSExpr, bool ForFoldExpression) {
16284 if (!LHSExpr || !RHSExpr)
16285 return ExprError();
16286
16287 // We want to end up calling one of SemaPseudoObject::checkAssignment
16288 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16289 // both expressions are overloadable or either is type-dependent),
16290 // or CreateBuiltinBinOp (in any other case). We also want to get
16291 // any placeholder types out of the way.
16292
16293 // Handle pseudo-objects in the LHS.
16294 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16295 // Assignments with a pseudo-object l-value need special analysis.
16296 if (pty->getKind() == BuiltinType::PseudoObject &&
16298 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16299
16300 // Don't resolve overloads if the other type is overloadable.
16301 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16302 // We can't actually test that if we still have a placeholder,
16303 // though. Fortunately, none of the exceptions we see in that
16304 // code below are valid when the LHS is an overload set. Note
16305 // that an overload set can be dependently-typed, but it never
16306 // instantiates to having an overloadable type.
16307 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16308 if (resolvedRHS.isInvalid()) return ExprError();
16309 RHSExpr = resolvedRHS.get();
16310
16311 if (RHSExpr->isTypeDependent() ||
16312 RHSExpr->getType()->isOverloadableType())
16313 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16314 }
16315
16316 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16317 // template, diagnose the missing 'template' keyword instead of diagnosing
16318 // an invalid use of a bound member function.
16319 //
16320 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16321 // to C++1z [over.over]/1.4, but we already checked for that case above.
16322 if (Opc == BO_LT && inTemplateInstantiation() &&
16323 (pty->getKind() == BuiltinType::BoundMember ||
16324 pty->getKind() == BuiltinType::Overload)) {
16325 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16326 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16327 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16328 return isa<FunctionTemplateDecl>(ND);
16329 })) {
16330 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16331 : OE->getNameLoc(),
16332 diag::err_template_kw_missing)
16333 << OE->getName().getAsIdentifierInfo();
16334 return ExprError();
16335 }
16336 }
16337
16338 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16339 if (LHS.isInvalid()) return ExprError();
16340 LHSExpr = LHS.get();
16341 }
16342
16343 // Handle pseudo-objects in the RHS.
16344 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16345 // An overload in the RHS can potentially be resolved by the type
16346 // being assigned to.
16347 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16348 if (getLangOpts().CPlusPlus &&
16349 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16350 LHSExpr->getType()->isOverloadableType()))
16351 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16352
16353 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16354 ForFoldExpression);
16355 }
16356
16357 // Don't resolve overloads if the other type is overloadable.
16358 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16359 LHSExpr->getType()->isOverloadableType())
16360 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16361
16362 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16363 if (!resolvedRHS.isUsable()) return ExprError();
16364 RHSExpr = resolvedRHS.get();
16365 }
16366
16367 if (getLangOpts().HLSL) {
16368 if (LHSExpr->getType()->isHLSLResourceRecord() ||
16369 LHSExpr->getType()->isHLSLResourceRecordArray()) {
16370 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
16371 return ExprError();
16372 } else if (RHSExpr->getType()->isHLSLResourceRecord()) {
16373 std::optional<ExprResult> ConvRHS =
16375 if (ConvRHS && Context.hasSameUnqualifiedType(
16376 LHSExpr->getType(), ConvRHS->get()->getType())) {
16377 assert(!ConvRHS->isInvalid());
16378 RHSExpr = ConvRHS->get();
16379 }
16380 }
16381 }
16382
16383 if (getLangOpts().CPlusPlus) {
16384 bool CanOverloadBinOp =
16385 !getLangOpts().HLSL ||
16386 HLSL().canHaveOverloadedBinOp(LHSExpr->getType(), Opc) ||
16387 HLSL().canHaveOverloadedBinOp(RHSExpr->getType(), Opc);
16388 bool TypeDependent =
16389 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16390 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16391 RHSExpr->getType()->isOverloadableType();
16392 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16393 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16394 }
16395
16396 if (getLangOpts().RecoveryAST &&
16397 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16398 assert(!getLangOpts().CPlusPlus);
16399 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16400 "Should only occur in error-recovery path.");
16402 // C [6.15.16] p3:
16403 // An assignment expression has the value of the left operand after the
16404 // assignment, but is not an lvalue.
16406 Context, LHSExpr, RHSExpr, Opc,
16408 OpLoc, CurFPFeatureOverrides());
16409 QualType ResultType;
16410 switch (Opc) {
16411 case BO_Assign:
16412 ResultType = LHSExpr->getType().getUnqualifiedType();
16413 break;
16414 case BO_LT:
16415 case BO_GT:
16416 case BO_LE:
16417 case BO_GE:
16418 case BO_EQ:
16419 case BO_NE:
16420 case BO_LAnd:
16421 case BO_LOr:
16422 // These operators have a fixed result type regardless of operands.
16423 ResultType = Context.IntTy;
16424 break;
16425 case BO_Comma:
16426 ResultType = RHSExpr->getType();
16427 break;
16428 default:
16429 ResultType = Context.DependentTy;
16430 break;
16431 }
16432 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16433 VK_PRValue, OK_Ordinary, OpLoc,
16435 }
16436
16437 // Build a built-in binary operation.
16438 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16439}
16440
16442 if (T.isNull() || T->isDependentType())
16443 return false;
16444
16445 if (!Ctx.isPromotableIntegerType(T))
16446 return true;
16447
16448 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16449}
16450
16452 UnaryOperatorKind Opc, Expr *InputExpr,
16453 bool IsAfterAmp) {
16454 ExprResult Input = InputExpr;
16457 QualType resultType;
16458 bool CanOverflow = false;
16459
16460 bool ConvertHalfVec = false;
16461 if (getLangOpts().OpenCL) {
16462 QualType Ty = InputExpr->getType();
16463 // The only legal unary operation for atomics is '&'.
16464 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16465 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16466 // only with a builtin functions and therefore should be disallowed here.
16467 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16468 || Ty->isBlockPointerType())) {
16469 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16470 << InputExpr->getType()
16471 << Input.get()->getSourceRange());
16472 }
16473 }
16474
16475 if (getLangOpts().HLSL && OpLoc.isValid()) {
16476 if (Opc == UO_AddrOf)
16477 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16478 if (Opc == UO_Deref)
16479 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16480 }
16481
16482 if (InputExpr->isTypeDependent() &&
16483 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
16484 resultType = Context.DependentTy;
16485 } else {
16486 switch (Opc) {
16487 case UO_PreInc:
16488 case UO_PreDec:
16489 case UO_PostInc:
16490 case UO_PostDec:
16491 resultType =
16492 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
16493 Opc == UO_PreInc || Opc == UO_PostInc,
16494 Opc == UO_PreInc || Opc == UO_PreDec);
16495 CanOverflow = isOverflowingIntegerType(Context, resultType);
16496 break;
16497 case UO_AddrOf:
16498 resultType = CheckAddressOfOperand(Input, OpLoc);
16499 CheckAddressOfNoDeref(InputExpr);
16500 RecordModifiableNonNullParam(*this, InputExpr);
16501 break;
16502 case UO_Deref: {
16504 if (Input.isInvalid())
16505 return ExprError();
16506 resultType =
16507 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16508 break;
16509 }
16510 case UO_Plus:
16511 case UO_Minus:
16512 CanOverflow = Opc == UO_Minus &&
16514 Input = UsualUnaryConversions(Input.get());
16515 if (Input.isInvalid())
16516 return ExprError();
16517 // Unary plus and minus require promoting an operand of half vector to a
16518 // float vector and truncating the result back to a half vector. For now,
16519 // we do this only when HalfArgsAndReturns is set (that is, when the
16520 // target is arm or arm64).
16521 ConvertHalfVec = needsConversionOfHalfVec(
16522 true, Context, Input.get()->getType(), Input.get());
16523
16524 // If the operand is a half vector, promote it to a float vector.
16525 if (ConvertHalfVec)
16526 Input = convertVector(Input.get(), Context.FloatTy, *this);
16527 resultType = Input.get()->getType();
16528 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16529 break;
16530 else if (resultType->isVectorType() &&
16531 // The z vector extensions don't allow + or - with bool vectors.
16532 (!Context.getLangOpts().ZVector ||
16533 resultType->castAs<VectorType>()->getVectorKind() !=
16535 break;
16536 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16537 break;
16538 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16539 Opc == UO_Plus && resultType->isPointerType())
16540 break;
16541
16542 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16543 << resultType << Input.get()->getSourceRange());
16544
16545 case UO_Not: // bitwise complement
16546 Input = UsualUnaryConversions(Input.get());
16547 if (Input.isInvalid())
16548 return ExprError();
16549 resultType = Input.get()->getType();
16550 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16551 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16552 // C99 does not support '~' for complex conjugation.
16553 Diag(OpLoc, diag::ext_integer_complement_complex)
16554 << resultType << Input.get()->getSourceRange();
16555 else if (resultType->hasIntegerRepresentation())
16556 break;
16557 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16558 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16559 // on vector float types.
16560 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16561 if (!T->isIntegerType())
16562 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16563 << resultType << Input.get()->getSourceRange());
16564 } else {
16565 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16566 << resultType << Input.get()->getSourceRange());
16567 }
16568 break;
16569
16570 case UO_LNot: // logical negation
16571 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16573 if (Input.isInvalid())
16574 return ExprError();
16575 resultType = Input.get()->getType();
16576
16577 // Though we still have to promote half FP to float...
16578 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16579 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16580 .get();
16581 resultType = Context.FloatTy;
16582 }
16583
16584 // WebAsembly tables can't be used in unary expressions.
16585 if (resultType->isPointerType() &&
16587 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16588 << resultType << Input.get()->getSourceRange());
16589 }
16590
16591 if (resultType->isScalarType() && !isScopedEnumerationType(resultType) &&
16592 !resultType->isMetaInfoType()) {
16593 // Before C++26, scalar types are contextually converted to bool,
16594 // std::meta::info is a scalar type but not an arithmetic type.
16595
16596 // C99 6.5.3.3p1: ok, fallthrough;
16597 if (Context.getLangOpts().CPlusPlus) {
16598 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16599 // operand contextually converted to bool.
16600 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16601 ScalarTypeToBooleanCastKind(resultType));
16602 } else if (Context.getLangOpts().OpenCL &&
16603 Context.getLangOpts().OpenCLVersion < 120) {
16604 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16605 // operate on scalar float types.
16606 if (!resultType->isIntegerType() && !resultType->isPointerType())
16607 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16608 << resultType << Input.get()->getSourceRange());
16609 }
16610 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16611 !resultType->hasBooleanRepresentation()) {
16612 // HLSL unary logical 'not' behaves like C++, which states that the
16613 // operand is converted to bool and the result is bool, however HLSL
16614 // extends this property to vectors.
16615 const VectorType *VTy = resultType->castAs<VectorType>();
16616 resultType =
16617 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16618
16619 Input = ImpCastExprToType(
16620 Input.get(), resultType,
16622 .get();
16623 break;
16624 } else if (resultType->isExtVectorType()) {
16625 if (Context.getLangOpts().OpenCL &&
16626 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16627 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16628 // operate on vector float types.
16629 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16630 if (!T->isIntegerType())
16631 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16632 << resultType << Input.get()->getSourceRange());
16633 }
16634 // Vector logical not returns the signed variant of the operand type.
16635 resultType = GetSignedVectorType(resultType);
16636 break;
16637 } else if (Context.getLangOpts().CPlusPlus &&
16638 resultType->isVectorType()) {
16639 const VectorType *VTy = resultType->castAs<VectorType>();
16640 if (VTy->getVectorKind() != VectorKind::Generic)
16641 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16642 << resultType << Input.get()->getSourceRange());
16643
16644 // Vector logical not returns the signed variant of the operand type.
16645 resultType = GetSignedVectorType(resultType);
16646 break;
16647 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16648 resultType = Context.getLogicalOperationType();
16649 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(InputExpr);
16650 break;
16651 } else {
16652 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16653 << resultType << Input.get()->getSourceRange());
16654 }
16655
16656 // LNot always has type int. C99 6.5.3.3p5.
16657 // In C++, it's bool. C++ 5.3.1p8
16658 resultType = Context.getLogicalOperationType();
16659 break;
16660 case UO_Real:
16661 case UO_Imag:
16662 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16663 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16664 // ordinary complex l-values to ordinary l-values and all other values to
16665 // r-values.
16666 if (Input.isInvalid())
16667 return ExprError();
16668 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16669 if (Input.get()->isGLValue() &&
16670 Input.get()->getObjectKind() == OK_Ordinary)
16671 VK = Input.get()->getValueKind();
16672 } else if (!getLangOpts().CPlusPlus) {
16673 // In C, a volatile scalar is read by __imag. In C++, it is not.
16674 Input = DefaultLvalueConversion(Input.get());
16675 }
16676 break;
16677 case UO_Extension:
16678 resultType = Input.get()->getType();
16679 VK = Input.get()->getValueKind();
16680 OK = Input.get()->getObjectKind();
16681 break;
16682 case UO_Coawait:
16683 // It's unnecessary to represent the pass-through operator co_await in the
16684 // AST; just return the input expression instead.
16685 assert(!Input.get()->getType()->isDependentType() &&
16686 "the co_await expression must be non-dependant before "
16687 "building operator co_await");
16688 return Input;
16689 }
16690 }
16691 if (resultType.isNull() || Input.isInvalid())
16692 return ExprError();
16693
16694 // Check for array bounds violations in the operand of the UnaryOperator,
16695 // except for the '*' and '&' operators that have to be handled specially
16696 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16697 // that are explicitly defined as valid by the standard).
16698 if (Opc != UO_AddrOf && Opc != UO_Deref)
16699 CheckArrayAccess(Input.get());
16700
16701 auto *UO =
16702 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16703 OpLoc, CanOverflow, CurFPFeatureOverrides());
16704
16705 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16706 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16708 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16709
16710 // Convert the result back to a half vector.
16711 if (ConvertHalfVec)
16712 return convertVector(UO, Context.HalfTy, *this);
16713 return UO;
16714}
16715
16717 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16718 if (!DRE->getQualifier())
16719 return false;
16720
16721 ValueDecl *VD = DRE->getDecl();
16722 if (!VD->isCXXClassMember())
16723 return false;
16724
16726 return true;
16727 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16728 return Method->isImplicitObjectMemberFunction();
16729
16730 return false;
16731 }
16732
16733 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16734 if (!ULE->getQualifier())
16735 return false;
16736
16737 for (NamedDecl *D : ULE->decls()) {
16738 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16739 if (Method->isImplicitObjectMemberFunction())
16740 return true;
16741 } else {
16742 // Overload set does not contain methods.
16743 break;
16744 }
16745 }
16746
16747 return false;
16748 }
16749
16750 return false;
16751}
16752
16754 UnaryOperatorKind Opc, Expr *Input,
16755 bool IsAfterAmp) {
16756 // First things first: handle placeholders so that the
16757 // overloaded-operator check considers the right type.
16758 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16759 // Increment and decrement of pseudo-object references.
16760 if (pty->getKind() == BuiltinType::PseudoObject &&
16762 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16763
16764 // extension is always a builtin operator.
16765 if (Opc == UO_Extension)
16766 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16767
16768 // & gets special logic for several kinds of placeholder.
16769 // The builtin code knows what to do.
16770 if (Opc == UO_AddrOf &&
16771 (pty->getKind() == BuiltinType::Overload ||
16772 pty->getKind() == BuiltinType::UnknownAny ||
16773 pty->getKind() == BuiltinType::BoundMember))
16774 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16775
16776 // Anything else needs to be handled now.
16778 if (Result.isInvalid()) return ExprError();
16779 Input = Result.get();
16780 }
16781
16782 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16784 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16785 // Find all of the overloaded operators visible from this point.
16786 UnresolvedSet<16> Functions;
16788 if (S && OverOp != OO_None)
16789 LookupOverloadedOperatorName(OverOp, S, Functions);
16790
16791 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16792 }
16793
16794 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16795}
16796
16798 Expr *Input, bool IsAfterAmp) {
16799 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16800 IsAfterAmp);
16801}
16802
16804 LabelDecl *TheDecl) {
16805 TheDecl->markUsed(Context);
16806 // Create the AST node. The address of a label always has type 'void*'.
16807 auto *Res = new (Context) AddrLabelExpr(
16808 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16809
16810 if (getCurFunction())
16811 getCurFunction()->AddrLabels.push_back(Res);
16812
16813 return Res;
16814}
16815
16818 // Make sure we diagnose jumping into a statement expression.
16820}
16821
16823 // Note that function is also called by TreeTransform when leaving a
16824 // StmtExpr scope without rebuilding anything.
16825
16828}
16829
16831 SourceLocation RPLoc) {
16832 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16833}
16834
16836 SourceLocation RPLoc, unsigned TemplateDepth) {
16837 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16838 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16839
16842 assert(!Cleanup.exprNeedsCleanups() &&
16843 "cleanups within StmtExpr not correctly bound!");
16845
16846 // FIXME: there are a variety of strange constraints to enforce here, for
16847 // example, it is not possible to goto into a stmt expression apparently.
16848 // More semantic analysis is needed.
16849
16850 // If there are sub-stmts in the compound stmt, take the type of the last one
16851 // as the type of the stmtexpr.
16852 QualType Ty = Context.VoidTy;
16853 bool StmtExprMayBindToTemp = false;
16854 if (!Compound->body_empty()) {
16855 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16856 if (const Expr *Value = LastStmt->getExprStmt()) {
16857 StmtExprMayBindToTemp = true;
16858 Ty = Value->getType();
16859 }
16860 }
16861 }
16862
16863 // FIXME: Check that expression type is complete/non-abstract; statement
16864 // expressions are not lvalues.
16865 Expr *ResStmtExpr =
16866 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16867 if (StmtExprMayBindToTemp)
16868 return MaybeBindToTemporary(ResStmtExpr);
16869 return ResStmtExpr;
16870}
16871
16873 if (ER.isInvalid())
16874 return ExprError();
16875
16876 // Do function/array conversion on the last expression, but not
16877 // lvalue-to-rvalue. However, initialize an unqualified type.
16879 if (ER.isInvalid())
16880 return ExprError();
16881 Expr *E = ER.get();
16882
16883 if (E->isTypeDependent())
16884 return E;
16885
16886 // In ARC, if the final expression ends in a consume, splice
16887 // the consume out and bind it later. In the alternate case
16888 // (when dealing with a retainable type), the result
16889 // initialization will create a produce. In both cases the
16890 // result will be +1, and we'll need to balance that out with
16891 // a bind.
16892 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16893 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16894 return Cast->getSubExpr();
16895
16896 // FIXME: Provide a better location for the initialization.
16900 SourceLocation(), E);
16901}
16902
16904 TypeSourceInfo *TInfo,
16905 const Designation &Desig,
16906 SourceLocation RParenLoc) {
16907 QualType ArgTy = TInfo->getType();
16908 bool Dependent = ArgTy->isDependentType();
16909 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16910
16911 // We must have at least one component that refers to the type, and the first
16912 // one is known to be a field designator. Verify that the ArgTy represents
16913 // a struct/union/class.
16914 if (!Dependent && !ArgTy->isRecordType())
16915 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16916 << ArgTy << TypeRange);
16917
16918 // Type must be complete per C99 7.17p3 because a declaring a variable
16919 // with an incomplete type would be ill-formed.
16920 if (!Dependent
16921 && RequireCompleteType(BuiltinLoc, ArgTy,
16922 diag::err_offsetof_incomplete_type, TypeRange))
16923 return ExprError();
16924
16925 bool DidWarnAboutNonPOD = false;
16926 QualType CurrentType = ArgTy;
16929 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
16930 const Designator &D = Desig.getDesignator(I);
16931 assert(!D.isArrayRangeDesignator());
16932 if (D.isArrayDesignator()) {
16933 // Offset of an array sub-field. TODO: Should we allow vector elements?
16934 if (!CurrentType->isDependentType()) {
16935 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16936 if(!AT)
16937 return ExprError(Diag(D.getEndLoc(), diag::err_offsetof_array_type)
16938 << CurrentType);
16939 CurrentType = AT->getElementType();
16940 } else
16941 CurrentType = Context.DependentTy;
16942
16944 if (IdxRval.isInvalid())
16945 return ExprError();
16946 Expr *Idx = IdxRval.get();
16947
16948 // The expression must be an integral expression.
16949 // FIXME: An integral constant expression?
16950 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16951 !Idx->getType()->isIntegerType())
16952 return ExprError(
16953 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16954 << Idx->getSourceRange());
16955
16956 // Record this array index.
16957 Comps.push_back(
16958 OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
16959 Exprs.push_back(Idx);
16960 continue;
16961 }
16962
16963 assert(D.isFieldDesignator());
16964 const IdentifierInfo *Name = D.getFieldDecl();
16965
16966 // Offset of a field.
16967 if (CurrentType->isDependentType()) {
16968 // We have the offset of a field, but we can't look into the dependent
16969 // type. Just record the identifier of the field.
16970 Comps.push_back(OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
16971 CurrentType = Context.DependentTy;
16972 continue;
16973 }
16974
16975 // We need to have a complete type to look into.
16976 if (RequireCompleteType(D.getBeginLoc(), CurrentType,
16977 diag::err_offsetof_incomplete_type))
16978 return ExprError();
16979
16980 // Look for the designated field.
16981 auto *RD = CurrentType->getAsRecordDecl();
16982 if (!RD)
16983 return ExprError(Diag(D.getEndLoc(), diag::err_offsetof_record_type)
16984 << CurrentType);
16985
16986 // C++ [lib.support.types]p5:
16987 // The macro offsetof accepts a restricted set of type arguments in this
16988 // International Standard. type shall be a POD structure or a POD union
16989 // (clause 9).
16990 // C++11 [support.types]p4:
16991 // If type is not a standard-layout class (Clause 9), the results are
16992 // undefined.
16993 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16994 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16995 unsigned DiagID =
16996 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16997 : diag::ext_offsetof_non_pod_type;
16998
16999 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
17000 Diag(BuiltinLoc, DiagID)
17002 << CurrentType;
17003 DidWarnAboutNonPOD = true;
17004 }
17005 }
17006
17007 // Look for the field.
17008 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
17009 LookupQualifiedName(R, RD);
17010 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
17011 IndirectFieldDecl *IndirectMemberDecl = nullptr;
17012 if (!MemberDecl) {
17013 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
17014 MemberDecl = IndirectMemberDecl->getAnonField();
17015 }
17016
17017 if (!MemberDecl) {
17018 // Lookup could be ambiguous when looking up a placeholder variable
17019 // __builtin_offsetof(S, _).
17020 // In that case we would already have emitted a diagnostic
17021 if (!R.isAmbiguous())
17022 Diag(BuiltinLoc, diag::err_no_member)
17023 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
17024 return ExprError();
17025 }
17026
17027 // C99 7.17p3:
17028 // (If the specified member is a bit-field, the behavior is undefined.)
17029 //
17030 // We diagnose this as an error.
17031 if (MemberDecl->isBitField()) {
17032 Diag(D.getEndLoc(), diag::err_offsetof_bitfield)
17033 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17034 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
17035 return ExprError();
17036 }
17037
17038 RecordDecl *Parent = MemberDecl->getParent();
17039 if (IndirectMemberDecl)
17040 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
17041
17042 // If the member was found in a base class, introduce OffsetOfNodes for
17043 // the base class indirections.
17044 CXXBasePaths Paths;
17045 if (IsDerivedFrom(D.getBeginLoc(), CurrentType,
17046 Context.getCanonicalTagType(Parent), Paths)) {
17047 if (Paths.getDetectedVirtual()) {
17048 Diag(D.getEndLoc(), diag::err_offsetof_field_of_virtual_base)
17049 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17050 return ExprError();
17051 }
17052
17053 CXXBasePath &Path = Paths.front();
17054 for (const CXXBasePathElement &B : Path)
17055 Comps.push_back(OffsetOfNode(B.Base));
17056 }
17057
17058 if (IndirectMemberDecl) {
17059 for (auto *FI : IndirectMemberDecl->chain()) {
17060 assert(isa<FieldDecl>(FI));
17061 Comps.push_back(
17063 }
17064 } else
17065 Comps.push_back(OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
17066
17067 CurrentType = MemberDecl->getType().getNonReferenceType();
17068 }
17069
17070 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
17071 Comps, Exprs, RParenLoc);
17072}
17073
17076 ParsedType ParsedArgTy,
17077 const Designation &Desig,
17078 SourceLocation RParenLoc) {
17079
17080 TypeSourceInfo *ArgTInfo;
17081 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
17082 if (ArgTy.isNull())
17083 return ExprError();
17084
17085 if (!ArgTInfo)
17086 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
17087
17088 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Desig, RParenLoc);
17089}
17090
17092 Expr *CondExpr,
17093 Expr *LHSExpr, Expr *RHSExpr,
17094 SourceLocation RPLoc) {
17095 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
17096
17099 QualType resType;
17100 bool CondIsTrue = false;
17101 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
17102 resType = Context.DependentTy;
17103 } else {
17104 // The conditional expression is required to be a constant expression.
17105 llvm::APSInt condEval(32);
17107 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
17108 if (CondICE.isInvalid())
17109 return ExprError();
17110 CondExpr = CondICE.get();
17111 CondIsTrue = condEval.getZExtValue();
17112
17113 // If the condition is > zero, then the AST type is the same as the LHSExpr.
17114 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
17115
17116 resType = ActiveExpr->getType();
17117 VK = ActiveExpr->getValueKind();
17118 OK = ActiveExpr->getObjectKind();
17119 }
17120
17121 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
17122 resType, VK, OK, RPLoc, CondIsTrue);
17123}
17124
17125//===----------------------------------------------------------------------===//
17126// Clang Extensions.
17127//===----------------------------------------------------------------------===//
17128
17129void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
17131
17132 if (LangOpts.CPlusPlus) {
17134 Decl *ManglingContextDecl;
17135 std::tie(MCtx, ManglingContextDecl) =
17136 getCurrentMangleNumberContext(Block->getDeclContext());
17137 if (MCtx) {
17138 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
17139 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
17140 }
17141 }
17142
17143 PushBlockScope(CurScope, Block);
17144 CurContext->addDecl(Block);
17145 if (CurScope)
17146 PushDeclContext(CurScope, Block);
17147 else
17148 CurContext = Block;
17149
17151
17152 // Enter a new evaluation context to insulate the block from any
17153 // cleanups from the enclosing full-expression.
17156}
17157
17159 Scope *CurScope) {
17160 assert(ParamInfo.getIdentifier() == nullptr &&
17161 "block-id should have no identifier!");
17162 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
17163 BlockScopeInfo *CurBlock = getCurBlock();
17164
17165 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
17166 QualType T = Sig->getType();
17168
17169 // GetTypeForDeclarator always produces a function type for a block
17170 // literal signature. Furthermore, it is always a FunctionProtoType
17171 // unless the function was written with a typedef.
17172 assert(T->isFunctionType() &&
17173 "GetTypeForDeclarator made a non-function block signature");
17174
17175 // Look for an explicit signature in that function type.
17176 FunctionProtoTypeLoc ExplicitSignature;
17177
17178 if ((ExplicitSignature = Sig->getTypeLoc()
17180
17181 // Check whether that explicit signature was synthesized by
17182 // GetTypeForDeclarator. If so, don't save that as part of the
17183 // written signature.
17184 if (ExplicitSignature.getLocalRangeBegin() ==
17185 ExplicitSignature.getLocalRangeEnd()) {
17186 // This would be much cheaper if we stored TypeLocs instead of
17187 // TypeSourceInfos.
17188 TypeLoc Result = ExplicitSignature.getReturnLoc();
17189 unsigned Size = Result.getFullDataSize();
17190 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
17191 Sig->getTypeLoc().initializeFullCopy(Result, Size);
17192
17193 ExplicitSignature = FunctionProtoTypeLoc();
17194 }
17195 }
17196
17197 CurBlock->TheDecl->setSignatureAsWritten(Sig);
17198 CurBlock->FunctionType = T;
17199
17200 const auto *Fn = T->castAs<FunctionType>();
17201 QualType RetTy = Fn->getReturnType();
17202 bool isVariadic =
17203 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
17204
17205 CurBlock->TheDecl->setIsVariadic(isVariadic);
17206
17207 // Context.DependentTy is used as a placeholder for a missing block
17208 // return type. TODO: what should we do with declarators like:
17209 // ^ * { ... }
17210 // If the answer is "apply template argument deduction"....
17211 if (RetTy != Context.DependentTy) {
17212 CurBlock->ReturnType = RetTy;
17213 CurBlock->TheDecl->setBlockMissingReturnType(false);
17214 CurBlock->HasImplicitReturnType = false;
17215 }
17216
17217 // Push block parameters from the declarator if we had them.
17219 if (ExplicitSignature) {
17220 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17221 ParmVarDecl *Param = ExplicitSignature.getParam(I);
17222 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17223 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17224 // Diagnose this as an extension in C17 and earlier.
17225 if (!getLangOpts().C23)
17226 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
17227 }
17228 Params.push_back(Param);
17229 }
17230
17231 // Fake up parameter variables if we have a typedef, like
17232 // ^ fntype { ... }
17233 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17234 for (const auto &I : Fn->param_types()) {
17236 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
17237 Params.push_back(Param);
17238 }
17239 }
17240
17241 // Set the parameters on the block decl.
17242 if (!Params.empty()) {
17243 CurBlock->TheDecl->setParams(Params);
17245 /*CheckParameterNames=*/false);
17246 }
17247
17248 // Finally we can process decl attributes.
17249 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
17250
17251 // Put the parameter variables in scope.
17252 for (auto *AI : CurBlock->TheDecl->parameters()) {
17253 AI->setOwningFunction(CurBlock->TheDecl);
17254
17255 // If this has an identifier, add it to the scope stack.
17256 if (AI->getIdentifier()) {
17257 CheckShadow(CurBlock->TheScope, AI);
17258
17259 PushOnScopeChains(AI, CurBlock->TheScope);
17260 }
17261
17262 if (AI->isInvalidDecl())
17263 CurBlock->TheDecl->setInvalidDecl();
17264 }
17265}
17266
17267void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17268 // Leave the expression-evaluation context.
17271
17272 // Pop off CurBlock, handle nested blocks.
17275}
17276
17278 Stmt *Body, Scope *CurScope) {
17279 // If blocks are disabled, emit an error.
17280 if (!LangOpts.Blocks)
17281 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
17282
17283 // Leave the expression-evaluation context.
17286 assert(!Cleanup.exprNeedsCleanups() &&
17287 "cleanups within block not correctly bound!");
17289
17291 BlockDecl *BD = BSI->TheDecl;
17292
17294
17295 if (BSI->HasImplicitReturnType)
17297
17298 QualType RetTy = Context.VoidTy;
17299 if (!BSI->ReturnType.isNull())
17300 RetTy = BSI->ReturnType;
17301
17302 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17303 QualType BlockTy;
17304
17305 // If the user wrote a function type in some form, try to use that.
17306 if (!BSI->FunctionType.isNull()) {
17307 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17308
17309 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17310 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17311
17312 // Turn protoless block types into nullary block types.
17313 if (isa<FunctionNoProtoType>(FTy)) {
17315 EPI.ExtInfo = Ext;
17316 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17317
17318 // Otherwise, if we don't need to change anything about the function type,
17319 // preserve its sugar structure.
17320 } else if (FTy->getReturnType() == RetTy &&
17321 (!NoReturn || FTy->getNoReturnAttr())) {
17322 BlockTy = BSI->FunctionType;
17323
17324 // Otherwise, make the minimal modifications to the function type.
17325 } else {
17328 EPI.TypeQuals = Qualifiers();
17329 EPI.ExtInfo = Ext;
17330 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17331 }
17332
17333 // If we don't have a function type, just build one from nothing.
17334 } else {
17336 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17337 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17338 }
17339
17341 BlockTy = Context.getBlockPointerType(BlockTy);
17342
17343 // If needed, diagnose invalid gotos and switches in the block.
17344 if (getCurFunction()->NeedsScopeChecking() &&
17345 !PP.isCodeCompletionEnabled())
17347
17348 BD->setBody(cast<CompoundStmt>(Body));
17349
17350 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17352
17353 // Try to apply the named return value optimization. We have to check again
17354 // if we can do this, though, because blocks keep return statements around
17355 // to deduce an implicit return type.
17356 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17357 !BD->isDependentContext())
17358 computeNRVO(Body, BSI);
17359
17365
17367
17368 // Set the captured variables on the block.
17370 for (Capture &Cap : BSI->Captures) {
17371 if (Cap.isInvalid() || Cap.isThisCapture())
17372 continue;
17373 // Cap.getVariable() is always a VarDecl because
17374 // blocks cannot capture structured bindings or other ValueDecl kinds.
17375 auto *Var = cast<VarDecl>(Cap.getVariable());
17376 Expr *CopyExpr = nullptr;
17377 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17378 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17379 // The capture logic needs the destructor, so make sure we mark it.
17380 // Usually this is unnecessary because most local variables have
17381 // their destructors marked at declaration time, but parameters are
17382 // an exception because it's technically only the call site that
17383 // actually requires the destructor.
17384 if (isa<ParmVarDecl>(Var))
17386
17387 // Enter a separate potentially-evaluated context while building block
17388 // initializers to isolate their cleanups from those of the block
17389 // itself.
17390 // FIXME: Is this appropriate even when the block itself occurs in an
17391 // unevaluated operand?
17394
17395 SourceLocation Loc = Cap.getLocation();
17396
17398 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17399
17400 // According to the blocks spec, the capture of a variable from
17401 // the stack requires a const copy constructor. This is not true
17402 // of the copy/move done to move a __block variable to the heap.
17403 if (!Result.isInvalid() &&
17404 !Result.get()->getType().isConstQualified()) {
17406 Result.get()->getType().withConst(),
17407 CK_NoOp, VK_LValue);
17408 }
17409
17410 if (!Result.isInvalid()) {
17412 InitializedEntity::InitializeBlock(Var->getLocation(),
17413 Cap.getCaptureType()),
17414 Loc, Result.get());
17415 }
17416
17417 // Build a full-expression copy expression if initialization
17418 // succeeded and used a non-trivial constructor. Recover from
17419 // errors by pretending that the copy isn't necessary.
17420 if (!Result.isInvalid() &&
17421 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17422 ->isTrivial()) {
17424 CopyExpr = Result.get();
17425 }
17426 }
17427 }
17428
17429 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17430 CopyExpr);
17431 Captures.push_back(NewCap);
17432 }
17433 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17434
17435 // Pop the block scope now but keep it alive to the end of this function.
17437 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
17438 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17439
17440 BlockExpr *Result = new (Context)
17441 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17442
17443 // If the block isn't obviously global, i.e. it captures anything at
17444 // all, then we need to do a few things in the surrounding context:
17445 if (Result->getBlockDecl()->hasCaptures()) {
17446 // First, this expression has a new cleanup object.
17447 ExprCleanupObjects.push_back(Result->getBlockDecl());
17448 Cleanup.setExprNeedsCleanups(true);
17449
17450 // It also gets a branch-protected scope if any of the captured
17451 // variables needs destruction.
17452 for (const auto &CI : Result->getBlockDecl()->captures()) {
17453 const VarDecl *var = CI.getVariable();
17454 if (var->getType().isDestructedType() != QualType::DK_none) {
17456 break;
17457 }
17458 }
17459 }
17460
17461 if (getCurFunction())
17462 getCurFunction()->addBlock(BD);
17463
17464 // This can happen if the block's return type is deduced, but
17465 // the return expression is invalid.
17466 if (BD->isInvalidDecl())
17467 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17468 {Result}, Result->getType());
17469 return Result;
17470}
17471
17473 SourceLocation RPLoc) {
17474 TypeSourceInfo *TInfo;
17475 GetTypeFromParser(Ty, &TInfo);
17476 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17477}
17478
17480 Expr *E, TypeSourceInfo *TInfo,
17481 SourceLocation RPLoc) {
17482 Expr *OrigExpr = E;
17484
17485 // CUDA device global function does not support varargs.
17486 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17487 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17490 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17491 }
17492 }
17493
17494 // NVPTX does not support va_arg expression.
17495 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17496 Context.getTargetInfo().getTriple().isNVPTX())
17497 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17498
17499 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17500 // as Microsoft ABI on an actual Microsoft platform, where
17501 // __builtin_ms_va_list and __builtin_va_list are the same.)
17502 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17503 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17504 QualType MSVaListType = Context.getBuiltinMSVaListType();
17505 if (Context.hasSameType(MSVaListType, E->getType())) {
17506 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17507 return ExprError();
17508 VAKind = VAArgExpr::VA_MS;
17509 }
17510 }
17511
17512 // Get the va_list type
17513 QualType VaListType = Context.getBuiltinVaListType();
17514
17515 // It might be a __builtin_zos_va_list!
17516 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinZOSVaList()) {
17517 // E->getType() can be:
17518 // - va_list: equal to array (char*)[2] (inside function)
17519 // - char **: decayed array (va_list passed as parameter)
17520 // We need to check for both cases.
17521 QualType ZOSVaListType = Context.getBuiltinZOSVaListType();
17522 assert(ZOSVaListType->isArrayType() &&
17523 "__builtin_zos_va_list must be an array type");
17524 QualType DecayedType = Context.getArrayDecayedType(ZOSVaListType);
17525 if (Context.hasSameType(ZOSVaListType, E->getType()) ||
17526 Context.hasSameType(DecayedType, E->getType())) {
17527 VAKind = VAArgExpr::VA_ZOS;
17528 VaListType = ZOSVaListType;
17529 }
17530 }
17531
17532 if (VAKind != VAArgExpr::VA_MS) {
17533 if (VaListType->isArrayType()) {
17534 // Deal with implicit array decay; for example, on x86-64,
17535 // va_list is an array, but it's supposed to decay to
17536 // a pointer for va_arg.
17537 VaListType = Context.getArrayDecayedType(VaListType);
17538 // Make sure the input expression also decays appropriately.
17540 if (Result.isInvalid())
17541 return ExprError();
17542 E = Result.get();
17543 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17544 // If va_list is a record type and we are compiling in C++ mode,
17545 // check the argument using reference binding.
17547 Context, Context.getLValueReferenceType(VaListType), false);
17549 if (Init.isInvalid())
17550 return ExprError();
17551 E = Init.getAs<Expr>();
17552 } else {
17553 // Otherwise, the va_list argument must be an l-value because
17554 // it is modified by va_arg.
17555 if (!E->isTypeDependent() &&
17556 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17557 return ExprError();
17558 }
17559 }
17560
17561 if ((VAKind != VAArgExpr::VA_MS) && !E->isTypeDependent() &&
17562 !Context.hasSameType(VaListType, E->getType()))
17563 return ExprError(
17564 Diag(E->getBeginLoc(),
17565 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17566 << OrigExpr->getType() << E->getSourceRange());
17567
17568 if (!TInfo->getType()->isDependentType()) {
17569 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17570 diag::err_second_parameter_to_va_arg_incomplete,
17571 TInfo->getTypeLoc()))
17572 return ExprError();
17573
17575 TInfo->getType(),
17576 diag::err_second_parameter_to_va_arg_abstract,
17577 TInfo->getTypeLoc()))
17578 return ExprError();
17579
17580 if (!TInfo->getType().isPODType(Context)) {
17581 Diag(TInfo->getTypeLoc().getBeginLoc(),
17582 TInfo->getType()->isObjCLifetimeType()
17583 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17584 : diag::warn_second_parameter_to_va_arg_not_pod)
17585 << TInfo->getType()
17586 << TInfo->getTypeLoc().getSourceRange();
17587 }
17588
17589 if (TInfo->getType()->isArrayType()) {
17591 PDiag(diag::warn_second_parameter_to_va_arg_array)
17592 << TInfo->getType()
17593 << TInfo->getTypeLoc().getSourceRange());
17594 }
17595
17596 // Check for va_arg where arguments of the given type will be promoted
17597 // (i.e. this va_arg is guaranteed to have undefined behavior).
17598 QualType PromoteType;
17599 if (Context.isPromotableIntegerType(TInfo->getType())) {
17600 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17601 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17602 // and C23 7.16.1.1p2 says, in part:
17603 // If type is not compatible with the type of the actual next argument
17604 // (as promoted according to the default argument promotions), the
17605 // behavior is undefined, except for the following cases:
17606 // - both types are pointers to qualified or unqualified versions of
17607 // compatible types;
17608 // - one type is compatible with a signed integer type, the other
17609 // type is compatible with the corresponding unsigned integer type,
17610 // and the value is representable in both types;
17611 // - one type is pointer to qualified or unqualified void and the
17612 // other is a pointer to a qualified or unqualified character type;
17613 // - or, the type of the next argument is nullptr_t and type is a
17614 // pointer type that has the same representation and alignment
17615 // requirements as a pointer to a character type.
17616 // Given that type compatibility is the primary requirement (ignoring
17617 // qualifications), you would think we could call typesAreCompatible()
17618 // directly to test this. However, in C++, that checks for *same type*,
17619 // which causes false positives when passing an enumeration type to
17620 // va_arg. Instead, get the underlying type of the enumeration and pass
17621 // that.
17622 QualType UnderlyingType = TInfo->getType();
17623 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17624 UnderlyingType = ED->getIntegerType();
17625 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17626 /*CompareUnqualified*/ true))
17627 PromoteType = QualType();
17628
17629 // If the types are still not compatible, we need to test whether the
17630 // promoted type and the underlying type are the same except for
17631 // signedness. Ask the AST for the correctly corresponding type and see
17632 // if that's compatible.
17633 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17634 PromoteType->isUnsignedIntegerType() !=
17635 UnderlyingType->isUnsignedIntegerType()) {
17636 UnderlyingType =
17637 UnderlyingType->isUnsignedIntegerType()
17638 ? Context.getCorrespondingSignedType(UnderlyingType)
17639 : Context.getCorrespondingUnsignedType(UnderlyingType);
17640 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17641 /*CompareUnqualified*/ true))
17642 PromoteType = QualType();
17643 }
17644 }
17645 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17646 PromoteType = Context.DoubleTy;
17647 if (!PromoteType.isNull())
17649 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17650 << TInfo->getType()
17651 << PromoteType
17652 << TInfo->getTypeLoc().getSourceRange());
17653 }
17654
17656 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, VAKind);
17657}
17658
17660 // The type of __null will be int or long, depending on the size of
17661 // pointers on the target.
17662 QualType Ty;
17663 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17664 if (pw == Context.getTargetInfo().getIntWidth())
17665 Ty = Context.IntTy;
17666 else if (pw == Context.getTargetInfo().getLongWidth())
17667 Ty = Context.LongTy;
17668 else if (pw == Context.getTargetInfo().getLongLongWidth())
17669 Ty = Context.LongLongTy;
17670 else {
17671 llvm_unreachable("I don't know size of pointer!");
17672 }
17673
17674 return new (Context) GNUNullExpr(Ty, TokenLoc);
17675}
17676
17678 CXXRecordDecl *ImplDecl = nullptr;
17679
17680 // Fetch the std::source_location::__impl decl.
17681 if (NamespaceDecl *Std = S.getStdNamespace()) {
17682 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17684 if (S.LookupQualifiedName(ResultSL, Std)) {
17685 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17686 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17688 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17689 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17690 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17691 }
17692 }
17693 }
17694 }
17695
17696 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17697 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17698 return nullptr;
17699 }
17700
17701 // Verify that __impl is a trivial struct type, with no base classes, and with
17702 // only the four expected fields.
17703 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17704 ImplDecl->getNumBases() != 0) {
17705 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17706 return nullptr;
17707 }
17708
17709 unsigned Count = 0;
17710 for (FieldDecl *F : ImplDecl->fields()) {
17711 StringRef Name = F->getName();
17712
17713 if (Name == "_M_file_name") {
17714 if (F->getType() !=
17716 break;
17717 Count++;
17718 } else if (Name == "_M_function_name") {
17719 if (F->getType() !=
17721 break;
17722 Count++;
17723 } else if (Name == "_M_line") {
17724 if (!F->getType()->isIntegerType())
17725 break;
17726 Count++;
17727 } else if (Name == "_M_column") {
17728 if (!F->getType()->isIntegerType())
17729 break;
17730 Count++;
17731 } else {
17732 Count = 100; // invalid
17733 break;
17734 }
17735 }
17736 if (Count != 4) {
17737 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17738 return nullptr;
17739 }
17740
17741 return ImplDecl;
17742}
17743
17745 SourceLocation BuiltinLoc,
17746 SourceLocation RPLoc) {
17747 QualType ResultTy;
17748 switch (Kind) {
17753 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17754 ResultTy =
17755 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17756 break;
17757 }
17760 ResultTy = Context.UnsignedIntTy;
17761 break;
17765 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17767 return ExprError();
17768 }
17769 ResultTy = Context.getPointerType(
17770 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17771 break;
17772 }
17773
17774 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17775}
17776
17778 SourceLocation BuiltinLoc,
17779 SourceLocation RPLoc,
17780 DeclContext *ParentContext) {
17781 return new (Context)
17782 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17783}
17784
17786 StringLiteral *BinaryData, StringRef FileName) {
17788 Data->BinaryData = BinaryData;
17789 Data->FileName = FileName;
17790 return new (Context)
17791 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17792 Data->getDataElementCount());
17793}
17794
17796 const Expr *SrcExpr) {
17797 if (!DstType->isFunctionPointerType() ||
17798 !SrcExpr->getType()->isFunctionType())
17799 return false;
17800
17801 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17802 if (!DRE)
17803 return false;
17804
17805 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17806 if (!FD)
17807 return false;
17808
17810 /*Complain=*/true,
17811 SrcExpr->getBeginLoc());
17812}
17813
17815 SourceLocation Loc,
17816 QualType DstType, QualType SrcType,
17817 Expr *SrcExpr, AssignmentAction Action,
17818 bool *Complained) {
17819 if (Complained)
17820 *Complained = false;
17821
17822 // Decode the result (notice that AST's are still created for extensions).
17823 bool CheckInferredResultType = false;
17824 bool isInvalid = false;
17825 unsigned DiagKind = 0;
17826 ConversionFixItGenerator ConvHints;
17827 bool MayHaveConvFixit = false;
17828 bool MayHaveFunctionDiff = false;
17829 const ObjCInterfaceDecl *IFace = nullptr;
17830 const ObjCProtocolDecl *PDecl = nullptr;
17831
17832 switch (ConvTy) {
17834 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17835 return false;
17837 // Still a valid conversion, but we may want to diagnose for C++
17838 // compatibility reasons.
17839 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17840 break;
17842 if (getLangOpts().CPlusPlus) {
17843 DiagKind = diag::err_typecheck_convert_pointer_int;
17844 isInvalid = true;
17845 } else {
17846 DiagKind = diag::ext_typecheck_convert_pointer_int;
17847 }
17848 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17849 MayHaveConvFixit = true;
17850 break;
17852 if (getLangOpts().CPlusPlus) {
17853 DiagKind = diag::err_typecheck_convert_int_pointer;
17854 isInvalid = true;
17855 } else {
17856 DiagKind = diag::ext_typecheck_convert_int_pointer;
17857 }
17858 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17859 MayHaveConvFixit = true;
17860 break;
17862 DiagKind =
17863 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17864 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17865 MayHaveConvFixit = true;
17866 break;
17868 if (getLangOpts().CPlusPlus) {
17869 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17870 isInvalid = true;
17871 } else {
17872 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17873 }
17874 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17875 MayHaveConvFixit = true;
17876 break;
17879 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17880 } else if (getLangOpts().CPlusPlus) {
17881 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17882 isInvalid = true;
17883 } else {
17884 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17885 }
17886 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17887 SrcType->isObjCObjectPointerType();
17888 if (CheckInferredResultType) {
17889 SrcType = SrcType.getUnqualifiedType();
17890 DstType = DstType.getUnqualifiedType();
17891 } else {
17892 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17893 }
17894 MayHaveConvFixit = true;
17895 break;
17897 if (getLangOpts().CPlusPlus) {
17898 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17899 isInvalid = true;
17900 } else {
17901 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17902 }
17903 break;
17905 if (getLangOpts().CPlusPlus) {
17906 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17907 isInvalid = true;
17908 } else {
17909 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17910 }
17911 break;
17913 // Perform decay if necessary.
17914 if (SrcType->canDecayToPointerType())
17915 SrcType = Context.getDecayedType(SrcType);
17916
17917 isInvalid = true;
17918
17919 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17920 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17921 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17922 DiagKind = diag::err_typecheck_incompatible_address_space;
17923 break;
17924 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17925 DiagKind = diag::err_typecheck_incompatible_ownership;
17926 break;
17927 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17928 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17929 break;
17930 }
17931
17932 llvm_unreachable("unknown error case for discarding qualifiers!");
17933 // fallthrough
17934 }
17936 if (SrcType->isArrayType())
17937 SrcType = Context.getArrayDecayedType(SrcType);
17938
17939 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17940 break;
17942 // If the qualifiers lost were because we were applying the
17943 // (deprecated) C++ conversion from a string literal to a char*
17944 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17945 // Ideally, this check would be performed in
17946 // checkPointerTypesForAssignment. However, that would require a
17947 // bit of refactoring (so that the second argument is an
17948 // expression, rather than a type), which should be done as part
17949 // of a larger effort to fix checkPointerTypesForAssignment for
17950 // C++ semantics.
17951 if (getLangOpts().CPlusPlus &&
17953 return false;
17954 if (getLangOpts().CPlusPlus) {
17955 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17956 isInvalid = true;
17957 } else {
17958 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17959 }
17960
17961 break;
17963 if (getLangOpts().CPlusPlus) {
17964 isInvalid = true;
17965 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17966 } else {
17967 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17968 }
17969 break;
17971 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17972 isInvalid = true;
17973 break;
17975 DiagKind = diag::err_int_to_block_pointer;
17976 isInvalid = true;
17977 break;
17979 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17980 isInvalid = true;
17981 break;
17983 if (SrcType->isObjCQualifiedIdType()) {
17984 const ObjCObjectPointerType *srcOPT =
17985 SrcType->castAs<ObjCObjectPointerType>();
17986 for (auto *srcProto : srcOPT->quals()) {
17987 PDecl = srcProto;
17988 break;
17989 }
17990 if (const ObjCInterfaceType *IFaceT =
17992 IFace = IFaceT->getDecl();
17993 }
17994 else if (DstType->isObjCQualifiedIdType()) {
17995 const ObjCObjectPointerType *dstOPT =
17996 DstType->castAs<ObjCObjectPointerType>();
17997 for (auto *dstProto : dstOPT->quals()) {
17998 PDecl = dstProto;
17999 break;
18000 }
18001 if (const ObjCInterfaceType *IFaceT =
18003 IFace = IFaceT->getDecl();
18004 }
18005 if (getLangOpts().CPlusPlus) {
18006 DiagKind = diag::err_incompatible_qualified_id;
18007 isInvalid = true;
18008 } else {
18009 DiagKind = diag::warn_incompatible_qualified_id;
18010 }
18011 break;
18012 }
18014 if (getLangOpts().CPlusPlus) {
18015 DiagKind = diag::err_incompatible_vectors;
18016 isInvalid = true;
18017 } else {
18018 DiagKind = diag::warn_incompatible_vectors;
18019 }
18020 break;
18022 DiagKind = diag::err_arc_weak_unavailable_assign;
18023 isInvalid = true;
18024 break;
18026 return false;
18028 assert(!SrcType->isFunctionType() &&
18029 "Unexpected function type found in IncompatibleOBTKinds assignment");
18030 if (SrcType->canDecayToPointerType())
18031 SrcType = Context.getDecayedType(SrcType);
18032
18033 auto getOBTKindName = [](QualType Ty) -> StringRef {
18034 if (Ty->isPointerType())
18035 Ty = Ty->getPointeeType();
18036 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
18037 return OBT->getBehaviorKind() ==
18038 OverflowBehaviorType::OverflowBehaviorKind::Trap
18039 ? "__ob_trap"
18040 : "__ob_wrap";
18041 }
18042 llvm_unreachable("OBT kind unhandled");
18043 };
18044
18045 Diag(Loc, diag::err_incompatible_obt_kinds_assignment)
18046 << DstType << SrcType << getOBTKindName(DstType)
18047 << getOBTKindName(SrcType);
18048 isInvalid = true;
18049 return true;
18050 }
18052 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
18053 if (Complained)
18054 *Complained = true;
18055 return true;
18056 }
18057
18058 DiagKind = diag::err_typecheck_convert_incompatible;
18059 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
18060 MayHaveConvFixit = true;
18061 isInvalid = true;
18062 MayHaveFunctionDiff = true;
18063 break;
18064 }
18065
18066 QualType FirstType, SecondType;
18067 switch (Action) {
18070 // The destination type comes first.
18071 FirstType = DstType;
18072 SecondType = SrcType;
18073 break;
18074
18081 // The source type comes first.
18082 FirstType = SrcType;
18083 SecondType = DstType;
18084 break;
18085 }
18086
18087 PartialDiagnostic FDiag = PDiag(DiagKind);
18088 AssignmentAction ActionForDiag = Action;
18090 ActionForDiag = AssignmentAction::Passing;
18091
18092 FDiag << FirstType << SecondType << ActionForDiag
18093 << SrcExpr->getSourceRange();
18094
18095 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
18096 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
18097 auto isPlainChar = [](const clang::Type *Type) {
18098 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
18099 Type->isSpecificBuiltinType(BuiltinType::Char_U);
18100 };
18101 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
18102 isPlainChar(SecondType->getPointeeOrArrayElementType()));
18103 }
18104
18105 // If we can fix the conversion, suggest the FixIts.
18106 if (!ConvHints.isNull()) {
18107 for (FixItHint &H : ConvHints.Hints)
18108 FDiag << H;
18109 }
18110
18111 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
18112
18113 if (MayHaveFunctionDiff)
18114 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
18115
18116 Diag(Loc, FDiag);
18117 if ((DiagKind == diag::warn_incompatible_qualified_id ||
18118 DiagKind == diag::err_incompatible_qualified_id) &&
18119 PDecl && IFace && !IFace->hasDefinition())
18120 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
18121 << IFace << PDecl;
18122
18123 if (SecondType == Context.OverloadTy)
18125 FirstType, /*TakingAddress=*/true);
18126
18127 if (CheckInferredResultType)
18129
18130 if (Action == AssignmentAction::Returning &&
18133
18134 if (Complained)
18135 *Complained = true;
18136 return isInvalid;
18137}
18138
18140 llvm::APSInt *Result,
18141 AllowFoldKind CanFold) {
18142 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
18143 public:
18144 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
18145 QualType T) override {
18146 return S.Diag(Loc, diag::err_ice_not_integral)
18147 << T << S.LangOpts.CPlusPlus;
18148 }
18149 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18150 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
18151 }
18152 } Diagnoser;
18153
18154 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18155}
18156
18158 llvm::APSInt *Result,
18159 unsigned DiagID,
18160 AllowFoldKind CanFold) {
18161 class IDDiagnoser : public VerifyICEDiagnoser {
18162 unsigned DiagID;
18163
18164 public:
18165 IDDiagnoser(unsigned DiagID)
18166 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
18167
18168 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18169 return S.Diag(Loc, DiagID);
18170 }
18171 } Diagnoser(DiagID);
18172
18173 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18174}
18175
18181
18184 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
18185}
18186
18189 VerifyICEDiagnoser &Diagnoser,
18190 AllowFoldKind CanFold) {
18191 SourceLocation DiagLoc = E->getBeginLoc();
18192
18193 if (getLangOpts().CPlusPlus11) {
18194 // C++11 [expr.const]p5:
18195 // If an expression of literal class type is used in a context where an
18196 // integral constant expression is required, then that class type shall
18197 // have a single non-explicit conversion function to an integral or
18198 // unscoped enumeration type
18199 ExprResult Converted;
18200 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
18201 VerifyICEDiagnoser &BaseDiagnoser;
18202 public:
18203 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
18204 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18205 BaseDiagnoser.Suppress, true),
18206 BaseDiagnoser(BaseDiagnoser) {}
18207
18208 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18209 QualType T) override {
18210 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18211 }
18212
18213 SemaDiagnosticBuilder diagnoseIncomplete(
18214 Sema &S, SourceLocation Loc, QualType T) override {
18215 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
18216 }
18217
18218 SemaDiagnosticBuilder diagnoseExplicitConv(
18219 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18220 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
18221 }
18222
18223 SemaDiagnosticBuilder noteExplicitConv(
18224 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18225 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18226 << ConvTy->isEnumeralType() << ConvTy;
18227 }
18228
18229 SemaDiagnosticBuilder diagnoseAmbiguous(
18230 Sema &S, SourceLocation Loc, QualType T) override {
18231 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
18232 }
18233
18234 SemaDiagnosticBuilder noteAmbiguous(
18235 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18236 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18237 << ConvTy->isEnumeralType() << ConvTy;
18238 }
18239
18240 SemaDiagnosticBuilder diagnoseConversion(
18241 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18242 llvm_unreachable("conversion functions are permitted");
18243 }
18244 } ConvertDiagnoser(Diagnoser);
18245
18246 Converted = PerformContextualImplicitConversion(DiagLoc, E,
18247 ConvertDiagnoser);
18248 if (Converted.isInvalid())
18249 return Converted;
18250 E = Converted.get();
18251 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
18252 // don't try to evaluate it later. We also don't want to return the
18253 // RecoveryExpr here, as it results in this call succeeding, thus callers of
18254 // this function will attempt to use 'Value'.
18255 if (isa<RecoveryExpr>(E))
18256 return ExprError();
18258 return ExprError();
18259 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18260 // An ICE must be of integral or unscoped enumeration type.
18261 if (!Diagnoser.Suppress)
18262 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
18263 << E->getSourceRange();
18264 return ExprError();
18265 }
18266
18267 ExprResult RValueExpr = DefaultLvalueConversion(E);
18268 if (RValueExpr.isInvalid())
18269 return ExprError();
18270
18271 E = RValueExpr.get();
18272
18273 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18274 // in the non-ICE case.
18277 if (Result)
18279 if (!isa<ConstantExpr>(E))
18282
18283 if (Notes.empty())
18284 return E;
18285
18286 // If our only note is the usual "invalid subexpression" note, just point
18287 // the caret at its location rather than producing an essentially
18288 // redundant note.
18289 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18290 diag::note_invalid_subexpr_in_const_expr) {
18291 DiagLoc = Notes[0].first;
18292 Notes.clear();
18293 }
18294
18295 if (getLangOpts().CPlusPlus) {
18296 if (!Diagnoser.Suppress) {
18297 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18298 for (const PartialDiagnosticAt &Note : Notes)
18299 Diag(Note.first, Note.second);
18300 }
18301 return ExprError();
18302 }
18303
18304 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18305 for (const PartialDiagnosticAt &Note : Notes)
18306 Diag(Note.first, Note.second);
18307
18308 return E;
18309 }
18310
18311 Expr::EvalResult EvalResult;
18314 EvalResult.Diag = &Notes;
18315 EvalResult.ExtendedDiag = &MSWarning;
18316
18317 // Try to evaluate the expression, and produce diagnostics explaining why it's
18318 // not a constant expression as a side-effect.
18319 bool Folded =
18320 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
18321 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18322 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18323
18324 if (!isa<ConstantExpr>(E))
18325 E = ConstantExpr::Create(Context, E, EvalResult.Val);
18326
18327 // For -fms-compatibility mode we relax some requirements
18328 // for constant folding in non-SFINAE contexts
18329 if (!MSWarning.empty()) {
18330 if (isSFINAEContext()) {
18331 Folded = false;
18332 } else {
18333 for (auto &Info : MSWarning)
18334 Diag(Info.first, Info.second);
18335 }
18336 }
18337
18338 // In C++11, we can rely on diagnostics being produced for any expression
18339 // which is not a constant expression. If no diagnostics were produced, then
18340 // this is a constant expression.
18341 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18342 if (Result)
18343 *Result = EvalResult.Val.getInt();
18344 return E;
18345 }
18346
18347 // If our only note is the usual "invalid subexpression" note, just point
18348 // the caret at its location rather than producing an essentially
18349 // redundant note.
18350 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18351 diag::note_invalid_subexpr_in_const_expr) {
18352 DiagLoc = Notes[0].first;
18353 Notes.clear();
18354 }
18355
18356 if (!Folded || CanFold == AllowFoldKind::No) {
18357 if (!Diagnoser.Suppress) {
18358 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18359 for (const PartialDiagnosticAt &Note : Notes)
18360 Diag(Note.first, Note.second);
18361 }
18362
18363 return ExprError();
18364 }
18365
18366 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18367 for (const PartialDiagnosticAt &Note : Notes)
18368 Diag(Note.first, Note.second);
18369
18370 if (Result)
18371 *Result = EvalResult.Val.getInt();
18372 return E;
18373}
18374
18375namespace {
18376 // Handle the case where we conclude a expression which we speculatively
18377 // considered to be unevaluated is actually evaluated.
18378 class TransformToPE : public TreeTransform<TransformToPE> {
18379 typedef TreeTransform<TransformToPE> BaseTransform;
18380
18381 public:
18382 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18383
18384 // Make sure we redo semantic analysis
18385 bool AlwaysRebuild() { return true; }
18386 bool ReplacingOriginal() { return true; }
18387
18388 // We need to special-case DeclRefExprs referring to FieldDecls which
18389 // are not part of a member pointer formation; normal TreeTransforming
18390 // doesn't catch this case because of the way we represent them in the AST.
18391 // FIXME: This is a bit ugly; is it really the best way to handle this
18392 // case?
18393 //
18394 // Error on DeclRefExprs referring to FieldDecls.
18395 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18396 if (isa<FieldDecl>(E->getDecl()) &&
18397 !SemaRef.isUnevaluatedContext())
18398 return SemaRef.Diag(E->getLocation(),
18399 diag::err_invalid_non_static_member_use)
18400 << E->getDecl() << E->getSourceRange();
18401
18402 return BaseTransform::TransformDeclRefExpr(E);
18403 }
18404
18405 // Exception: filter out member pointer formation
18406 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18407 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18408 return E;
18409
18410 return BaseTransform::TransformUnaryOperator(E);
18411 }
18412
18413 // The body of a lambda-expression is in a separate expression evaluation
18414 // context so never needs to be transformed.
18415 // FIXME: Ideally we wouldn't transform the closure type either, and would
18416 // just recreate the capture expressions and lambda expression.
18417 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18418 return SkipLambdaBody(E, Body);
18419 }
18420 };
18421}
18422
18424 assert(isUnevaluatedContext() &&
18425 "Should only transform unevaluated expressions");
18426 ExprEvalContexts.back().Context =
18427 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18429 return E;
18430 return TransformToPE(*this).TransformExpr(E);
18431}
18432
18434 assert(isUnevaluatedContext() &&
18435 "Should only transform unevaluated expressions");
18438 return TInfo;
18439 return TransformToPE(*this).TransformType(TInfo);
18440}
18441
18442void
18444 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18446 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18447 LambdaContextDecl, ExprContext);
18448
18449 // Discarded statements and immediate contexts nested in other
18450 // discarded statements or immediate context are themselves
18451 // a discarded statement or an immediate context, respectively.
18452 ExprEvalContexts.back().InDiscardedStatement =
18454
18455 // C++23 [expr.const]/p15
18456 // An expression or conversion is in an immediate function context if [...]
18457 // it is a subexpression of a manifestly constant-evaluated expression or
18458 // conversion.
18459 const auto &Prev = parentEvaluationContext();
18460 ExprEvalContexts.back().InImmediateFunctionContext =
18461 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18462
18463 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18464 Prev.InImmediateEscalatingFunctionContext;
18465
18466 Cleanup.reset();
18467 if (!MaybeODRUseExprs.empty())
18468 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18469}
18470
18471void
18475 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18476 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18477}
18478
18480 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18481 // [expr.const]/p14.1
18482 // An expression or conversion is in an immediate function context if it is
18483 // potentially evaluated and either: its innermost enclosing non-block scope
18484 // is a function parameter scope of an immediate function.
18486 FD && FD->isConsteval()
18488 : NewContext);
18492
18493 Current.InDiscardedStatement = false;
18494
18495 if (FD) {
18496
18497 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18498 // context is nested in an immediate function context, so smaller contexts
18499 // that appear inside immediate functions (like variable initializers) are
18500 // considered to be inside an immediate function context even though by
18501 // themselves they are not immediate function contexts. But when a new
18502 // function is entered, we need to reset this tracking, since the entered
18503 // function might be not an immediate function.
18504
18506 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18507
18508 if (isLambdaMethod(FD))
18510 FD->isConsteval() ||
18511 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
18512 Parent.isImmediateFunctionContext()));
18513 else
18515 }
18516}
18517
18519 TypeSourceInfo *TSI) {
18520 return BuildCXXReflectExpr(CaretCaretLoc, TSI);
18521}
18522
18524 TypeSourceInfo *TSI) {
18525 return CXXReflectExpr::Create(Context, CaretCaretLoc, TSI);
18526}
18527
18528namespace {
18529
18530const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18531 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18532 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18533 if (E->getOpcode() == UO_Deref)
18534 return CheckPossibleDeref(S, E->getSubExpr());
18535 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18536 return CheckPossibleDeref(S, E->getBase());
18537 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18538 return CheckPossibleDeref(S, E->getBase());
18539 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18540 QualType Inner;
18541 QualType Ty = E->getType();
18542 if (const auto *Ptr = Ty->getAs<PointerType>())
18543 Inner = Ptr->getPointeeType();
18544 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18545 Inner = Arr->getElementType();
18546 else
18547 return nullptr;
18548
18549 if (Inner->hasAttr(attr::NoDeref))
18550 return E;
18551 }
18552 return nullptr;
18553}
18554
18555} // namespace
18556
18558 for (const Expr *E : Rec.PossibleDerefs) {
18559 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18560 if (DeclRef) {
18561 const ValueDecl *Decl = DeclRef->getDecl();
18562 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18563 << Decl->getName() << E->getSourceRange();
18564 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18565 } else {
18566 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18567 << E->getSourceRange();
18568 }
18569 }
18570 Rec.PossibleDerefs.clear();
18571}
18572
18575 return;
18576
18577 // Note: ignoring parens here is not justified by the standard rules, but
18578 // ignoring parentheses seems like a more reasonable approach, and this only
18579 // drives a deprecation warning so doesn't affect conformance.
18580 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18581 if (BO->getOpcode() == BO_Assign) {
18582 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18583 llvm::erase(LHSs, BO->getLHS());
18584 }
18585 }
18586}
18587
18589 assert(getLangOpts().CPlusPlus20 &&
18590 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18591 "Cannot mark an immediate escalating expression outside of an "
18592 "immediate escalating context");
18593 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18594 Call && Call->getCallee()) {
18595 if (auto *DeclRef =
18596 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18597 DeclRef->setIsImmediateEscalating(true);
18598 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18599 Ctr->setIsImmediateEscalating(true);
18600 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18601 DeclRef->setIsImmediateEscalating(true);
18602 } else {
18603 assert(false && "expected an immediately escalating expression");
18604 }
18606 FI->FoundImmediateEscalatingExpression = true;
18607}
18608
18610 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18611 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18614 return E;
18615
18616 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18617 /// It's OK if this fails; we'll also remove this in
18618 /// HandleImmediateInvocations, but catching it here allows us to avoid
18619 /// walking the AST looking for it in simple cases.
18620 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18621 if (auto *DeclRef =
18622 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18623 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18624
18625 // C++23 [expr.const]/p16
18626 // An expression or conversion is immediate-escalating if it is not initially
18627 // in an immediate function context and it is [...] an immediate invocation
18628 // that is not a constant expression and is not a subexpression of an
18629 // immediate invocation.
18630 APValue Cached;
18631 auto CheckConstantExpressionAndKeepResult = [&]() {
18632 Expr::EvalResult Eval;
18633 bool Res = E.get()->EvaluateAsConstantExpr(
18634 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18635 if (Res && !Eval.DiagEmitted) {
18636 Cached = std::move(Eval.Val);
18637 return true;
18638 }
18639 return false;
18640 };
18641
18642 if (!E.get()->isValueDependent() &&
18643 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18644 !CheckConstantExpressionAndKeepResult()) {
18646 return E;
18647 }
18648
18649 if (Cleanup.exprNeedsCleanups()) {
18650 // Since an immediate invocation is a full expression itself - it requires
18651 // an additional ExprWithCleanups node, but it can participate to a bigger
18652 // full expression which actually requires cleanups to be run after so
18653 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18654 // may discard cleanups for outer expression too early.
18655
18656 // Note that ExprWithCleanups created here must always have empty cleanup
18657 // objects:
18658 // - compound literals do not create cleanup objects in C++ and immediate
18659 // invocations are C++-only.
18660 // - blocks are not allowed inside constant expressions and compiler will
18661 // issue an error if they appear there.
18662 //
18663 // Hence, in correct code any cleanup objects created inside current
18664 // evaluation context must be outside the immediate invocation.
18666 Cleanup.cleanupsHaveSideEffects(), {});
18667 }
18668
18670 getASTContext(), E.get(),
18671 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18672 getASTContext()),
18673 /*IsImmediateInvocation*/ true);
18674 if (Cached.hasValue())
18675 Res->MoveIntoResult(Cached, getASTContext());
18676 /// Value-dependent constant expressions should not be immediately
18677 /// evaluated until they are instantiated.
18678 if (!Res->isValueDependent())
18679 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18680 return Res;
18681}
18682
18686 Expr::EvalResult Eval;
18687 Eval.Diag = &Notes;
18688 ConstantExpr *CE = Candidate.getPointer();
18689 bool Result = CE->EvaluateAsConstantExpr(
18690 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18691 if (!Result || !Notes.empty()) {
18693 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18694 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18695 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18696 FunctionDecl *FD = nullptr;
18697 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18698 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18699 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18700 FD = Call->getConstructor();
18701 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18702 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18703
18704 assert(FD && FD->isImmediateFunction() &&
18705 "could not find an immediate function in this expression");
18706 if (FD->isInvalidDecl())
18707 return;
18708 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18709 << FD << FD->isConsteval();
18710 if (auto Context =
18712 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18713 << Context->Decl;
18714 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18715 }
18716 if (!FD->isConsteval())
18718 for (auto &Note : Notes)
18719 SemaRef.Diag(Note.first, Note.second);
18720 return;
18721 }
18723}
18724
18728 struct ComplexRemove : TreeTransform<ComplexRemove> {
18730 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18733 CurrentII;
18734 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18737 4>::reverse_iterator Current)
18738 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18739 void RemoveImmediateInvocation(ConstantExpr* E) {
18740 auto It = std::find_if(CurrentII, IISet.rend(),
18742 return Elem.getPointer() == E;
18743 });
18744 // It is possible that some subexpression of the current immediate
18745 // invocation was handled from another expression evaluation context. Do
18746 // not handle the current immediate invocation if some of its
18747 // subexpressions failed before.
18748 if (It == IISet.rend()) {
18749 if (SemaRef.FailedImmediateInvocations.contains(E))
18750 CurrentII->setInt(1);
18751 } else {
18752 It->setInt(1); // Mark as deleted
18753 }
18754 }
18755 ExprResult TransformConstantExpr(ConstantExpr *E) {
18756 if (!E->isImmediateInvocation())
18757 return Base::TransformConstantExpr(E);
18758 RemoveImmediateInvocation(E);
18759 return Base::TransformExpr(E->getSubExpr());
18760 }
18761 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18762 /// we need to remove its DeclRefExpr from the DRSet.
18763 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18764 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18765 return Base::TransformCXXOperatorCallExpr(E);
18766 }
18767 /// Base::TransformUserDefinedLiteral doesn't preserve the
18768 /// UserDefinedLiteral node.
18769 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18770 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18771 /// here.
18772 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18773 if (!Init)
18774 return Init;
18775
18776 // We cannot use IgnoreImpCasts because we need to preserve
18777 // full expressions.
18778 while (true) {
18779 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18780 Init = ICE->getSubExpr();
18781 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18782 Init = ICE->getSubExpr();
18783 else
18784 break;
18785 }
18786 /// ConstantExprs are the first layer of implicit node to be removed so if
18787 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18788 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18789 CE && CE->isImmediateInvocation())
18790 RemoveImmediateInvocation(CE);
18791 return Base::TransformInitializer(Init, NotCopyInit);
18792 }
18793 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18794 DRSet.erase(E);
18795 return E;
18796 }
18797 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18798 // Do not rebuild lambdas to avoid creating a new type.
18799 // Lambdas have already been processed inside their eval contexts.
18800 return E;
18801 }
18802
18803 // We do not have enough information to transform opaque expressions and
18804 // assume they do not contain immediate subexpressions.
18805 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18806
18807 bool AlwaysRebuild() { return false; }
18808 bool ReplacingOriginal() { return true; }
18809 bool AllowSkippingCXXConstructExpr() {
18810 bool Res = AllowSkippingFirstCXXConstructExpr;
18811 AllowSkippingFirstCXXConstructExpr = true;
18812 return Res;
18813 }
18814 bool AllowSkippingFirstCXXConstructExpr = true;
18815 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18817
18818 /// CXXConstructExpr with a single argument are getting skipped by
18819 /// TreeTransform in some situtation because they could be implicit. This
18820 /// can only occur for the top-level CXXConstructExpr because it is used
18821 /// nowhere in the expression being transformed therefore will not be rebuilt.
18822 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18823 /// skipping the first CXXConstructExpr.
18824 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18825 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18826
18827 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18828 // The result may not be usable in case of previous compilation errors.
18829 // In this case evaluation of the expression may result in crash so just
18830 // don't do anything further with the result.
18831 if (Res.isUsable()) {
18833 It->getPointer()->setSubExpr(Res.get());
18834 }
18835}
18836
18837static void
18840 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18841 Rec.ReferenceToConsteval.size() == 0) ||
18843 return;
18844
18845 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18846 // [...]
18847 // - the initializer of a variable that is usable in constant expressions or
18848 // has constant initialization.
18849 if (SemaRef.getLangOpts().CPlusPlus23 &&
18850 Rec.ExprContext ==
18852 auto *VD = dyn_cast<VarDecl>(Rec.ManglingContextDecl);
18853 if (VD && (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18854 VD->hasConstantInitialization())) {
18855 // An expression or conversion is in an 'immediate function context' if it
18856 // is potentially evaluated and either:
18857 // [...]
18858 // - it is a subexpression of a manifestly constant-evaluated expression
18859 // or conversion.
18860 return;
18861 }
18862 }
18863
18864 /// When we have more than 1 ImmediateInvocationCandidates or previously
18865 /// failed immediate invocations, we need to check for nested
18866 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18867 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18868 /// invocation.
18869 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18871
18872 /// Prevent sema calls during the tree transform from adding pointers that
18873 /// are already in the sets.
18874 llvm::SaveAndRestore DisableIITracking(
18876
18877 /// Prevent diagnostic during tree transfrom as they are duplicates
18879
18880 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18881 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18882 if (!It->getInt())
18884 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18885 Rec.ReferenceToConsteval.size()) {
18886 struct SimpleRemove : DynamicRecursiveASTVisitor {
18887 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18888 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18889 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18890 DRSet.erase(E);
18891 return DRSet.size();
18892 }
18893 } Visitor(Rec.ReferenceToConsteval);
18894 Visitor.TraverseStmt(
18895 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18896 }
18897 for (auto CE : Rec.ImmediateInvocationCandidates)
18898 if (!CE.getInt())
18900 for (auto *DR : Rec.ReferenceToConsteval) {
18901 // If the expression is immediate escalating, it is not an error;
18902 // The outer context itself becomes immediate and further errors,
18903 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18904 if (DR->isImmediateEscalating())
18905 continue;
18906 auto *FD = cast<FunctionDecl>(DR->getDecl());
18907 const NamedDecl *ND = FD;
18908 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18909 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18910 ND = MD->getParent();
18911
18912 // C++23 [expr.const]/p16
18913 // An expression or conversion is immediate-escalating if it is not
18914 // initially in an immediate function context and it is [...] a
18915 // potentially-evaluated id-expression that denotes an immediate function
18916 // that is not a subexpression of an immediate invocation.
18917 bool ImmediateEscalating = false;
18918 bool IsPotentiallyEvaluated =
18919 Rec.Context ==
18921 Rec.Context ==
18923 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18924 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18925
18927 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18928 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18929 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18930 if (!FD->getBuiltinID())
18931 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18932 if (auto Context =
18934 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18935 << Context->Decl;
18936 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18937 }
18938 if (FD->isImmediateEscalating() && !FD->isConsteval())
18940
18941 } else {
18943 }
18944 }
18945}
18946
18949 if (!Rec.Lambdas.empty()) {
18951 if (!getLangOpts().CPlusPlus20 &&
18952 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18953 Rec.isUnevaluated() ||
18955 unsigned D;
18956 if (Rec.isUnevaluated()) {
18957 // C++11 [expr.prim.lambda]p2:
18958 // A lambda-expression shall not appear in an unevaluated operand
18959 // (Clause 5).
18960 D = diag::err_lambda_unevaluated_operand;
18961 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18962 // C++1y [expr.const]p2:
18963 // A conditional-expression e is a core constant expression unless the
18964 // evaluation of e, following the rules of the abstract machine, would
18965 // evaluate [...] a lambda-expression.
18966 D = diag::err_lambda_in_constant_expression;
18967 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18968 // C++17 [expr.prim.lamda]p2:
18969 // A lambda-expression shall not appear [...] in a template-argument.
18970 D = diag::err_lambda_in_invalid_context;
18971 } else
18972 llvm_unreachable("Couldn't infer lambda error message.");
18973
18974 for (const auto *L : Rec.Lambdas)
18975 Diag(L->getBeginLoc(), D);
18976 }
18977 }
18978
18979 // Append the collected materialized temporaries into previous context before
18980 // exit if the previous also is a lifetime extending context.
18982 parentEvaluationContext().InLifetimeExtendingContext &&
18983 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18986 }
18987
18989 HandleImmediateInvocations(*this, Rec);
18990
18991 // Warn on any volatile-qualified simple-assignments that are not discarded-
18992 // value expressions nor unevaluated operands (those cases get removed from
18993 // this list by CheckUnusedVolatileAssignment).
18994 for (auto *BO : Rec.VolatileAssignmentLHSs)
18995 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18996 << BO->getType();
18997
18998 // When are coming out of an unevaluated context, clear out any
18999 // temporaries that we may have created as part of the evaluation of
19000 // the expression in that context: they aren't relevant because they
19001 // will never be constructed.
19002 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
19004 ExprCleanupObjects.end());
19005 Cleanup = Rec.ParentCleanup;
19008 // Otherwise, merge the contexts together.
19009 } else {
19010 Cleanup.mergeFrom(Rec.ParentCleanup);
19011 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
19012 }
19013
19015
19016 // Pop the current expression evaluation context off the stack.
19017 ExprEvalContexts.pop_back();
19018}
19019
19021 ExprCleanupObjects.erase(
19022 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
19023 ExprCleanupObjects.end());
19024 Cleanup.reset();
19025 MaybeODRUseExprs.clear();
19026}
19027
19030 if (Result.isInvalid())
19031 return ExprError();
19032 E = Result.get();
19033 if (!E->getType()->isVariablyModifiedType())
19034 return E;
19036}
19037
19038/// Are we in a context that is potentially constant evaluated per C++20
19039/// [expr.const]p12?
19041 /// C++2a [expr.const]p12:
19042 // An expression or conversion is potentially constant evaluated if it is
19043 switch (SemaRef.ExprEvalContexts.back().Context) {
19046
19047 // -- a manifestly constant-evaluated expression,
19051 // -- a potentially-evaluated expression,
19053 // -- an immediate subexpression of a braced-init-list,
19054
19055 // -- [FIXME] an expression of the form & cast-expression that occurs
19056 // within a templated entity
19057 // -- a subexpression of one of the above that is not a subexpression of
19058 // a nested unevaluated operand.
19059 return true;
19060
19063 // Expressions in this context are never evaluated.
19064 return false;
19065 }
19066 llvm_unreachable("Invalid context");
19067}
19068
19069/// Return true if this function has a calling convention that requires mangling
19070/// in the size of the parameter pack.
19072 // These manglings are only applicable for targets whcih use Microsoft
19073 // mangling scheme for C.
19075 return false;
19076
19077 // If this is C++ and this isn't an extern "C" function, parameters do not
19078 // need to be complete. In this case, C++ mangling will apply, which doesn't
19079 // use the size of the parameters.
19080 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
19081 return false;
19082
19083 // Stdcall, fastcall, and vectorcall need this special treatment.
19084 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19085 switch (CC) {
19086 case CC_X86StdCall:
19087 case CC_X86FastCall:
19088 case CC_X86VectorCall:
19089 return true;
19090 default:
19091 break;
19092 }
19093 return false;
19094}
19095
19096/// Require that all of the parameter types of function be complete. Normally,
19097/// parameter types are only required to be complete when a function is called
19098/// or defined, but to mangle functions with certain calling conventions, the
19099/// mangler needs to know the size of the parameter list. In this situation,
19100/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
19101/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
19102/// result in a linker error. Clang doesn't implement this behavior, and instead
19103/// attempts to error at compile time.
19105 SourceLocation Loc) {
19106 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
19107 FunctionDecl *FD;
19108 ParmVarDecl *Param;
19109
19110 public:
19111 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
19112 : FD(FD), Param(Param) {}
19113
19114 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19115 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19116 StringRef CCName;
19117 switch (CC) {
19118 case CC_X86StdCall:
19119 CCName = "stdcall";
19120 break;
19121 case CC_X86FastCall:
19122 CCName = "fastcall";
19123 break;
19124 case CC_X86VectorCall:
19125 CCName = "vectorcall";
19126 break;
19127 default:
19128 llvm_unreachable("CC does not need mangling");
19129 }
19130
19131 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
19132 << Param->getDeclName() << FD->getDeclName() << CCName;
19133 }
19134 };
19135
19136 for (ParmVarDecl *Param : FD->parameters()) {
19137 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
19138 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
19139 }
19140}
19141
19142namespace {
19143enum class OdrUseContext {
19144 /// Declarations in this context are not odr-used.
19145 None,
19146 /// Declarations in this context are formally odr-used, but this is a
19147 /// dependent context.
19148 Dependent,
19149 /// Declarations in this context are odr-used but not actually used (yet).
19150 FormallyOdrUsed,
19151 /// Declarations in this context are used.
19152 Used
19153};
19154}
19155
19156/// Are we within a context in which references to resolved functions or to
19157/// variables result in odr-use?
19158static OdrUseContext isOdrUseContext(Sema &SemaRef) {
19161
19162 if (Context.isUnevaluated())
19163 return OdrUseContext::None;
19164
19166 return OdrUseContext::Dependent;
19167
19168 if (Context.isDiscardedStatementContext())
19169 return OdrUseContext::FormallyOdrUsed;
19170
19171 else if (Context.Context ==
19173 return OdrUseContext::FormallyOdrUsed;
19174
19175 return OdrUseContext::Used;
19176}
19177
19179 if (!Func->isConstexpr())
19180 return false;
19181
19182 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
19183 return true;
19184
19185 // Lambda conversion operators are never user provided.
19186 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
19187 return isLambdaConversionOperator(Conv);
19188
19189 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
19190 return CCD && CCD->getInheritedConstructor();
19191}
19192
19194 bool MightBeOdrUse) {
19195 assert(Func && "No function?");
19196
19197 Func->setReferenced();
19198
19199 // Recursive functions aren't really used until they're used from some other
19200 // context.
19201 bool IsRecursiveCall = CurContext == Func;
19202
19203 // C++11 [basic.def.odr]p3:
19204 // A function whose name appears as a potentially-evaluated expression is
19205 // odr-used if it is the unique lookup result or the selected member of a
19206 // set of overloaded functions [...].
19207 //
19208 // We (incorrectly) mark overload resolution as an unevaluated context, so we
19209 // can just check that here.
19210 OdrUseContext OdrUse =
19211 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
19212 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
19213 OdrUse = OdrUseContext::FormallyOdrUsed;
19214
19215 // Trivial default constructors and destructors are never actually used.
19216 // FIXME: What about other special members?
19217 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
19218 OdrUse == OdrUseContext::Used) {
19219 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
19220 if (Constructor->isDefaultConstructor())
19221 OdrUse = OdrUseContext::FormallyOdrUsed;
19223 OdrUse = OdrUseContext::FormallyOdrUsed;
19224 }
19225
19226 // C++20 [expr.const]p12:
19227 // A function [...] is needed for constant evaluation if it is [...] a
19228 // constexpr function that is named by an expression that is potentially
19229 // constant evaluated
19230 bool NeededForConstantEvaluation =
19233
19234 // Determine whether we require a function definition to exist, per
19235 // C++11 [temp.inst]p3:
19236 // Unless a function template specialization has been explicitly
19237 // instantiated or explicitly specialized, the function template
19238 // specialization is implicitly instantiated when the specialization is
19239 // referenced in a context that requires a function definition to exist.
19240 // C++20 [temp.inst]p7:
19241 // The existence of a definition of a [...] function is considered to
19242 // affect the semantics of the program if the [...] function is needed for
19243 // constant evaluation by an expression
19244 // C++20 [basic.def.odr]p10:
19245 // Every program shall contain exactly one definition of every non-inline
19246 // function or variable that is odr-used in that program outside of a
19247 // discarded statement
19248 // C++20 [special]p1:
19249 // The implementation will implicitly define [defaulted special members]
19250 // if they are odr-used or needed for constant evaluation.
19251 //
19252 // Note that we skip the implicit instantiation of templates that are only
19253 // used in unused default arguments or by recursive calls to themselves.
19254 // This is formally non-conforming, but seems reasonable in practice.
19255 bool NeedDefinition =
19256 !IsRecursiveCall &&
19257 (OdrUse == OdrUseContext::Used ||
19258 (NeededForConstantEvaluation && !Func->isPureVirtual()));
19259
19260 // C++14 [temp.expl.spec]p6:
19261 // If a template [...] is explicitly specialized then that specialization
19262 // shall be declared before the first use of that specialization that would
19263 // cause an implicit instantiation to take place, in every translation unit
19264 // in which such a use occurs
19265 if (NeedDefinition &&
19266 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
19267 Func->getMemberSpecializationInfo()))
19269
19270 if (getLangOpts().CUDA)
19271 CUDA().CheckCall(Loc, Func);
19272
19273 // If we need a definition, try to create one.
19274 if (NeedDefinition && !Func->getBody()) {
19277 dyn_cast<CXXConstructorDecl>(Func)) {
19279 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19280 if (Constructor->isDefaultConstructor()) {
19281 if (Constructor->isTrivial() &&
19282 !Constructor->hasAttr<DLLExportAttr>())
19283 return;
19285 } else if (Constructor->isCopyConstructor()) {
19287 } else if (Constructor->isMoveConstructor()) {
19289 }
19290 } else if (Constructor->getInheritedConstructor()) {
19292 }
19293 } else if (CXXDestructorDecl *Destructor =
19294 dyn_cast<CXXDestructorDecl>(Func)) {
19296 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19297 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19298 return;
19300 }
19301 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19302 MarkVTableUsed(Loc, Destructor->getParent());
19303 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
19304 if (MethodDecl->isOverloadedOperator() &&
19305 MethodDecl->getOverloadedOperator() == OO_Equal) {
19306 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
19307 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19308 if (MethodDecl->isCopyAssignmentOperator())
19309 DefineImplicitCopyAssignment(Loc, MethodDecl);
19310 else if (MethodDecl->isMoveAssignmentOperator())
19311 DefineImplicitMoveAssignment(Loc, MethodDecl);
19312 }
19313 } else if (isa<CXXConversionDecl>(MethodDecl) &&
19314 MethodDecl->getParent()->isLambda()) {
19315 CXXConversionDecl *Conversion =
19316 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
19317 if (Conversion->isLambdaToBlockPointerConversion())
19319 else
19321 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19322 MarkVTableUsed(Loc, MethodDecl->getParent());
19323 }
19324
19325 if (Func->isDefaulted() && !Func->isDeleted()) {
19326 DefaultedComparisonKind DCK = Func->getDefaultedComparisonKind();
19329 }
19330
19331 // Implicit instantiation of function templates and member functions of
19332 // class templates.
19333 if (Func->isImplicitlyInstantiable()) {
19335 Func->getTemplateSpecializationKindForInstantiation();
19336 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19337 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19338 if (FirstInstantiation) {
19339 PointOfInstantiation = Loc;
19340 if (auto *MSI = Func->getMemberSpecializationInfo())
19341 MSI->setPointOfInstantiation(Loc);
19342 // FIXME: Notify listener.
19343 else
19344 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19345 } else if (TSK != TSK_ImplicitInstantiation) {
19346 // Use the point of use as the point of instantiation, instead of the
19347 // point of explicit instantiation (which we track as the actual point
19348 // of instantiation). This gives better backtraces in diagnostics.
19349 PointOfInstantiation = Loc;
19350 }
19351
19352 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19353 Func->isConstexpr()) {
19354 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19355 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19356 CodeSynthesisContexts.size())
19358 std::make_pair(Func, PointOfInstantiation));
19359 else if (Func->isConstexpr())
19360 // Do not defer instantiations of constexpr functions, to avoid the
19361 // expression evaluator needing to call back into Sema if it sees a
19362 // call to such a function.
19363 InstantiateFunctionDefinition(PointOfInstantiation, Func);
19364 else {
19365 Func->setInstantiationIsPending(true);
19366 PendingInstantiations.push_back(
19367 std::make_pair(Func, PointOfInstantiation));
19368 if (llvm::isTimeTraceVerbose()) {
19369 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
19370 std::string Name;
19371 llvm::raw_string_ostream OS(Name);
19372 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
19373 /*Qualified=*/true);
19374 return Name;
19375 });
19376 }
19377 // Notify the consumer that a function was implicitly instantiated.
19378 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
19379 }
19380 }
19381 } else {
19382 // Walk redefinitions, as some of them may be instantiable.
19383 for (auto *i : Func->redecls()) {
19384 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19385 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19386 }
19387 }
19388 });
19389 }
19390
19391 // If a constructor was defined in the context of a default parameter
19392 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19393 // context), its initializers may not be referenced yet.
19394 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19396 *this,
19397 Constructor->isImmediateFunction()
19400 Constructor);
19401 for (CXXCtorInitializer *Init : Constructor->inits()) {
19402 if (Init->isInClassMemberInitializer())
19403 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19404 MarkDeclarationsReferencedInExpr(Init->getInit());
19405 });
19406 }
19407 }
19408
19409 // C++14 [except.spec]p17:
19410 // An exception-specification is considered to be needed when:
19411 // - the function is odr-used or, if it appears in an unevaluated operand,
19412 // would be odr-used if the expression were potentially-evaluated;
19413 //
19414 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19415 // function is a pure virtual function we're calling, and in that case the
19416 // function was selected by overload resolution and we need to resolve its
19417 // exception specification for a different reason.
19418 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19420 ResolveExceptionSpec(Loc, FPT);
19421
19422 // A callee could be called by a host function then by a device function.
19423 // If we only try recording once, we will miss recording the use on device
19424 // side. Therefore keep trying until it is recorded.
19425 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19426 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19428
19429 // If this is the first "real" use, act on that.
19430 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19431 // Keep track of used but undefined functions.
19432 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19433 if (mightHaveNonExternalLinkage(Func))
19434 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19435 else if (Func->getMostRecentDecl()->isInlined() &&
19436 !LangOpts.GNUInline &&
19437 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19438 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19440 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19441 }
19442
19443 // Some x86 Windows calling conventions mangle the size of the parameter
19444 // pack into the name. Computing the size of the parameters requires the
19445 // parameter types to be complete. Check that now.
19448
19449 // In the MS C++ ABI, the compiler emits destructor variants where they are
19450 // used. If the destructor is used here but defined elsewhere, mark the
19451 // virtual base destructors referenced. If those virtual base destructors
19452 // are inline, this will ensure they are defined when emitting the complete
19453 // destructor variant. This checking may be redundant if the destructor is
19454 // provided later in this TU.
19455 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19456 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19457 CXXRecordDecl *Parent = Dtor->getParent();
19458 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19460 }
19461 }
19462
19463 Func->markUsed(Context);
19464 }
19465}
19466
19467/// Directly mark a variable odr-used. Given a choice, prefer to use
19468/// MarkVariableReferenced since it does additional checks and then
19469/// calls MarkVarDeclODRUsed.
19470/// If the variable must be captured:
19471/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19472/// - else capture it in the DeclContext that maps to the
19473/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19474static void
19476 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19477 // Keep track of used but undefined variables.
19478 // FIXME: We shouldn't suppress this warning for static data members.
19479 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19480 assert(Var && "expected a capturable variable");
19481
19483 (!Var->isExternallyVisible() || Var->isInline() ||
19485 !(Var->isStaticDataMember() && Var->hasInit())) {
19487 if (old.isInvalid())
19488 old = Loc;
19489 }
19490 QualType CaptureType, DeclRefType;
19491 if (SemaRef.LangOpts.OpenMP)
19494 /*EllipsisLoc*/ SourceLocation(),
19495 /*BuildAndDiagnose*/ true, CaptureType,
19496 DeclRefType, FunctionScopeIndexToStopAt);
19497
19498 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19499 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19500 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
19501 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
19502 if (VarTarget == SemaCUDA::CVT_Host &&
19503 (UserTarget == CUDAFunctionTarget::Device ||
19504 UserTarget == CUDAFunctionTarget::HostDevice ||
19505 UserTarget == CUDAFunctionTarget::Global)) {
19506 // Diagnose ODR-use of host global variables in device functions.
19507 // Reference of device global variables in host functions is allowed
19508 // through shadow variables therefore it is not diagnosed.
19509 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19510 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19511 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19513 Var->getType().isConstQualified()
19514 ? diag::note_cuda_const_var_unpromoted
19515 : diag::note_cuda_host_var);
19516 }
19517 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19518 // Also capture __device__ const variables, which are classified
19519 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19520 // an explicit CUDADeviceAttr to distinguish them from plain
19521 // const variables (no __device__), which also get CVT_Both but
19522 // only have an implicit CUDADeviceAttr.
19523 (VarTarget == SemaCUDA::CVT_Both &&
19524 Var->hasAttr<CUDADeviceAttr>() &&
19525 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19526 !Var->hasAttr<CUDASharedAttr>() &&
19527 (UserTarget == CUDAFunctionTarget::Host ||
19528 UserTarget == CUDAFunctionTarget::HostDevice)) {
19529 // Record a CUDA/HIP device side variable if it is ODR-used
19530 // by host code. This is done conservatively, when the variable is
19531 // referenced in any of the following contexts:
19532 // - a non-function context
19533 // - a host function
19534 // - a host device function
19535 // This makes the ODR-use of the device side variable by host code to
19536 // be visible in the device compilation for the compiler to be able to
19537 // emit template variables instantiated by host code only and to
19538 // externalize the static device side variable ODR-used by host code.
19539 if (!Var->hasExternalStorage())
19541 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19542 (!FD || (!FD->getDescribedFunctionTemplate() &&
19546 }
19547 }
19548
19549 V->markUsed(SemaRef.Context);
19550}
19551
19553 SourceLocation Loc,
19554 unsigned CapturingScopeIndex) {
19555 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19556}
19557
19559 SourceLocation loc,
19560 ValueDecl *var) {
19561 DeclContext *VarDC =
19562 var->getDeclContext()->getEnclosingNonExpansionStatementContext();
19563
19564 // If the parameter still belongs to the translation unit, then
19565 // we're actually just using one parameter in the declaration of
19566 // the next.
19567 if (isa<ParmVarDecl>(var) &&
19569 return;
19570
19571 // For C code, don't diagnose about capture if we're not actually in code
19572 // right now; it's impossible to write a non-constant expression outside of
19573 // function context, so we'll get other (more useful) diagnostics later.
19574 //
19575 // For C++, things get a bit more nasty... it would be nice to suppress this
19576 // diagnostic for certain cases like using a local variable in an array bound
19577 // for a member of a local class, but the correct predicate is not obvious.
19578 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19579 return;
19580
19581 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19582 unsigned ContextKind = 3; // unknown
19583 if (isa<CXXMethodDecl>(VarDC) &&
19584 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19585 ContextKind = 2;
19586 } else if (isa<FunctionDecl>(VarDC)) {
19587 ContextKind = 0;
19588 } else if (isa<BlockDecl>(VarDC)) {
19589 ContextKind = 1;
19590 }
19591
19592 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19593 << var << ValueKind << ContextKind << VarDC;
19594 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19595 << var;
19596
19597 // FIXME: Add additional diagnostic info about class etc. which prevents
19598 // capture.
19599}
19600
19602 ValueDecl *Var,
19603 bool &SubCapturesAreNested,
19604 QualType &CaptureType,
19605 QualType &DeclRefType) {
19606 // Check whether we've already captured it.
19607 if (CSI->CaptureMap.count(Var)) {
19608 // If we found a capture, any subcaptures are nested.
19609 SubCapturesAreNested = true;
19610
19611 // Retrieve the capture type for this variable.
19612 CaptureType = CSI->getCapture(Var).getCaptureType();
19613
19614 // Compute the type of an expression that refers to this variable.
19615 DeclRefType = CaptureType.getNonReferenceType();
19616
19617 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19618 // are mutable in the sense that user can change their value - they are
19619 // private instances of the captured declarations.
19620 const Capture &Cap = CSI->getCapture(Var);
19621 // C++ [expr.prim.lambda]p10:
19622 // The type of such a data member is [...] an lvalue reference to the
19623 // referenced function type if the entity is a reference to a function.
19624 // [...]
19625 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19626 !(isa<LambdaScopeInfo>(CSI) &&
19627 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19629 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19630 DeclRefType.addConst();
19631 return true;
19632 }
19633 return false;
19634}
19635
19636// Only block literals, captured statements, and lambda expressions can
19637// capture; other scopes don't work.
19639 ValueDecl *Var,
19640 SourceLocation Loc,
19641 const bool Diagnose,
19642 Sema &S) {
19645
19646 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19647 if (Underlying) {
19648 if (Underlying->hasLocalStorage() && Diagnose)
19650 }
19651 return nullptr;
19652}
19653
19654// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19655// certain types of variables (unnamed, variably modified types etc.)
19656// so check for eligibility.
19658 SourceLocation Loc, const bool Diagnose,
19659 Sema &S) {
19660
19661 assert((isa<VarDecl, BindingDecl>(Var)) &&
19662 "Only variables and structured bindings can be captured");
19663
19664 bool IsBlock = isa<BlockScopeInfo>(CSI);
19665 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19666
19667 // Reject bindings referenced from a lambda or block that wraps an OpenMP
19668 // region.
19669 if ((IsLambda || IsBlock) && S.getLangOpts().OpenMP &&
19671 if (Diagnose)
19672 S.Diag(Loc, diag::err_omp_unsupported_on_binding) << 3;
19673 return false;
19674 }
19675
19676 // Lambdas are not allowed to capture unnamed variables
19677 // (e.g. anonymous unions).
19678 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19679 // assuming that's the intent.
19680 if (IsLambda && !Var->getDeclName()) {
19681 if (Diagnose) {
19682 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19683 S.Diag(Var->getLocation(), diag::note_declared_at);
19684 }
19685 return false;
19686 }
19687
19688 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19689 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19690 if (Diagnose) {
19691 S.Diag(Loc, diag::err_ref_vm_type);
19692 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19693 }
19694 return false;
19695 }
19696 // Prohibit structs with flexible array members too.
19697 // We cannot capture what is in the tail end of the struct.
19698 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19699 VTD && VTD->hasFlexibleArrayMember()) {
19700 if (Diagnose) {
19701 if (IsBlock)
19702 S.Diag(Loc, diag::err_ref_flexarray_type);
19703 else
19704 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19705 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19706 }
19707 return false;
19708 }
19709 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19710 // Lambdas and captured statements are not allowed to capture __block
19711 // variables; they don't support the expected semantics.
19712 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19713 if (Diagnose) {
19714 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19715 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19716 }
19717 return false;
19718 }
19719 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19720 if (S.getLangOpts().OpenCL && IsBlock &&
19721 Var->getType()->isBlockPointerType()) {
19722 if (Diagnose)
19723 S.Diag(Loc, diag::err_opencl_block_ref_block);
19724 return false;
19725 }
19726
19727 if (auto *BD = dyn_cast<BindingDecl>(Var)) {
19728 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19729 if (RSI->CapRegionKind == CR_OpenMP) {
19730 if (BD->getHoldingVar()) {
19731 if (Diagnose) {
19732 S.Diag(Loc, diag::err_capture_tuple_binding_openmp) << Var;
19733 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19734 }
19735 return false;
19736 }
19737 if (Diagnose && S.getLangOpts().CPlusPlus) {
19738 S.DiagCompat(Loc, diag_compat::capture_binding) << Var;
19739 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19740 }
19741 return true;
19742 }
19743 }
19744 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19745 if (Diagnose)
19747 return false;
19748 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19749 S.DiagCompat(Loc, diag_compat::capture_binding) << Var;
19750 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19751 }
19752 }
19753
19754 return true;
19755}
19756
19757// Returns true if the capture by block was successful.
19759 SourceLocation Loc, const bool BuildAndDiagnose,
19760 QualType &CaptureType, QualType &DeclRefType,
19761 const bool Nested, Sema &S, bool Invalid) {
19762 bool ByRef = false;
19763
19764 // Blocks are not allowed to capture arrays, excepting OpenCL.
19765 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19766 // (decayed to pointers).
19767 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19768 if (BuildAndDiagnose) {
19769 S.Diag(Loc, diag::err_ref_array_type);
19770 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19771 Invalid = true;
19772 } else {
19773 return false;
19774 }
19775 }
19776
19777 // Forbid the block-capture of autoreleasing variables.
19778 if (!Invalid &&
19780 if (BuildAndDiagnose) {
19781 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19782 << /*block*/ 0;
19783 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19784 Invalid = true;
19785 } else {
19786 return false;
19787 }
19788 }
19789
19790 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19791 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19792 QualType PointeeTy = PT->getPointeeType();
19793
19794 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19796 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19797 if (BuildAndDiagnose) {
19798 SourceLocation VarLoc = Var->getLocation();
19799 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19800 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19801 }
19802 }
19803 }
19804
19805 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19806 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19807 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19808 // Block capture by reference does not change the capture or
19809 // declaration reference types.
19810 ByRef = true;
19811 } else {
19812 // Block capture by copy introduces 'const'.
19813 CaptureType = CaptureType.getNonReferenceType().withConst();
19814 DeclRefType = CaptureType;
19815 }
19816
19817 // Actually capture the variable.
19818 if (BuildAndDiagnose)
19819 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19820 CaptureType, Invalid);
19821
19822 return !Invalid;
19823}
19824
19825/// Capture the given variable in the captured region.
19828 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19829 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19830 Sema &S, bool Invalid) {
19831 // By default, capture variables by reference.
19832 bool ByRef = true;
19833 bool IsBindingDecl = isa<BindingDecl>(Var);
19834 ValueDecl *DSAVar = Var;
19835 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19836 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19837 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19838 // Using an LValue reference type is consistent with Lambdas (see below).
19839 if (VarDecl *VD = S.OpenMP().isOpenMPCapturedDecl(Var)) {
19840 Var = VD; // Capture the DecompositionDecl.
19841 bool HasConst = DeclRefType.isConstQualified();
19842 // Note: DeclRefType should remain the BindingDecl's type (e.g., int),
19843 // not the DecompositionDecl's type (e.g., Point). The variable being
19844 // captured is the DecompositionDecl, but expressions still reference
19845 // the individual binding's type.
19846 DeclRefType = DeclRefType.getUnqualifiedType();
19847 // Don't lose diagnostics about assignments to const.
19848 if (HasConst)
19849 DeclRefType.addConst();
19850 }
19851 // Do not capture firstprivates in tasks. For bindings the DSA is on the
19852 // binding, not on the DecompositionDecl; the task firstprivate path still
19853 // needs the DecompositionDecl capture, so skip only private.
19855 IsBindingDecl ? DSAVar : Var, RSI->OpenMPLevel,
19856 RSI->OpenMPCaptureLevel);
19857 if (IsBindingDecl ? PrivateKind == OMPC_private
19858 : PrivateKind != OMPC_unknown)
19859 return true;
19860 ByRef = S.OpenMP().isOpenMPCapturedByRef(DSAVar, RSI->OpenMPLevel,
19861 RSI->OpenMPCaptureLevel);
19862 // Bindings share the DecompositionDecl storage; a second capture with
19863 // a different capture kind is not representable.
19864 if (BuildAndDiagnose && IsBindingDecl) {
19865 unsigned Idx = RSI->CaptureMap.lookup(Var);
19866 if (Idx != 0 && RSI->Captures[Idx - 1].isReferenceCapture() != ByRef) {
19867 S.Diag(Loc,
19868 diag::err_omp_decomposition_bindings_different_capture_kinds)
19869 << DSAVar;
19870 return false;
19871 }
19872 }
19873 }
19874
19875 if (ByRef)
19876 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19877 else
19878 CaptureType = DeclRefType;
19879
19880 // Actually capture the variable.
19881 if (BuildAndDiagnose)
19882 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19883 Loc, SourceLocation(), CaptureType, Invalid);
19884
19885 if (BuildAndDiagnose && IsBindingDecl)
19886 // Key the binding to its own capture entry so repeated uses hit the
19887 // already-captured path.
19888 RSI->CaptureMap[DSAVar] = RSI->Captures.size();
19889
19890 return !Invalid;
19891}
19892
19893/// Capture the given variable in the lambda.
19895 SourceLocation Loc, const bool BuildAndDiagnose,
19896 QualType &CaptureType, QualType &DeclRefType,
19897 const bool RefersToCapturedVariable,
19898 const TryCaptureKind Kind,
19899 SourceLocation EllipsisLoc, const bool IsTopScope,
19900 Sema &S, bool Invalid) {
19901 // Determine whether we are capturing by reference or by value.
19902 bool ByRef = false;
19903 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19904 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19905 } else {
19906 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19907 }
19908
19909 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19911 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19912 Invalid = true;
19913 }
19914
19915 // Compute the type of the field that will capture this variable.
19916 if (ByRef) {
19917 // C++11 [expr.prim.lambda]p15:
19918 // An entity is captured by reference if it is implicitly or
19919 // explicitly captured but not captured by copy. It is
19920 // unspecified whether additional unnamed non-static data
19921 // members are declared in the closure type for entities
19922 // captured by reference.
19923 //
19924 // FIXME: It is not clear whether we want to build an lvalue reference
19925 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19926 // to do the former, while EDG does the latter. Core issue 1249 will
19927 // clarify, but for now we follow GCC because it's a more permissive and
19928 // easily defensible position.
19929 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19930 } else {
19931 // C++11 [expr.prim.lambda]p14:
19932 // For each entity captured by copy, an unnamed non-static
19933 // data member is declared in the closure type. The
19934 // declaration order of these members is unspecified. The type
19935 // of such a data member is the type of the corresponding
19936 // captured entity if the entity is not a reference to an
19937 // object, or the referenced type otherwise. [Note: If the
19938 // captured entity is a reference to a function, the
19939 // corresponding data member is also a reference to a
19940 // function. - end note ]
19941 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19942 if (!RefType->getPointeeType()->isFunctionType())
19943 CaptureType = RefType->getPointeeType();
19944 }
19945
19946 // Forbid the lambda copy-capture of autoreleasing variables.
19947 if (!Invalid &&
19949 if (BuildAndDiagnose) {
19950 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19951 S.Diag(Var->getLocation(), diag::note_previous_decl)
19952 << Var->getDeclName();
19953 Invalid = true;
19954 } else {
19955 return false;
19956 }
19957 }
19958
19959 // Make sure that by-copy captures are of a complete and non-abstract type.
19960 if (!Invalid && BuildAndDiagnose) {
19961 if (!CaptureType->isDependentType() &&
19963 Loc, CaptureType,
19964 diag::err_capture_of_incomplete_or_sizeless_type,
19965 Var->getDeclName()))
19966 Invalid = true;
19967 else if (S.RequireNonAbstractType(Loc, CaptureType,
19968 diag::err_capture_of_abstract_type))
19969 Invalid = true;
19970 }
19971 }
19972
19973 // Compute the type of a reference to this captured variable.
19974 if (ByRef)
19975 DeclRefType = CaptureType.getNonReferenceType();
19976 else {
19977 // C++ [expr.prim.lambda]p5:
19978 // The closure type for a lambda-expression has a public inline
19979 // function call operator [...]. This function call operator is
19980 // declared const (9.3.1) if and only if the lambda-expression's
19981 // parameter-declaration-clause is not followed by mutable.
19982 DeclRefType = CaptureType.getNonReferenceType();
19983 bool Const = LSI->lambdaCaptureShouldBeConst();
19984 // C++ [expr.prim.lambda]p10:
19985 // The type of such a data member is [...] an lvalue reference to the
19986 // referenced function type if the entity is a reference to a function.
19987 // [...]
19988 if (Const && !CaptureType->isReferenceType() &&
19989 !DeclRefType->isFunctionType())
19990 DeclRefType.addConst();
19991 }
19992
19993 // Add the capture.
19994 if (BuildAndDiagnose)
19995 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19996 Loc, EllipsisLoc, CaptureType, Invalid);
19997
19998 return !Invalid;
19999}
20000
20002 const ASTContext &Context) {
20003 // Offer a Copy fix even if the type is dependent.
20004 if (Var->getType()->isDependentType())
20005 return true;
20007 if (T.isTriviallyCopyableType(Context))
20008 return true;
20009 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
20010
20011 if (!(RD = RD->getDefinition()))
20012 return false;
20013 if (RD->hasSimpleCopyConstructor())
20014 return true;
20015 if (RD->hasUserDeclaredCopyConstructor())
20016 for (CXXConstructorDecl *Ctor : RD->ctors())
20017 if (Ctor->isCopyConstructor())
20018 return !Ctor->isDeleted();
20019 }
20020 return false;
20021}
20022
20023/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
20024/// default capture. Fixes may be omitted if they aren't allowed by the
20025/// standard, for example we can't emit a default copy capture fix-it if we
20026/// already explicitly copy capture capture another variable.
20028 ValueDecl *Var) {
20030 // Don't offer Capture by copy of default capture by copy fixes if Var is
20031 // known not to be copy constructible.
20032 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
20033
20034 SmallString<32> FixBuffer;
20035 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
20036 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
20037 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
20038 if (ShouldOfferCopyFix) {
20039 // Offer fixes to insert an explicit capture for the variable.
20040 // [] -> [VarName]
20041 // [OtherCapture] -> [OtherCapture, VarName]
20042 FixBuffer.assign({Separator, Var->getName()});
20043 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
20044 << Var << /*value*/ 0
20045 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
20046 }
20047 // As above but capture by reference.
20048 FixBuffer.assign({Separator, "&", Var->getName()});
20049 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
20050 << Var << /*reference*/ 1
20051 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
20052 }
20053
20054 // Only try to offer default capture if there are no captures excluding this
20055 // and init captures.
20056 // [this]: OK.
20057 // [X = Y]: OK.
20058 // [&A, &B]: Don't offer.
20059 // [A, B]: Don't offer.
20060 if (llvm::any_of(LSI->Captures, [](Capture &C) {
20061 return !C.isThisCapture() && !C.isInitCapture();
20062 }))
20063 return;
20064
20065 // The default capture specifiers, '=' or '&', must appear first in the
20066 // capture body.
20067 SourceLocation DefaultInsertLoc =
20069
20070 if (ShouldOfferCopyFix) {
20071 bool CanDefaultCopyCapture = true;
20072 // [=, *this] OK since c++17
20073 // [=, this] OK since c++20
20074 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
20075 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
20077 : false;
20078 // We can't use default capture by copy if any captures already specified
20079 // capture by copy.
20080 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
20081 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
20082 })) {
20083 FixBuffer.assign({"=", Separator});
20084 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
20085 << /*value*/ 0
20086 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
20087 }
20088 }
20089
20090 // We can't use default capture by reference if any captures already specified
20091 // capture by reference.
20092 if (llvm::none_of(LSI->Captures, [](Capture &C) {
20093 return !C.isInitCapture() && C.isReferenceCapture() &&
20094 !C.isThisCapture();
20095 })) {
20096 FixBuffer.assign({"&", Separator});
20097 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
20098 << /*reference*/ 1
20099 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
20100 }
20101}
20102
20104 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
20105 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
20106 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
20107 // An init-capture is notionally from the context surrounding its
20108 // declaration, but its parent DC is the lambda class.
20109 DeclContext *VarDC =
20111 DeclContext *DC = CurContext;
20112
20113 // Skip past RequiresExprBodys because they don't constitute function scopes.
20114 while (DC->isRequiresExprBody() || DC->isExpansionStmt())
20115 DC = DC->getParent();
20116
20117 // tryCaptureVariable is called every time a DeclRef is formed,
20118 // it can therefore have non-negigible impact on performances.
20119 // For local variables and when there is no capturing scope,
20120 // we can bailout early.
20121 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
20122 return true;
20123
20124 // Exception: Function parameters are not tied to the function's DeclContext
20125 // until we enter the function definition. Capturing them anyway would result
20126 // in an out-of-bounds error while traversing DC and its parents.
20127 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
20128 return true;
20129
20130 const auto *VD = dyn_cast<VarDecl>(Var);
20131 if (VD) {
20132 if (VD->isInitCapture())
20133 VarDC = VarDC->getParent();
20134 } else {
20136 }
20137 assert(VD && "Cannot capture a null variable");
20138
20139 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
20140 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
20141 // We need to sync up the Declaration Context with the
20142 // FunctionScopeIndexToStopAt
20143 if (FunctionScopeIndexToStopAt) {
20144 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
20145 unsigned FSIndex = FunctionScopes.size() - 1;
20146 // When we're parsing the lambda parameter list, the current DeclContext is
20147 // NOT the lambda but its parent. So move away the current LSI before
20148 // aligning DC and FunctionScopeIndexToStopAt.
20149 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
20150 FSIndex && LSI && !LSI->AfterParameterList)
20151 --FSIndex;
20152 assert(MaxFunctionScopesIndex <= FSIndex &&
20153 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
20154 "FunctionScopes.");
20155 while (FSIndex != MaxFunctionScopesIndex) {
20157 --FSIndex;
20158 }
20159 }
20160
20161 // Capture global variables if it is required to use private copy of this
20162 // variable.
20163 bool IsGlobal = !VD->hasLocalStorage();
20164 if (IsGlobal && !(LangOpts.OpenMP &&
20165 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
20166 MaxFunctionScopesIndex)))
20167 return true;
20168
20169 if (isa<VarDecl>(Var))
20170 Var = cast<VarDecl>(Var->getCanonicalDecl());
20171
20172 // Walk up the stack to determine whether we can capture the variable,
20173 // performing the "simple" checks that don't depend on type. We stop when
20174 // we've either hit the declared scope of the variable or find an existing
20175 // capture of that variable. We start from the innermost capturing-entity
20176 // (the DC) and ensure that all intervening capturing-entities
20177 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
20178 // declcontext can either capture the variable or have already captured
20179 // the variable.
20180 CaptureType = Var->getType();
20181 DeclRefType = CaptureType.getNonReferenceType();
20182 bool Nested = false;
20183 bool Explicit = (Kind != TryCaptureKind::Implicit);
20184 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
20185 do {
20186
20187 LambdaScopeInfo *LSI = nullptr;
20188 if (!FunctionScopes.empty())
20189 LSI = dyn_cast_or_null<LambdaScopeInfo>(
20190 FunctionScopes[FunctionScopesIndex]);
20191
20192 bool IsInScopeDeclarationContext =
20193 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
20194
20195 if (LSI && !LSI->AfterParameterList) {
20196 // This allows capturing parameters from a default value which does not
20197 // seems correct
20198 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
20199 return true;
20200 }
20201 // If the variable is declared in the current context, there is no need to
20202 // capture it.
20203 if (IsInScopeDeclarationContext &&
20204 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
20205 return true;
20206
20207 // Only block literals, captured statements, and lambda expressions can
20208 // capture; other scopes don't work.
20209 DeclContext *ParentDC =
20210 !IsInScopeDeclarationContext
20211 ? DC->getParent()
20212 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
20213 BuildAndDiagnose, *this);
20214 // We need to check for the parent *first* because, if we *have*
20215 // private-captured a global variable, we need to recursively capture it in
20216 // intermediate blocks, lambdas, etc.
20217 if (!ParentDC) {
20218 if (IsGlobal) {
20219 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
20220 break;
20221 }
20222 return true;
20223 }
20224
20225 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
20227
20228 // Check whether we've already captured it.
20229 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
20230 DeclRefType)) {
20231 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
20232 break;
20233 }
20234
20235 // When evaluating some attributes (like enable_if) we might refer to a
20236 // function parameter appertaining to the same declaration as that
20237 // attribute.
20238 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
20239 Parm && Parm->getDeclContext() == DC)
20240 return true;
20241
20242 // If we are instantiating a generic lambda call operator body,
20243 // we do not want to capture new variables. What was captured
20244 // during either a lambdas transformation or initial parsing
20245 // should be used.
20247 if (BuildAndDiagnose) {
20250 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
20251 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
20252 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
20253 buildLambdaCaptureFixit(*this, LSI, Var);
20254 } else
20256 }
20257 return true;
20258 }
20259
20260 // Try to capture variable-length arrays types.
20261 if (Var->getType()->isVariablyModifiedType()) {
20262 // We're going to walk down into the type and look for VLA
20263 // expressions.
20264 QualType QTy = Var->getType();
20265 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
20266 QTy = PVD->getOriginalType();
20268 }
20269
20270 if (getLangOpts().OpenMP) {
20271 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20272 // OpenMP private variables should not be captured in outer scope, so
20273 // just break here. Similarly, global variables that are captured in a
20274 // target region should not be captured outside the scope of the region.
20275 if (RSI->CapRegionKind == CR_OpenMP) {
20276 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
20277 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
20278 // If the variable is private (i.e. not captured) and has variably
20279 // modified type, we still need to capture the type for correct
20280 // codegen in all regions, associated with the construct. Currently,
20281 // it is captured in the innermost captured region only.
20282 if (IsOpenMPPrivateDecl != OMPC_unknown &&
20283 Var->getType()->isVariablyModifiedType()) {
20284 QualType QTy = Var->getType();
20285 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
20286 QTy = PVD->getOriginalType();
20287 for (int I = 1,
20288 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
20289 I < E; ++I) {
20290 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
20291 FunctionScopes[FunctionScopesIndex - I]);
20292 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
20293 "Wrong number of captured regions associated with the "
20294 "OpenMP construct.");
20295 captureVariablyModifiedType(Context, QTy, OuterRSI);
20296 }
20297 }
20298 bool IsTargetCap =
20299 IsOpenMPPrivateDecl != OMPC_private &&
20300 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
20301 RSI->OpenMPCaptureLevel);
20302 // Do not capture global if it is not privatized in outer regions.
20303 bool IsGlobalCap =
20304 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
20305 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
20306
20307 // When we detect target captures we are looking from inside the
20308 // target region, therefore we need to propagate the capture from the
20309 // enclosing region. Therefore, the capture is not initially nested.
20310 if (IsTargetCap)
20311 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
20312 RSI->OpenMPLevel);
20313
20314 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
20315 (IsGlobal && !IsGlobalCap)) {
20316 Nested = !IsTargetCap;
20317 bool HasConst = DeclRefType.isConstQualified();
20318 DeclRefType = DeclRefType.getUnqualifiedType();
20319 // Don't lose diagnostics about assignments to const.
20320 if (HasConst)
20321 DeclRefType.addConst();
20322 CaptureType = Context.getLValueReferenceType(DeclRefType);
20323 break;
20324 }
20325 }
20326 }
20327 }
20329 // No capture-default, and this is not an explicit capture
20330 // so cannot capture this variable.
20331 if (BuildAndDiagnose) {
20332 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
20333 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
20334 auto *LSI = cast<LambdaScopeInfo>(CSI);
20335 if (LSI->Lambda) {
20336 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
20337 buildLambdaCaptureFixit(*this, LSI, Var);
20338 }
20339 // FIXME: If we error out because an outer lambda can not implicitly
20340 // capture a variable that an inner lambda explicitly captures, we
20341 // should have the inner lambda do the explicit capture - because
20342 // it makes for cleaner diagnostics later. This would purely be done
20343 // so that the diagnostic does not misleadingly claim that a variable
20344 // can not be captured by a lambda implicitly even though it is captured
20345 // explicitly. Suggestion:
20346 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20347 // at the function head
20348 // - cache the StartingDeclContext - this must be a lambda
20349 // - captureInLambda in the innermost lambda the variable.
20350 }
20351 return true;
20352 }
20353 Explicit = false;
20354 FunctionScopesIndex--;
20355 if (IsInScopeDeclarationContext)
20356 DC = ParentDC;
20357 } while (!VarDC->Equals(DC));
20358
20359 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20360 // computing the type of the capture at each step, checking type-specific
20361 // requirements, and adding captures if requested.
20362 // If the variable had already been captured previously, we start capturing
20363 // at the lambda nested within that one.
20364 bool Invalid = false;
20365 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20366 ++I) {
20368
20369 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20370 // certain types of variables (unnamed, variably modified types etc.)
20371 // so check for eligibility.
20372 if (!Invalid)
20373 Invalid =
20374 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
20375
20376 // After encountering an error, if we're actually supposed to capture, keep
20377 // capturing in nested contexts to suppress any follow-on diagnostics.
20378 if (Invalid && !BuildAndDiagnose)
20379 return true;
20380
20381 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
20382 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20383 DeclRefType, Nested, *this, Invalid);
20384 Nested = true;
20385 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20387 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
20388 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
20389 Nested = true;
20390 } else {
20392 Invalid =
20393 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20394 DeclRefType, Nested, Kind, EllipsisLoc,
20395 /*IsTopScope*/ I == N - 1, *this, Invalid);
20396 Nested = true;
20397 }
20398
20399 if (Invalid && !BuildAndDiagnose)
20400 return true;
20401 }
20402 return Invalid;
20403}
20404
20406 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20407 QualType CaptureType;
20408 QualType DeclRefType;
20409 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
20410 /*BuildAndDiagnose=*/true, CaptureType,
20411 DeclRefType, nullptr);
20412}
20413
20415 QualType CaptureType;
20416 QualType DeclRefType;
20417 return !tryCaptureVariable(
20419 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
20420}
20421
20423 assert(Var && "Null value cannot be captured");
20424
20425 QualType CaptureType;
20426 QualType DeclRefType;
20427
20428 // Determine whether we can capture this variable.
20430 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20431 nullptr))
20432 return QualType();
20433
20434 return DeclRefType;
20435}
20436
20437namespace {
20438// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20439// The produced TemplateArgumentListInfo* points to data stored within this
20440// object, so should only be used in contexts where the pointer will not be
20441// used after the CopiedTemplateArgs object is destroyed.
20442class CopiedTemplateArgs {
20443 bool HasArgs;
20444 TemplateArgumentListInfo TemplateArgStorage;
20445public:
20446 template<typename RefExpr>
20447 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20448 if (HasArgs)
20449 E->copyTemplateArgumentsInto(TemplateArgStorage);
20450 }
20451 operator TemplateArgumentListInfo*()
20452#ifdef __has_cpp_attribute
20453#if __has_cpp_attribute(clang::lifetimebound)
20454 [[clang::lifetimebound]]
20455#endif
20456#endif
20457 {
20458 return HasArgs ? &TemplateArgStorage : nullptr;
20459 }
20460};
20461}
20462
20463/// Walk the set of potential results of an expression and mark them all as
20464/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20465///
20466/// \return A new expression if we found any potential results, ExprEmpty() if
20467/// not, and ExprError() if we diagnosed an error.
20469 NonOdrUseReason NOUR) {
20470 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20471 // an object that satisfies the requirements for appearing in a
20472 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20473 // is immediately applied." This function handles the lvalue-to-rvalue
20474 // conversion part.
20475 //
20476 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20477 // transform it into the relevant kind of non-odr-use node and rebuild the
20478 // tree of nodes leading to it.
20479 //
20480 // This is a mini-TreeTransform that only transforms a restricted subset of
20481 // nodes (and only certain operands of them).
20482
20483 // Rebuild a subexpression.
20484 auto Rebuild = [&](Expr *Sub) {
20485 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20486 };
20487
20488 // Check whether a potential result satisfies the requirements of NOUR.
20489 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20490 // Any entity other than a VarDecl is always odr-used whenever it's named
20491 // in a potentially-evaluated expression.
20492 auto *VD = dyn_cast<VarDecl>(D);
20493 if (!VD)
20494 return true;
20495
20496 // C++2a [basic.def.odr]p4:
20497 // A variable x whose name appears as a potentially-evalauted expression
20498 // e is odr-used by e unless
20499 // -- x is a reference that is usable in constant expressions, or
20500 // -- x is a variable of non-reference type that is usable in constant
20501 // expressions and has no mutable subobjects, and e is an element of
20502 // the set of potential results of an expression of
20503 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20504 // conversion is applied, or
20505 // -- x is a variable of non-reference type, and e is an element of the
20506 // set of potential results of a discarded-value expression to which
20507 // the lvalue-to-rvalue conversion is not applied
20508 //
20509 // We check the first bullet and the "potentially-evaluated" condition in
20510 // BuildDeclRefExpr. We check the type requirements in the second bullet
20511 // in CheckLValueToRValueConversionOperand below.
20512 switch (NOUR) {
20513 case NOUR_None:
20514 case NOUR_Unevaluated:
20515 llvm_unreachable("unexpected non-odr-use-reason");
20516
20517 case NOUR_Constant:
20518 // Constant references were handled when they were built.
20519 if (VD->getType()->isReferenceType())
20520 return true;
20521 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20522 if (RD->hasDefinition() && RD->hasMutableFields())
20523 return true;
20524 if (!VD->isUsableInConstantExpressions(S.Context))
20525 return true;
20526 break;
20527
20528 case NOUR_Discarded:
20529 if (VD->getType()->isReferenceType())
20530 return true;
20531 break;
20532 }
20533 return false;
20534 };
20535
20536 // Check whether this expression may be odr-used in CUDA/HIP.
20537 auto MaybeCUDAODRUsed = [&]() -> bool {
20538 if (!S.LangOpts.CUDA)
20539 return false;
20540 LambdaScopeInfo *LSI = S.getCurLambda();
20541 if (!LSI)
20542 return false;
20543 auto *DRE = dyn_cast<DeclRefExpr>(E);
20544 if (!DRE)
20545 return false;
20546 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
20547 if (!VD)
20548 return false;
20549 return LSI->CUDAPotentialODRUsedVars.count(VD);
20550 };
20551
20552 // Mark that this expression does not constitute an odr-use.
20553 auto MarkNotOdrUsed = [&] {
20554 if (!MaybeCUDAODRUsed()) {
20555 S.MaybeODRUseExprs.remove(E);
20556 if (LambdaScopeInfo *LSI = S.getCurLambda())
20557 LSI->markVariableExprAsNonODRUsed(E);
20558 }
20559 };
20560
20561 // C++2a [basic.def.odr]p2:
20562 // The set of potential results of an expression e is defined as follows:
20563 switch (E->getStmtClass()) {
20564 // -- If e is an id-expression, ...
20565 case Expr::DeclRefExprClass: {
20566 auto *DRE = cast<DeclRefExpr>(E);
20567 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20568 break;
20569
20570 // Rebuild as a non-odr-use DeclRefExpr.
20571 MarkNotOdrUsed();
20572 return DeclRefExpr::Create(
20573 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20574 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20575 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20576 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20577 }
20578
20579 case Expr::FunctionParmPackExprClass: {
20580 auto *FPPE = cast<FunctionParmPackExpr>(E);
20581 // If any of the declarations in the pack is odr-used, then the expression
20582 // as a whole constitutes an odr-use.
20583 for (ValueDecl *D : *FPPE)
20584 if (IsPotentialResultOdrUsed(D))
20585 return ExprEmpty();
20586
20587 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20588 // nothing cares about whether we marked this as an odr-use, but it might
20589 // be useful for non-compiler tools.
20590 MarkNotOdrUsed();
20591 break;
20592 }
20593
20594 // -- If e is a subscripting operation with an array operand...
20595 case Expr::ArraySubscriptExprClass: {
20596 auto *ASE = cast<ArraySubscriptExpr>(E);
20597 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20598 if (!OldBase->getType()->isArrayType())
20599 break;
20600 ExprResult Base = Rebuild(OldBase);
20601 if (!Base.isUsable())
20602 return Base;
20603 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20604 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20605 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20606 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20607 ASE->getRBracketLoc());
20608 }
20609
20610 case Expr::MemberExprClass: {
20611 auto *ME = cast<MemberExpr>(E);
20612 // -- If e is a class member access expression [...] naming a non-static
20613 // data member...
20614 if (isa<FieldDecl>(ME->getMemberDecl())) {
20615 ExprResult Base = Rebuild(ME->getBase());
20616 if (!Base.isUsable())
20617 return Base;
20618 return MemberExpr::Create(
20619 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20620 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20621 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20622 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20623 ME->getObjectKind(), ME->isNonOdrUse());
20624 }
20625
20626 if (ME->getMemberDecl()->isCXXInstanceMember())
20627 break;
20628
20629 // -- If e is a class member access expression naming a static data member,
20630 // ...
20631 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20632 break;
20633
20634 // Rebuild as a non-odr-use MemberExpr.
20635 MarkNotOdrUsed();
20636 return MemberExpr::Create(
20637 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20638 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20639 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20640 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20641 }
20642
20643 case Expr::BinaryOperatorClass: {
20644 auto *BO = cast<BinaryOperator>(E);
20645 Expr *LHS = BO->getLHS();
20646 Expr *RHS = BO->getRHS();
20647 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20648 if (BO->getOpcode() == BO_PtrMemD) {
20649 ExprResult Sub = Rebuild(LHS);
20650 if (!Sub.isUsable())
20651 return Sub;
20652 BO->setLHS(Sub.get());
20653 // -- If e is a comma expression, ...
20654 } else if (BO->getOpcode() == BO_Comma) {
20655 ExprResult Sub = Rebuild(RHS);
20656 if (!Sub.isUsable())
20657 return Sub;
20658 BO->setRHS(Sub.get());
20659 } else {
20660 break;
20661 }
20662 return ExprResult(BO);
20663 }
20664
20665 // -- If e has the form (e1)...
20666 case Expr::ParenExprClass: {
20667 auto *PE = cast<ParenExpr>(E);
20668 ExprResult Sub = Rebuild(PE->getSubExpr());
20669 if (!Sub.isUsable())
20670 return Sub;
20671 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20672 }
20673
20674 // -- If e is a glvalue conditional expression, ...
20675 // We don't apply this to a binary conditional operator. FIXME: Should we?
20676 case Expr::ConditionalOperatorClass: {
20677 auto *CO = cast<ConditionalOperator>(E);
20678 ExprResult LHS = Rebuild(CO->getLHS());
20679 if (LHS.isInvalid())
20680 return ExprError();
20681 ExprResult RHS = Rebuild(CO->getRHS());
20682 if (RHS.isInvalid())
20683 return ExprError();
20684 if (!LHS.isUsable() && !RHS.isUsable())
20685 return ExprEmpty();
20686 if (!LHS.isUsable())
20687 LHS = CO->getLHS();
20688 if (!RHS.isUsable())
20689 RHS = CO->getRHS();
20690 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20691 CO->getCond(), LHS.get(), RHS.get());
20692 }
20693
20694 // [Clang extension]
20695 // -- If e has the form __extension__ e1...
20696 case Expr::UnaryOperatorClass: {
20697 auto *UO = cast<UnaryOperator>(E);
20698 if (UO->getOpcode() != UO_Extension)
20699 break;
20700 ExprResult Sub = Rebuild(UO->getSubExpr());
20701 if (!Sub.isUsable())
20702 return Sub;
20703 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20704 Sub.get());
20705 }
20706
20707 // [Clang extension]
20708 // -- If e has the form _Generic(...), the set of potential results is the
20709 // union of the sets of potential results of the associated expressions.
20710 case Expr::GenericSelectionExprClass: {
20711 auto *GSE = cast<GenericSelectionExpr>(E);
20712
20713 SmallVector<Expr *, 4> AssocExprs;
20714 bool AnyChanged = false;
20715 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20716 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20717 if (AssocExpr.isInvalid())
20718 return ExprError();
20719 if (AssocExpr.isUsable()) {
20720 AssocExprs.push_back(AssocExpr.get());
20721 AnyChanged = true;
20722 } else {
20723 AssocExprs.push_back(OrigAssocExpr);
20724 }
20725 }
20726
20727 void *ExOrTy = nullptr;
20728 bool IsExpr = GSE->isExprPredicate();
20729 if (IsExpr)
20730 ExOrTy = GSE->getControllingExpr();
20731 else
20732 ExOrTy = GSE->getControllingType();
20733 return AnyChanged ? S.CreateGenericSelectionExpr(
20734 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20735 GSE->getRParenLoc(), IsExpr, ExOrTy,
20736 GSE->getAssocTypeSourceInfos(), AssocExprs)
20737 : ExprEmpty();
20738 }
20739
20740 // [Clang extension]
20741 // -- If e has the form __builtin_choose_expr(...), the set of potential
20742 // results is the union of the sets of potential results of the
20743 // second and third subexpressions.
20744 case Expr::ChooseExprClass: {
20745 auto *CE = cast<ChooseExpr>(E);
20746
20747 ExprResult LHS = Rebuild(CE->getLHS());
20748 if (LHS.isInvalid())
20749 return ExprError();
20750
20751 ExprResult RHS = Rebuild(CE->getLHS());
20752 if (RHS.isInvalid())
20753 return ExprError();
20754
20755 if (!LHS.get() && !RHS.get())
20756 return ExprEmpty();
20757 if (!LHS.isUsable())
20758 LHS = CE->getLHS();
20759 if (!RHS.isUsable())
20760 RHS = CE->getRHS();
20761
20762 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20763 RHS.get(), CE->getRParenLoc());
20764 }
20765
20766 // Step through non-syntactic nodes.
20767 case Expr::ConstantExprClass: {
20768 auto *CE = cast<ConstantExpr>(E);
20769 ExprResult Sub = Rebuild(CE->getSubExpr());
20770 if (!Sub.isUsable())
20771 return Sub;
20772 return ConstantExpr::Create(S.Context, Sub.get());
20773 }
20774
20775 // We could mostly rely on the recursive rebuilding to rebuild implicit
20776 // casts, but not at the top level, so rebuild them here.
20777 case Expr::ImplicitCastExprClass: {
20778 auto *ICE = cast<ImplicitCastExpr>(E);
20779 // Only step through the narrow set of cast kinds we expect to encounter.
20780 // Anything else suggests we've left the region in which potential results
20781 // can be found.
20782 switch (ICE->getCastKind()) {
20783 case CK_NoOp:
20784 case CK_DerivedToBase:
20785 case CK_UncheckedDerivedToBase: {
20786 ExprResult Sub = Rebuild(ICE->getSubExpr());
20787 if (!Sub.isUsable())
20788 return Sub;
20789 CXXCastPath Path(ICE->path());
20790 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20791 ICE->getValueKind(), &Path);
20792 }
20793
20794 default:
20795 break;
20796 }
20797 break;
20798 }
20799
20800 default:
20801 break;
20802 }
20803
20804 // Can't traverse through this node. Nothing to do.
20805 return ExprEmpty();
20806}
20807
20809 // Check whether the operand is or contains an object of non-trivial C union
20810 // type.
20811 if (E->getType().isVolatileQualified() &&
20817
20818 // C++2a [basic.def.odr]p4:
20819 // [...] an expression of non-volatile-qualified non-class type to which
20820 // the lvalue-to-rvalue conversion is applied [...]
20821 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20822 return E;
20823
20826 if (Result.isInvalid())
20827 return ExprError();
20828 return Result.get() ? Result : E;
20829}
20830
20832 if (!Res.isUsable())
20833 return Res;
20834
20835 // If a constant-expression is a reference to a variable where we delay
20836 // deciding whether it is an odr-use, just assume we will apply the
20837 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20838 // (a non-type template argument), we have special handling anyway.
20840}
20841
20843 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20844 // call.
20845 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20846 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20847
20848 for (Expr *E : LocalMaybeODRUseExprs) {
20849 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20850 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20851 DRE->getLocation(), *this);
20852 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20853 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20854 *this);
20855 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20856 for (ValueDecl *VD : *FP)
20857 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20858 } else {
20859 llvm_unreachable("Unexpected expression");
20860 }
20861 }
20862
20863 assert(MaybeODRUseExprs.empty() &&
20864 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20865}
20866
20868 ValueDecl *Var, Expr *E) {
20870 if (!VD)
20871 return;
20872
20873 const bool RefersToEnclosingScope =
20874 (SemaRef.CurContext != VD->getDeclContext() &&
20876 if (RefersToEnclosingScope) {
20877 LambdaScopeInfo *const LSI =
20878 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20879 if (LSI && (!LSI->CallOperator ||
20880 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20881 // If a variable could potentially be odr-used, defer marking it so
20882 // until we finish analyzing the full expression for any
20883 // lvalue-to-rvalue
20884 // or discarded value conversions that would obviate odr-use.
20885 // Add it to the list of potential captures that will be analyzed
20886 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20887 // unless the variable is a reference that was initialized by a constant
20888 // expression (this will never need to be captured or odr-used).
20889 //
20890 // FIXME: We can simplify this a lot after implementing P0588R1.
20891 assert(E && "Capture variable should be used in an expression.");
20892 if (!Var->getType()->isReferenceType() ||
20895 }
20896 }
20897}
20898
20900 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20901 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20902 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20904 "Invalid Expr argument to DoMarkVarDeclReferenced");
20905 Var->setReferenced();
20906
20907 if (Var->isInvalidDecl())
20908 return;
20909
20910 auto *MSI = Var->getMemberSpecializationInfo();
20911 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20913
20914 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20915 bool UsableInConstantExpr =
20917
20918 // Only track variables with internal linkage or local scope.
20919 // Use canonical decl so in-class declarations and out-of-class definitions
20920 // of static data members in anonymous namespaces are tracked as a single
20921 // entry.
20922 const VarDecl *CanonVar = Var->getCanonicalDecl();
20923 if ((CanonVar->isLocalVarDeclOrParm() ||
20924 CanonVar->isInternalLinkageFileVar()) &&
20925 !CanonVar->hasExternalStorage()) {
20926 RefsMinusAssignments.insert({CanonVar, 0}).first->getSecond()++;
20927 }
20928
20929 // C++20 [expr.const]p12:
20930 // A variable [...] is needed for constant evaluation if it is [...] a
20931 // variable whose name appears as a potentially constant evaluated
20932 // expression that is either a contexpr variable or is of non-volatile
20933 // const-qualified integral type or of reference type
20934 bool NeededForConstantEvaluation =
20935 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20936
20937 bool NeedDefinition =
20938 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20939 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20940 Var->getType()->isUndeducedType());
20941
20943 "Can't instantiate a partial template specialization.");
20944
20945 // If this might be a member specialization of a static data member, check
20946 // the specialization is visible. We already did the checks for variable
20947 // template specializations when we created them.
20948 if (NeedDefinition && TSK != TSK_Undeclared &&
20951
20952 // Perform implicit instantiation of static data members, static data member
20953 // templates of class templates, and variable template specializations. Delay
20954 // instantiations of variable templates, except for those that could be used
20955 // in a constant expression.
20956 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20957 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20958 // instantiation declaration if a variable is usable in a constant
20959 // expression (among other cases).
20960 bool TryInstantiating =
20962 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20963
20964 if (TryInstantiating) {
20965 SourceLocation PointOfInstantiation =
20966 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20967 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20968 if (FirstInstantiation) {
20969 PointOfInstantiation = Loc;
20970 if (MSI)
20971 MSI->setPointOfInstantiation(PointOfInstantiation);
20972 // FIXME: Notify listener.
20973 else
20974 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20975 }
20976
20977 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20978 // Do not defer instantiations of variables that could be used in a
20979 // constant expression.
20980 // The type deduction also needs a complete initializer.
20981 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20982 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20983 });
20984
20985 // The size of an incomplete array type can be updated by
20986 // instantiating the initializer. The DeclRefExpr's type should be
20987 // updated accordingly too, or users of it would be confused!
20988 if (E)
20990
20991 // Re-set the member to trigger a recomputation of the dependence bits
20992 // for the expression.
20993 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20994 DRE->setDecl(DRE->getDecl());
20995 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20996 ME->setMemberDecl(ME->getMemberDecl());
20997 } else if (FirstInstantiation) {
20999 .push_back(std::make_pair(Var, PointOfInstantiation));
21000 } else {
21001 bool Inserted = false;
21002 for (auto &I : SemaRef.SavedPendingInstantiations) {
21003 auto Iter = llvm::find_if(
21004 I, [Var](const Sema::PendingImplicitInstantiation &P) {
21005 return P.first == Var;
21006 });
21007 if (Iter != I.end()) {
21008 SemaRef.PendingInstantiations.push_back(*Iter);
21009 I.erase(Iter);
21010 Inserted = true;
21011 break;
21012 }
21013 }
21014
21015 // FIXME: For a specialization of a variable template, we don't
21016 // distinguish between "declaration and type implicitly instantiated"
21017 // and "implicit instantiation of definition requested", so we have
21018 // no direct way to avoid enqueueing the pending instantiation
21019 // multiple times.
21020 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
21022 .push_back(std::make_pair(Var, PointOfInstantiation));
21023 }
21024 }
21025 }
21026
21027 // C++2a [basic.def.odr]p4:
21028 // A variable x whose name appears as a potentially-evaluated expression e
21029 // is odr-used by e unless
21030 // -- x is a reference that is usable in constant expressions
21031 // -- x is a variable of non-reference type that is usable in constant
21032 // expressions and has no mutable subobjects [FIXME], and e is an
21033 // element of the set of potential results of an expression of
21034 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
21035 // conversion is applied
21036 // -- x is a variable of non-reference type, and e is an element of the set
21037 // of potential results of a discarded-value expression to which the
21038 // lvalue-to-rvalue conversion is not applied [FIXME]
21039 //
21040 // We check the first part of the second bullet here, and
21041 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
21042 // FIXME: To get the third bullet right, we need to delay this even for
21043 // variables that are not usable in constant expressions.
21044
21045 // If we already know this isn't an odr-use, there's nothing more to do.
21046 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
21047 if (DRE->isNonOdrUse())
21048 return;
21049 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
21050 if (ME->isNonOdrUse())
21051 return;
21052
21053 switch (OdrUse) {
21054 case OdrUseContext::None:
21055 // In some cases, a variable may not have been marked unevaluated, if it
21056 // appears in a defaukt initializer.
21057 assert((!E || isa<FunctionParmPackExpr>(E) ||
21059 "missing non-odr-use marking for unevaluated decl ref");
21060 break;
21061
21062 case OdrUseContext::FormallyOdrUsed:
21063 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
21064 // behavior.
21065 break;
21066
21067 case OdrUseContext::Used:
21068 // If we might later find that this expression isn't actually an odr-use,
21069 // delay the marking.
21071 SemaRef.MaybeODRUseExprs.insert(E);
21072 else
21073 MarkVarDeclODRUsed(Var, Loc, SemaRef);
21074 break;
21075
21076 case OdrUseContext::Dependent:
21077 // If this is a dependent context, we don't need to mark variables as
21078 // odr-used, but we may still need to track them for lambda capture.
21079 // FIXME: Do we also need to do this inside dependent typeid expressions
21080 // (which are modeled as unevaluated at this point)?
21081 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
21082 break;
21083 }
21084}
21085
21087 BindingDecl *BD, Expr *E) {
21088 BD->setReferenced();
21089
21090 if (BD->isInvalidDecl())
21091 return;
21092
21093 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
21094 if (OdrUse == OdrUseContext::Used) {
21095 QualType CaptureType, DeclRefType;
21097 /*EllipsisLoc*/ SourceLocation(),
21098 /*BuildAndDiagnose*/ true, CaptureType,
21099 DeclRefType,
21100 /*FunctionScopeIndexToStopAt*/ nullptr);
21101 } else if (OdrUse == OdrUseContext::Dependent) {
21102 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
21103 }
21104}
21105
21107 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
21108}
21109
21110// C++ [temp.dep.expr]p3:
21111// An id-expression is type-dependent if it contains:
21112// - an identifier associated by name lookup with an entity captured by copy
21113// in a lambda-expression that has an explicit object parameter whose type
21114// is dependent ([dcl.fct]),
21116 Sema &SemaRef, ValueDecl *D, Expr *E) {
21117 auto *ID = dyn_cast<DeclRefExpr>(E);
21118 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
21119 return;
21120
21121 // If any enclosing lambda with a dependent explicit object parameter either
21122 // explicitly captures the variable by value, or has a capture default of '='
21123 // and does not capture the variable by reference, then the type of the DRE
21124 // is dependent on the type of that lambda's explicit object parameter.
21125 auto IsDependent = [&]() {
21126 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
21127 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
21128 if (!LSI)
21129 continue;
21130
21131 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
21132 LSI->AfterParameterList)
21133 return false;
21134
21135 const auto *MD = LSI->CallOperator;
21136 if (MD->getType().isNull())
21137 continue;
21138
21139 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
21140 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
21141 !Ty->getParamType(0)->isDependentType())
21142 continue;
21143
21144 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
21145 if (C->isCopyCapture())
21146 return true;
21147 continue;
21148 }
21149
21150 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
21151 return true;
21152 }
21153 return false;
21154 }();
21155
21156 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
21157 IsDependent, SemaRef.getASTContext());
21158}
21159
21160static void
21162 bool MightBeOdrUse,
21163 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
21166
21167 if (SemaRef.getLangOpts().OpenACC)
21168 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
21169
21170 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
21172 if (SemaRef.getLangOpts().CPlusPlus)
21174 Var, E);
21175 return;
21176 }
21177
21178 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
21180 if (SemaRef.getLangOpts().CPlusPlus)
21182 Decl, E);
21183 return;
21184 }
21185 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
21186
21187 // If this is a call to a method via a cast, also mark the method in the
21188 // derived class used in case codegen can devirtualize the call.
21189 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
21190 if (!ME)
21191 return;
21192 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
21193 if (!MD)
21194 return;
21195 // Only attempt to devirtualize if this is truly a virtual call.
21196 bool IsVirtualCall = MD->isVirtual() &&
21198 if (!IsVirtualCall)
21199 return;
21200
21201 // If it's possible to devirtualize the call, mark the called function
21202 // referenced.
21204 ME->getBase(), SemaRef.getLangOpts().AppleKext);
21205 if (DM)
21206 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
21207}
21208
21210 // [basic.def.odr] (CWG 1614)
21211 // A function is named by an expression or conversion [...]
21212 // unless it is a pure virtual function and either the expression is not an
21213 // id-expression naming the function with an explicitly qualified name or
21214 // the expression forms a pointer to member
21215 bool OdrUse = true;
21216 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
21217 if (Method->isVirtual() &&
21218 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
21219 OdrUse = false;
21220
21221 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
21225 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
21226 !FD->isDependentContext())
21227 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
21228 }
21229 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
21231}
21232
21234 // C++11 [basic.def.odr]p2:
21235 // A non-overloaded function whose name appears as a potentially-evaluated
21236 // expression or a member of a set of candidate functions, if selected by
21237 // overload resolution when referred to from a potentially-evaluated
21238 // expression, is odr-used, unless it is a pure virtual function and its
21239 // name is not explicitly qualified.
21240 bool MightBeOdrUse = true;
21242 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
21243 if (Method->isPureVirtual())
21244 MightBeOdrUse = false;
21245 }
21246 SourceLocation Loc =
21247 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
21248 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
21250}
21251
21257
21258/// Perform marking for a reference to an arbitrary declaration. It
21259/// marks the declaration referenced, and performs odr-use checking for
21260/// functions and variables. This method should not be used when building a
21261/// normal expression which refers to a variable.
21263 bool MightBeOdrUse) {
21264 if (MightBeOdrUse) {
21265 if (auto *VD = dyn_cast<VarDecl>(D)) {
21266 MarkVariableReferenced(Loc, VD);
21267 return;
21268 }
21269 }
21270 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
21271 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
21272 return;
21273 }
21274 D->setReferenced();
21275}
21276
21277namespace {
21278 // Mark all of the declarations used by a type as referenced.
21279 // FIXME: Not fully implemented yet! We need to have a better understanding
21280 // of when we're entering a context we should not recurse into.
21281 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
21282 // TreeTransforms rebuilding the type in a new context. Rather than
21283 // duplicating the TreeTransform logic, we should consider reusing it here.
21284 // Currently that causes problems when rebuilding LambdaExprs.
21285class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
21286 Sema &S;
21287 SourceLocation Loc;
21288
21289public:
21290 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
21291
21292 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
21293};
21294}
21295
21296bool MarkReferencedDecls::TraverseTemplateArgument(
21297 const TemplateArgument &Arg) {
21298 {
21299 // A non-type template argument is a constant-evaluated context.
21300 EnterExpressionEvaluationContext Evaluated(
21303 if (Decl *D = Arg.getAsDecl())
21304 S.MarkAnyDeclReferenced(Loc, D, true);
21305 } else if (Arg.getKind() == TemplateArgument::Expression) {
21307 }
21308 }
21309
21311}
21312
21314 MarkReferencedDecls Marker(*this, Loc);
21315 Marker.TraverseType(T);
21316}
21317
21318namespace {
21319/// Helper class that marks all of the declarations referenced by
21320/// potentially-evaluated subexpressions as "referenced".
21321class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21322public:
21323 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21324 bool SkipLocalVariables;
21326
21327 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21329 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21330
21331 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21333 }
21334
21335 void Visit(Expr *E) {
21336 if (llvm::is_contained(StopAt, E))
21337 return;
21338 Inherited::Visit(E);
21339 }
21340
21341 void VisitConstantExpr(ConstantExpr *E) {
21342 // Don't mark declarations within a ConstantExpression, as this expression
21343 // will be evaluated and folded to a value.
21344 }
21345
21346 void VisitDeclRefExpr(DeclRefExpr *E) {
21347 // If we were asked not to visit local variables, don't.
21348 if (SkipLocalVariables) {
21349 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
21350 if (VD->hasLocalStorage())
21351 return;
21352 }
21353
21354 // FIXME: This can trigger the instantiation of the initializer of a
21355 // variable, which can cause the expression to become value-dependent
21356 // or error-dependent. Do we need to propagate the new dependence bits?
21358 }
21359
21360 void VisitMemberExpr(MemberExpr *E) {
21362 Visit(E->getBase());
21363 }
21364};
21365} // namespace
21366
21368 bool SkipLocalVariables,
21369 ArrayRef<const Expr*> StopAt) {
21370 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21371}
21372
21373/// Emit a diagnostic when statements are reachable.
21375 const PartialDiagnostic &PD) {
21376 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21377 // The initializer of a constexpr variable or of the first declaration of a
21378 // static data member is not syntactically a constant evaluated constant,
21379 // but nonetheless is always required to be a constant expression, so we
21380 // can skip diagnosing.
21381 if (Decl &&
21382 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21383 Decl->isFirstDecl() && !Decl->isInline())))
21384 return false;
21385
21386 if (Stmts.empty()) {
21387 Diag(Loc, PD);
21388 return true;
21389 }
21390
21391 if (getCurFunction()) {
21392 // This queue flushes after the function is analyzed, by which time an
21393 // ignore-all-warnings region live here is gone, so sample it now. A note
21394 // is not error-class either, so this also drops the notes that accompany a
21395 // skipped warning. They arrive on their own call, out of reach of the
21396 // engine's rule that drops a note whose warning was ignored.
21397 if (Diags.getIgnoreAllWarnings() &&
21398 Diags.getDiagnosticIDs()->isWarningOrExtension(PD.getDiagID()))
21399 return false;
21400 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21401 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21402 return true;
21403 }
21404
21405 // For non-constexpr file-scope variables with reachability context (non-empty
21406 // Stmts), build a CFG for the initializer and check whether the context in
21407 // question is reachable.
21408 if (Decl && Decl->isFileVarDecl()) {
21409 AnalysisWarnings.registerVarDeclWarning(
21410 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21411 return true;
21412 }
21413
21414 Diag(Loc, PD);
21415 return true;
21416}
21417
21418/// Emit a diagnostic that describes an effect on the run-time behavior
21419/// of the program being compiled.
21420///
21421/// This routine emits the given diagnostic when the code currently being
21422/// type-checked is "potentially evaluated", meaning that there is a
21423/// possibility that the code will actually be executable. Code in sizeof()
21424/// expressions, code used only during overload resolution, etc., are not
21425/// potentially evaluated. This routine will suppress such diagnostics or,
21426/// in the absolutely nutty case of potentially potentially evaluated
21427/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21428/// later.
21429///
21430/// This routine should be used for all diagnostics that describe the run-time
21431/// behavior of a program, such as passing a non-POD value through an ellipsis.
21432/// Failure to do so will likely result in spurious diagnostics or failures
21433/// during overload resolution or within sizeof/alignof/typeof/typeid.
21435 const PartialDiagnostic &PD) {
21436
21437 if (ExprEvalContexts.back().isDiscardedStatementContext())
21438 return false;
21439
21440 switch (ExprEvalContexts.back().Context) {
21445 // The argument will never be evaluated, so don't complain.
21446 break;
21447
21450 // Relevant diagnostics should be produced by constant evaluation.
21451 break;
21452
21455 return DiagIfReachable(Loc, Stmts, PD);
21456 }
21457
21458 return false;
21459}
21460
21462 const PartialDiagnostic &PD) {
21463 return DiagRuntimeBehavior(
21464 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21465 PD);
21466}
21467
21469 CallExpr *CE, FunctionDecl *FD) {
21470 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21471 return false;
21472
21473 // If we're inside a decltype's expression, don't check for a valid return
21474 // type or construct temporaries until we know whether this is the last call.
21475 if (ExprEvalContexts.back().ExprContext ==
21477 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21478 return false;
21479 }
21480
21481 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21482 FunctionDecl *FD;
21483 CallExpr *CE;
21484
21485 public:
21486 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21487 : FD(FD), CE(CE) { }
21488
21489 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21490 if (!FD) {
21491 S.Diag(Loc, diag::err_call_incomplete_return)
21492 << T << CE->getSourceRange();
21493 return;
21494 }
21495
21496 S.Diag(Loc, diag::err_call_function_incomplete_return)
21497 << CE->getSourceRange() << FD << T;
21498 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21499 << FD->getDeclName();
21500 }
21501 } Diagnoser(FD, CE);
21502
21503 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21504 return true;
21505
21506 return false;
21507}
21508
21509// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21510// will prevent this condition from triggering, which is what we want.
21512 SourceLocation Loc;
21513
21514 unsigned diagnostic = diag::warn_condition_is_assignment;
21515 bool IsOrAssign = false;
21516
21517 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21518 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21519 return;
21520
21521 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21522
21523 // Greylist some idioms by putting them into a warning subcategory.
21524 if (ObjCMessageExpr *ME
21525 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21526 Selector Sel = ME->getSelector();
21527
21528 // self = [<foo> init...]
21529 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21530 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21531
21532 // <foo> = [<bar> nextObject]
21533 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21534 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21535 }
21536
21537 Loc = Op->getOperatorLoc();
21538 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21539 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21540 return;
21541
21542 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21543 Loc = Op->getOperatorLoc();
21544 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21545 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21546 else {
21547 // Not an assignment.
21548 return;
21549 }
21550
21551 Diag(Loc, diagnostic) << E->getSourceRange();
21552
21555 Diag(Loc, diag::note_condition_assign_silence)
21557 << FixItHint::CreateInsertion(Close, ")");
21558
21559 if (IsOrAssign)
21560 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21561 << FixItHint::CreateReplacement(Loc, "!=");
21562 else
21563 Diag(Loc, diag::note_condition_assign_to_comparison)
21564 << FixItHint::CreateReplacement(Loc, "==");
21565}
21566
21568 // Don't warn if the parens came from a macro.
21569 SourceLocation parenLoc = ParenE->getBeginLoc();
21570 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21571 return;
21572 // Don't warn for dependent expressions.
21573 if (ParenE->isTypeDependent())
21574 return;
21575
21576 Expr *E = ParenE->IgnoreParens();
21577 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21578 return;
21579
21580 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21581 if (opE->getOpcode() == BO_EQ &&
21582 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21583 == Expr::MLV_Valid) {
21584 SourceLocation Loc = opE->getOperatorLoc();
21585
21586 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21587 SourceRange ParenERange = ParenE->getSourceRange();
21588 Diag(Loc, diag::note_equality_comparison_silence)
21589 << FixItHint::CreateRemoval(ParenERange.getBegin())
21590 << FixItHint::CreateRemoval(ParenERange.getEnd());
21591 Diag(Loc, diag::note_equality_comparison_to_assign)
21592 << FixItHint::CreateReplacement(Loc, "=");
21593 }
21594}
21595
21597 bool IsConstexpr) {
21599 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21601
21602 ExprResult result = CheckPlaceholderExpr(E);
21603 if (result.isInvalid()) return ExprError();
21604 E = result.get();
21605
21606 if (!E->isTypeDependent()) {
21607 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21609
21610 if (getLangOpts().CPlusPlus)
21611 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21612
21614 if (ERes.isInvalid())
21615 return ExprError();
21616 E = ERes.get();
21617
21618 QualType T = E->getType();
21619 if (!T->isScalarType()) { // C99 6.8.4.1p1
21620 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21621 << T << E->getSourceRange();
21622 return ExprError();
21623 }
21624 CheckBoolLikeConversion(E, Loc);
21625 }
21626
21627 return E;
21628}
21629
21631 Expr *SubExpr, ConditionKind CK,
21632 bool MissingOK) {
21633 // MissingOK indicates whether having no condition expression is valid
21634 // (for loop) or invalid (e.g. while loop).
21635 if (!SubExpr)
21636 return MissingOK ? ConditionResult() : ConditionError();
21637
21638 ExprResult Cond;
21639 switch (CK) {
21641 Cond = CheckBooleanCondition(Loc, SubExpr);
21642 break;
21643
21645 // Note: this might produce a FullExpr
21646 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21647 break;
21648
21650 Cond = CheckSwitchCondition(Loc, SubExpr);
21651 break;
21652 }
21653 if (Cond.isInvalid()) {
21654 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21655 {SubExpr}, PreferredConditionType(CK));
21656 if (!Cond.get())
21657 return ConditionError();
21658 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
21659 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
21660
21661 if (!Cond.isUsable())
21662 return ConditionError();
21663
21664 return ConditionResult(*this, nullptr, Cond,
21666}
21667
21668namespace {
21669 /// A visitor for rebuilding a call to an __unknown_any expression
21670 /// to have an appropriate type.
21671 struct RebuildUnknownAnyFunction
21672 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21673
21674 Sema &S;
21675
21676 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21677
21678 ExprResult VisitStmt(Stmt *S) {
21679 llvm_unreachable("unexpected statement!");
21680 }
21681
21682 ExprResult VisitExpr(Expr *E) {
21683 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21684 << E->getSourceRange();
21685 return ExprError();
21686 }
21687
21688 /// Rebuild an expression which simply semantically wraps another
21689 /// expression which it shares the type and value kind of.
21690 template <class T> ExprResult rebuildSugarExpr(T *E) {
21691 ExprResult SubResult = Visit(E->getSubExpr());
21692 if (SubResult.isInvalid()) return ExprError();
21693
21694 Expr *SubExpr = SubResult.get();
21695 E->setSubExpr(SubExpr);
21696 E->setType(SubExpr->getType());
21697 E->setValueKind(SubExpr->getValueKind());
21698 assert(E->getObjectKind() == OK_Ordinary);
21699 return E;
21700 }
21701
21702 ExprResult VisitParenExpr(ParenExpr *E) {
21703 return rebuildSugarExpr(E);
21704 }
21705
21706 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21707 return rebuildSugarExpr(E);
21708 }
21709
21710 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21711 ExprResult SubResult = Visit(E->getSubExpr());
21712 if (SubResult.isInvalid()) return ExprError();
21713
21714 Expr *SubExpr = SubResult.get();
21715 E->setSubExpr(SubExpr);
21716 E->setType(S.Context.getPointerType(SubExpr->getType()));
21717 assert(E->isPRValue());
21718 assert(E->getObjectKind() == OK_Ordinary);
21719 return E;
21720 }
21721
21722 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21723 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21724
21725 E->setType(VD->getType());
21726
21727 assert(E->isPRValue());
21728 if (S.getLangOpts().CPlusPlus &&
21729 !(isa<CXXMethodDecl>(VD) &&
21730 cast<CXXMethodDecl>(VD)->isInstance()))
21732
21733 return E;
21734 }
21735
21736 ExprResult VisitMemberExpr(MemberExpr *E) {
21737 return resolveDecl(E, E->getMemberDecl());
21738 }
21739
21740 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21741 return resolveDecl(E, E->getDecl());
21742 }
21743 };
21744}
21745
21746/// Given a function expression of unknown-any type, try to rebuild it
21747/// to have a function type.
21749 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21750 if (Result.isInvalid()) return ExprError();
21751 return S.DefaultFunctionArrayConversion(Result.get());
21752}
21753
21754namespace {
21755 /// A visitor for rebuilding an expression of type __unknown_anytype
21756 /// into one which resolves the type directly on the referring
21757 /// expression. Strict preservation of the original source
21758 /// structure is not a goal.
21759 struct RebuildUnknownAnyExpr
21760 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21761
21762 Sema &S;
21763
21764 /// The current destination type.
21765 QualType DestType;
21766
21767 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21768 : S(S), DestType(CastType) {}
21769
21770 ExprResult VisitStmt(Stmt *S) {
21771 llvm_unreachable("unexpected statement!");
21772 }
21773
21774 ExprResult VisitExpr(Expr *E) {
21775 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21776 << E->getSourceRange();
21777 return ExprError();
21778 }
21779
21780 ExprResult VisitCallExpr(CallExpr *E);
21781 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21782
21783 /// Rebuild an expression which simply semantically wraps another
21784 /// expression which it shares the type and value kind of.
21785 template <class T> ExprResult rebuildSugarExpr(T *E) {
21786 ExprResult SubResult = Visit(E->getSubExpr());
21787 if (SubResult.isInvalid()) return ExprError();
21788 Expr *SubExpr = SubResult.get();
21789 E->setSubExpr(SubExpr);
21790 E->setType(SubExpr->getType());
21791 E->setValueKind(SubExpr->getValueKind());
21792 assert(E->getObjectKind() == OK_Ordinary);
21793 return E;
21794 }
21795
21796 ExprResult VisitParenExpr(ParenExpr *E) {
21797 return rebuildSugarExpr(E);
21798 }
21799
21800 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21801 return rebuildSugarExpr(E);
21802 }
21803
21804 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21805 const PointerType *Ptr = DestType->getAs<PointerType>();
21806 if (!Ptr) {
21807 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21808 << E->getSourceRange();
21809 return ExprError();
21810 }
21811
21812 if (isa<CallExpr>(E->getSubExpr())) {
21813 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21814 << E->getSourceRange();
21815 return ExprError();
21816 }
21817
21818 assert(E->isPRValue());
21819 assert(E->getObjectKind() == OK_Ordinary);
21820 E->setType(DestType);
21821
21822 // Build the sub-expression as if it were an object of the pointee type.
21823 DestType = Ptr->getPointeeType();
21824 ExprResult SubResult = Visit(E->getSubExpr());
21825 if (SubResult.isInvalid()) return ExprError();
21826 E->setSubExpr(SubResult.get());
21827 return E;
21828 }
21829
21830 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21831
21832 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21833
21834 ExprResult VisitMemberExpr(MemberExpr *E) {
21835 return resolveDecl(E, E->getMemberDecl());
21836 }
21837
21838 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21839 return resolveDecl(E, E->getDecl());
21840 }
21841 };
21842}
21843
21844/// Rebuilds a call expression which yielded __unknown_anytype.
21845ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21846 Expr *CalleeExpr = E->getCallee();
21847
21848 enum FnKind {
21849 FK_MemberFunction,
21850 FK_FunctionPointer,
21851 FK_BlockPointer
21852 };
21853
21854 FnKind Kind;
21855 QualType CalleeType = CalleeExpr->getType();
21856 if (CalleeType == S.Context.BoundMemberTy) {
21858 Kind = FK_MemberFunction;
21859 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21860 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21861 CalleeType = Ptr->getPointeeType();
21862 Kind = FK_FunctionPointer;
21863 } else {
21864 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21865 Kind = FK_BlockPointer;
21866 }
21867 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21868
21869 // Verify that this is a legal result type of a function.
21870 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21871 DestType->isFunctionType()) {
21872 unsigned diagID = diag::err_func_returning_array_function;
21873 if (Kind == FK_BlockPointer)
21874 diagID = diag::err_block_returning_array_function;
21875
21876 S.Diag(E->getExprLoc(), diagID)
21877 << DestType->isFunctionType() << DestType;
21878 return ExprError();
21879 }
21880
21881 // Otherwise, go ahead and set DestType as the call's result.
21882 E->setType(DestType.getNonLValueExprType(S.Context));
21884 assert(E->getObjectKind() == OK_Ordinary);
21885
21886 // Rebuild the function type, replacing the result type with DestType.
21887 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21888 if (Proto) {
21889 // __unknown_anytype(...) is a special case used by the debugger when
21890 // it has no idea what a function's signature is.
21891 //
21892 // We want to build this call essentially under the K&R
21893 // unprototyped rules, but making a FunctionNoProtoType in C++
21894 // would foul up all sorts of assumptions. However, we cannot
21895 // simply pass all arguments as variadic arguments, nor can we
21896 // portably just call the function under a non-variadic type; see
21897 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21898 // However, it turns out that in practice it is generally safe to
21899 // call a function declared as "A foo(B,C,D);" under the prototype
21900 // "A foo(B,C,D,...);". The only known exception is with the
21901 // Windows ABI, where any variadic function is implicitly cdecl
21902 // regardless of its normal CC. Therefore we change the parameter
21903 // types to match the types of the arguments.
21904 //
21905 // This is a hack, but it is far superior to moving the
21906 // corresponding target-specific code from IR-gen to Sema/AST.
21907
21908 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21909 SmallVector<QualType, 8> ArgTypes;
21910 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21911 ArgTypes.reserve(E->getNumArgs());
21912 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21913 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21914 }
21915 ParamTypes = ArgTypes;
21916 }
21917 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21918 Proto->getExtProtoInfo());
21919 } else {
21920 DestType = S.Context.getFunctionNoProtoType(DestType,
21921 FnType->getExtInfo());
21922 }
21923
21924 // Rebuild the appropriate pointer-to-function type.
21925 switch (Kind) {
21926 case FK_MemberFunction:
21927 // Nothing to do.
21928 break;
21929
21930 case FK_FunctionPointer:
21931 DestType = S.Context.getPointerType(DestType);
21932 break;
21933
21934 case FK_BlockPointer:
21935 DestType = S.Context.getBlockPointerType(DestType);
21936 break;
21937 }
21938
21939 // Finally, we can recurse.
21940 ExprResult CalleeResult = Visit(CalleeExpr);
21941 if (!CalleeResult.isUsable()) return ExprError();
21942 E->setCallee(CalleeResult.get());
21943
21944 // Bind a temporary if necessary.
21945 return S.MaybeBindToTemporary(E);
21946}
21947
21948ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21949 // Verify that this is a legal result type of a call.
21950 if (DestType->isArrayType() || DestType->isFunctionType()) {
21951 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21952 << DestType->isFunctionType() << DestType;
21953 return ExprError();
21954 }
21955
21956 // Rewrite the method result type if available.
21957 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21958 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21959 Method->setReturnType(DestType);
21960 }
21961
21962 // Change the type of the message.
21963 E->setType(DestType.getNonReferenceType());
21965
21966 return S.MaybeBindToTemporary(E);
21967}
21968
21969ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21970 // The only case we should ever see here is a function-to-pointer decay.
21971 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21972 assert(E->isPRValue());
21973 assert(E->getObjectKind() == OK_Ordinary);
21974
21975 E->setType(DestType);
21976
21977 // Rebuild the sub-expression as the pointee (function) type.
21978 DestType = DestType->castAs<PointerType>()->getPointeeType();
21979
21980 ExprResult Result = Visit(E->getSubExpr());
21981 if (!Result.isUsable()) return ExprError();
21982
21983 E->setSubExpr(Result.get());
21984 return E;
21985 } else if (E->getCastKind() == CK_LValueToRValue) {
21986 assert(E->isPRValue());
21987 assert(E->getObjectKind() == OK_Ordinary);
21988
21989 assert(isa<BlockPointerType>(E->getType()));
21990
21991 E->setType(DestType);
21992
21993 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21994 DestType = S.Context.getLValueReferenceType(DestType);
21995
21996 ExprResult Result = Visit(E->getSubExpr());
21997 if (!Result.isUsable()) return ExprError();
21998
21999 E->setSubExpr(Result.get());
22000 return E;
22001 } else {
22002 llvm_unreachable("Unhandled cast type!");
22003 }
22004}
22005
22006ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
22007 ExprValueKind ValueKind = VK_LValue;
22008 QualType Type = DestType;
22009
22010 // We know how to make this work for certain kinds of decls:
22011
22012 // - functions
22013 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
22014 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
22015 DestType = Ptr->getPointeeType();
22016 ExprResult Result = resolveDecl(E, VD);
22017 if (Result.isInvalid()) return ExprError();
22018 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
22019 VK_PRValue);
22020 }
22021
22022 if (!Type->isFunctionType()) {
22023 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
22024 << VD << E->getSourceRange();
22025 return ExprError();
22026 }
22027 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
22028 // We must match the FunctionDecl's type to the hack introduced in
22029 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
22030 // type. See the lengthy commentary in that routine.
22031 QualType FDT = FD->getType();
22032 const FunctionType *FnType = FDT->castAs<FunctionType>();
22033 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
22034 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
22035 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
22036 SourceLocation Loc = FD->getLocation();
22037 FunctionDecl *NewFD = FunctionDecl::Create(
22038 S.Context, FD->getDeclContext(), Loc, Loc,
22039 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
22041 false /*isInlineSpecified*/, FD->hasPrototype(),
22042 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
22043
22044 if (FD->getQualifier())
22045 NewFD->setQualifierInfo(FD->getQualifierLoc());
22046
22047 SmallVector<ParmVarDecl*, 16> Params;
22048 for (const auto &AI : FT->param_types()) {
22049 ParmVarDecl *Param =
22050 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
22051 Param->setScopeInfo(0, Params.size());
22052 Params.push_back(Param);
22053 }
22054 NewFD->setParams(Params);
22055 DRE->setDecl(NewFD);
22056 VD = DRE->getDecl();
22057 }
22058 }
22059
22060 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
22061 if (MD->isInstance()) {
22062 ValueKind = VK_PRValue;
22064 }
22065
22066 // Function references aren't l-values in C.
22067 if (!S.getLangOpts().CPlusPlus)
22068 ValueKind = VK_PRValue;
22069
22070 // - variables
22071 } else if (isa<VarDecl>(VD)) {
22072 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
22073 Type = RefTy->getPointeeType();
22074 } else if (Type->isFunctionType()) {
22075 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
22076 << VD << E->getSourceRange();
22077 return ExprError();
22078 }
22079
22080 // - nothing else
22081 } else {
22082 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
22083 << VD << E->getSourceRange();
22084 return ExprError();
22085 }
22086
22087 // Modifying the declaration like this is friendly to IR-gen but
22088 // also really dangerous.
22089 VD->setType(DestType);
22090 E->setType(Type);
22091 E->setValueKind(ValueKind);
22092 return E;
22093}
22094
22097 ExprValueKind &VK, CXXCastPath &Path) {
22098 // The type we're casting to must be either void or complete.
22099 if (!CastType->isVoidType() &&
22101 diag::err_typecheck_cast_to_incomplete))
22102 return ExprError();
22103
22104 // Rewrite the casted expression from scratch.
22105 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
22106 if (!result.isUsable()) return ExprError();
22107
22108 CastExpr = result.get();
22110 CastKind = CK_NoOp;
22111
22112 return CastExpr;
22113}
22114
22116 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
22117}
22118
22120 Expr *arg, QualType &paramType) {
22121 // If the syntactic form of the argument is not an explicit cast of
22122 // any sort, just do default argument promotion.
22123 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
22124 if (!castArg) {
22126 if (result.isInvalid()) return ExprError();
22127 paramType = result.get()->getType();
22128 return result;
22129 }
22130
22131 // Otherwise, use the type that was written in the explicit cast.
22132 assert(!arg->hasPlaceholderType());
22133 paramType = castArg->getTypeAsWritten();
22134
22135 // Copy-initialize a parameter of that type.
22136 InitializedEntity entity =
22138 /*consumed*/ false);
22139 return PerformCopyInitialization(entity, callLoc, arg);
22140}
22141
22143 Expr *orig = E;
22144 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
22145 while (true) {
22146 E = E->IgnoreParenImpCasts();
22147 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
22148 E = call->getCallee();
22149 diagID = diag::err_uncasted_call_of_unknown_any;
22150 } else {
22151 break;
22152 }
22153 }
22154
22155 SourceLocation loc;
22156 NamedDecl *d;
22157 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
22158 loc = ref->getLocation();
22159 d = ref->getDecl();
22160 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
22161 loc = mem->getMemberLoc();
22162 d = mem->getMemberDecl();
22163 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
22164 diagID = diag::err_uncasted_call_of_unknown_any;
22165 loc = msg->getSelectorStartLoc();
22166 d = msg->getMethodDecl();
22167 if (!d) {
22168 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
22169 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
22170 << orig->getSourceRange();
22171 return ExprError();
22172 }
22173 } else {
22174 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
22175 << E->getSourceRange();
22176 return ExprError();
22177 }
22178
22179 S.Diag(loc, diagID) << d << orig->getSourceRange();
22180
22181 // Never recoverable.
22182 return ExprError();
22183}
22184
22186 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
22187 if (!placeholderType) return E;
22188
22189 switch (placeholderType->getKind()) {
22190 case BuiltinType::UnresolvedTemplate: {
22191 auto *ULE = cast<UnresolvedLookupExpr>(E->IgnoreParens());
22192 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
22193 // There's only one FoundDecl for UnresolvedTemplate type. See
22194 // BuildTemplateIdExpr.
22195 NamedDecl *Temp = *ULE->decls_begin();
22196 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
22197
22198 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
22199 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
22200 // as it models only the unqualified-id case, where this case can clearly be
22201 // qualified. Thus we can't just qualify an assumed template.
22202 TemplateName TN;
22203 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
22204 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
22205 TemplateName(TD));
22206 else
22207 TN = Context.getAssumedTemplateName(NameInfo.getName());
22208
22209 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
22210 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
22211 Diag(Temp->getLocation(), diag::note_referenced_type_template)
22212 << IsTypeAliasTemplateDecl;
22213
22214 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
22215 bool HasAnyDependentTA = false;
22216 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
22217 HasAnyDependentTA |= Arg.getArgument().isDependent();
22218 TAL.addArgument(Arg);
22219 }
22220
22221 QualType TST;
22222 {
22223 SFINAETrap Trap(*this);
22224 TST = CheckTemplateIdType(
22225 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
22226 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
22227 }
22228 if (TST.isNull())
22229 TST = Context.getTemplateSpecializationType(
22230 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
22231 /*CanonicalArgs=*/{},
22232 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
22233 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
22234 TST);
22235 }
22236
22237 // Overloaded expressions.
22238 case BuiltinType::Overload: {
22239 // Try to resolve a single function template specialization.
22240 // This is obligatory.
22241 ExprResult Result = E;
22243 return Result;
22244
22245 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
22246 // leaves Result unchanged on failure.
22247 Result = E;
22249 return Result;
22250
22251 // If that failed, try to recover with a call.
22252 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
22253 /*complain*/ true);
22254 return Result;
22255 }
22256
22257 // Bound member functions.
22258 case BuiltinType::BoundMember: {
22259 ExprResult result = E;
22260 const Expr *BME = E->IgnoreParens();
22261 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
22262 // Try to give a nicer diagnostic if it is a bound member that we recognize.
22264 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
22265 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
22266 if (ME->getMemberNameInfo().getName().getNameKind() ==
22268 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
22269 }
22270 tryToRecoverWithCall(result, PD,
22271 /*complain*/ true);
22272 return result;
22273 }
22274
22275 // ARC unbridged casts.
22276 case BuiltinType::ARCUnbridgedCast: {
22277 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
22278 ObjC().diagnoseARCUnbridgedCast(realCast);
22279 return realCast;
22280 }
22281
22282 // Expressions of unknown type.
22283 case BuiltinType::UnknownAny:
22284 return diagnoseUnknownAnyExpr(*this, E);
22285
22286 // Pseudo-objects.
22287 case BuiltinType::PseudoObject:
22288 return PseudoObject().checkRValue(E);
22289
22290 case BuiltinType::BuiltinFn: {
22291 // Accept __noop without parens by implicitly converting it to a call expr.
22292 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
22293 if (DRE) {
22294 auto *FD = cast<FunctionDecl>(DRE->getDecl());
22295 unsigned BuiltinID = FD->getBuiltinID();
22296 if (BuiltinID == Builtin::BI__noop) {
22297 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
22298 CK_BuiltinFnToFnPtr)
22299 .get();
22300 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
22303 }
22304
22305 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
22306 // Any use of these other than a direct call is ill-formed as of C++20,
22307 // because they are not addressable functions. In earlier language
22308 // modes, warn and force an instantiation of the real body.
22309 Diag(E->getBeginLoc(),
22311 ? diag::err_use_of_unaddressable_function
22312 : diag::warn_cxx20_compat_use_of_unaddressable_function);
22313 if (FD->isImplicitlyInstantiable()) {
22314 // Require a definition here because a normal attempt at
22315 // instantiation for a builtin will be ignored, and we won't try
22316 // again later. We assume that the definition of the template
22317 // precedes this use.
22319 /*Recursive=*/false,
22320 /*DefinitionRequired=*/true,
22321 /*AtEndOfTU=*/false);
22322 }
22323 // Produce a properly-typed reference to the function.
22324 CXXScopeSpec SS;
22325 SS.Adopt(DRE->getQualifierLoc());
22326 TemplateArgumentListInfo TemplateArgs;
22327 DRE->copyTemplateArgumentsInto(TemplateArgs);
22328 return BuildDeclRefExpr(
22329 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
22330 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
22331 DRE->getTemplateKeywordLoc(),
22332 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22333 }
22334 }
22335
22336 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
22337 return ExprError();
22338 }
22339
22340 case BuiltinType::IncompleteMatrixIdx: {
22341 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
22342 // At this point, we know there was no second [] to complete the operator.
22343 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22344 if (getLangOpts().HLSL) {
22346 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
22347 }
22348 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
22349 return ExprError();
22350 }
22351
22352 // Expressions of unknown type.
22353 case BuiltinType::ArraySection:
22354 // If we've already diagnosed something on the array section type, we
22355 // shouldn't need to do any further diagnostic here.
22356 if (!E->containsErrors())
22357 Diag(E->getBeginLoc(), diag::err_array_section_use)
22358 << cast<ArraySectionExpr>(E->IgnoreParens())->isOMPArraySection();
22359 return ExprError();
22360
22361 // Expressions of unknown type.
22362 case BuiltinType::OMPArrayShaping:
22363 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
22364
22365 case BuiltinType::OMPIterator:
22366 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
22367
22368 // Everything else should be impossible.
22369#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22370 case BuiltinType::Id:
22371#include "clang/Basic/OpenCLImageTypes.def"
22372#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22373 case BuiltinType::Id:
22374#include "clang/Basic/OpenCLExtensionTypes.def"
22375#define SVE_TYPE(Name, Id, SingletonId) \
22376 case BuiltinType::Id:
22377#include "clang/Basic/AArch64ACLETypes.def"
22378#define PPC_VECTOR_TYPE(Name, Id, Size) \
22379 case BuiltinType::Id:
22380#include "clang/Basic/PPCTypes.def"
22381#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22382#include "clang/Basic/RISCVVTypes.def"
22383#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22384#include "clang/Basic/WebAssemblyReferenceTypes.def"
22385#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22386#include "clang/Basic/AMDGPUTypes.def"
22387#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22388#include "clang/Basic/HLSLIntangibleTypes.def"
22389#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22390#include "clang/Basic/HLSLPackedTypes.def"
22391#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22392#include "clang/Basic/SPIRVTypes.def"
22393#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22394#define PLACEHOLDER_TYPE(Id, SingletonId)
22395#include "clang/AST/BuiltinTypes.def"
22396 break;
22397 }
22398
22399 llvm_unreachable("invalid placeholder type!");
22400}
22401
22403 if (E->isTypeDependent())
22404 return true;
22406 return E->getType()->isIntegralOrEnumerationType();
22407 return false;
22408}
22409
22411 ArrayRef<Expr *> SubExprs, QualType T) {
22412 if (!Context.getLangOpts().RecoveryAST)
22413 return ExprError();
22414
22415 if (isSFINAEContext())
22416 return ExprError();
22417
22418 if (T.isNull() || T->isUndeducedType() ||
22419 !Context.getLangOpts().RecoveryASTType)
22420 // We don't know the concrete type, fallback to dependent type.
22421 T = Context.DependentTy;
22422
22423 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
22424}
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
static bool isObjCPointer(const MemRegion *R)
Defines enumerations for traits support.
Defines enum values for all the target-independent builtin functions.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
Token Tok
The Token.
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static QualType getUnderlyingType(const SubRegion *R)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:50
static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy, SourceLocation OpLoc)
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, QualType FloatTy)
Test if a (constant) integer Int can be casted to floating point type FloatTy without losing precisio...
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison operators are mixed in a way t...
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
static Decl * getPredefinedExprDecl(Sema &S, DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, const Expr *LHSExpr, const Expr *RHSExpr)
DiagnoseConditionalPrecedence - Emit a warning when a conditional operator and binary operator are mi...
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Return the resulting type for the conditional operator in OpenCL (aka "ternary selection operator",...
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
@ NCCK_Block
@ NCCK_None
@ NCCK_Lambda
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, QualType scalarTy, QualType vectorEltTy, QualType vectorTy, unsigned &DiagID)
Try to convert a value of non-vector type to a vector type by converting the type to the element type...
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes,...
static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
static void SuggestParentheses(Sema &Self, SourceLocation Loc, const PartialDiagnostic &Note, SourceRange ParenRange)
SuggestParentheses - Emit a note with a fixit hint that wraps ParenRange in parentheses.
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
static bool checkForArray(const Expr *E)
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T, QualType U)
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool MayBeFunctionType(const ASTContext &Context, const Expr *E)
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type.
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, const Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
@ ConstUnknown
@ ConstVariable
@ NestedConstMember
@ ConstMember
@ ConstFunction
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union.
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn't need to call Usual...
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, const Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition SemaExpr.cpp:151
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:167
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:566
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void CheckSufficientAllocSize(Sema &S, QualType DestType, const Expr *E)
Check that a call to alloc_size function specifies sufficient space for the destination type.
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
OriginalExprKind
@ OEK_Variable
@ OEK_LValue
@ OEK_Member
static bool diagnoseFunctionLikeMacro(Sema &SemaRef, DeclarationName Name, SourceLocation TypoLoc)
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
static FieldDecl * FindFieldDeclInstantiationPattern(const ASTContext &Ctx, FieldDecl *Field)
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
static bool IsReadonlyMessage(Expr *E, Sema &S)
static std::optional< bool > isTautologicalBoundsCheck(Sema &S, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opc)
Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a pointer and size is an unsigne...
static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, ValueDecl *Var)
Create up to 4 fix-its for explicit reference and value capture of Var or default capture.
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the captured region.
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer,...
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
static bool IsArithmeticOp(BinaryOperatorKind Opc)
static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Convert complex integers to complex floats and real integers to real floats as required for complex a...
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition SemaExpr.cpp:591
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type.
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, FunctionDecl *FDecl, MultiExprArg ArgExprs)
If a builtin function has a pointer argument with no explicit address space, then it should be able t...
static bool isProvablyZeroSize(const ASTContext &Ctx, QualType T)
Determine whether the size of T is provably zero: some array dimension is provably zero or the base e...
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition SemaExpr.cpp:113
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, QualType ResultTy, Expr *E0, Expr *E1=nullptr)
Returns true if conversion between vectors of halfs and vectors of floats is needed.
static bool isObjCObjectLiteral(ExprResult &E)
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, QualType OtherIntTy)
Test if a (constant) integer Int can be casted to another integer type IntTy without losing precision...
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, NonOdrUseReason NOUR)
Walk the set of potential results of an expression and mark them all as non-odr-uses if they satisfy ...
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
static bool isScopedEnumerationType(QualType T)
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis for expressions involving.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
@ Open
The standard open() call: int open(const char *path, int oflag, ...);.
a trap message and trap category.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:124
APSInt & getInt()
Definition APValue.h:533
bool hasValue() const
Definition APValue.h:507
bool isInt() const
Definition APValue.h:509
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:1038
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:854
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CanQualType LongDoubleTy
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:850
const LangOptions & getLangOpts() const
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:972
bool typesAreBlockPointerCompatible(QualType, QualType)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType getCorrespondingSaturatedType(QualType Ty) const
CanQualType BoundMemberTy
CanQualType CharTy
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnknownAnyTy
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType ShortTy
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:969
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
QualType getCorrespondingUnsignedType(QualType T) const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
unsigned getTargetAddressSpace(LangAS AS) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
CanQualType HalfTy
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4594
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2765
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2820
Wrapper for source info for arrays.
Definition TypeLoc.h:1808
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3834
QualType getElementType() const
Definition TypeBase.h:3832
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition Expr.h:6783
Attr - This represents one attribute.
Definition Attr.h:46
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4497
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4082
Expr * getLHS() const
Definition Expr.h:4132
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4176
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2214
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4182
StringRef getOpcodeStr() const
Definition Expr.h:4148
bool isRelationalOp() const
Definition Expr.h:4177
SourceLocation getOperatorLoc() const
Definition Expr.h:4124
bool isMultiplicativeOp() const
Definition Expr.h:4167
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2167
bool isShiftOp() const
Definition Expr.h:4171
Expr * getRHS() const
Definition Expr.h:4134
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:5141
bool isBitwiseOp() const
Definition Expr.h:4174
bool isAdditiveOp() const
Definition Expr.h:4169
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4218
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4223
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:2239
Opcode getOpcode() const
Definition Expr.h:4127
bool isAssignmentOp() const
Definition Expr.h:4221
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2176
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4179
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4173
BinaryOperatorKind Opcode
Definition Expr.h:4087
A binding in a decomposition declaration.
Definition DeclCXX.h:4215
A class which contains all the information about a particular captured value.
Definition Decl.h:4816
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4810
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.cpp:5517
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition Decl.h:4892
void setBlockMissingReturnType(bool val=true)
Definition Decl.h:4949
void setIsVariadic(bool value)
Definition Decl.h:4886
SourceLocation getCaretLocation() const
Definition Decl.h:4883
void setBody(CompoundStmt *B)
Definition Decl.h:4890
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4896
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition Decl.cpp:5528
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5721
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6722
Pointer to a block type.
Definition TypeBase.h:3653
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
bool isSVEBool() const
Definition TypeBase.h:3328
Kind getKind() const
Definition TypeBase.h:3299
static CUDAKernelCallExpr * Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:2007
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const RecordType * getDetectedVirtual() const
The virtual base discovered on the path (if we are merely detecting virtuals).
CXXBasePath & front()
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2977
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition DeclCXX.cpp:3297
Represents a C++ base or member initializer.
Definition DeclCXX.h:2407
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1275
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition ExprCXX.cpp:1071
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1382
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext, Expr *RewrittenInitExpr)
Field is the non-static data member whose default initializer is used by this expression.
Definition ExprCXX.cpp:1125
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1137
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1581
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
bool isVirtual() const
Definition DeclCXX.h:2205
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2293
CXXMethodDecl * getDevirtualizedMethod(const Expr *Base, bool IsAppleKext)
If it's possible to devirtualize a call to this method, return the called function.
Definition DeclCXX.cpp:2524
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:86
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:157
SourceRange getSourceRange() const
Definition ExprCXX.h:169
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:2038
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2750
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1235
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:606
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1028
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:2087
bool hasDefinition() const
Definition DeclCXX.h:562
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:523
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:624
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
static CXXReflectExpr * Create(ASTContext &C, SourceLocation OperatorLoc, const TypeSourceInfo *TSI)
Definition ExprCXX.cpp:1983
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Represents the this expression in C++.
Definition ExprCXX.h:1159
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3204
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition Expr.cpp:1549
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3170
Expr * getCallee()
Definition Expr.h:3134
void computeDependence()
Compute and set dependence bits.
Definition Expr.h:3210
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3178
void setCallee(Expr *F)
Definition Expr.h:3136
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:3720
CastKind getCastKind() const
Definition Expr.h:3764
const char * getCastKindName() const
Definition Expr.h:3768
void setSubExpr(Expr *E)
Definition Expr.h:3772
Expr * getSubExpr()
Definition Expr.h:3770
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
unsigned getValue() const
Definition Expr.h:1649
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4892
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
QualType getElementType() const
Definition TypeBase.h:3372
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition Expr.cpp:5163
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3649
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1752
bool body_empty() const
Definition Stmt.h:1796
Stmt * body_back()
Definition Stmt.h:1820
ConditionalOperator - The ?
Definition Expr.h:4435
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3934
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1102
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition Expr.cpp:308
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition Expr.cpp:384
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1152
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
bool isImmediateInvocation() const
Definition Expr.h:1174
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4490
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4512
std::optional< LayoutKind > getLayout() const
Definition TypeBase.h:4514
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4509
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
void setTypoName(const IdentifierInfo *II)
void setTypoNNS(NestedNameSpecifier NNS)
Wrapper for source info for pointers decayed from arrays and functions.
Definition TypeLoc.h:1505
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3636
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2279
bool isRequiresExprBody() const
Definition DeclBase.h:2231
DeclContextLookupResult lookup_result
Definition DeclBase.h:2627
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:2226
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2181
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
bool isExpansionStmt() const
Definition DeclBase.h:2235
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1401
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition Expr.h:1445
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1391
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1494
void setDecl(ValueDecl *NewD)
Definition Expr.cpp:554
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition Expr.h:1449
DeclarationNameInfo getNameInfo() const
Definition Expr.h:1362
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition Expr.h:1417
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:498
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition Expr.h:1379
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1383
ValueDecl * getDecl()
Definition Expr.h:1358
SourceLocation getBeginLoc() const
Definition Expr.h:1369
SourceLocation getLocation() const
Definition Expr.h:1366
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:581
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition DeclBase.cpp:779
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:594
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition DeclBase.h:1087
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setReferenced(bool R=true)
Definition DeclBase.h:631
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2016
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1955
DeclaratorContext getContext() const
Definition DeclSpec.h:2127
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2138
bool isInvalidType() const
Definition DeclSpec.h:2769
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2385
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:574
Designation - Represent a full designation, which is a sequence of designators.
Definition Designator.h:221
const Designator & getDesignator(unsigned Idx) const
Definition Designator.h:232
unsigned getNumDesignators() const
Definition Designator.h:231
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
bool isArrayDesignator() const
Definition Designator.h:108
SourceLocation getEndLoc() const
Returns the end location of this designator.
Definition Designator.h:147
bool isArrayRangeDesignator() const
Definition Designator.h:109
bool isFieldDesignator() const
Definition Designator.h:107
const IdentifierInfo * getFieldDecl() const
Definition Designator.h:123
SourceLocation getBeginLoc() const
Returns the start location of this designator.
Definition Designator.h:140
Expr * getArrayIndex() const
Definition Designator.h:162
A little helper class used to produce diagnostics.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:992
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:761
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Represents a reference to emded data.
Definition Expr.h:5179
RAII object that enters a new expression evaluation context.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4319
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3972
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3999
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1496
This represents one expression.
Definition Expr.h:113
LValueClassification
Definition Expr.h:290
@ LV_ArrayTemporary
Definition Expr.h:301
@ LV_ClassTemporary
Definition Expr.h:300
@ LV_MemberFunction
Definition Expr.h:298
@ LV_IncompleteVoidType
Definition Expr.h:293
@ LV_Valid
Definition Expr.h:291
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:288
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:3153
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:695
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition Expr.cpp:3082
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:3131
void setType(QualType t)
Definition Expr.h:146
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:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition Expr.h:242
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3126
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3114
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3135
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3122
bool isPRValue() const
Definition Expr.h:286
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3375
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:851
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:847
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:855
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:455
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:3725
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:224
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3106
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:822
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:831
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:834
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition Expr.h:837
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:824
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:4107
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:272
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:465
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr's will refer to the same value as a comparison operand.
Definition Expr.cpp:4366
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:468
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:480
isModifiableLvalueResult
Definition Expr.h:306
@ MLV_DuplicateVectorComponents
Definition Expr.h:310
@ MLV_LValueCast
Definition Expr.h:313
@ MLV_InvalidMessageExpression
Definition Expr.h:322
@ MLV_DuplicateMatrixComponents
Definition Expr.h:311
@ MLV_ConstQualifiedField
Definition Expr.h:316
@ MLV_InvalidExpression
Definition Expr.h:312
@ MLV_IncompleteType
Definition Expr.h:314
@ MLV_Valid
Definition Expr.h:307
@ MLV_ConstQualified
Definition Expr.h:315
@ MLV_NoSetterProperty
Definition Expr.h:319
@ MLV_ArrayTemporary
Definition Expr.h:324
@ MLV_SubObjCPropertySetting
Definition Expr.h:321
@ MLV_ConstAddrSpace
Definition Expr.h:317
@ MLV_MemberFunction
Definition Expr.h:320
@ MLV_NotObjectType
Definition Expr.h:308
@ MLV_ArrayType
Definition Expr.h:318
@ MLV_ClassTemporary
Definition Expr.h:323
@ MLV_IncompleteVoidType
Definition Expr.h:309
QualType getType() const
Definition Expr.h:145
bool isOrdinaryOrBitFieldObject() const
Definition Expr.h:459
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:527
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:438
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:138
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6660
ExtVectorType - Extended vector type.
Definition TypeBase.h:4365
Represents difference between two FPOptions values.
bool isFPConstrained() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3398
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3475
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3531
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
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:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
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:103
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:1007
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1086
const Expr * getSubExpr() const
Definition Expr.h:1082
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:2059
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:2303
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3889
bool isImmediateFunction() const
Definition Decl.cpp:3382
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4066
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3804
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3907
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3052
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2570
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3660
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isImmediateEscalating() const
Definition Decl.cpp:3353
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:3064
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4169
bool isConsteval() const
Definition Decl.h:2609
size_t param_size() const
Definition Decl.h:2921
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3186
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition Decl.cpp:4079
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition Decl.h:3012
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4895
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4924
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5416
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5920
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5723
bool isParamConsumed(unsigned I) const
Definition TypeBase.h:5934
unsigned getNumParams() const
Definition TypeBase.h:5694
QualType getParamType(unsigned i) const
Definition TypeBase.h:5696
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5820
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5705
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5701
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5856
Declaration of a template function.
unsigned getNumParams() const
Definition TypeLoc.h:1747
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1753
SourceLocation getLocalRangeEnd() const
Definition TypeLoc.h:1699
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1756
SourceLocation getLocalRangeBegin() const
Definition TypeLoc.h:1691
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4723
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4794
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4651
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4612
ExtInfo getExtInfo() const
Definition TypeBase.h:4968
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4960
bool getCFIUncheckedCalleeAttr() const
Determine whether this is a function prototype that includes the cfi_unchecked_callee attribute.
Definition Type.cpp:3841
QualType getReturnType() const
Definition TypeBase.h:4952
bool getCmseNSCallAttr() const
Definition TypeBase.h:4966
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4980
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4967
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:4762
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:1751
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3897
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2106
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:626
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3602
Describes an C or C++ initializer list.
Definition Expr.h:5352
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 InitializeMemberFromDefaultMemberInitializer(FieldDecl *Member)
Create the initialization entity for a default member initializer.
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:985
Represents the declaration of a label.
Definition Decl.h:525
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1973
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition ExprCXX.cpp:1436
FPEvalMethodKind
Possible float expression evaluation method choices.
@ FEM_Extended
Use extended type for fp arithmetic.
@ FEM_Double
Use the type double for fp arithmetic.
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
@ FEM_Source
Use the declared type for fp arithmetic.
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
@ None
Permit no implicit vector bitcasts.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
bool isSignedOverflowDefined() const
bool allowArrayReturnTypes() const
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1075
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition Lexer.h:409
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments=false)
Finds the token that comes right after the given location.
Definition Lexer.cpp:1381
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition Lexer.cpp:320
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
A global _GUID constant.
Definition DeclCXX.h:4451
MS property subscript expression.
Definition ExprCXX.h:1011
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:40
bool isFunctionLike() const
Definition MacroInfo.h:202
SourceLocation getDefinitionLoc() const
Return the location that the macro was defined at.
Definition MacroInfo.h:126
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
MatrixSingleSubscriptExpr - Matrix single subscript expression for the MatrixType extension when you ...
Definition Expr.h:2839
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2909
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4435
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4454
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3597
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
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:1783
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3626
Expr * getBase() const
Definition Expr.h:3485
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1827
This represents a decl that may have a name.
Definition Decl.h:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1682
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
bool isExternallyVisible() const
Definition Decl.h:434
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:398
Represent a C++ namespace.
Definition Decl.h:593
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:1160
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1534
ivar_iterator ivar_begin() const
Definition DeclObjC.h:1459
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8031
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition ExprObjC.h:1530
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:581
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprObjC.h:627
SourceLocation getLocation() const
Definition ExprObjC.h:624
SourceLocation getOpLoc() const
Definition ExprObjC.h:632
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:611
bool isArrow() const
Definition ExprObjC.h:619
SourceLocation getEndLoc() const LLVM_READONLY
Definition ExprObjC.h:630
const Expr * getBase() const
Definition ExprObjC.h:615
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:972
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1396
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition DeclObjC.h:421
bool isClassMethod() const
Definition DeclObjC.h:437
Represents a pointer to an Objective C object.
Definition TypeBase.h:8087
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:2009
qual_range quals() const
Definition TypeBase.h:8206
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:734
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2090
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:1687
Helper class for OffsetOfExpr.
Definition Expr.h:2465
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:1198
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1164
@ CSK_Normal
Normal lookup.
Definition Overload.h:1168
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1380
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:3143
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3204
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2226
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2247
const Expr * getSubExpr() const
Definition Expr.h:2243
bool isProducedByFoldExpansion() const
Definition Expr.h:2268
Expr * getExpr(unsigned Init)
Definition Expr.h:6162
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:5013
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6160
SourceLocation getLParenLoc() const
Definition Expr.h:6179
SourceLocation getRParenLoc() const
Definition Expr.h:6180
Represents a parameter to a function.
Definition Decl.h:1820
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1853
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:2943
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition Expr.cpp:643
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition Expr.cpp:683
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
bool isMacroDefined(StringRef Id)
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6854
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8530
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8535
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:85
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3825
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:3149
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition TypeBase.h:1432
QualType withConst() const
Definition TypeBase.h:1175
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8446
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8572
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition Type.h:79
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8486
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:2926
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
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:8631
QualType getCanonicalType() const
Definition TypeBase.h:8498
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8540
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:3168
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1195
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition TypeBase.h:8638
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8519
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1839
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
bool isCanonical() const
Definition TypeBase.h:8503
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1325
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2914
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:8611
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8478
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition Type.h:73
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
void removeObjCLifetime()
Definition TypeBase.h:552
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:728
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:709
void removeAddressSpace()
Definition TypeBase.h:597
void setAddressSpace(LangAS space)
Definition TypeBase.h:592
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:534
Qualifiers withoutObjCGCAttr() const
Definition TypeBase.h:529
LangAS getAddressSpace() const
Definition TypeBase.h:572
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:751
Represents a struct/union/class.
Definition Decl.h:4460
bool hasFlexibleArrayMember() const
Definition Decl.h:4493
field_iterator field_end() const
Definition Decl.h:4666
field_range fields() const
Definition Decl.h:4663
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4648
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition Expr.cpp:5507
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:3678
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:414
bool Contains(const Scope &rhs) const
Returns if rhs has a higher scope depth than this.
Definition Scope.h:623
bool isInCFunctionScope() const
isInObjcMethodScope - Return true if this scope is, or is contained, in an C function body.
Definition Scope.h:434
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:473
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
Expr * ExpandAMDGPUPredicateBuiltIn(Expr *CE)
Expand a valid use of the feature identification builtins into its corresponding sequence of instruct...
void AddPotentiallyUnguardedBuiltinUser(FunctionDecl *FD)
Diagnose unguarded usages of AMDGPU builtins and recommend guarding with __builtin_amdgcn_is_invocabl...
bool checkSVETypeSupport(QualType Ty, SourceLocation Loc, const FunctionDecl *FD, const llvm::StringMap< bool > &FeatureMap)
Definition SemaARM.cpp:1913
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void RecordImplicitHostDeviceFuncUsedByDevice(const FunctionDecl *FD)
Record FD if it is a CUDA/HIP implicit host device function used on device side in device compilation...
Definition SemaCUDA.cpp:840
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:211
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition SemaCUDA.h:121
@ CVT_Both
Emitted on host side only.
Definition SemaCUDA.h:122
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
bool canHaveOverloadedBinOp(QualType Ty, BinaryOperatorKind Opc)
std::optional< ExprResult > tryPerformConstantBufferConversion(Expr *BaseExpr)
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition SemaObjC.h:859
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.
void checkBuiltinReadImage(FunctionDecl *FDecl, CallExpr *Call)
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:385
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
const ValueDecl * getOpenMPDeclareMapperVarName() const
ExprResult checkAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
ExprResult checkIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
ExprResult checkRValue(Expr *E)
void CheckDeviceUseOfDecl(NamedDecl *ND, SourceLocation Loc)
Issues a deferred diagnostic if use of the declaration designated by 'ND' is invalid in a device cont...
Definition SemaSYCL.cpp:225
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8549
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12623
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12667
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7819
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:863
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1474
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:8306
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13781
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1165
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:8352
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8274
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:971
bool isAttrContext() const
Definition Sema.h:7043
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
ExprResult BuildBoolLiteral(SourceLocation Loc, bool Value)
Build a boolean-typed literal expression.
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:8345
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9444
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9483
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9452
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:418
ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx, SourceLocation RBLoc)
ExprResult ActOnConstantExpression(ExprResult Res)
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool areVectorTypesSameSize(QualType srcType, QualType destType)
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition Sema.h:1559
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:1275
SemaCUDA & CUDA()
Definition Sema.h:1499
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:7940
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7942
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7941
bool needsRebuildOfDefaultArgOrInit() const
Definition Sema.h:8294
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:8432
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1268
Preprocessor & getPreprocessor() const
Definition Sema.h:934
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7021
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2474
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:8421
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
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:6850
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
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:2107
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 ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, const Designation &Desig, SourceLocation RParenLoc)
SemaSYCL & SYCL()
Definition Sema.h:1584
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:7033
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:1769
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:847
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
QualType CheckMatrixCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
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:1332
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:8261
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E)
Perform Bounds Safety semantic checks for uses of invalid uses counted_by or counted_by_or_null point...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:228
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
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:1544
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:3053
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:768
bool isImmediateFunctionContext() const
Definition Sema.h:8286
ASTContext & getASTContext() const
Definition Sema.h:935
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1077
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:778
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:778
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition SemaExpr.cpp:897
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)
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, const Designation &Desig, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1236
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1774
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:11586
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:515
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:8321
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition SemaStmt.cpp:406
FPOptions & getCurFPFeatures()
Definition Sema.h:930
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8415
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:278
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_Block
Block expression.
Definition Sema.h:14640
const LangOptions & getLangOpts() const
Definition Sema.h:928
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void DiagnoseInvalidJumps(Stmt *Body)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2605
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:1549
ReuseLambdaContextDecl_t
Definition Sema.h:7112
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false)
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
Preprocessor & PP
Definition Sema.h:1331
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:2280
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
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:1330
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2720
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:966
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6594
SemaHLSL & HLSL()
Definition Sema.h:1509
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:15910
ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr)
Prepare SplattedExpr for a matrix splat operation, adding implicit casts if necessary.
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:217
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5395
ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc, TypeSourceInfo *TSI)
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:79
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:7057
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6624
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:14185
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:885
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:1367
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)
ExprResult BuildCXXAggregateDefaultInitExpr(SourceLocation Loc, FieldDecl *Field, const InitializedEntity &MemberEntity)
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:7054
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2457
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation)
type checking for vector binary operators.
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:648
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)
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:8157
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2675
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1472
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:12694
SemaOpenCL & OpenCL()
Definition Sema.h:1554
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:14194
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8282
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1748
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)
ExprResult CheckVarOrConceptTemplateTemplateId(const DeclarationNameInfo &NameInfo, TemplateName Template, const TemplateArgumentListInfo *TemplateArgs)
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition Sema.h:6853
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:14129
SourceManager & getSourceManager() const
Definition Sema.h:933
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
bool CheckVecStepExpr(Expr *E)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks, ObjCInterfaceDecl *ClassReceiver)
CallExpr::ADLCallKind ADLCallKind
Definition Sema.h:7566
@ NTCUK_Destruct
Definition Sema.h:4206
@ NTCUK_Copy
Definition Sema.h:4207
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8431
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:2505
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:6851
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool isSFINAEContext() const
Definition Sema.h:13872
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15673
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:2660
bool isConstantEvaluatedContext() const
Definition Sema.h:2691
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:1333
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4772
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:7061
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:127
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1372
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14177
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:6795
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6817
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6807
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6822
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6812
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6832
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6801
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6827
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6842
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:1291
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:8272
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:8418
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:1335
@ TemplateNameIsRequired
Definition Sema.h:11563
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:797
ExprResult BuildCXXCtorDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
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:1334
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:929
FPOptions CurFPFeatures
Definition Sema.h:1328
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:524
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types?
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc, bool IsExplicit)
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
friend class InitializationSequence
Definition Sema.h:1614
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:6628
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:647
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:2263
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
QualType PreferredConditionType(ConditionKind K) const
Definition Sema.h:8080
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9497
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9503
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9495
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9500
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9511
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9507
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:6509
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:14173
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:7926
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 ...
SemaPseudoObject & PseudoObject()
Definition Sema.h:1569
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2651
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:8298
SemaARM & ARM()
Definition Sema.h:1479
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
SmallVector< std::pair< Scope *, SourceLocation >, 2 > CurrentDefer
Stack of '_Defer' statements that are currently being parsed, as well as the locations of their '_Def...
Definition Sema.h:11093
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:8762
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:5070
SourceLocation getBeginLoc() const
Definition Expr.h:5115
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition Expr.h:5111
SourceLocation getEndLoc() const
Definition Expr.h:5116
SourceLocIdentKind getIdentKind() const
Definition Expr.h:5090
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.
This class handles loading and caching of source files into memory.
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:301
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:312
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false, bool AllowRelaxedEval=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
void setToType(unsigned Idx, QualType T)
Definition Overload.h:399
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4639
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:367
StmtClass getStmtClass() const
Definition Stmt.h:1505
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1819
unsigned getLength() const
Definition Expr.h:1944
uint32_t getCodeUnit(size_t I) const
Return the code unit at the given position.
Definition Expr.h:1906
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:1198
StringRef getString() const
Definition Expr.h:1887
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3953
bool isUnion() const
Definition Decl.h:4063
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
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:729
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:341
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.
PackIndexingTemplateStorage * getAsPackIndexingTemplate() const
Retrieve the pack-index-template-name storage, if any.
A template parameter object.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
void setKind(tok::TokenKind K)
Definition Token.h:100
void startToken()
Reset all flags to cleared.
Definition Token.h:187
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
EnsureImmediateInvocationInDefaultArgs & getDerived()
Represents a declaration of a type.
Definition Decl.h:3648
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3682
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:160
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2766
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8417
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8428
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2549
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition TypeBase.h:9140
bool isBlockPointerType() const
Definition TypeBase.h:8703
bool isVoidType() const
Definition TypeBase.h:9068
bool isBooleanType() const
Definition TypeBase.h:9209
bool isObjCBuiltinType() const
Definition TypeBase.h:8913
bool isMFloat8Type() const
Definition TypeBase.h:9097
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:2120
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9259
bool isIncompleteArrayType() const
Definition TypeBase.h:8790
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:9044
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:855
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2297
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:9239
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:2243
bool isVoidPointerType() const
Definition Type.cpp:843
const ComplexType * getAsComplexIntegerType() const
Definition Type.cpp:876
bool isArrayType() const
Definition TypeBase.h:8782
bool isCharType() const
Definition Type.cpp:2317
bool isFunctionPointerType() const
Definition TypeBase.h:8750
bool isArithmeticType() const
Definition Type.cpp:2548
bool isConstantMatrixType() const
Definition TypeBase.h:8850
bool isPointerType() const
Definition TypeBase.h:8683
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9116
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2793
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9366
bool isReferenceType() const
Definition TypeBase.h:8707
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:9160
bool isEnumeralType() const
Definition TypeBase.h:8814
bool isScalarType() const
Definition TypeBase.h:9178
bool isVariableArrayType() const
Definition TypeBase.h:8794
bool isSizelessBuiltinType() const
Definition Type.cpp:2749
bool isClkEventT() const
Definition TypeBase.h:8935
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2827
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2280
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8883
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:883
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9194
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2502
bool isExtVectorType() const
Definition TypeBase.h:8826
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2353
bool isExtVectorBoolType() const
Definition TypeBase.h:8830
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2866
bool isImageType() const
Definition TypeBase.h:8947
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition TypeBase.h:9062
bool isPipeType() const
Definition TypeBase.h:8954
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2871
bool isBitIntType() const
Definition TypeBase.h:8958
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9037
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8806
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isAnyComplexType() const
Definition TypeBase.h:8818
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9132
bool isHalfType() const
Definition TypeBase.h:9076
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9148
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2580
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9050
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2434
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2777
bool isQueueT() const
Definition TypeBase.h:8939
bool isMemberPointerType() const
Definition TypeBase.h:8764
bool isAtomicType() const
Definition TypeBase.h:8875
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9222
bool isObjCIdType() const
Definition TypeBase.h:8895
bool isMatrixType() const
Definition TypeBase.h:8846
bool isOverflowBehaviorType() const
Definition TypeBase.h:8854
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:2881
bool isComplexIntegerType() const
Definition Type.cpp:861
bool isUnscopedEnumerationType() const
Definition Type.cpp:2310
bool isObjCObjectType() const
Definition TypeBase.h:8866
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition Type.cpp:5539
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9352
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5628
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9215
bool isHLSLResourceRecord() const
Definition Type.cpp:5713
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isDoubleType() const
Definition TypeBase.h:9089
bool isMetaInfoType() const
Definition TypeBase.h:9072
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2653
bool isFunctionType() const
Definition TypeBase.h:8679
bool isObjCObjectPointerType() const
Definition TypeBase.h:8862
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2523
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:9174
bool isVectorType() const
Definition TypeBase.h:8822
bool isObjCQualifiedClassType() const
Definition TypeBase.h:8889
bool isObjCClassType() const
Definition TypeBase.h:8901
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2531
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2814
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
@ STK_FloatingComplex
Definition TypeBase.h:2845
@ STK_ObjCObjectPointer
Definition TypeBase.h:2839
@ STK_IntegralComplex
Definition TypeBase.h:2844
@ STK_MemberPointer
Definition TypeBase.h:2840
bool isFloatingType() const
Definition Type.cpp:2515
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:2458
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:3009
bool isAnyPointerType() const
Definition TypeBase.h:8691
bool isRealType() const
Definition Type.cpp:2537
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isSubscriptableVectorType() const
Definition TypeBase.h:8842
bool isSamplerT() const
Definition TypeBase.h:8927
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
bool isNullPtrType() const
Definition TypeBase.h:9109
bool isRecordType() const
Definition TypeBase.h:8810
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5717
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition Type.cpp:866
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5325
bool isUnicodeCharacterType() const
Definition Type.cpp:2373
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2570
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
std::string getAsString(const LangOptions &LO) const
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2669
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
void setSubExpr(Expr *E)
Definition Expr.h:2330
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition Expr.h:2333
Expr * getSubExpr() const
Definition Expr.h:2329
Opcode getOpcode() const
Definition Expr.h:2324
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1462
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2384
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:5198
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4508
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1042
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1130
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1124
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1094
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3373
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:464
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4180
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition ExprCXX.cpp:1713
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:1675
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:645
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:5001
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
void setType(QualType newType)
Definition Decl.h:725
QualType getType() const
Definition Decl.h:724
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5652
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3695
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:933
bool hasInit() const
Definition Decl.cpp:2378
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2237
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1603
bool isInternalLinkageFileVar() const
Returns true if this is a file-scope variable with internal linkage.
Definition Decl.h:1223
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1307
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1248
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:2466
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:2877
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1576
const Expr * getInit() const
Definition Decl.h:1392
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1239
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1191
@ TLS_None
Not a TLS variable.
Definition Decl.h:953
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1319
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2355
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:2508
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:2770
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1286
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:2749
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2868
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Expr * getSizeExpr() const
Definition TypeBase.h:4078
Represents a GCC generic vector type.
Definition TypeBase.h:4273
unsigned getNumElements() const
Definition TypeBase.h:4288
VectorKind getVectorKind() const
Definition TypeBase.h:4293
QualType getElementType() const
Definition TypeBase.h:4287
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:791
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition ScopeInfo.h:797
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition ScopeInfo.h:801
ValueDecl * getVariable() const
Definition ScopeInfo.h:676
bool isBlockCapture() const
Definition ScopeInfo.h:657
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:687
void markUsed(bool IsODRUse)
Definition ScopeInfo.h:669
bool isInvalid() const
Definition ScopeInfo.h:662
bool isThisCapture() const
Definition ScopeInfo.h:650
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition ScopeInfo.h:696
bool isCopyCapture() const
Definition ScopeInfo.h:655
bool isNested() const
Definition ScopeInfo.h:660
Retains information about a captured region.
Definition ScopeInfo.h:817
unsigned short CapRegionKind
The kind of captured region.
Definition ScopeInfo.h:832
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:746
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:733
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:729
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:722
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:709
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition ScopeInfo.h:719
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:759
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition ScopeInfo.h:715
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:756
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:738
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition ScopeInfo.h:772
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:1093
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:494
llvm::SmallVector< AddrLabelExpr *, 4 > AddrLabels
The set of GNU address of label extension "&&label".
Definition ScopeInfo.h:251
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:887
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:995
void addPotentialThisCapture(SourceLocation Loc)
Definition ScopeInfo.h:1001
llvm::SmallPtrSet< VarDecl *, 4 > CUDAPotentialODRUsedVars
Variables that are potentially ODR-used in CUDA/HIP.
Definition ScopeInfo.h:956
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:872
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:895
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:880
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:875
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:101
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
Top level wrappers for InstallAPI frontend operations.
const char * getTraitSpelling(TypeTrait T) LLVM_READONLY
Return the spelling of the trait T. Never null.
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:216
@ 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:507
bool isTargetAddressSpace(LangAS AS)
CUDAFunctionTarget
Definition Cuda.h:65
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
TryCaptureKind
Definition Sema.h:647
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition Sema.h:655
@ BitwiseOp
A bitwise operation.
Definition Sema.h:659
@ Arithmetic
An arithmetic operation.
Definition Sema.h:657
@ Conditional
A conditional (?:) operator.
Definition Sema.h:663
@ CompAssign
A compound assignment expression.
Definition Sema.h:665
@ Comparison
A comparison.
Definition Sema.h:661
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:350
@ Nullable
Values of this type can be null.
Definition Specifiers.h:354
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:359
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:352
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:153
@ OK_VectorComponent
A vector component is an element or range of elements of a vector.
Definition Specifiers.h:161
@ 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:165
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition Specifiers.h:158
@ OK_MatrixComponent
A matrix component is a single element or range of elements of a matrix.
Definition Specifiers.h:173
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:1036
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1034
@ AS_none
Definition Specifiers.h:131
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:255
@ SC_Register
Definition Specifiers.h:261
@ SC_None
Definition Specifiers.h:254
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
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:906
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:205
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:683
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:706
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:781
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:698
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:753
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:743
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:770
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:757
@ CompatibleOBTDiscards
CompatibleOBTDiscards - Assignment discards overflow behavior.
Definition Sema.h:777
@ IncompatibleOBTKinds
IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType kinds, e....
Definition Sema.h:774
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:690
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:732
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:727
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:766
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:685
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:717
@ IncompatiblePointerDiscardsOverflowBehavior
IncompatiblePointerDiscardsOverflowBehavior - The assignment discards overflow behavior annotations b...
Definition Sema.h:737
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:694
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:702
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:749
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:711
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:723
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:761
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
@ AR_Unavailable
Definition DeclBase.h:76
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Decl.h:2030
@ None
This is not a defaultable comparison operator.
Definition Decl.h:2032
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:649
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
VarArgKind
Definition Sema.h:670
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
AssignmentAction
Definition Sema.h:217
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:515
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:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
@ CA_ToLiteralEncoding
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:279
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:285
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:293
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:282
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:289
StringLiteralKind
Definition Expr.h:1783
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:192
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:206
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_X86VectorCall
Definition Specifiers.h:287
@ CC_X86StdCall
Definition Specifiers.h:284
@ CC_X86FastCall
Definition Specifiers.h:285
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4243
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4252
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4237
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4240
@ Neon
is ARM Neon vector
Definition TypeBase.h:4246
@ Generic
not a target-specific vector type
Definition TypeBase.h:4234
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4258
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4261
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4255
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:5057
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6035
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:1775
PredefinedIdentKind
Definition Expr.h:2033
@ Implicit
An implicit conversion.
Definition Sema.h:434
OptionalUnsigned< NullabilityKind > NullabilityKindOrNone
Definition Specifiers.h:366
CharacterLiteralKind
Definition Expr.h:1623
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:177
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition Specifiers.h:187
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:181
@ NOUR_None
This is an odr-use.
Definition Specifiers.h:179
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition Specifiers.h:184
#define false
Definition stdbool.h:26
ExprResult TransformSourceLocExpr(SourceLocExpr *E)
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
ExprResult TransformBlockExpr(BlockExpr *E)
ExprResult TransformLambdaExpr(LambdaExpr *E)
bool VisitSourceLocExpr(SourceLocExpr *E) override
bool VisitCXXConstructExpr(CXXConstructExpr *E) override
bool VisitCallExpr(CallExpr *E) override
const ASTContext & Context
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override
bool VisitLambdaExpr(LambdaExpr *E) override
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override
ImmediateCallVisitor(const ASTContext &Ctx)
Represents an element in a path from a derived class to a base class.
The class facilities generation and storage of conversion FixIts.
OverloadFixItKind Kind
The type of fix applied.
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
Stores data related to a single embed directive.
Definition Expr.h:5146
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
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:650
bool DiagEmitted
Whether any diagnostic has been emitted.
Definition Expr.h:634
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition Expr.h:630
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:625
SmallVectorImpl< PartialDiagnosticAt > * ExtendedDiag
Location where we spot ptr to int cast or null subobject while evaluating constant expression in MS c...
Definition Expr.h:654
Extra information about a function prototype.
Definition TypeBase.h:5501
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13300
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6857
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6892
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6943
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6877
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6897
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:6905
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6901
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6911
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:6872
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6919
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6862
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6859
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6866
Abstract class used to diagnose incomplete types.
Definition Sema.h:8359
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.