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 // Under the MS ABI, lock down the inheritance model now.
726 if (T->isMemberPointerType() &&
727 Context.getTargetInfo().getCXXABI().isMicrosoft())
728 (void)isCompleteType(E->getExprLoc(), T);
729
731 if (Res.isInvalid())
732 return Res;
733 E = Res.get();
734
735 // Loading a __weak object implicitly retains the value, so we need a cleanup to
736 // balance that.
738 Cleanup.setExprNeedsCleanups(true);
739
741 Cleanup.setExprNeedsCleanups(true);
742
744 return ExprError();
745
746 // C++ [conv.lval]p3:
747 // If T is cv std::nullptr_t, the result is a null pointer constant.
748 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
749 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
751
752 // C11 6.3.2.1p2:
753 // ... if the lvalue has atomic type, the value has the non-atomic version
754 // of the type of the lvalue ...
755 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
756 T = Atomic->getValueType().getUnqualifiedType();
757 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
758 nullptr, VK_PRValue, FPOptionsOverride());
759 }
760
761 return Res;
762}
763
766 if (Res.isInvalid())
767 return ExprError();
768 Res = DefaultLvalueConversion(Res.get());
769 if (Res.isInvalid())
770 return ExprError();
771 return Res;
772}
773
775 QualType Ty = E->getType();
776 ExprResult Res = E;
777 // Only do implicit cast for a function type, but not for a pointer
778 // to function type.
779 if (Ty->isFunctionType()) {
780 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
781 CK_FunctionToPointerDecay);
782 if (Res.isInvalid())
783 return ExprError();
784 }
785 Res = DefaultLvalueConversion(Res.get());
786 if (Res.isInvalid())
787 return ExprError();
788 return Res.get();
789}
790
791/// UsualUnaryFPConversions - Promotes floating-point types according to the
792/// current language semantics.
794 QualType Ty = E->getType();
795 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
796
797 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
798 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
799 (getLangOpts().getFPEvalMethod() !=
801 PP.getLastFPEvalPragmaLocation().isValid())) {
802 switch (EvalMethod) {
803 default:
804 llvm_unreachable("Unrecognized float evaluation method");
805 break;
807 llvm_unreachable("Float evaluation method should be set by now");
808 break;
810 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
811 // Widen the expression to double.
812 return Ty->isComplexType()
814 Context.getComplexType(Context.DoubleTy),
815 CK_FloatingComplexCast)
816 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
817 break;
819 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
820 // Widen the expression to long double.
821 return Ty->isComplexType()
823 E, Context.getComplexType(Context.LongDoubleTy),
824 CK_FloatingComplexCast)
825 : ImpCastExprToType(E, Context.LongDoubleTy,
826 CK_FloatingCast);
827 break;
828 }
829 }
830
831 // Half FP have to be promoted to float unless it is natively supported
832 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
833 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
834
835 return E;
836}
837
838/// UsualUnaryConversions - Performs various conversions that are common to most
839/// operators (C99 6.3). The conversions of array and function types are
840/// sometimes suppressed. For example, the array->pointer conversion doesn't
841/// apply if the array is an argument to the sizeof or address (&) operators.
842/// In these instances, this routine should *not* be called.
844 // First, convert to an r-value.
846 if (Res.isInvalid())
847 return ExprError();
848
849 // Promote floating-point types.
850 Res = UsualUnaryFPConversions(Res.get());
851 if (Res.isInvalid())
852 return ExprError();
853 E = Res.get();
854
855 QualType Ty = E->getType();
856 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
857
858 // Try to perform integral promotions if the object has a theoretically
859 // promotable type.
861 // C99 6.3.1.1p2:
862 //
863 // The following may be used in an expression wherever an int or
864 // unsigned int may be used:
865 // - an object or expression with an integer type whose integer
866 // conversion rank is less than or equal to the rank of int
867 // and unsigned int.
868 // - A bit-field of type _Bool, int, signed int, or unsigned int.
869 //
870 // If an int can represent all values of the original type, the
871 // value is converted to an int; otherwise, it is converted to an
872 // unsigned int. These are called the integer promotions. All
873 // other types are unchanged by the integer promotions.
874
875 QualType PTy = Context.isPromotableBitField(E);
876 if (!PTy.isNull()) {
877 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
878 return E;
879 }
880 if (Context.isPromotableIntegerType(Ty)) {
881 QualType PT = Context.getPromotedIntegerType(Ty);
882 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
883 return E;
884 }
885 }
886 return E;
887}
888
889/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
890/// do not have a prototype. Arguments that have type float or __fp16
891/// are promoted to double. All other argument types are converted by
892/// UsualUnaryConversions().
894 QualType Ty = E->getType();
895 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
896
898 if (Res.isInvalid())
899 return ExprError();
900 E = Res.get();
901
902 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
903 // promote to double.
904 // Note that default argument promotion applies only to float (and
905 // half/fp16); it does not apply to _Float16.
906 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
907 if (BTy && (BTy->getKind() == BuiltinType::Half ||
908 BTy->getKind() == BuiltinType::Float)) {
909 if (getLangOpts().OpenCL &&
910 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
911 if (BTy->getKind() == BuiltinType::Half) {
912 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
913 }
914 } else {
915 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
916 }
917 }
918 if (BTy &&
919 getLangOpts().getExtendIntArgs() ==
921 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
922 Context.getTypeSizeInChars(BTy) <
923 Context.getTypeSizeInChars(Context.LongLongTy)) {
924 E = (Ty->isUnsignedIntegerType())
925 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
926 .get()
927 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
928 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
929 "Unexpected typesize for LongLongTy");
930 }
931
932 // C++ performs lvalue-to-rvalue conversion as a default argument
933 // promotion, even on class types, but note:
934 // C++11 [conv.lval]p2:
935 // When an lvalue-to-rvalue conversion occurs in an unevaluated
936 // operand or a subexpression thereof the value contained in the
937 // referenced object is not accessed. Otherwise, if the glvalue
938 // has a class type, the conversion copy-initializes a temporary
939 // of type T from the glvalue and the result of the conversion
940 // is a prvalue for the temporary.
941 // FIXME: add some way to gate this entire thing for correctness in
942 // potentially potentially evaluated contexts.
946 E->getExprLoc(), E);
947 if (Temp.isInvalid())
948 return ExprError();
949 E = Temp.get();
950 }
951
952 // C++ [expr.call]p7, per CWG722:
953 // An argument that has (possibly cv-qualified) type std::nullptr_t is
954 // converted to void* ([conv.ptr]).
955 // (This does not apply to C23 nullptr)
957 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
958
959 return E;
960}
961
963 if (Ty->isIncompleteType()) {
964 // C++11 [expr.call]p7:
965 // After these conversions, if the argument does not have arithmetic,
966 // enumeration, pointer, pointer to member, or class type, the program
967 // is ill-formed.
968 //
969 // Since we've already performed null pointer conversion, array-to-pointer
970 // decay and function-to-pointer decay, the only such type in C++ is cv
971 // void. This also handles initializer lists as variadic arguments.
972 if (Ty->isVoidType())
973 return VarArgKind::Invalid;
974
975 if (Ty->isObjCObjectType())
976 return VarArgKind::Invalid;
977 return VarArgKind::Valid;
978 }
979
981 return VarArgKind::Invalid;
982
983 if (Context.getTargetInfo().getTriple().isWasm() &&
985 return VarArgKind::Invalid;
986 }
987
988 if (Ty.isCXX98PODType(Context))
989 return VarArgKind::Valid;
990
991 // C++11 [expr.call]p7:
992 // Passing a potentially-evaluated argument of class type (Clause 9)
993 // having a non-trivial copy constructor, a non-trivial move constructor,
994 // or a non-trivial destructor, with no corresponding parameter,
995 // is conditionally-supported with implementation-defined semantics.
998 if (!Record->hasNonTrivialCopyConstructor() &&
999 !Record->hasNonTrivialMoveConstructor() &&
1000 !Record->hasNonTrivialDestructor())
1002
1003 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1004 return VarArgKind::Valid;
1005
1006 if (Ty->isObjCObjectType())
1007 return VarArgKind::Invalid;
1008
1009 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1010 return VarArgKind::Valid;
1011
1012 if (getLangOpts().MSVCCompat)
1014
1015 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1016 return VarArgKind::Valid;
1017
1018 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1019 // permitted to reject them. We should consider doing so.
1020 return VarArgKind::Undefined;
1021}
1022
1024 // Don't allow one to pass an Objective-C interface to a vararg.
1025 const QualType &Ty = E->getType();
1026 VarArgKind VAK = isValidVarArgType(Ty);
1027
1028 // Complain about passing non-POD types through varargs.
1029 switch (VAK) {
1032 E->getBeginLoc(), nullptr,
1033 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1034 [[fallthrough]];
1035 case VarArgKind::Valid:
1036 if (Ty->isRecordType()) {
1037 // This is unlikely to be what the user intended. If the class has a
1038 // 'c_str' member function, the user probably meant to call that.
1039 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1040 PDiag(diag::warn_pass_class_arg_to_vararg)
1041 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1042 }
1043 break;
1044
1047 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1048 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1049 << getLangOpts().CPlusPlus11 << Ty << CT);
1050 break;
1051
1054 Diag(E->getBeginLoc(),
1055 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1056 << Ty << CT;
1057 else if (Ty->isObjCObjectType())
1058 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1059 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1060 << Ty << CT);
1061 else
1062 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1063 << isa<InitListExpr>(E) << Ty << CT;
1064 break;
1065 }
1066}
1067
1069 FunctionDecl *FDecl) {
1070 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1071 // Strip the unbridged-cast placeholder expression off, if applicable.
1072 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1073 (CT == VariadicCallType::Method ||
1074 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1075 E = ObjC().stripARCUnbridgedCast(E);
1076
1077 // Otherwise, do normal placeholder checking.
1078 } else {
1079 ExprResult ExprRes = CheckPlaceholderExpr(E);
1080 if (ExprRes.isInvalid())
1081 return ExprError();
1082 E = ExprRes.get();
1083 }
1084 }
1085
1087 if (ExprRes.isInvalid())
1088 return ExprError();
1089
1090 // Copy blocks to the heap.
1091 if (ExprRes.get()->getType()->isBlockPointerType())
1092 maybeExtendBlockObject(ExprRes);
1093
1094 E = ExprRes.get();
1095
1096 // Diagnostics regarding non-POD argument types are
1097 // emitted along with format string checking in Sema::CheckFunctionCall().
1099 // Turn this into a trap.
1100 CXXScopeSpec SS;
1101 SourceLocation TemplateKWLoc;
1102 UnqualifiedId Name;
1103 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1104 E->getBeginLoc());
1105 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1106 /*HasTrailingLParen=*/true,
1107 /*IsAddressOfOperand=*/false);
1108 if (TrapFn.isInvalid())
1109 return ExprError();
1110
1111 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1112 E->getEndLoc());
1113 if (Call.isInvalid())
1114 return ExprError();
1115
1116 ExprResult Comma =
1117 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1118 if (Comma.isInvalid())
1119 return ExprError();
1120 return Comma.get();
1121 }
1122
1123 if (!getLangOpts().CPlusPlus &&
1125 diag::err_call_incomplete_argument))
1126 return ExprError();
1127
1128 return E;
1129}
1130
1131/// Convert complex integers to complex floats and real integers to
1132/// real floats as required for complex arithmetic. Helper function of
1133/// UsualArithmeticConversions()
1134///
1135/// \return false if the integer expression is an integer type and is
1136/// successfully converted to the (complex) float type.
1138 ExprResult &ComplexExpr,
1139 QualType IntTy,
1140 QualType ComplexTy,
1141 bool SkipCast) {
1142 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1143 if (SkipCast) return false;
1144 if (IntTy->isIntegerType()) {
1145 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1146 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1147 } else {
1148 assert(IntTy->isComplexIntegerType());
1149 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1150 CK_IntegralComplexToFloatingComplex);
1151 }
1152 return false;
1153}
1154
1155// This handles complex/complex, complex/float, or float/complex.
1156// When both operands are complex, the shorter operand is converted to the
1157// type of the longer, and that is the type of the result. This corresponds
1158// to what is done when combining two real floating-point operands.
1159// The fun begins when size promotion occur across type domains.
1160// From H&S 6.3.4: When one operand is complex and the other is a real
1161// floating-point type, the less precise type is converted, within it's
1162// real or complex domain, to the precision of the other type. For example,
1163// when combining a "long double" with a "double _Complex", the
1164// "double _Complex" is promoted to "long double _Complex".
1166 QualType ShorterType,
1167 QualType LongerType,
1168 bool PromotePrecision) {
1169 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1171 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1172
1173 if (PromotePrecision) {
1174 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1175 Shorter =
1176 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1177 } else {
1178 if (LongerIsComplex)
1179 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1180 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1181 }
1182 }
1183 return Result;
1184}
1185
1186/// Handle arithmetic conversion with complex types. Helper function of
1187/// UsualArithmeticConversions()
1189 ExprResult &RHS, QualType LHSType,
1190 QualType RHSType, bool IsCompAssign) {
1191 // Handle (complex) integer types.
1192 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1193 /*SkipCast=*/false))
1194 return LHSType;
1195 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1196 /*SkipCast=*/IsCompAssign))
1197 return RHSType;
1198
1199 // Compute the rank of the two types, regardless of whether they are complex.
1200 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1201 if (Order < 0)
1202 // Promote the precision of the LHS if not an assignment.
1203 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1204 /*PromotePrecision=*/!IsCompAssign);
1205 // Promote the precision of the RHS unless it is already the same as the LHS.
1206 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1207 /*PromotePrecision=*/Order > 0);
1208}
1209
1210/// Handle arithmetic conversion from integer to float. Helper function
1211/// of UsualArithmeticConversions()
1213 ExprResult &IntExpr,
1214 QualType FloatTy, QualType IntTy,
1215 bool ConvertFloat, bool ConvertInt) {
1216 if (IntTy->isIntegerType()) {
1217 if (ConvertInt)
1218 // Convert intExpr to the lhs floating point type.
1219 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1220 CK_IntegralToFloating);
1221 return FloatTy;
1222 }
1223
1224 // Convert both sides to the appropriate complex float.
1225 assert(IntTy->isComplexIntegerType());
1226 QualType result = S.Context.getComplexType(FloatTy);
1227
1228 // _Complex int -> _Complex float
1229 if (ConvertInt)
1230 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1231 CK_IntegralComplexToFloatingComplex);
1232
1233 // float -> _Complex float
1234 if (ConvertFloat)
1235 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1236 CK_FloatingRealToComplex);
1237
1238 return result;
1239}
1240
1241/// Handle arithmethic conversion with floating point types. Helper
1242/// function of UsualArithmeticConversions()
1244 ExprResult &RHS, QualType LHSType,
1245 QualType RHSType, bool IsCompAssign) {
1246 bool LHSFloat = LHSType->isRealFloatingType();
1247 bool RHSFloat = RHSType->isRealFloatingType();
1248
1249 // N1169 4.1.4: If one of the operands has a floating type and the other
1250 // operand has a fixed-point type, the fixed-point operand
1251 // is converted to the floating type [...]
1252 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1253 if (LHSFloat)
1254 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1255 else if (!IsCompAssign)
1256 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1257 return LHSFloat ? LHSType : RHSType;
1258 }
1259
1260 // If we have two real floating types, convert the smaller operand
1261 // to the bigger result.
1262 if (LHSFloat && RHSFloat) {
1263 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1264 if (order > 0) {
1265 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1266 return LHSType;
1267 }
1268
1269 assert(order < 0 && "illegal float comparison");
1270 if (!IsCompAssign)
1271 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1272 return RHSType;
1273 }
1274
1275 if (LHSFloat) {
1276 // Half FP has to be promoted to float unless it is natively supported
1277 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1278 LHSType = S.Context.FloatTy;
1279
1280 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1281 /*ConvertFloat=*/!IsCompAssign,
1282 /*ConvertInt=*/ true);
1283 }
1284 assert(RHSFloat);
1285 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1286 /*ConvertFloat=*/ true,
1287 /*ConvertInt=*/!IsCompAssign);
1288}
1289
1290/// Diagnose attempts to convert between __float128, __ibm128 and
1291/// long double if there is no support for such conversion.
1292/// Helper function of UsualArithmeticConversions().
1293static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1294 QualType RHSType) {
1295 // No issue if either is not a floating point type.
1296 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1297 return false;
1298
1299 // No issue if both have the same 128-bit float semantics.
1300 auto *LHSComplex = LHSType->getAs<ComplexType>();
1301 auto *RHSComplex = RHSType->getAs<ComplexType>();
1302
1303 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1304 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1305
1306 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1307 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1308
1309 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1310 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1311 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1312 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1313 return false;
1314
1315 return true;
1316}
1317
1318typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1319
1320namespace {
1321/// These helper callbacks are placed in an anonymous namespace to
1322/// permit their use as function template parameters.
1323ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1324 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1325}
1326
1327ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1328 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1329 CK_IntegralComplexCast);
1330}
1331}
1332
1333/// Handle integer arithmetic conversions. Helper function of
1334/// UsualArithmeticConversions()
1335template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1337 ExprResult &RHS, QualType LHSType,
1338 QualType RHSType, bool IsCompAssign) {
1339 // The rules for this case are in C99 6.3.1.8
1340 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1341 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1342 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1343 if (LHSSigned == RHSSigned) {
1344 // Same signedness; use the higher-ranked type
1345 if (order >= 0) {
1346 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1347 return LHSType;
1348 } else if (!IsCompAssign)
1349 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1350 return RHSType;
1351 } else if (order != (LHSSigned ? 1 : -1)) {
1352 // The unsigned type has greater than or equal rank to the
1353 // signed type, so use the unsigned type
1354 if (RHSSigned) {
1355 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1356 return LHSType;
1357 } else if (!IsCompAssign)
1358 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1359 return RHSType;
1360 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1361 // The two types are different widths; if we are here, that
1362 // means the signed type is larger than the unsigned type, so
1363 // use the signed type.
1364 if (LHSSigned) {
1365 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1366 return LHSType;
1367 } else if (!IsCompAssign)
1368 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1369 return RHSType;
1370 } else {
1371 // The signed type is higher-ranked than the unsigned type,
1372 // but isn't actually any bigger (like unsigned int and long
1373 // on most 32-bit systems). Use the unsigned type corresponding
1374 // to the signed type.
1375 QualType result =
1376 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1377 RHS = (*doRHSCast)(S, RHS.get(), result);
1378 if (!IsCompAssign)
1379 LHS = (*doLHSCast)(S, LHS.get(), result);
1380 return result;
1381 }
1382}
1383
1384/// Handle conversions with GCC complex int extension. Helper function
1385/// of UsualArithmeticConversions()
1387 ExprResult &RHS, QualType LHSType,
1388 QualType RHSType,
1389 bool IsCompAssign) {
1390 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1391 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1392
1393 if (LHSComplexInt && RHSComplexInt) {
1394 QualType LHSEltType = LHSComplexInt->getElementType();
1395 QualType RHSEltType = RHSComplexInt->getElementType();
1396 QualType ScalarType =
1398 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1399
1400 return S.Context.getComplexType(ScalarType);
1401 }
1402
1403 if (LHSComplexInt) {
1404 QualType LHSEltType = LHSComplexInt->getElementType();
1405 QualType ScalarType =
1407 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1409 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1410 CK_IntegralRealToComplex);
1411
1412 return ComplexType;
1413 }
1414
1415 assert(RHSComplexInt);
1416
1417 QualType RHSEltType = RHSComplexInt->getElementType();
1418 QualType ScalarType =
1420 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1422
1423 if (!IsCompAssign)
1424 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1425 CK_IntegralRealToComplex);
1426 return ComplexType;
1427}
1428
1430 ExprResult &RHS,
1431 QualType LHSType,
1432 QualType RHSType,
1433 bool IsCompAssign) {
1434
1435 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1436 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1437
1438 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1439 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1440
1441 bool LHSHasTrap =
1442 LhsOBT && LhsOBT->getBehaviorKind() ==
1443 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1444 bool RHSHasTrap =
1445 RhsOBT && RhsOBT->getBehaviorKind() ==
1446 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1447 bool LHSHasWrap =
1448 LhsOBT && LhsOBT->getBehaviorKind() ==
1449 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1450 bool RHSHasWrap =
1451 RhsOBT && RhsOBT->getBehaviorKind() ==
1452 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1453
1454 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1455 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1456
1457 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1458 if (LHSHasTrap || RHSHasTrap)
1459 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1460 else if (LHSHasWrap || RHSHasWrap)
1461 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1462
1463 QualType LHSConvType = LHSUnderlyingType;
1464 QualType RHSConvType = RHSUnderlyingType;
1465 if (DominantBehavior) {
1466 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1467 LHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1468 LHSUnderlyingType);
1469 else
1470 LHSConvType = LHSType;
1471
1472 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1473 RHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1474 RHSUnderlyingType);
1475 else
1476 RHSConvType = RHSType;
1477 }
1478
1480 S, LHS, RHS, LHSConvType, RHSConvType, IsCompAssign);
1481}
1482
1483/// Return the rank of a given fixed point or integer type. The value itself
1484/// doesn't matter, but the values must be increasing with proper increasing
1485/// rank as described in N1169 4.1.1.
1486static unsigned GetFixedPointRank(QualType Ty) {
1487 const auto *BTy = Ty->getAs<BuiltinType>();
1488 assert(BTy && "Expected a builtin type.");
1489
1490 switch (BTy->getKind()) {
1491 case BuiltinType::ShortFract:
1492 case BuiltinType::UShortFract:
1493 case BuiltinType::SatShortFract:
1494 case BuiltinType::SatUShortFract:
1495 return 1;
1496 case BuiltinType::Fract:
1497 case BuiltinType::UFract:
1498 case BuiltinType::SatFract:
1499 case BuiltinType::SatUFract:
1500 return 2;
1501 case BuiltinType::LongFract:
1502 case BuiltinType::ULongFract:
1503 case BuiltinType::SatLongFract:
1504 case BuiltinType::SatULongFract:
1505 return 3;
1506 case BuiltinType::ShortAccum:
1507 case BuiltinType::UShortAccum:
1508 case BuiltinType::SatShortAccum:
1509 case BuiltinType::SatUShortAccum:
1510 return 4;
1511 case BuiltinType::Accum:
1512 case BuiltinType::UAccum:
1513 case BuiltinType::SatAccum:
1514 case BuiltinType::SatUAccum:
1515 return 5;
1516 case BuiltinType::LongAccum:
1517 case BuiltinType::ULongAccum:
1518 case BuiltinType::SatLongAccum:
1519 case BuiltinType::SatULongAccum:
1520 return 6;
1521 default:
1522 if (BTy->isInteger())
1523 return 0;
1524 llvm_unreachable("Unexpected fixed point or integer type");
1525 }
1526}
1527
1528/// handleFixedPointConversion - Fixed point operations between fixed
1529/// point types and integers or other fixed point types do not fall under
1530/// usual arithmetic conversion since these conversions could result in loss
1531/// of precsision (N1169 4.1.4). These operations should be calculated with
1532/// the full precision of their result type (N1169 4.1.6.2.1).
1534 QualType RHSTy) {
1535 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1536 "Expected at least one of the operands to be a fixed point type");
1537 assert((LHSTy->isFixedPointOrIntegerType() ||
1538 RHSTy->isFixedPointOrIntegerType()) &&
1539 "Special fixed point arithmetic operation conversions are only "
1540 "applied to ints or other fixed point types");
1541
1542 // If one operand has signed fixed-point type and the other operand has
1543 // unsigned fixed-point type, then the unsigned fixed-point operand is
1544 // converted to its corresponding signed fixed-point type and the resulting
1545 // type is the type of the converted operand.
1546 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1548 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1550
1551 // The result type is the type with the highest rank, whereby a fixed-point
1552 // conversion rank is always greater than an integer conversion rank; if the
1553 // type of either of the operands is a saturating fixedpoint type, the result
1554 // type shall be the saturating fixed-point type corresponding to the type
1555 // with the highest rank; the resulting value is converted (taking into
1556 // account rounding and overflow) to the precision of the resulting type.
1557 // Same ranks between signed and unsigned types are resolved earlier, so both
1558 // types are either signed or both unsigned at this point.
1559 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1560 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1561
1562 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1563
1565 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1566
1567 return ResultTy;
1568}
1569
1570/// Check that the usual arithmetic conversions can be performed on this pair of
1571/// expressions that might be of enumeration type.
1573 SourceLocation Loc,
1574 ArithConvKind ACK) {
1575 // C++2a [expr.arith.conv]p1:
1576 // If one operand is of enumeration type and the other operand is of a
1577 // different enumeration type or a floating-point type, this behavior is
1578 // deprecated ([depr.arith.conv.enum]).
1579 //
1580 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1581 // Eventually we will presumably reject these cases (in C++23 onwards?).
1583 R = RHS->getEnumCoercedType(Context);
1584 bool LEnum = L->isUnscopedEnumerationType(),
1585 REnum = R->isUnscopedEnumerationType();
1586 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1587 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1588 (REnum && L->isFloatingType())) {
1589 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1591 ? diag::warn_arith_conv_enum_float_cxx20
1592 : diag::warn_arith_conv_enum_float)
1593 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1594 << L << R;
1595 } else if (!IsCompAssign && LEnum && REnum &&
1596 !Context.hasSameUnqualifiedType(L, R)) {
1597 unsigned DiagID;
1598 // In C++ 26, usual arithmetic conversions between 2 different enum types
1599 // are ill-formed.
1601 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1602 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1603 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1604 // If either enumeration type is unnamed, it's less likely that the
1605 // user cares about this, but this situation is still deprecated in
1606 // C++2a. Use a different warning group.
1607 DiagID = getLangOpts().CPlusPlus20
1608 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1609 : diag::warn_arith_conv_mixed_anon_enum_types;
1610 } else if (ACK == ArithConvKind::Conditional) {
1611 // Conditional expressions are separated out because they have
1612 // historically had a different warning flag.
1613 DiagID = getLangOpts().CPlusPlus20
1614 ? diag::warn_conditional_mixed_enum_types_cxx20
1615 : diag::warn_conditional_mixed_enum_types;
1616 } else if (ACK == ArithConvKind::Comparison) {
1617 // Comparison expressions are separated out because they have
1618 // historically had a different warning flag.
1619 DiagID = getLangOpts().CPlusPlus20
1620 ? diag::warn_comparison_mixed_enum_types_cxx20
1621 : diag::warn_comparison_mixed_enum_types;
1622 } else {
1623 DiagID = getLangOpts().CPlusPlus20
1624 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1625 : diag::warn_arith_conv_mixed_enum_types;
1626 }
1627 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1628 << (int)ACK << L << R;
1629 }
1630}
1631
1633 Expr *RHS, SourceLocation Loc,
1634 ArithConvKind ACK) {
1635 QualType LHSType = LHS->getType().getUnqualifiedType();
1636 QualType RHSType = RHS->getType().getUnqualifiedType();
1637
1638 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1639 !RHSType->isUnicodeCharacterType())
1640 return;
1641
1642 if (ACK == ArithConvKind::Comparison) {
1643 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1644 return;
1645
1646 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1647 if (T->isChar8Type())
1648 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1649 if (T->isChar16Type())
1650 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1651 assert(T->isChar32Type());
1652 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1653 };
1654
1655 Expr::EvalResult LHSRes, RHSRes;
1656 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1658 SemaRef.isConstantEvaluatedContext());
1659 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1661 SemaRef.isConstantEvaluatedContext());
1662
1663 // Don't warn if the one known value is a representable
1664 // in the type of both expressions.
1665 if (LHSSuccess != RHSuccess) {
1666 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1667 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1668 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1669 return;
1670 }
1671
1672 if (!LHSSuccess || !RHSuccess) {
1673 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1674 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1675 << RHSType;
1676 return;
1677 }
1678
1679 llvm::APSInt LHSValue(32);
1680 LHSValue = LHSRes.Val.getInt();
1681 llvm::APSInt RHSValue(32);
1682 RHSValue = RHSRes.Val.getInt();
1683
1684 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1685 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1686 if (LHSSafe && RHSSafe)
1687 return;
1688
1689 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1690 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1691 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1692 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1693 return;
1694 }
1695
1696 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1697 return;
1698
1699 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1700 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1701 << RHSType;
1702}
1703
1704/// UsualArithmeticConversions - Performs various conversions that are common to
1705/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1706/// routine returns the first non-arithmetic type found. The client is
1707/// responsible for emitting appropriate error diagnostics.
1709 SourceLocation Loc,
1710 ArithConvKind ACK) {
1711
1712 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1713
1714 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1715
1716 if (ACK != ArithConvKind::CompAssign) {
1717 LHS = UsualUnaryConversions(LHS.get());
1718 if (LHS.isInvalid())
1719 return QualType();
1720 }
1721
1722 RHS = UsualUnaryConversions(RHS.get());
1723 if (RHS.isInvalid())
1724 return QualType();
1725
1726 // For conversion purposes, we ignore any qualifiers.
1727 // For example, "const float" and "float" are equivalent.
1728 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1729 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1730
1731 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1732 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1733 LHSType = AtomicLHS->getValueType();
1734
1735 // If both types are identical, no conversion is needed.
1736 if (Context.hasSameType(LHSType, RHSType))
1737 return Context.getCommonSugaredType(LHSType, RHSType);
1738
1739 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1740 // The caller can deal with this (e.g. pointer + int).
1741 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1742 return QualType();
1743
1744 // Apply unary and bitfield promotions to the LHS's type.
1745 QualType LHSUnpromotedType = LHSType;
1746 if (Context.isPromotableIntegerType(LHSType))
1747 LHSType = Context.getPromotedIntegerType(LHSType);
1748 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1749 if (!LHSBitfieldPromoteTy.isNull())
1750 LHSType = LHSBitfieldPromoteTy;
1751 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1752 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1753
1754 // If both types are identical, no conversion is needed.
1755 if (Context.hasSameType(LHSType, RHSType))
1756 return Context.getCommonSugaredType(LHSType, RHSType);
1757
1758 // At this point, we have two different arithmetic types.
1759
1760 if ((LHSType->isFixedPointType() && RHSType->isBitIntType()) ||
1761 (LHSType->isBitIntType() && RHSType->isFixedPointType()))
1762 return QualType();
1763
1764 // Diagnose attempts to convert between __ibm128, __float128 and long double
1765 // where such conversions currently can't be handled.
1766 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1767 return QualType();
1768
1769 // Handle complex types first (C99 6.3.1.8p1).
1770 if (LHSType->isComplexType() || RHSType->isComplexType())
1771 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1773
1774 // Now handle "real" floating types (i.e. float, double, long double).
1775 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1776 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1778
1779 // Handle GCC complex int extension.
1780 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1781 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1783
1784 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1785 return handleFixedPointConversion(*this, LHSType, RHSType);
1786
1787 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1789 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1790
1791 // Finally, we have two differing integer types.
1793 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1794}
1795
1796//===----------------------------------------------------------------------===//
1797// Semantic Analysis for various Expression Types
1798//===----------------------------------------------------------------------===//
1799
1800
1802 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1803 bool PredicateIsExpr, void *ControllingExprOrType,
1804 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1805 unsigned NumAssocs = ArgTypes.size();
1806 assert(NumAssocs == ArgExprs.size());
1807
1808 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1809 for (unsigned i = 0; i < NumAssocs; ++i) {
1810 if (ArgTypes[i])
1811 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1812 else
1813 Types[i] = nullptr;
1814 }
1815
1816 // If we have a controlling type, we need to convert it from a parsed type
1817 // into a semantic type and then pass that along.
1818 if (!PredicateIsExpr) {
1819 TypeSourceInfo *ControllingType;
1820 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1821 &ControllingType);
1822 assert(ControllingType && "couldn't get the type out of the parser");
1823 ControllingExprOrType = ControllingType;
1824 }
1825
1827 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1828 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1829 delete [] Types;
1830 return ER;
1831}
1832
1833// Helper function to determine type compatibility for C _Generic expressions.
1834// Multiple compatible types within the same _Generic expression is ambiguous
1835// and not valid.
1837 QualType U) {
1838 // Try to handle special types like OverflowBehaviorTypes
1839 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1840 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1841
1842 if (TOBT || UOBT) {
1843 if (TOBT && UOBT) {
1844 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1845 return Ctx.typesAreCompatible(TOBT->getUnderlyingType(),
1846 UOBT->getUnderlyingType());
1847 return false;
1848 }
1849 return false;
1850 }
1851
1852 // We're dealing with types that don't require special handling.
1853 return Ctx.typesAreCompatible(T, U);
1854}
1855
1857 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1858 bool PredicateIsExpr, void *ControllingExprOrType,
1860 unsigned NumAssocs = Types.size();
1861 assert(NumAssocs == Exprs.size());
1862 assert(ControllingExprOrType &&
1863 "Must have either a controlling expression or a controlling type");
1864
1865 Expr *ControllingExpr = nullptr;
1866 TypeSourceInfo *ControllingType = nullptr;
1867 if (PredicateIsExpr) {
1868 // Decay and strip qualifiers for the controlling expression type, and
1869 // handle placeholder type replacement. See committee discussion from WG14
1870 // DR423.
1874 reinterpret_cast<Expr *>(ControllingExprOrType));
1875 if (R.isInvalid())
1876 return ExprError();
1877 ControllingExpr = R.get();
1878 } else {
1879 // The extension form uses the type directly rather than converting it.
1880 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1881 if (!ControllingType)
1882 return ExprError();
1883 }
1884
1885 bool TypeErrorFound = false,
1886 IsResultDependent = ControllingExpr
1887 ? ControllingExpr->isTypeDependent()
1888 : ControllingType->getType()->isDependentType(),
1889 ContainsUnexpandedParameterPack =
1890 ControllingExpr
1891 ? ControllingExpr->containsUnexpandedParameterPack()
1892 : ControllingType->getType()->containsUnexpandedParameterPack();
1893
1894 // The controlling expression is an unevaluated operand, so side effects are
1895 // likely unintended.
1896 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1897 ControllingExpr->HasSideEffects(Context, false))
1898 Diag(ControllingExpr->getExprLoc(),
1899 diag::warn_side_effects_unevaluated_context);
1900
1901 for (unsigned i = 0; i < NumAssocs; ++i) {
1902 if (Exprs[i]->containsUnexpandedParameterPack())
1903 ContainsUnexpandedParameterPack = true;
1904
1905 if (Types[i]) {
1906 if (Types[i]->getType()->containsUnexpandedParameterPack())
1907 ContainsUnexpandedParameterPack = true;
1908
1909 if (Types[i]->getType()->isDependentType()) {
1910 IsResultDependent = true;
1911 } else {
1912 // We relax the restriction on use of incomplete types and non-object
1913 // types with the type-based extension of _Generic. Allowing incomplete
1914 // objects means those can be used as "tags" for a type-safe way to map
1915 // to a value. Similarly, matching on function types rather than
1916 // function pointer types can be useful. However, the restriction on VM
1917 // types makes sense to retain as there are open questions about how
1918 // the selection can be made at compile time.
1919 //
1920 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1921 // complete object type other than a variably modified type."
1922 // C2y removed the requirement that an expression form must
1923 // use a complete type, though it's still as-if the type has undergone
1924 // lvalue conversion. We support this as an extension in C23 and
1925 // earlier because GCC does so.
1926 unsigned D = 0;
1927 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1928 D = LangOpts.C2y ? diag::compat_c2y_assoc_type_incomplete
1929 : diag::compat_pre_c2y_assoc_type_incomplete;
1930 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1931 D = diag::err_assoc_type_nonobject;
1932 else if (Types[i]->getType()->isVariablyModifiedType())
1933 D = diag::err_assoc_type_variably_modified;
1934 else if (ControllingExpr) {
1935 // Because the controlling expression undergoes lvalue conversion,
1936 // array conversion, and function conversion, an association which is
1937 // of array type, function type, or is qualified can never be
1938 // reached. We will warn about this so users are less surprised by
1939 // the unreachable association. However, we don't have to handle
1940 // function types; that's not an object type, so it's handled above.
1941 //
1942 // The logic is somewhat different for C++ because C++ has different
1943 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1944 // If T is a non-class type, the type of the prvalue is the cv-
1945 // unqualified version of T. Otherwise, the type of the prvalue is T.
1946 // The result of these rules is that all qualified types in an
1947 // association in C are unreachable, and in C++, only qualified non-
1948 // class types are unreachable.
1949 //
1950 // NB: this does not apply when the first operand is a type rather
1951 // than an expression, because the type form does not undergo
1952 // conversion.
1953 unsigned Reason = 0;
1954 QualType QT = Types[i]->getType();
1955 if (QT->isArrayType())
1956 Reason = 1;
1957 else if (QT.hasQualifiers() &&
1958 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1959 Reason = 2;
1960
1961 if (Reason)
1962 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1963 diag::warn_unreachable_association)
1964 << QT << (Reason - 1);
1965 }
1966
1967 if (D != 0) {
1968 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1969 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1970 if (getDiagnostics().getDiagnosticLevel(
1971 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1973 TypeErrorFound = true;
1974 }
1975
1976 // C11 6.5.1.1p2 "No two generic associations in the same generic
1977 // selection shall specify compatible types."
1978 for (unsigned j = i+1; j < NumAssocs; ++j)
1979 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1981 Types[j]->getType())) {
1982 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1983 diag::err_assoc_compatible_types)
1984 << Types[j]->getTypeLoc().getSourceRange()
1985 << Types[j]->getType()
1986 << Types[i]->getType();
1987 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1988 diag::note_compat_assoc)
1989 << Types[i]->getTypeLoc().getSourceRange()
1990 << Types[i]->getType();
1991 TypeErrorFound = true;
1992 }
1993 }
1994 }
1995 }
1996 if (TypeErrorFound)
1997 return ExprError();
1998
1999 // If we determined that the generic selection is result-dependent, don't
2000 // try to compute the result expression.
2001 if (IsResultDependent) {
2002 if (ControllingExpr)
2003 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
2004 Types, Exprs, DefaultLoc, RParenLoc,
2005 ContainsUnexpandedParameterPack);
2006 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
2007 Exprs, DefaultLoc, RParenLoc,
2008 ContainsUnexpandedParameterPack);
2009 }
2010
2011 SmallVector<unsigned, 1> CompatIndices;
2012 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2013 // Look at the canonical type of the controlling expression in case it was a
2014 // deduced type like __auto_type. However, when issuing diagnostics, use the
2015 // type the user wrote in source rather than the canonical one.
2016 for (unsigned i = 0; i < NumAssocs; ++i) {
2017 if (!Types[i])
2018 DefaultIndex = i;
2019 else {
2020 bool Compatible;
2021 QualType ControllingQT =
2022 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2023 : ControllingType->getType().getCanonicalType();
2024 QualType AssocQT = Types[i]->getType();
2025
2026 Compatible =
2027 areTypesCompatibleForGeneric(Context, ControllingQT, AssocQT);
2028
2029 if (Compatible)
2030 CompatIndices.push_back(i);
2031 }
2032 }
2033
2034 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2035 TypeSourceInfo *ControllingType) {
2036 // We strip parens here because the controlling expression is typically
2037 // parenthesized in macro definitions.
2038 if (ControllingExpr)
2039 ControllingExpr = ControllingExpr->IgnoreParens();
2040
2041 SourceRange SR = ControllingExpr
2042 ? ControllingExpr->getSourceRange()
2043 : ControllingType->getTypeLoc().getSourceRange();
2044 QualType QT = ControllingExpr ? ControllingExpr->getType()
2045 : ControllingType->getType();
2046
2047 return std::make_pair(SR, QT);
2048 };
2049
2050 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2051 // type compatible with at most one of the types named in its generic
2052 // association list."
2053 if (CompatIndices.size() > 1) {
2054 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2055 SourceRange SR = P.first;
2056 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
2057 << SR << P.second << (unsigned)CompatIndices.size();
2058 for (unsigned I : CompatIndices) {
2059 Diag(Types[I]->getTypeLoc().getBeginLoc(),
2060 diag::note_compat_assoc)
2061 << Types[I]->getTypeLoc().getSourceRange()
2062 << Types[I]->getType();
2063 }
2064 return ExprError();
2065 }
2066
2067 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2068 // its controlling expression shall have type compatible with exactly one of
2069 // the types named in its generic association list."
2070 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2071 CompatIndices.size() == 0) {
2072 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2073 SourceRange SR = P.first;
2074 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
2075 return ExprError();
2076 }
2077
2078 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2079 // type name that is compatible with the type of the controlling expression,
2080 // then the result expression of the generic selection is the expression
2081 // in that generic association. Otherwise, the result expression of the
2082 // generic selection is the expression in the default generic association."
2083 unsigned ResultIndex =
2084 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2085
2086 if (ControllingExpr) {
2088 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
2089 ContainsUnexpandedParameterPack, ResultIndex);
2090 }
2092 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
2093 ContainsUnexpandedParameterPack, ResultIndex);
2094}
2095
2097 switch (Kind) {
2098 default:
2099 llvm_unreachable("unexpected TokenKind");
2100 case tok::kw___func__:
2101 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2102 case tok::kw___FUNCTION__:
2104 case tok::kw___FUNCDNAME__:
2105 return PredefinedIdentKind::FuncDName; // [MS]
2106 case tok::kw___FUNCSIG__:
2107 return PredefinedIdentKind::FuncSig; // [MS]
2108 case tok::kw_L__FUNCTION__:
2109 return PredefinedIdentKind::LFunction; // [MS]
2110 case tok::kw_L__FUNCSIG__:
2111 return PredefinedIdentKind::LFuncSig; // [MS]
2112 case tok::kw___PRETTY_FUNCTION__:
2114 }
2115}
2116
2117/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2118/// to determine the value of a PredefinedExpr. This can be either a
2119/// block, lambda, captured statement, function, otherwise a nullptr.
2121 auto LSI = S.FunctionScopes.rbegin();
2122
2123 auto tryAdjustLambdaContext = [&S, &LSI](DeclContext *&DC) {
2124 if (isLambdaCallOperator(DC)) {
2125 auto E = S.FunctionScopes.rend();
2126 while (LSI != E && !isa<LambdaScopeInfo>(*LSI))
2127 ++LSI;
2128 assert(LSI != E && "Should be in a lambda scope info");
2129 if (dyn_cast<LambdaScopeInfo>(*LSI)->BeforeCompoundStatement)
2130 DC = DC->getParent();
2131 ++LSI;
2132 }
2133 };
2134
2135 tryAdjustLambdaContext(DC);
2136 while (DC &&
2138 DC = DC->getParent();
2139 tryAdjustLambdaContext(DC);
2140 }
2141
2142 return cast_or_null<Decl>(DC);
2143}
2144
2145/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2146/// location of the token and the offset of the ud-suffix within it.
2148 unsigned Offset) {
2149 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2150 S.getLangOpts());
2151}
2152
2153/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2154/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2156 IdentifierInfo *UDSuffix,
2157 SourceLocation UDSuffixLoc,
2158 ArrayRef<Expr*> Args,
2159 SourceLocation LitEndLoc) {
2160 assert(Args.size() <= 2 && "too many arguments for literal operator");
2161
2162 QualType ArgTy[2];
2163 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2164 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2165 if (ArgTy[ArgIdx]->isArrayType())
2166 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2167 }
2168
2169 DeclarationName OpName =
2171 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2172 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2173
2174 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2175 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2176 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2177 /*AllowStringTemplatePack*/ false,
2178 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2179 return ExprError();
2180
2181 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2182}
2183
2185 // StringToks needs backing storage as it doesn't hold array elements itself
2186 std::vector<Token> ExpandedToks;
2187 if (getLangOpts().MicrosoftExt)
2188 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2189
2190 StringLiteralParser Literal(StringToks, PP,
2192 if (Literal.hadError)
2193 return ExprError();
2194
2195 SmallVector<SourceLocation, 4> StringTokLocs;
2196 for (const Token &Tok : StringToks)
2197 StringTokLocs.push_back(Tok.getLocation());
2198
2199 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2201 false, {}, StringTokLocs);
2202
2203 if (!Literal.getUDSuffix().empty()) {
2204 SourceLocation UDSuffixLoc =
2205 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2206 Literal.getUDSuffixOffset());
2207 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2208 }
2209
2210 return Lit;
2211}
2212
2213std::vector<Token>
2215 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2216 // local macros that expand to string literals that may be concatenated.
2217 // These macros are expanded here (in Sema), because StringLiteralParser
2218 // (in Lex) doesn't know the enclosing function (because it hasn't been
2219 // parsed yet).
2220 assert(getLangOpts().MicrosoftExt);
2221
2222 // Note: Although function local macros are defined only inside functions,
2223 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2224 // expansion of macros into empty string literals without additional checks.
2225 Decl *CurrentDecl = getPredefinedExprDecl(*this, CurContext);
2226 if (!CurrentDecl)
2227 CurrentDecl = Context.getTranslationUnitDecl();
2228
2229 std::vector<Token> ExpandedToks;
2230 ExpandedToks.reserve(Toks.size());
2231 for (const Token &Tok : Toks) {
2233 assert(tok::isStringLiteral(Tok.getKind()));
2234 ExpandedToks.emplace_back(Tok);
2235 continue;
2236 }
2237 if (isa<TranslationUnitDecl>(CurrentDecl))
2238 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2239 // Stringify predefined expression
2240 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2241 << Tok.getKind();
2242 SmallString<64> Str;
2243 llvm::raw_svector_ostream OS(Str);
2244 Token &Exp = ExpandedToks.emplace_back();
2245 Exp.startToken();
2246 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2247 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2248 OS << 'L';
2249 Exp.setKind(tok::wide_string_literal);
2250 } else {
2251 Exp.setKind(tok::string_literal);
2252 }
2253 OS << '"'
2255 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2256 << '"';
2257 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2258 }
2259 return ExpandedToks;
2260}
2261
2264 assert(!StringToks.empty() && "Must have at least one string!");
2265
2266 // StringToks needs backing storage as it doesn't hold array elements itself
2267 std::vector<Token> ExpandedToks;
2268 if (getLangOpts().MicrosoftExt)
2269 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2270
2271 StringLiteralParser Literal(
2273 if (Literal.hadError)
2274 return ExprError();
2275
2276 SmallVector<SourceLocation, 4> StringTokLocs;
2277 for (const Token &Tok : StringToks)
2278 StringTokLocs.push_back(Tok.getLocation());
2279
2280 QualType CharTy = Context.CharTy;
2282 if (Literal.isWide()) {
2283 CharTy = Context.getWideCharType();
2285 } else if (Literal.isUTF8()) {
2286 if (getLangOpts().Char8)
2287 CharTy = Context.Char8Ty;
2288 else if (getLangOpts().C23)
2289 CharTy = Context.UnsignedCharTy;
2291 } else if (Literal.isUTF16()) {
2292 CharTy = Context.Char16Ty;
2294 } else if (Literal.isUTF32()) {
2295 CharTy = Context.Char32Ty;
2297 } else if (Literal.isPascal()) {
2298 CharTy = Context.UnsignedCharTy;
2299 }
2300
2301 // Warn on u8 string literals before C++20 and C23, whose type
2302 // was an array of char before but becomes an array of char8_t.
2303 // In C++20, it cannot be used where a pointer to char is expected.
2304 // In C23, it might have an unexpected value if char was signed.
2305 if (Kind == StringLiteralKind::UTF8 &&
2307 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2308 : !getLangOpts().C23)) {
2309 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2310 ? diag::warn_cxx20_compat_utf8_string
2311 : diag::warn_c23_compat_utf8_string);
2312
2313 // Create removals for all 'u8' prefixes in the string literal(s). This
2314 // ensures C++20/C23 compatibility (but may change the program behavior when
2315 // built by non-Clang compilers for which the execution character set is
2316 // not always UTF-8).
2317 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2318 SourceLocation RemovalDiagLoc;
2319 for (const Token &Tok : StringToks) {
2320 if (Tok.getKind() == tok::utf8_string_literal) {
2321 if (RemovalDiagLoc.isInvalid())
2322 RemovalDiagLoc = Tok.getLocation();
2324 Tok.getLocation(),
2325 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2327 }
2328 }
2329 Diag(RemovalDiagLoc, RemovalDiag);
2330 }
2331
2332 QualType StrTy =
2333 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2334
2335 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2337 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2338 if (Literal.getUDSuffix().empty())
2339 return Lit;
2340
2341 // We're building a user-defined literal.
2342 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2343 SourceLocation UDSuffixLoc =
2344 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2345 Literal.getUDSuffixOffset());
2346
2347 // Make sure we're allowed user-defined literals here.
2348 if (!UDLScope)
2349 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2350
2351 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2352 // operator "" X (str, len)
2353 QualType SizeType = Context.getSizeType();
2354
2355 DeclarationName OpName =
2356 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2357 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2358 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2359
2360 QualType ArgTy[] = {
2361 Context.getArrayDecayedType(StrTy), SizeType
2362 };
2363
2364 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2365 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2366 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2367 /*AllowStringTemplatePack*/ true,
2368 /*DiagnoseMissing*/ true, Lit)) {
2369
2370 case LOLR_Cooked: {
2371 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2372 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2373 StringTokLocs[0]);
2374 Expr *Args[] = { Lit, LenArg };
2375
2376 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2377 }
2378
2379 case LOLR_Template: {
2380 TemplateArgumentListInfo ExplicitArgs;
2381 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2382 TemplateArgumentLocInfo ArgInfo(Lit);
2383 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2384 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2385 &ExplicitArgs);
2386 }
2387
2389 TemplateArgumentListInfo ExplicitArgs;
2390
2391 unsigned CharBits = Context.getIntWidth(CharTy);
2392 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2393 llvm::APSInt Value(CharBits, CharIsUnsigned);
2394
2395 TemplateArgument TypeArg(CharTy);
2396 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2397 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2398
2399 SourceLocation Loc = StringTokLocs.back();
2400 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2401 Value = Lit->getCodeUnit(I);
2402 TemplateArgument Arg(Context, Value, CharTy);
2404 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2405 }
2406 return BuildLiteralOperatorCall(R, OpNameInfo, {}, Loc, &ExplicitArgs);
2407 }
2408 case LOLR_Raw:
2410 llvm_unreachable("unexpected literal operator lookup result");
2411 case LOLR_Error:
2412 return ExprError();
2413 }
2414 llvm_unreachable("unexpected literal operator lookup result");
2415}
2416
2419 SourceLocation Loc,
2420 const CXXScopeSpec *SS) {
2421 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2422 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2423}
2424
2427 const DeclarationNameInfo &NameInfo,
2428 const CXXScopeSpec *SS, NamedDecl *FoundD,
2429 SourceLocation TemplateKWLoc,
2430 const TemplateArgumentListInfo *TemplateArgs) {
2433 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2434 TemplateArgs);
2435}
2436
2437// CUDA/HIP: Check whether a captured reference variable is referencing a
2438// host variable in a device or host device lambda.
2440 VarDecl *VD) {
2441 if (!S.getLangOpts().CUDA || !VD->hasInit())
2442 return false;
2443 assert(VD->getType()->isReferenceType());
2444
2445 // Check whether the reference variable is referencing a host variable.
2446 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2447 if (!DRE)
2448 return false;
2449 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2450 if (!Referee || !Referee->hasGlobalStorage() ||
2451 Referee->hasAttr<CUDADeviceAttr>())
2452 return false;
2453
2454 // Check whether the current function is a device or host device lambda.
2455 // Check whether the reference variable is a capture by getDeclContext()
2456 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2457 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2458 if (MD && MD->getParent()->isLambda() &&
2459 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2460 VD->getDeclContext() != MD)
2461 return true;
2462
2463 return false;
2464}
2465
2467 // A declaration named in an unevaluated operand never constitutes an odr-use.
2469 return NOUR_Unevaluated;
2470
2471 // C++2a [basic.def.odr]p4:
2472 // A variable x whose name appears as a potentially-evaluated expression e
2473 // is odr-used by e unless [...] x is a reference that is usable in
2474 // constant expressions.
2475 // CUDA/HIP:
2476 // If a reference variable referencing a host variable is captured in a
2477 // device or host device lambda, the value of the referee must be copied
2478 // to the capture and the reference variable must be treated as odr-use
2479 // since the value of the referee is not known at compile time and must
2480 // be loaded from the captured.
2481 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2482 if (VD->getType()->isReferenceType() &&
2483 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2485 VD->isUsableInConstantExpressions(Context))
2486 return NOUR_Constant;
2487 }
2488
2489 // All remaining non-variable cases constitute an odr-use. For variables, we
2490 // need to wait and see how the expression is used.
2491 return NOUR_None;
2492}
2493
2496 const DeclarationNameInfo &NameInfo,
2497 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2498 SourceLocation TemplateKWLoc,
2499 const TemplateArgumentListInfo *TemplateArgs) {
2500 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2501 NeedToCaptureVariable(D, NameInfo.getLoc());
2502
2504 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2505 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2507
2508 // C++ [except.spec]p17:
2509 // An exception-specification is considered to be needed when:
2510 // - in an expression, the function is the unique lookup result or
2511 // the selected member of a set of overloaded functions.
2512 //
2513 // We delay doing this until after we've built the function reference and
2514 // marked it as used so that:
2515 // a) if the function is defaulted, we get errors from defining it before /
2516 // instead of errors from computing its exception specification, and
2517 // b) if the function is a defaulted comparison, we can use the body we
2518 // build when defining it as input to the exception specification
2519 // computation rather than computing a new body.
2520 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2521 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2522 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2523 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2524 }
2525 }
2526
2527 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2529 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2531
2532 const auto *FD = dyn_cast<FieldDecl>(D);
2533 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2534 FD = IFD->getAnonField();
2535 if (FD) {
2536 UnusedPrivateFields.remove(FD);
2537 // Just in case we're building an illegal pointer-to-member.
2538 if (FD->isBitField())
2540 }
2541
2542 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2543 // designates a bit-field.
2544 if (const auto *BD = dyn_cast<BindingDecl>(D))
2545 if (const auto *BE = BD->getBinding())
2546 E->setObjectKind(BE->getObjectKind());
2547
2548 return E;
2549}
2550
2551// Diagnose when a macro cannot be expanded because it's a function-like macro
2552// being used as a function-like macro. Returns true if a diagnostic is emitted.
2554 SourceLocation TypoLoc) {
2555
2556 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
2557 if (II->hasMacroDefinition()) {
2558 MacroInfo *MI = SemaRef.PP.getMacroInfo(II);
2559 if (MI && MI->isFunctionLike()) {
2560 // If the identifier is immediately followed by '(', the user did
2561 // attempt to invoke it as a function-like macro; the failure is
2562 // for some other reason (e.g. wrong argument count), which the
2563 // preprocessor already diagnosed separately. Don't suggest adding
2564 // parens in that case, since they're already there.
2565 SourceManager &SM = SemaRef.getSourceManager();
2566 const LangOptions &LangOpts = SemaRef.getLangOpts();
2567 std::optional<Token> NextTok =
2568 Lexer::findNextToken(TypoLoc, SM, LangOpts);
2569 if (NextTok && NextTok->is(tok::l_paren))
2570 return false;
2571 SemaRef.Diag(TypoLoc,
2572 diag::err_undeclared_var_use_suggest_func_like_macro)
2573 << II->getName();
2574 SemaRef.Diag(MI->getDefinitionLoc(),
2575 diag::note_function_like_macro_requires_parens)
2576 << II->getName();
2577 return true;
2578 }
2579 }
2580 }
2581 return false;
2582}
2583
2584void
2587 DeclarationNameInfo &NameInfo,
2588 const TemplateArgumentListInfo *&TemplateArgs) {
2590 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2591 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2592
2593 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2594 Id.TemplateId->NumArgs);
2595 translateTemplateArguments(TemplateArgsPtr, Buffer);
2596
2597 TemplateName TName = Id.TemplateId->Template.get();
2599 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2600 TemplateArgs = &Buffer;
2601 } else {
2602 NameInfo = GetNameFromUnqualifiedId(Id);
2603 TemplateArgs = nullptr;
2604 }
2605}
2606
2608 // During a default argument instantiation the CurContext points
2609 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2610 // function parameter list, hence add an explicit check.
2611 bool isDefaultArgument =
2612 !CodeSynthesisContexts.empty() &&
2613 CodeSynthesisContexts.back().Kind ==
2615 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2616 bool isInstance = CurMethod && CurMethod->isInstance() &&
2617 R.getNamingClass() == CurMethod->getParent() &&
2618 !isDefaultArgument;
2619
2620 // There are two ways we can find a class-scope declaration during template
2621 // instantiation that we did not find in the template definition: if it is a
2622 // member of a dependent base class, or if it is declared after the point of
2623 // use in the same class. Distinguish these by comparing the class in which
2624 // the member was found to the naming class of the lookup.
2625 unsigned DiagID = diag::err_found_in_dependent_base;
2626 unsigned NoteID = diag::note_member_declared_at;
2627 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2628 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2629 : diag::err_found_later_in_class;
2630 } else if (getLangOpts().MSVCCompat) {
2631 DiagID = diag::ext_found_in_dependent_base;
2632 NoteID = diag::note_dependent_member_use;
2633 }
2634
2635 if (isInstance) {
2636 // Give a code modification hint to insert 'this->'.
2637 Diag(R.getNameLoc(), DiagID)
2638 << R.getLookupName()
2639 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2640 CheckCXXThisCapture(R.getNameLoc());
2641 } else {
2642 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2643 // they're not shadowed).
2644 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2645 }
2646
2647 for (const NamedDecl *D : R)
2648 Diag(D->getLocation(), NoteID);
2649
2650 // Return true if we are inside a default argument instantiation
2651 // and the found name refers to an instance member function, otherwise
2652 // the caller will try to create an implicit member call and this is wrong
2653 // for default arguments.
2654 //
2655 // FIXME: Is this special case necessary? We could allow the caller to
2656 // diagnose this.
2657 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2658 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2659 return true;
2660 }
2661
2662 // Tell the callee to try to recover.
2663 return false;
2664}
2665
2668 TemplateArgumentListInfo *ExplicitTemplateArgs,
2669 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2670 DeclarationName Name = R.getLookupName();
2671 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2672
2673 unsigned diagnostic = diag::err_undeclared_var_use;
2674 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2678 diagnostic = diag::err_undeclared_use;
2679 diagnostic_suggest = diag::err_undeclared_use_suggest;
2680 }
2681
2682 // If the original lookup was an unqualified lookup, fake an
2683 // unqualified lookup. This is useful when (for example) the
2684 // original lookup would not have found something because it was a
2685 // dependent name.
2686 DeclContext *DC =
2687 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2688 while (DC) {
2689 if (isa<CXXRecordDecl>(DC)) {
2690 if (ExplicitTemplateArgs) {
2692 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2693 /*EnteringContext*/ false, TemplateNameIsRequired,
2694 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2695 return true;
2696 } else {
2697 LookupQualifiedName(R, DC);
2698 }
2699
2700 if (!R.empty()) {
2701 // Don't give errors about ambiguities in this lookup.
2702 R.suppressDiagnostics();
2703
2704 // If there's a best viable function among the results, only mention
2705 // that one in the notes.
2706 OverloadCandidateSet Candidates(R.getNameLoc(),
2708 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2710 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2711 OR_Success) {
2712 R.clear();
2713 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2714 R.resolveKind();
2715 }
2716
2718 }
2719
2720 R.clear();
2721 }
2722
2723 DC = DC->getLookupParent();
2724 }
2725
2726 // We didn't find anything, so try to correct for a typo.
2727 TypoCorrection Corrected;
2728 if (S && (Corrected =
2729 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2730 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2731 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2732 bool DroppedSpecifier =
2733 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2734 R.setLookupName(Corrected.getCorrection());
2735
2736 bool AcceptableWithRecovery = false;
2737 bool AcceptableWithoutRecovery = false;
2738 NamedDecl *ND = Corrected.getFoundDecl();
2739 if (ND) {
2740 if (Corrected.isOverloaded()) {
2741 OverloadCandidateSet OCS(R.getNameLoc(),
2744 for (NamedDecl *CD : Corrected) {
2745 if (FunctionTemplateDecl *FTD =
2746 dyn_cast<FunctionTemplateDecl>(CD))
2748 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2749 Args, OCS);
2750 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2751 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2753 Args, OCS);
2754 }
2755 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2756 case OR_Success:
2757 ND = Best->FoundDecl;
2758 Corrected.setCorrectionDecl(ND);
2759 break;
2760 default:
2761 // FIXME: Arbitrarily pick the first declaration for the note.
2762 Corrected.setCorrectionDecl(ND);
2763 break;
2764 }
2765 }
2766 R.addDecl(ND);
2767 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2770 if (!Record)
2773 R.setNamingClass(Record);
2774 }
2775
2776 auto *UnderlyingND = ND->getUnderlyingDecl();
2777 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2778 isa<FunctionTemplateDecl>(UnderlyingND);
2779 // FIXME: If we ended up with a typo for a type name or
2780 // Objective-C class name, we're in trouble because the parser
2781 // is in the wrong place to recover. Suggest the typo
2782 // correction, but don't make it a fix-it since we're not going
2783 // to recover well anyway.
2784 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2785 getAsTypeTemplateDecl(UnderlyingND) ||
2786 isa<ObjCInterfaceDecl>(UnderlyingND);
2787 } else {
2788 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2789 // because we aren't able to recover.
2790 AcceptableWithoutRecovery = true;
2791 }
2792
2793 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2794 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2795 ? diag::note_implicit_param_decl
2796 : diag::note_previous_decl;
2797 if (SS.isEmpty())
2798 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2799 PDiag(NoteID), AcceptableWithRecovery);
2800 else
2801 diagnoseTypo(Corrected,
2802 PDiag(diag::err_no_member_suggest)
2803 << Name << computeDeclContext(SS, false)
2804 << DroppedSpecifier << NameRange,
2805 PDiag(NoteID), AcceptableWithRecovery);
2806
2807 if (Corrected.WillReplaceSpecifier()) {
2809 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2810 SS.MakeTrivial(Context, NNS,
2811 NNS ? NameRange.getBegin() : SourceRange());
2812 }
2813
2814 // Tell the callee whether to try to recover.
2815 return !AcceptableWithRecovery;
2816 }
2817 }
2818 R.clear();
2819
2820 if (diagnoseFunctionLikeMacro(SemaRef, Name, R.getNameLoc()))
2821 return true;
2822
2823 // Emit a special diagnostic for failed member lookups.
2824 // FIXME: computing the declaration context might fail here (?)
2825 if (!SS.isEmpty()) {
2826 Diag(R.getNameLoc(), diag::err_no_member)
2827 << Name << computeDeclContext(SS, false) << NameRange;
2828 return true;
2829 }
2830
2831 // Give up, we can't recover.
2832 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2833 return true;
2834}
2835
2836/// In Microsoft mode, if we are inside a template class whose parent class has
2837/// dependent base classes, and we can't resolve an unqualified identifier, then
2838/// assume the identifier is a member of a dependent base class. We can only
2839/// recover successfully in static methods, instance methods, and other contexts
2840/// where 'this' is available. This doesn't precisely match MSVC's
2841/// instantiation model, but it's close enough.
2842static Expr *
2844 DeclarationNameInfo &NameInfo,
2845 SourceLocation TemplateKWLoc,
2846 const TemplateArgumentListInfo *TemplateArgs) {
2847 // Only try to recover from lookup into dependent bases in static methods or
2848 // contexts where 'this' is available.
2849 QualType ThisType = S.getCurrentThisType();
2850 const CXXRecordDecl *RD = nullptr;
2851 if (!ThisType.isNull())
2852 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2853 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2854 RD = MD->getParent();
2855 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2856 return nullptr;
2857
2858 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2859 // is available, suggest inserting 'this->' as a fixit.
2860 SourceLocation Loc = NameInfo.getLoc();
2861 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2862 DB << NameInfo.getName() << RD;
2863
2864 if (!ThisType.isNull()) {
2865 DB << FixItHint::CreateInsertion(Loc, "this->");
2867 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2868 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2869 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2870 }
2871
2872 // Synthesize a fake NNS that points to the derived class. This will
2873 // perform name lookup during template instantiation.
2874 CXXScopeSpec SS;
2875 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2876 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2878 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2879 TemplateArgs);
2880}
2881
2883 SourceLocation TemplateKWLoc,
2884 UnqualifiedId &Id, bool HasTrailingLParen,
2885 bool IsAddressOfOperand,
2887 bool IsInlineAsmIdentifier) {
2888 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2889 "cannot be direct & operand and have a trailing lparen");
2890 if (SS.isInvalid())
2891 return ExprError();
2892
2893 TemplateArgumentListInfo TemplateArgsBuffer;
2894
2895 // Decompose the UnqualifiedId into the following data.
2896 DeclarationNameInfo NameInfo;
2897 const TemplateArgumentListInfo *TemplateArgs;
2898 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2899
2900 DeclarationName Name = NameInfo.getName();
2902 SourceLocation NameLoc = NameInfo.getLoc();
2903
2905 Id.TemplateId->Template)
2906 if (TemplateName TN = Id.TemplateId->Template.get();
2908 return CheckVarOrConceptTemplateTemplateId(NameInfo, TN, TemplateArgs);
2909
2910 if (II && II->isEditorPlaceholder()) {
2911 // FIXME: When typed placeholders are supported we can create a typed
2912 // placeholder expression node.
2913 return ExprError();
2914 }
2915
2916 // This specially handles arguments of attributes appertains to a type of C
2917 // struct field such that the name lookup within a struct finds the member
2918 // name, which is not the case for other contexts in C.
2919 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2920 // See if this is reference to a field of struct.
2921 LookupResult R(*this, NameInfo, LookupMemberName);
2922 // LookupName handles a name lookup from within anonymous struct.
2923 if (LookupName(R, S)) {
2924 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2925 QualType type = VD->getType().getNonReferenceType();
2926 // This will eventually be translated into MemberExpr upon
2927 // the use of instantiated struct fields.
2928 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2929 }
2930 }
2931 }
2932
2933 // Perform the required lookup.
2934 LookupResult R(*this, NameInfo,
2938 if (TemplateKWLoc.isValid() || TemplateArgs) {
2939 // Lookup the template name again to correctly establish the context in
2940 // which it was found. This is really unfortunate as we already did the
2941 // lookup to determine that it was a template name in the first place. If
2942 // this becomes a performance hit, we can work harder to preserve those
2943 // results until we get here but it's likely not worth it.
2944 AssumedTemplateKind AssumedTemplate;
2945 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2946 /*EnteringContext=*/false, TemplateKWLoc,
2947 &AssumedTemplate))
2948 return ExprError();
2949
2950 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2951 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2952 IsAddressOfOperand, TemplateArgs);
2953 } else {
2954 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2955 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2956 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2957
2958 // If the result might be in a dependent base class, this is a dependent
2959 // id-expression.
2960 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2961 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2962 IsAddressOfOperand, TemplateArgs);
2963
2964 // If this reference is in an Objective-C method, then we need to do
2965 // some special Objective-C lookup, too.
2966 if (IvarLookupFollowUp) {
2967 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2968 if (E.isInvalid())
2969 return ExprError();
2970
2971 if (Expr *Ex = E.getAs<Expr>())
2972 return Ex;
2973 }
2974 }
2975
2976 if (R.isAmbiguous())
2977 return ExprError();
2978
2979 // This could be an implicitly declared function reference if the language
2980 // mode allows it as a feature.
2981 if (R.empty() && HasTrailingLParen && II &&
2982 getLangOpts().implicitFunctionsAllowed()) {
2983 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2984 if (D) R.addDecl(D);
2985 }
2986
2987 // Determine whether this name might be a candidate for
2988 // argument-dependent lookup.
2989 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2990
2991 if (R.empty() && !ADL) {
2992 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2993 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2994 TemplateKWLoc, TemplateArgs))
2995 return E;
2996 }
2997
2998 // Don't diagnose an empty lookup for inline assembly.
2999 if (IsInlineAsmIdentifier)
3000 return ExprError();
3001
3002 // If this name wasn't predeclared and if this is not a function
3003 // call, diagnose the problem.
3004 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
3005 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
3006 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
3007 "Typo correction callback misconfigured");
3008 if (CCC) {
3009 // Make sure the callback knows what the typo being diagnosed is.
3010 CCC->setTypoName(II);
3011 if (SS.isValid())
3012 CCC->setTypoNNS(SS.getScopeRep());
3013 }
3014 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
3015 // a template name, but we happen to have always already looked up the name
3016 // before we get here if it must be a template name.
3017 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
3018 {}, nullptr))
3019 return ExprError();
3020
3021 assert(!R.empty() &&
3022 "DiagnoseEmptyLookup returned false but added no results");
3023
3024 // If we found an Objective-C instance variable, let
3025 // LookupInObjCMethod build the appropriate expression to
3026 // reference the ivar.
3027 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
3028 R.clear();
3029 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
3030 // In a hopelessly buggy code, Objective-C instance variable
3031 // lookup fails and no expression will be built to reference it.
3032 if (!E.isInvalid() && !E.get())
3033 return ExprError();
3034 return E;
3035 }
3036 }
3037
3038 // This is guaranteed from this point on.
3039 assert(!R.empty() || ADL);
3040
3041 // Check whether this might be a C++ implicit instance member access.
3042 // C++ [class.mfct.non-static]p3:
3043 // When an id-expression that is not part of a class member access
3044 // syntax and not used to form a pointer to member is used in the
3045 // body of a non-static member function of class X, if name lookup
3046 // resolves the name in the id-expression to a non-static non-type
3047 // member of some class C, the id-expression is transformed into a
3048 // class member access expression using (*this) as the
3049 // postfix-expression to the left of the . operator.
3050 //
3051 // But we don't actually need to do this for '&' operands if R
3052 // resolved to a function or overloaded function set, because the
3053 // expression is ill-formed if it actually works out to be a
3054 // non-static member function:
3055 //
3056 // C++ [expr.ref]p4:
3057 // Otherwise, if E1.E2 refers to a non-static member function. . .
3058 // [t]he expression can be used only as the left-hand operand of a
3059 // member function call.
3060 //
3061 // There are other safeguards against such uses, but it's important
3062 // to get this right here so that we don't end up making a
3063 // spuriously dependent expression if we're inside a dependent
3064 // instance method.
3065 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3066 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
3067 S);
3068
3069 if (TemplateArgs || TemplateKWLoc.isValid()) {
3070
3071 // In C++1y, if this is a variable template id, then check it
3072 // in BuildTemplateIdExpr().
3073 // The single lookup result must be a variable template declaration.
3077 assert(R.getAsSingle<TemplateDecl>() &&
3078 "There should only be one declaration found.");
3079 }
3080
3081 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
3082 }
3083
3084 return BuildDeclarationNameExpr(SS, R, ADL);
3085}
3086
3088 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3089 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3090 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3091 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
3092
3093 if (R.isAmbiguous())
3094 return ExprError();
3095
3096 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3097 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3098 NameInfo, /*TemplateArgs=*/nullptr);
3099
3100 if (R.empty()) {
3101 // Don't diagnose problems with invalid record decl, the secondary no_member
3102 // diagnostic during template instantiation is likely bogus, e.g. if a class
3103 // is invalid because it's derived from an invalid base class, then missing
3104 // members were likely supposed to be inherited.
3106 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
3107 if (CD->isInvalidDecl() || CD->isBeingDefined())
3108 return ExprError();
3109 Diag(NameInfo.getLoc(), diag::err_no_member)
3110 << NameInfo.getName() << DC << SS.getRange();
3111 return ExprError();
3112 }
3113
3114 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3115 QualType ET;
3116 TypeLocBuilder TLB;
3117 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
3118 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
3119 SS.getScopeRep(), TagD,
3120 /*OwnsTag=*/false);
3121 auto TL = TLB.push<TagTypeLoc>(ET);
3123 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3124 TL.setNameLoc(NameInfo.getLoc());
3125 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
3126 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
3127 SS.getScopeRep(), TypedefD);
3128 TLB.push<TypedefTypeLoc>(ET).set(
3129 /*ElaboratedKeywordLoc=*/SourceLocation(),
3130 SS.getWithLocInContext(Context), NameInfo.getLoc());
3131 } else {
3132 // FIXME: What else can appear here?
3133 ET = SemaRef.Context.getTypeDeclType(TD);
3134 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
3135 assert(SS.isEmpty());
3136 }
3137
3138 // Diagnose a missing typename if this resolved unambiguously to a type in
3139 // a dependent context. If we can recover with a type, downgrade this to
3140 // a warning in Microsoft compatibility mode.
3141 unsigned DiagID = diag::err_typename_missing;
3142 if (RecoveryTSI && getLangOpts().MSVCCompat)
3143 DiagID = diag::ext_typename_missing;
3144 SourceLocation Loc = SS.getBeginLoc();
3145 auto D = Diag(Loc, DiagID);
3146 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3147
3148 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3149 // context.
3150 if (!RecoveryTSI)
3151 return ExprError();
3152
3153 // Only issue the fixit if we're prepared to recover.
3154 D << FixItHint::CreateInsertion(Loc, "typename ");
3155
3156 // Recover by pretending this was an elaborated type.
3157 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3158
3159 return ExprEmpty();
3160 }
3161
3162 // If necessary, build an implicit class member access.
3163 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3165 /*TemplateKWLoc=*/SourceLocation(),
3166 R, /*TemplateArgs=*/nullptr,
3167 /*S=*/nullptr);
3168
3169 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3170}
3171
3173 NestedNameSpecifier Qualifier,
3174 NamedDecl *FoundDecl,
3175 NamedDecl *Member) {
3176 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3177 if (!RD)
3178 return From;
3179
3180 QualType DestRecordType;
3181 QualType DestType;
3182 QualType FromRecordType;
3183 QualType FromType = From->getType();
3184 bool PointerConversions = false;
3185 if (isa<FieldDecl>(Member)) {
3186 DestRecordType = Context.getCanonicalTagType(RD);
3187 auto FromPtrType = FromType->getAs<PointerType>();
3188 DestRecordType = Context.getAddrSpaceQualType(
3189 DestRecordType, FromPtrType
3190 ? FromType->getPointeeType().getAddressSpace()
3191 : FromType.getAddressSpace());
3192
3193 if (FromPtrType) {
3194 DestType = Context.getPointerType(DestRecordType);
3195 FromRecordType = FromPtrType->getPointeeType();
3196 PointerConversions = true;
3197 } else {
3198 DestType = DestRecordType;
3199 FromRecordType = FromType;
3200 }
3201 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3202 if (!Method->isImplicitObjectMemberFunction())
3203 return From;
3204
3205 DestType = Method->getThisType().getNonReferenceType();
3206 DestRecordType = Method->getFunctionObjectParameterType();
3207
3208 if (FromType->getAs<PointerType>()) {
3209 FromRecordType = FromType->getPointeeType();
3210 PointerConversions = true;
3211 } else {
3212 FromRecordType = FromType;
3213 DestType = DestRecordType;
3214 }
3215
3216 LangAS FromAS = FromRecordType.getAddressSpace();
3217 LangAS DestAS = DestRecordType.getAddressSpace();
3218 if (FromAS != DestAS) {
3219 QualType FromRecordTypeWithoutAS =
3220 Context.removeAddrSpaceQualType(FromRecordType);
3221 QualType FromTypeWithDestAS =
3222 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3223 if (PointerConversions)
3224 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3225 From = ImpCastExprToType(From, FromTypeWithDestAS,
3226 CK_AddressSpaceConversion, From->getValueKind())
3227 .get();
3228 }
3229 } else {
3230 // No conversion necessary.
3231 return From;
3232 }
3233
3234 if (DestType->isDependentType() || FromType->isDependentType())
3235 return From;
3236
3237 // If the unqualified types are the same, no conversion is necessary.
3238 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3239 return From;
3240
3241 SourceRange FromRange = From->getSourceRange();
3242 SourceLocation FromLoc = FromRange.getBegin();
3243
3244 ExprValueKind VK = From->getValueKind();
3245
3246 // C++ [class.member.lookup]p8:
3247 // [...] Ambiguities can often be resolved by qualifying a name with its
3248 // class name.
3249 //
3250 // If the member was a qualified name and the qualified referred to a
3251 // specific base subobject type, we'll cast to that intermediate type
3252 // first and then to the object in which the member is declared. That allows
3253 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3254 //
3255 // class Base { public: int x; };
3256 // class Derived1 : public Base { };
3257 // class Derived2 : public Base { };
3258 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3259 //
3260 // void VeryDerived::f() {
3261 // x = 17; // error: ambiguous base subobjects
3262 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3263 // }
3264 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3265 QualType QType = QualType(Qualifier.getAsType(), 0);
3266 assert(QType->isRecordType() && "lookup done with non-record type");
3267
3268 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3269
3270 // In C++98, the qualifier type doesn't actually have to be a base
3271 // type of the object type, in which case we just ignore it.
3272 // Otherwise build the appropriate casts.
3273 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3274 CXXCastPath BasePath;
3275 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3276 FromLoc, FromRange, &BasePath))
3277 return ExprError();
3278
3279 if (PointerConversions)
3280 QType = Context.getPointerType(QType);
3281 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3282 VK, &BasePath).get();
3283
3284 FromType = QType;
3285 FromRecordType = QRecordType;
3286
3287 // If the qualifier type was the same as the destination type,
3288 // we're done.
3289 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3290 return From;
3291 }
3292 }
3293
3294 CXXCastPath BasePath;
3295 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3296 FromLoc, FromRange, &BasePath,
3297 /*IgnoreAccess=*/true))
3298 return ExprError();
3299
3300 // Propagate qualifiers to base subobjects as per:
3301 // C++ [basic.type.qualifier]p1.2:
3302 // A volatile object is [...] a subobject of a volatile object.
3303 Qualifiers FromTypeQuals = FromType.getQualifiers();
3304 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3305 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3306
3307 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3308 &BasePath);
3309}
3310
3312 const LookupResult &R,
3313 bool HasTrailingLParen) {
3314 // Only when used directly as the postfix-expression of a call.
3315 if (!HasTrailingLParen)
3316 return false;
3317
3318 // Never if a scope specifier was provided.
3319 if (SS.isNotEmpty())
3320 return false;
3321
3322 // Only in C++ or ObjC++.
3323 if (!getLangOpts().CPlusPlus)
3324 return false;
3325
3326 // Turn off ADL when we find certain kinds of declarations during
3327 // normal lookup:
3328 for (const NamedDecl *D : R) {
3329 // C++0x [basic.lookup.argdep]p3:
3330 // -- a declaration of a class member
3331 // Since using decls preserve this property, we check this on the
3332 // original decl.
3333 if (D->isCXXClassMember())
3334 return false;
3335
3336 // C++0x [basic.lookup.argdep]p3:
3337 // -- a block-scope function declaration that is not a
3338 // using-declaration
3339 // NOTE: we also trigger this for function templates (in fact, we
3340 // don't check the decl type at all, since all other decl types
3341 // turn off ADL anyway).
3342 if (isa<UsingShadowDecl>(D))
3343 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3344 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3345 return false;
3346
3347 // C++0x [basic.lookup.argdep]p3:
3348 // -- a declaration that is neither a function or a function
3349 // template
3350 // And also for builtin functions.
3351 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3352 // But also builtin functions.
3353 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3354 return false;
3355 } else if (!isa<FunctionTemplateDecl>(D))
3356 return false;
3357 }
3358
3359 return true;
3360}
3361
3362
3363/// Diagnoses obvious problems with the use of the given declaration
3364/// as an expression. This is only actually called for lookups that
3365/// were not overloaded, and it doesn't promise that the declaration
3366/// will in fact be used.
3368 bool AcceptInvalid) {
3369 if (D->isInvalidDecl() && !AcceptInvalid)
3370 return true;
3371
3372 if (isa<TypedefNameDecl>(D)) {
3373 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3374 return true;
3375 }
3376
3377 if (isa<ObjCInterfaceDecl>(D)) {
3378 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3379 return true;
3380 }
3381
3382 if (isa<NamespaceDecl>(D)) {
3383 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3384 return true;
3385 }
3386
3387 return false;
3388}
3389
3390// Certain multiversion types should be treated as overloaded even when there is
3391// only one result.
3393 assert(R.isSingleResult() && "Expected only a single result");
3394 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3395 return FD &&
3396 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3397}
3398
3400 LookupResult &R, bool NeedsADL,
3401 bool AcceptInvalidDecl) {
3402 // If this is a single, fully-resolved result and we don't need ADL,
3403 // just build an ordinary singleton decl ref.
3404 if (!NeedsADL && R.isSingleResult() &&
3405 !R.getAsSingle<FunctionTemplateDecl>() &&
3407 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3408 R.getRepresentativeDecl(), nullptr,
3409 AcceptInvalidDecl);
3410
3411 // We only need to check the declaration if there's exactly one
3412 // result, because in the overloaded case the results can only be
3413 // functions and function templates.
3414 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3415 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3416 AcceptInvalidDecl))
3417 return ExprError();
3418
3419 // Otherwise, just build an unresolved lookup expression. Suppress
3420 // any lookup-related diagnostics; we'll hash these out later, when
3421 // we've picked a target.
3422 R.suppressDiagnostics();
3423
3425 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3426 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3427 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3428
3429 return ULE;
3430}
3431
3433 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3434 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3435 bool AcceptInvalidDecl) {
3436 assert(D && "Cannot refer to a NULL declaration");
3437 assert(!isa<FunctionTemplateDecl>(D) &&
3438 "Cannot refer unambiguously to a function template");
3439
3440 SourceLocation Loc = NameInfo.getLoc();
3441 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3442 // Recovery from invalid cases (e.g. D is an invalid Decl).
3443 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3444 // diagnostics, as invalid decls use int as a fallback type.
3445 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3446 }
3447
3448 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3449 // Specifically diagnose references to class templates that are missing
3450 // a template argument list.
3451 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3452 return ExprError();
3453 }
3454
3455 // Make sure that we're referring to a value.
3457 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3458 Diag(D->getLocation(), diag::note_declared_at);
3459 return ExprError();
3460 }
3461
3462 // Check whether this declaration can be used. Note that we suppress
3463 // this check when we're going to perform argument-dependent lookup
3464 // on this function name, because this might not be the function
3465 // that overload resolution actually selects.
3466 if (DiagnoseUseOfDecl(D, Loc))
3467 return ExprError();
3468
3469 auto *VD = cast<ValueDecl>(D);
3470
3471 // Only create DeclRefExpr's for valid Decl's.
3472 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3473 return ExprError();
3474
3475 // Handle members of anonymous structs and unions. If we got here,
3476 // and the reference is to a class member indirect field, then this
3477 // must be the subject of a pointer-to-member expression.
3478 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3479 IndirectField && !IndirectField->isCXXClassMember())
3481 IndirectField);
3482
3483 QualType type = VD->getType();
3484 if (type.isNull())
3485 return ExprError();
3486 ExprValueKind valueKind = VK_PRValue;
3487
3488 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3489 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3490 // is expanded by some outer '...' in the context of the use.
3491 type = type.getNonPackExpansionType();
3492
3493 switch (D->getKind()) {
3494 // Ignore all the non-ValueDecl kinds.
3495#define ABSTRACT_DECL(kind)
3496#define VALUE(type, base)
3497#define DECL(type, base) case Decl::type:
3498#include "clang/AST/DeclNodes.inc"
3499 llvm_unreachable("invalid value decl kind");
3500
3501 // These shouldn't make it here.
3502 case Decl::ObjCAtDefsField:
3503 llvm_unreachable("forming non-member reference to ivar?");
3504
3505 // Enum constants are always r-values and never references.
3506 // Unresolved using declarations are dependent.
3507 case Decl::EnumConstant:
3508 case Decl::UnresolvedUsingValue:
3509 case Decl::OMPDeclareReduction:
3510 case Decl::OMPDeclareMapper:
3511 valueKind = VK_PRValue;
3512 break;
3513
3514 // Fields and indirect fields that got here must be for
3515 // pointer-to-member expressions; we just call them l-values for
3516 // internal consistency, because this subexpression doesn't really
3517 // exist in the high-level semantics.
3518 case Decl::Field:
3519 case Decl::IndirectField:
3520 case Decl::ObjCIvar:
3521 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3522 "building reference to field in C?");
3523
3524 // These can't have reference type in well-formed programs, but
3525 // for internal consistency we do this anyway.
3526 type = type.getNonReferenceType();
3527 valueKind = VK_LValue;
3528 break;
3529
3530 // Non-type template parameters are either l-values or r-values
3531 // depending on the type.
3532 case Decl::NonTypeTemplateParm: {
3533 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3534 type = reftype->getPointeeType();
3535 valueKind = VK_LValue; // even if the parameter is an r-value reference
3536 break;
3537 }
3538
3539 // [expr.prim.id.unqual]p2:
3540 // If the entity is a template parameter object for a template
3541 // parameter of type T, the type of the expression is const T.
3542 // [...] The expression is an lvalue if the entity is a [...] template
3543 // parameter object.
3544 if (type->isRecordType()) {
3545 type = type.getUnqualifiedType().withConst();
3546 valueKind = VK_LValue;
3547 break;
3548 }
3549
3550 // For non-references, we need to strip qualifiers just in case
3551 // the template parameter was declared as 'const int' or whatever.
3552 valueKind = VK_PRValue;
3553 type = type.getUnqualifiedType();
3554 break;
3555 }
3556
3557 case Decl::Var:
3558 case Decl::VarTemplateSpecialization:
3559 case Decl::VarTemplatePartialSpecialization:
3560 case Decl::Decomposition:
3561 case Decl::Binding:
3562 case Decl::OMPCapturedExpr:
3563 // In C, "extern void blah;" is valid and is an r-value.
3564 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3565 type->isVoidType()) {
3566 valueKind = VK_PRValue;
3567 break;
3568 }
3569 [[fallthrough]];
3570
3571 case Decl::ImplicitParam:
3572 case Decl::ParmVar: {
3573 // These are always l-values.
3574 valueKind = VK_LValue;
3575 type = type.getNonReferenceType();
3576
3577 // FIXME: Does the addition of const really only apply in
3578 // potentially-evaluated contexts? Since the variable isn't actually
3579 // captured in an unevaluated context, it seems that the answer is no.
3580 if (!isUnevaluatedContext()) {
3581 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3582 if (!CapturedType.isNull())
3583 type = CapturedType;
3584 }
3585 break;
3586 }
3587
3588 case Decl::Function: {
3589 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3590 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3591 type = Context.BuiltinFnTy;
3592 valueKind = VK_PRValue;
3593 break;
3594 }
3595 }
3596
3597 const FunctionType *fty = type->castAs<FunctionType>();
3598
3599 // If we're referring to a function with an __unknown_anytype
3600 // result type, make the entire expression __unknown_anytype.
3601 if (fty->getReturnType() == Context.UnknownAnyTy) {
3602 type = Context.UnknownAnyTy;
3603 valueKind = VK_PRValue;
3604 break;
3605 }
3606
3607 // Functions are l-values in C++.
3608 if (getLangOpts().CPlusPlus) {
3609 valueKind = VK_LValue;
3610 break;
3611 }
3612
3613 // C99 DR 316 says that, if a function type comes from a
3614 // function definition (without a prototype), that type is only
3615 // used for checking compatibility. Therefore, when referencing
3616 // the function, we pretend that we don't have the full function
3617 // type.
3618 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3619 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3620 fty->getExtInfo());
3621
3622 // Functions are r-values in C.
3623 valueKind = VK_PRValue;
3624 break;
3625 }
3626
3627 case Decl::CXXDeductionGuide:
3628 llvm_unreachable("building reference to deduction guide");
3629
3630 case Decl::MSProperty:
3631 case Decl::MSGuid:
3632 case Decl::TemplateParamObject:
3633 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3634 // capture in OpenMP, or duplicated between host and device?
3635 valueKind = VK_LValue;
3636 break;
3637
3638 case Decl::UnnamedGlobalConstant:
3639 valueKind = VK_LValue;
3640 break;
3641
3642 case Decl::CXXMethod:
3643 // If we're referring to a method with an __unknown_anytype
3644 // result type, make the entire expression __unknown_anytype.
3645 // This should only be possible with a type written directly.
3646 if (const FunctionProtoType *proto =
3647 dyn_cast<FunctionProtoType>(VD->getType()))
3648 if (proto->getReturnType() == Context.UnknownAnyTy) {
3649 type = Context.UnknownAnyTy;
3650 valueKind = VK_PRValue;
3651 break;
3652 }
3653
3654 // C++ methods are l-values if static, r-values if non-static.
3655 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3656 valueKind = VK_LValue;
3657 break;
3658 }
3659 [[fallthrough]];
3660
3661 case Decl::CXXConversion:
3662 case Decl::CXXDestructor:
3663 case Decl::CXXConstructor:
3664 valueKind = VK_PRValue;
3665 break;
3666 }
3667
3668 auto *E =
3669 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3670 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3671 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3672 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3673 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3674 // diagnostics).
3675 if (VD->isInvalidDecl() && E)
3676 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3677 return E;
3678}
3679
3680static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3682 Target.resize(CharByteWidth * (Source.size() + 1));
3683 char *ResultPtr = &Target[0];
3684 const llvm::UTF8 *ErrorPtr;
3685 bool success =
3686 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3687 (void)success;
3688 assert(success);
3689 Target.resize(ResultPtr - &Target[0]);
3690}
3691
3694 Decl *currentDecl = getPredefinedExprDecl(*this, CurContext);
3695 if (!currentDecl) {
3696 Diag(Loc, diag::ext_predef_outside_function);
3697 currentDecl = Context.getTranslationUnitDecl();
3698 }
3699
3700 QualType ResTy;
3701 StringLiteral *SL = nullptr;
3702 if (cast<DeclContext>(currentDecl)->isDependentContext())
3703 ResTy = Context.DependentTy;
3704 else {
3705 // Pre-defined identifiers are of type char[x], where x is the length of
3706 // the string.
3707 bool ForceElaboratedPrinting =
3708 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3709 auto Str =
3710 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3711 unsigned Length = Str.length();
3712
3713 llvm::APInt LengthI(32, Length + 1);
3716 ResTy =
3717 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3718 SmallString<32> RawChars;
3719 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3720 Str, RawChars);
3721 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3723 /*IndexTypeQuals*/ 0);
3725 /*Pascal*/ false, ResTy, Loc);
3726 } else {
3727 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3728 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3730 /*IndexTypeQuals*/ 0);
3732 /*Pascal*/ false, ResTy, Loc);
3733 }
3734 }
3735
3736 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3737 SL);
3738}
3739
3743
3745 SmallString<16> CharBuffer;
3746 bool Invalid = false;
3747 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3748 if (Invalid)
3749 return ExprError();
3750
3751 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3752 PP, Tok.getKind());
3753 if (Literal.hadError())
3754 return ExprError();
3755
3756 QualType Ty;
3757 if (Literal.isWide())
3758 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3759 else if (Literal.isUTF8() && getLangOpts().C23)
3760 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3761 else if (Literal.isUTF8() && getLangOpts().Char8)
3762 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3763 else if (Literal.isUTF16())
3764 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3765 else if (Literal.isUTF32())
3766 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3767 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3768 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3769 else
3770 Ty = Context.CharTy; // 'x' -> char in C++;
3771 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3772
3774 if (Literal.isWide())
3776 else if (Literal.isUTF16())
3778 else if (Literal.isUTF32())
3780 else if (Literal.isUTF8())
3782
3783 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3784 Tok.getLocation());
3785
3786 if (Literal.getUDSuffix().empty())
3787 return Lit;
3788
3789 // We're building a user-defined literal.
3790 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3791 SourceLocation UDSuffixLoc =
3792 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3793
3794 // Make sure we're allowed user-defined literals here.
3795 if (!UDLScope)
3796 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3797
3798 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3799 // operator "" X (ch)
3800 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3801 Lit, Tok.getLocation());
3802}
3803
3805 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3807 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3808 Context.IntTy, Loc);
3809}
3810
3812 ExprResult Inner;
3813 if (getLangOpts().CPlusPlus) {
3814 Inner = ActOnCXXBoolLiteral(Loc, Value ? tok::kw_true : tok::kw_false);
3815 } else {
3816 // C doesn't actually have a way to represent literal values of type
3817 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3818 Inner = ActOnIntegerConstant(Loc, Value ? 1 : 0);
3819 Inner =
3820 ImpCastExprToType(Inner.get(), Context.BoolTy, CK_IntegralToBoolean);
3821 }
3822 return Inner;
3823}
3824
3826 QualType Ty, SourceLocation Loc) {
3827 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3828
3829 using llvm::APFloat;
3830 APFloat Val(Format);
3831
3832 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3833 if (RM == llvm::RoundingMode::Dynamic)
3834 RM = llvm::RoundingMode::NearestTiesToEven;
3835 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3836
3837 // Overflow is always an error, but underflow is only an error if
3838 // we underflowed to zero (APFloat reports denormals as underflow).
3839 if ((result & APFloat::opOverflow) ||
3840 ((result & APFloat::opUnderflow) && Val.isZero())) {
3841 unsigned diagnostic;
3842 SmallString<20> buffer;
3843 if (result & APFloat::opOverflow) {
3844 diagnostic = diag::warn_float_overflow;
3845 APFloat::getLargest(Format).toString(buffer);
3846 } else {
3847 diagnostic = diag::warn_float_underflow;
3848 APFloat::getSmallest(Format).toString(buffer);
3849 }
3850
3851 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3852 }
3853
3854 bool isExact = (result == APFloat::opOK);
3855 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3856}
3857
3858bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3859 assert(E && "Invalid expression");
3860
3861 if (E->isValueDependent())
3862 return false;
3863
3864 QualType QT = E->getType();
3865 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3866 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3867 return true;
3868 }
3869
3870 llvm::APSInt ValueAPS;
3872
3873 if (R.isInvalid())
3874 return true;
3875
3876 // GCC allows the value of unroll count to be 0.
3877 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3878 // "The values of 0 and 1 block any unrolling of the loop."
3879 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3880 // '#pragma unroll' cases.
3881 bool ValueIsPositive =
3882 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3883 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3884 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3885 << toString(ValueAPS, 10) << ValueIsPositive;
3886 return true;
3887 }
3888
3889 return false;
3890}
3891
3893 // Fast path for a single digit (which is quite common). A single digit
3894 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3895 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3896 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3897 return ActOnIntegerConstant(Tok.getLocation(), Val);
3898 }
3899
3900 SmallString<128> SpellingBuffer;
3901 // NumericLiteralParser wants to overread by one character. Add padding to
3902 // the buffer in case the token is copied to the buffer. If getSpelling()
3903 // returns a StringRef to the memory buffer, it should have a null char at
3904 // the EOF, so it is also safe.
3905 SpellingBuffer.resize(Tok.getLength() + 1);
3906
3907 // Get the spelling of the token, which eliminates trigraphs, etc.
3908 bool Invalid = false;
3909 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3910 if (Invalid)
3911 return ExprError();
3912
3913 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3914 PP.getSourceManager(), PP.getLangOpts(),
3915 PP.getTargetInfo(), PP.getDiagnostics());
3916 if (Literal.hadError)
3917 return ExprError();
3918
3919 if (Literal.hasUDSuffix()) {
3920 // We're building a user-defined literal.
3921 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3922 SourceLocation UDSuffixLoc =
3923 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3924
3925 // Make sure we're allowed user-defined literals here.
3926 if (!UDLScope)
3927 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3928
3929 QualType CookedTy;
3930 if (Literal.isFloatingLiteral()) {
3931 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3932 // long double, the literal is treated as a call of the form
3933 // operator "" X (f L)
3934 CookedTy = Context.LongDoubleTy;
3935 } else {
3936 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3937 // unsigned long long, the literal is treated as a call of the form
3938 // operator "" X (n ULL)
3939 CookedTy = Context.UnsignedLongLongTy;
3940 }
3941
3942 DeclarationName OpName =
3943 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3944 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3945 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3946
3947 SourceLocation TokLoc = Tok.getLocation();
3948
3949 // Perform literal operator lookup to determine if we're building a raw
3950 // literal or a cooked one.
3951 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3952 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3953 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3954 /*AllowStringTemplatePack*/ false,
3955 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3957 // Lookup failure for imaginary constants isn't fatal, there's still the
3958 // GNU extension producing _Complex types.
3959 break;
3960 case LOLR_Error:
3961 return ExprError();
3962 case LOLR_Cooked: {
3963 Expr *Lit;
3964 if (Literal.isFloatingLiteral()) {
3965 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3966 } else {
3967 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3968 if (Literal.GetIntegerValue(ResultVal))
3969 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3970 << /* Unsigned */ 1;
3971 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3972 Tok.getLocation());
3973 }
3974 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3975 }
3976
3977 case LOLR_Raw: {
3978 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3979 // literal is treated as a call of the form
3980 // operator "" X ("n")
3981 unsigned Length = Literal.getUDSuffixOffset();
3982 QualType StrTy = Context.getConstantArrayType(
3983 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3984 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3985 Expr *Lit =
3986 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3988 /*Pascal*/ false, StrTy, TokLoc);
3989 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3990 }
3991
3992 case LOLR_Template: {
3993 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3994 // template), L is treated as a call fo the form
3995 // operator "" X <'c1', 'c2', ... 'ck'>()
3996 // where n is the source character sequence c1 c2 ... ck.
3997 TemplateArgumentListInfo ExplicitArgs;
3998 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3999 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4000 llvm::APSInt Value(CharBits, CharIsUnsigned);
4001 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4002 Value = TokSpelling[I];
4003 TemplateArgument Arg(Context, Value, Context.CharTy);
4005 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
4006 }
4007 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
4008 }
4010 llvm_unreachable("unexpected literal operator lookup result");
4011 }
4012 }
4013
4014 Expr *Res;
4015
4016 if (Literal.isFixedPointLiteral()) {
4017 QualType Ty;
4018
4019 if (Literal.isAccum) {
4020 if (Literal.isHalf) {
4021 Ty = Context.ShortAccumTy;
4022 } else if (Literal.isLong) {
4023 Ty = Context.LongAccumTy;
4024 } else {
4025 Ty = Context.AccumTy;
4026 }
4027 } else if (Literal.isFract) {
4028 if (Literal.isHalf) {
4029 Ty = Context.ShortFractTy;
4030 } else if (Literal.isLong) {
4031 Ty = Context.LongFractTy;
4032 } else {
4033 Ty = Context.FractTy;
4034 }
4035 }
4036
4037 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
4038
4039 bool isSigned = !Literal.isUnsigned;
4040 unsigned scale = Context.getFixedPointScale(Ty);
4041 unsigned bit_width = Context.getTypeInfo(Ty).Width;
4042
4043 llvm::APInt Val(bit_width, 0, isSigned);
4044 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
4045 bool ValIsZero = Val.isZero() && !Overflowed;
4046
4047 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4048 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4049 // Clause 6.4.4 - The value of a constant shall be in the range of
4050 // representable values for its type, with exception for constants of a
4051 // fract type with a value of exactly 1; such a constant shall denote
4052 // the maximal value for the type.
4053 --Val;
4054 else if (Val.ugt(MaxVal) || Overflowed)
4055 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4056
4058 Tok.getLocation(), scale);
4059 } else if (Literal.isFloatingLiteral()) {
4060 QualType Ty;
4061 if (Literal.isHalf){
4062 if (getLangOpts().HLSL ||
4063 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4064 Ty = Context.HalfTy;
4065 else {
4066 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4067 return ExprError();
4068 }
4069 } else if (Literal.isFloat)
4070 Ty = Context.FloatTy;
4071 else if (Literal.isLong)
4072 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4073 else if (Literal.isFloat16)
4074 Ty = Context.Float16Ty;
4075 else if (Literal.isFloat128)
4076 Ty = Context.Float128Ty;
4077 else if (getLangOpts().HLSL)
4078 Ty = Context.FloatTy;
4079 else
4080 Ty = Context.DoubleTy;
4081
4082 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4083
4084 if (Ty == Context.DoubleTy) {
4085 if (getLangOpts().SinglePrecisionConstants) {
4086 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4087 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4088 }
4089 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4090 "cl_khr_fp64", getLangOpts())) {
4091 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4092 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4094 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4095 }
4096 }
4097 } else if (!Literal.isIntegerLiteral()) {
4098 return ExprError();
4099 } else {
4100 QualType Ty;
4101
4102 // 'z/uz' literals are a C++23 feature.
4103 if (Literal.isSizeT) {
4104 if (getLangOpts().CPlusPlus)
4105 DiagCompat(Tok.getLocation(), diag_compat::size_t_suffix);
4106 else
4107 Diag(Tok.getLocation(), diag::err_cxx23_size_t_suffix);
4108 }
4109
4110 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4111 // but we do not currently support the suffix in C++ mode because it's not
4112 // entirely clear whether WG21 will prefer this suffix to return a library
4113 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4114 // literals are a C++ extension.
4115 if (Literal.isBitInt)
4116 PP.Diag(Tok.getLocation(),
4117 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4118 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4119 : diag::ext_c23_bitint_suffix);
4120
4121 // Get the value in the widest-possible width. What is "widest" depends on
4122 // whether the literal is a bit-precise integer or not. For a bit-precise
4123 // integer type, try to scan the source to determine how many bits are
4124 // needed to represent the value. This may seem a bit expensive, but trying
4125 // to get the integer value from an overly-wide APInt is *extremely*
4126 // expensive, so the naive approach of assuming
4127 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4128 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4129 if (Literal.isBitInt)
4130 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4131 Literal.getLiteralDigits(), Literal.getRadix());
4132 if (Literal.MicrosoftInteger) {
4133 if (Literal.MicrosoftInteger == 128 &&
4134 !Context.getTargetInfo().hasInt128Type())
4135 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4136 << Literal.isUnsigned;
4137 BitsNeeded = std::max<unsigned>(BitsNeeded, Literal.MicrosoftInteger);
4138 }
4139
4140 llvm::APInt ResultVal(BitsNeeded, 0);
4141
4142 if (Literal.GetIntegerValue(ResultVal)) {
4143 // If this value didn't fit into uintmax_t, error and force to ull.
4144 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4145 << /* Unsigned */ 1;
4146 Ty = Context.UnsignedLongLongTy;
4147 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4148 "long long is not intmax_t?");
4149 } else {
4150 // If this value fits into a ULL, try to figure out what else it fits into
4151 // according to the rules of C99 6.4.4.1p5.
4152
4153 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4154 // be an unsigned int.
4155 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4156
4157 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4158 // suffix for portability of code with C++, but both `l` and `ll` are
4159 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4160 // same.
4161 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4162 Literal.isLong = true;
4163 Literal.isLongLong = false;
4164 }
4165
4166 // Check from smallest to largest, picking the smallest type we can.
4167 unsigned Width = 0;
4168
4169 // Microsoft specific integer suffixes are explicitly sized.
4170 if (Literal.MicrosoftInteger) {
4171 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4172 Width = 8;
4173 Ty = Context.CharTy;
4174 } else {
4175 Width = Literal.MicrosoftInteger;
4176 Ty = Context.getIntTypeForBitwidth(Width,
4177 /*Signed=*/!Literal.isUnsigned);
4178 }
4179 // To maintain consistency with MSVC, we chose to truncate directly
4180 // without issuing any warnings.
4181 ResultVal = ResultVal.zextOrTrunc(Width);
4182 }
4183
4184 // Bit-precise integer literals are automagically-sized based on the
4185 // width required by the literal.
4186 if (Literal.isBitInt) {
4187 // The signed version has one more bit for the sign value. There are no
4188 // zero-width bit-precise integers, even if the literal value is 0.
4189 Width = std::max(ResultVal.getActiveBits(), 1u) +
4190 (Literal.isUnsigned ? 0u : 1u);
4191
4192 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4193 // and reset the type to the largest supported width.
4194 unsigned int MaxBitIntWidth =
4195 Context.getTargetInfo().getMaxBitIntWidth();
4196 if (Width > MaxBitIntWidth) {
4197 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4198 << Literal.isUnsigned;
4199 Width = MaxBitIntWidth;
4200 }
4201
4202 // Reset the result value to the smaller APInt and select the correct
4203 // type to be used. Note, we zext even for signed values because the
4204 // literal itself is always an unsigned value (a preceeding - is a
4205 // unary operator, not part of the literal).
4206 ResultVal = ResultVal.zextOrTrunc(Width);
4207 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4208 }
4209
4210 // Check C++23 size_t literals.
4211 if (Literal.isSizeT) {
4212 assert(!Literal.MicrosoftInteger &&
4213 "size_t literals can't be Microsoft literals");
4214 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4215 Context.getTargetInfo().getSizeType());
4216
4217 // Does it fit in size_t?
4218 if (ResultVal.isIntN(SizeTSize)) {
4219 // Does it fit in ssize_t?
4220 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4221 Ty = Context.getSignedSizeType();
4222 else if (AllowUnsigned)
4223 Ty = Context.getSizeType();
4224 Width = SizeTSize;
4225 }
4226 }
4227
4228 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4229 !Literal.isSizeT) {
4230 // Are int/unsigned possibilities?
4231 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4232
4233 // Does it fit in a unsigned int?
4234 if (ResultVal.isIntN(IntSize)) {
4235 // Does it fit in a signed int?
4236 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4237 Ty = Context.IntTy;
4238 else if (AllowUnsigned)
4239 Ty = Context.UnsignedIntTy;
4240 Width = IntSize;
4241 }
4242 }
4243
4244 // Are long/unsigned long possibilities?
4245 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4246 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4247
4248 // Does it fit in a unsigned long?
4249 if (ResultVal.isIntN(LongSize)) {
4250 // Does it fit in a signed long?
4251 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4252 Ty = Context.LongTy;
4253 else if (AllowUnsigned)
4254 Ty = Context.UnsignedLongTy;
4255 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4256 // is compatible.
4257 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4258 const unsigned LongLongSize =
4259 Context.getTargetInfo().getLongLongWidth();
4260 Diag(Tok.getLocation(),
4262 ? Literal.isLong
4263 ? diag::warn_old_implicitly_unsigned_long_cxx
4264 : /*C++98 UB*/ diag::
4265 ext_old_implicitly_unsigned_long_cxx
4266 : diag::warn_old_implicitly_unsigned_long)
4267 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4268 : /*will be ill-formed*/ 1);
4269 Ty = Context.UnsignedLongTy;
4270 }
4271 Width = LongSize;
4272 }
4273 }
4274
4275 // Check long long if needed.
4276 if (Ty.isNull() && !Literal.isSizeT) {
4277 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4278
4279 // Does it fit in a unsigned long long?
4280 if (ResultVal.isIntN(LongLongSize)) {
4281 // Does it fit in a signed long long?
4282 // To be compatible with MSVC, hex integer literals ending with the
4283 // LL or i64 suffix are always signed in Microsoft mode.
4284 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4285 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4286 Ty = Context.LongLongTy;
4287 else if (AllowUnsigned)
4288 Ty = Context.UnsignedLongLongTy;
4289 Width = LongLongSize;
4290
4291 // 'long long' is a C99 or C++11 feature, whether the literal
4292 // explicitly specified 'long long' or we needed the extra width.
4293 if (getLangOpts().CPlusPlus)
4294 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4295 ? diag::warn_cxx98_compat_longlong
4296 : diag::ext_cxx11_longlong);
4297 else if (!getLangOpts().C99)
4298 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4299 }
4300 }
4301
4302 // If we still couldn't decide a type, we either have 'size_t' literal
4303 // that is out of range, or a decimal literal that does not fit in a
4304 // signed long long and has no U suffix.
4305 if (Ty.isNull()) {
4306 if (Literal.isSizeT)
4307 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4308 << Literal.isUnsigned;
4309 else
4310 Diag(Tok.getLocation(),
4311 diag::ext_integer_literal_too_large_for_signed);
4312 Ty = Context.UnsignedLongLongTy;
4313 Width = Context.getTargetInfo().getLongLongWidth();
4314 }
4315
4316 if (ResultVal.getBitWidth() != Width)
4317 ResultVal = ResultVal.trunc(Width);
4318 }
4319 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4320 }
4321
4322 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4323 if (Literal.isImaginary) {
4324 Res = new (Context) ImaginaryLiteral(Res,
4325 Context.getComplexType(Res->getType()));
4326
4327 // In C++, this is a GNU extension. In C, it's a C2y extension.
4328 if (getLangOpts().CPlusPlus)
4329 Diag(Tok.getLocation(), diag::ext_gnu_imaginary_constant);
4330 else
4331 DiagCompat(Tok.getLocation(), diag_compat::imaginary_constant);
4332 }
4333 return Res;
4334}
4335
4337 assert(E && "ActOnParenExpr() missing expr");
4338 QualType ExprTy = E->getType();
4339 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4340 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4341 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4342 return new (Context) ParenExpr(L, R, E);
4343}
4344
4346 SourceLocation Loc,
4347 SourceRange ArgRange) {
4348 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4349 // scalar or vector data type argument..."
4350 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4351 // type (C99 6.2.5p18) or void.
4352 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4353 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4354 << T << ArgRange;
4355 return true;
4356 }
4357
4358 assert((T->isVoidType() || !T->isIncompleteType()) &&
4359 "Scalar types should always be complete");
4360 return false;
4361}
4362
4364 SourceLocation Loc,
4365 SourceRange ArgRange) {
4366 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4367 if (!T->isVectorType() && !T->isSizelessVectorType())
4368 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4369 << ""
4370 << "__builtin_vectorelements" << T << ArgRange;
4371
4372 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
4373 if (T->isSVESizelessBuiltinType()) {
4374 llvm::StringMap<bool> CallerFeatureMap;
4375 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
4376 return S.ARM().checkSVETypeSupport(T, Loc, FD, CallerFeatureMap);
4377 }
4378 }
4379
4380 return false;
4381}
4382
4384 SourceLocation Loc,
4385 SourceRange ArgRange) {
4386 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4387 return true;
4388
4389 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4390 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4391 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4392 return true;
4393 }
4394
4395 return false;
4396}
4397
4399 SourceLocation Loc,
4400 SourceRange ArgRange,
4401 UnaryExprOrTypeTrait TraitKind) {
4402 // Invalid types must be hard errors for SFINAE in C++.
4403 if (S.LangOpts.CPlusPlus)
4404 return true;
4405
4406 // C99 6.5.3.4p1:
4407 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4408 TraitKind == UETT_PreferredAlignOf) {
4409
4410 // sizeof(function)/alignof(function) is allowed as an extension.
4411 if (T->isFunctionType()) {
4412 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4413 << getTraitSpelling(TraitKind) << ArgRange;
4414 return false;
4415 }
4416
4417 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4418 // this is an error (OpenCL v1.1 s6.3.k)
4419 if (T->isVoidType()) {
4420 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4421 : diag::ext_sizeof_alignof_void_type;
4422 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4423 return false;
4424 }
4425 }
4426 return true;
4427}
4428
4430 SourceLocation Loc,
4431 SourceRange ArgRange,
4432 UnaryExprOrTypeTrait TraitKind) {
4433 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4434 // runtime doesn't allow it.
4435 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4436 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4437 << T << (TraitKind == UETT_SizeOf)
4438 << ArgRange;
4439 return true;
4440 }
4441
4442 return false;
4443}
4444
4445/// Check whether E is a pointer from a decayed array type (the decayed
4446/// pointer type is equal to T) and emit a warning if it is.
4448 const Expr *E) {
4449 // Don't warn if the operation changed the type.
4450 if (T != E->getType())
4451 return;
4452
4453 // Now look for array decays.
4454 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4455 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4456 return;
4457
4458 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4459 << ICE->getType()
4460 << ICE->getSubExpr()->getType();
4461}
4462
4464 UnaryExprOrTypeTrait ExprKind) {
4465 QualType ExprTy = E->getType();
4466 assert(!ExprTy->isReferenceType());
4467
4468 bool IsUnevaluatedOperand =
4469 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4470 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4471 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4472 if (IsUnevaluatedOperand) {
4474 if (Result.isInvalid())
4475 return true;
4476 E = Result.get();
4477 }
4478
4479 // The operand for sizeof and alignof is in an unevaluated expression context,
4480 // so side effects could result in unintended consequences.
4481 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4482 // used to build SFINAE gadgets.
4483 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4484 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4486 !E->getType()->isVariableArrayType() &&
4487 E->HasSideEffects(Context, false))
4488 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4489
4490 if (ExprKind == UETT_VecStep)
4491 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4492 E->getSourceRange());
4493
4494 if (ExprKind == UETT_VectorElements)
4495 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4496 E->getSourceRange());
4497
4498 // Explicitly list some types as extensions.
4499 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4500 E->getSourceRange(), ExprKind))
4501 return false;
4502
4503 // WebAssembly tables are always illegal operands to unary expressions and
4504 // type traits.
4505 if (Context.getTargetInfo().getTriple().isWasm() &&
4507 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4508 << getTraitSpelling(ExprKind);
4509 return true;
4510 }
4511
4512 // 'alignof' applied to an expression only requires the base element type of
4513 // the expression to be complete. 'sizeof' requires the expression's type to
4514 // be complete (and will attempt to complete it if it's an array of unknown
4515 // bound).
4516 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4518 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4519 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4520 getTraitSpelling(ExprKind), E->getSourceRange()))
4521 return true;
4522 } else {
4524 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4525 getTraitSpelling(ExprKind), E->getSourceRange()))
4526 return true;
4527 }
4528
4529 // Completing the expression's type may have changed it.
4530 ExprTy = E->getType();
4531 assert(!ExprTy->isReferenceType());
4532
4533 if (ExprTy->isFunctionType()) {
4534 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4535 << getTraitSpelling(ExprKind) << E->getSourceRange();
4536 return true;
4537 }
4538
4539 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4540 E->getSourceRange(), ExprKind))
4541 return true;
4542
4543 if (ExprKind == UETT_CountOf) {
4544 // The type has to be an array type. We already checked for incomplete
4545 // types above.
4546 QualType ExprType = E->IgnoreParens()->getType();
4547 if (!ExprType->isArrayType()) {
4548 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4549 return true;
4550 }
4551 // FIXME: warn on _Countof on an array parameter. Not warning on it
4552 // currently because there are papers in WG14 about array types which do
4553 // not decay that could impact this behavior, so we want to see if anything
4554 // changes here before coming up with a warning group for _Countof-related
4555 // diagnostics.
4556 }
4557
4558 if (ExprKind == UETT_SizeOf) {
4559 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4560 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4561 QualType OType = PVD->getOriginalType();
4562 QualType Type = PVD->getType();
4563 if (Type->isPointerType() && OType->isArrayType()) {
4564 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4565 << Type << OType;
4566 Diag(PVD->getLocation(), diag::note_declared_at);
4567 }
4568 }
4569 }
4570
4571 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4572 // decays into a pointer and returns an unintended result. This is most
4573 // likely a typo for "sizeof(array) op x".
4574 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4575 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4576 BO->getLHS());
4577 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4578 BO->getRHS());
4579 }
4580 }
4581
4582 return false;
4583}
4584
4585static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4586 // Cannot know anything else if the expression is dependent.
4587 if (E->isTypeDependent())
4588 return false;
4589
4590 if (E->getObjectKind() == OK_BitField) {
4591 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4592 << 1 << E->getSourceRange();
4593 return true;
4594 }
4595
4596 ValueDecl *D = nullptr;
4597 Expr *Inner = E->IgnoreParens();
4598 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4599 D = DRE->getDecl();
4600 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4601 D = ME->getMemberDecl();
4602 }
4603
4604 // If it's a field, require the containing struct to have a
4605 // complete definition so that we can compute the layout.
4606 //
4607 // This can happen in C++11 onwards, either by naming the member
4608 // in a way that is not transformed into a member access expression
4609 // (in an unevaluated operand, for instance), or by naming the member
4610 // in a trailing-return-type.
4611 //
4612 // For the record, since __alignof__ on expressions is a GCC
4613 // extension, GCC seems to permit this but always gives the
4614 // nonsensical answer 0.
4615 //
4616 // We don't really need the layout here --- we could instead just
4617 // directly check for all the appropriate alignment-lowing
4618 // attributes --- but that would require duplicating a lot of
4619 // logic that just isn't worth duplicating for such a marginal
4620 // use-case.
4621 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4622 // Fast path this check, since we at least know the record has a
4623 // definition if we can find a member of it.
4624 if (!FD->getParent()->isCompleteDefinition()) {
4625 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4626 << E->getSourceRange();
4627 return true;
4628 }
4629
4630 // Otherwise, if it's a field, and the field doesn't have
4631 // reference type, then it must have a complete type (or be a
4632 // flexible array member, which we explicitly want to
4633 // white-list anyway), which makes the following checks trivial.
4634 if (!FD->getType()->isReferenceType())
4635 return false;
4636 }
4637
4638 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4639}
4640
4642 E = E->IgnoreParens();
4643
4644 // Cannot know anything else if the expression is dependent.
4645 if (E->isTypeDependent())
4646 return false;
4647
4648 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4649}
4650
4652 CapturingScopeInfo *CSI) {
4653 assert(T->isVariablyModifiedType());
4654 assert(CSI != nullptr);
4655
4656 // We're going to walk down into the type and look for VLA expressions.
4657 do {
4658 const Type *Ty = T.getTypePtr();
4659 switch (Ty->getTypeClass()) {
4660#define TYPE(Class, Base)
4661#define ABSTRACT_TYPE(Class, Base)
4662#define NON_CANONICAL_TYPE(Class, Base)
4663#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4664#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4665#include "clang/AST/TypeNodes.inc"
4666 T = QualType();
4667 break;
4668 // These types are never variably-modified.
4669 case Type::Builtin:
4670 case Type::Complex:
4671 case Type::Vector:
4672 case Type::ExtVector:
4673 case Type::ConstantMatrix:
4674 case Type::Record:
4675 case Type::Enum:
4676 case Type::TemplateSpecialization:
4677 case Type::ObjCObject:
4678 case Type::ObjCInterface:
4679 case Type::ObjCObjectPointer:
4680 case Type::ObjCTypeParam:
4681 case Type::Pipe:
4682 case Type::BitInt:
4683 case Type::HLSLInlineSpirv:
4684 llvm_unreachable("type class is never variably-modified!");
4685 case Type::Adjusted:
4686 T = cast<AdjustedType>(Ty)->getOriginalType();
4687 break;
4688 case Type::Decayed:
4689 T = cast<DecayedType>(Ty)->getPointeeType();
4690 break;
4691 case Type::ArrayParameter:
4692 T = cast<ArrayParameterType>(Ty)->getElementType();
4693 break;
4694 case Type::Pointer:
4695 T = cast<PointerType>(Ty)->getPointeeType();
4696 break;
4697 case Type::BlockPointer:
4698 T = cast<BlockPointerType>(Ty)->getPointeeType();
4699 break;
4700 case Type::LValueReference:
4701 case Type::RValueReference:
4702 T = cast<ReferenceType>(Ty)->getPointeeType();
4703 break;
4704 case Type::MemberPointer:
4705 T = cast<MemberPointerType>(Ty)->getPointeeType();
4706 break;
4707 case Type::ConstantArray:
4708 case Type::IncompleteArray:
4709 // Losing element qualification here is fine.
4710 T = cast<ArrayType>(Ty)->getElementType();
4711 break;
4712 case Type::VariableArray: {
4713 // Losing element qualification here is fine.
4715
4716 // Unknown size indication requires no size computation.
4717 // Otherwise, evaluate and record it.
4718 auto Size = VAT->getSizeExpr();
4719 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4721 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4722
4723 T = VAT->getElementType();
4724 break;
4725 }
4726 case Type::FunctionProto:
4727 case Type::FunctionNoProto:
4728 T = cast<FunctionType>(Ty)->getReturnType();
4729 break;
4730 case Type::Paren:
4731 case Type::TypeOf:
4732 case Type::UnaryTransform:
4733 case Type::Attributed:
4734 case Type::BTFTagAttributed:
4735 case Type::OverflowBehavior:
4736 case Type::HLSLAttributedResource:
4737 case Type::SubstTemplateTypeParm:
4738 case Type::MacroQualified:
4739 case Type::CountAttributed:
4740 case Type::LateParsedAttr:
4741 // Keep walking after single level desugaring.
4742 T = T.getSingleStepDesugaredType(Context);
4743 break;
4744 case Type::Typedef:
4745 T = cast<TypedefType>(Ty)->desugar();
4746 break;
4747 case Type::Decltype:
4748 T = cast<DecltypeType>(Ty)->desugar();
4749 break;
4750 case Type::PackIndexing:
4751 T = cast<PackIndexingType>(Ty)->desugar();
4752 break;
4753 case Type::Using:
4754 T = cast<UsingType>(Ty)->desugar();
4755 break;
4756 case Type::Auto:
4757 case Type::DeducedTemplateSpecialization:
4758 T = cast<DeducedType>(Ty)->getDeducedType();
4759 break;
4760 case Type::TypeOfExpr:
4761 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4762 break;
4763 case Type::Atomic:
4764 T = cast<AtomicType>(Ty)->getValueType();
4765 break;
4766 case Type::PredefinedSugar:
4767 T = cast<PredefinedSugarType>(Ty)->desugar();
4768 break;
4769 }
4770 } while (!T.isNull() && T->isVariablyModifiedType());
4771}
4772
4774 SourceLocation OpLoc,
4775 SourceRange ExprRange,
4776 UnaryExprOrTypeTrait ExprKind,
4777 StringRef KWName) {
4778 if (ExprType->isDependentType())
4779 return false;
4780
4781 // These builtins evaluate with the operand type as written; a reference is
4782 // not looked through.
4783 if (ExprKind == UETT_VectorElements)
4784 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4785 ExprRange);
4786 if (ExprKind == UETT_VecStep)
4787 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4788 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4789 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4790 ExprRange);
4791
4792 // C++ [expr.sizeof]p2:
4793 // When applied to a reference or a reference type, the result
4794 // is the size of the referenced type.
4795 // C++11 [expr.alignof]p3:
4796 // When alignof is applied to a reference type, the result
4797 // shall be the alignment of the referenced type.
4798 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4799 ExprType = Ref->getPointeeType();
4800
4801 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4802 // When alignof or _Alignof is applied to an array type, the result
4803 // is the alignment of the element type.
4804 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4805 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4806 // If the trait is 'alignof' in C before C2y, the ability to apply the
4807 // trait to an incomplete array is an extension.
4808 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4809 ExprType->isIncompleteArrayType())
4810 DiagCompat(OpLoc, diag_compat::alignof_incomplete_array);
4811 ExprType = Context.getBaseElementType(ExprType);
4812 }
4813
4814 // Explicitly list some types as extensions.
4815 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4816 ExprKind))
4817 return false;
4818
4820 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4821 KWName, ExprRange))
4822 return true;
4823
4824 if (ExprType->isFunctionType()) {
4825 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4826 return true;
4827 }
4828
4829 if (ExprKind == UETT_CountOf) {
4830 // The type has to be an array type. We already checked for incomplete
4831 // types above.
4832 if (!ExprType->isArrayType()) {
4833 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4834 return true;
4835 }
4836 }
4837
4838 // WebAssembly tables are always illegal operands to unary expressions and
4839 // type traits.
4840 if (Context.getTargetInfo().getTriple().isWasm() &&
4841 ExprType->isWebAssemblyTableType()) {
4842 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4843 << getTraitSpelling(ExprKind);
4844 return true;
4845 }
4846
4847 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4848 ExprKind))
4849 return true;
4850
4851 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4852 if (auto *TT = ExprType->getAs<TypedefType>()) {
4853 for (auto I = FunctionScopes.rbegin(),
4854 E = std::prev(FunctionScopes.rend());
4855 I != E; ++I) {
4856 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4857 if (CSI == nullptr)
4858 break;
4859 DeclContext *DC = nullptr;
4860 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4861 DC = LSI->CallOperator;
4862 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4863 DC = CRSI->TheCapturedDecl;
4864 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4865 DC = BSI->TheDecl;
4866 if (DC) {
4867 if (DC->containsDecl(TT->getDecl()))
4868 break;
4869 captureVariablyModifiedType(Context, ExprType, CSI);
4870 }
4871 }
4872 }
4873 }
4874
4875 return false;
4876}
4877
4879 SourceLocation OpLoc,
4880 UnaryExprOrTypeTrait ExprKind,
4881 SourceRange R) {
4882 if (!TInfo)
4883 return ExprError();
4884
4885 QualType T = TInfo->getType();
4886
4887 if (!T->isDependentType() &&
4888 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4889 getTraitSpelling(ExprKind)))
4890 return ExprError();
4891
4892 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4893 // properly deal with VLAs in nested calls of sizeof and typeof.
4894 if (currentEvaluationContext().isUnevaluated() &&
4895 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4896 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4897 TInfo->getType()->isVariablyModifiedType())
4898 TInfo = TransformToPotentiallyEvaluated(TInfo);
4899
4900 // It's possible that the transformation above failed.
4901 if (!TInfo)
4902 return ExprError();
4903
4904 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4905 return new (Context) UnaryExprOrTypeTraitExpr(
4906 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4907}
4908
4911 UnaryExprOrTypeTrait ExprKind) {
4913 if (PE.isInvalid())
4914 return ExprError();
4915
4916 E = PE.get();
4917
4918 // Verify that the operand is valid.
4919 bool isInvalid = false;
4920 if (E->isTypeDependent()) {
4921 // Delay type-checking for type-dependent expressions.
4922 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4923 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4924 } else if (ExprKind == UETT_VecStep) {
4926 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4927 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4928 isInvalid = true;
4929 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4930 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4931 isInvalid = true;
4932 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4933 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4935 }
4936
4937 if (isInvalid)
4938 return ExprError();
4939
4940 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4941 E->getType()->isVariableArrayType()) {
4943 if (PE.isInvalid()) return ExprError();
4944 E = PE.get();
4945 }
4946
4947 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4948 return new (Context) UnaryExprOrTypeTraitExpr(
4949 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4950}
4951
4954 UnaryExprOrTypeTrait ExprKind, bool IsType,
4955 void *TyOrEx, SourceRange ArgRange) {
4956 // If error parsing type, ignore.
4957 if (!TyOrEx) return ExprError();
4958
4959 if (IsType) {
4960 TypeSourceInfo *TInfo;
4961 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4962 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4963 }
4964
4965 Expr *ArgEx = (Expr *)TyOrEx;
4966 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4967 return Result;
4968}
4969
4971 SourceLocation OpLoc, SourceRange R) {
4972 if (!TInfo)
4973 return true;
4974 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4975 UETT_AlignOf, KWName);
4976}
4977
4979 SourceLocation OpLoc, SourceRange R) {
4980 TypeSourceInfo *TInfo;
4982 &TInfo);
4983 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4984}
4985
4987 bool IsReal) {
4988 if (V.get()->isTypeDependent())
4989 return S.Context.DependentTy;
4990
4991 // _Real and _Imag are only l-values for normal l-values.
4992 if (V.get()->getObjectKind() != OK_Ordinary) {
4993 V = S.DefaultLvalueConversion(V.get());
4994 if (V.isInvalid())
4995 return QualType();
4996 }
4997
4998 // These operators return the element type of a complex type.
4999 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
5000 return CT->getElementType();
5001
5002 // Otherwise they pass through real integer and floating point types here.
5003 if (V.get()->getType()->isArithmeticType())
5004 return V.get()->getType();
5005
5006 // Test for placeholders.
5007 ExprResult PR = S.CheckPlaceholderExpr(V.get());
5008 if (PR.isInvalid()) return QualType();
5009 if (PR.get() != V.get()) {
5010 V = PR;
5011 return CheckRealImagOperand(S, V, Loc, IsReal);
5012 }
5013
5014 // Reject anything else.
5015 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
5016 << (IsReal ? "__real" : "__imag");
5017 return QualType();
5018}
5019
5020
5021
5024 tok::TokenKind Kind, Expr *Input) {
5026 switch (Kind) {
5027 default: llvm_unreachable("Unknown unary op!");
5028 case tok::plusplus: Opc = UO_PostInc; break;
5029 case tok::minusminus: Opc = UO_PostDec; break;
5030 }
5031
5032 // Since this might is a postfix expression, get rid of ParenListExprs.
5034 if (Result.isInvalid()) return ExprError();
5035 Input = Result.get();
5036
5037 return BuildUnaryOp(S, OpLoc, Opc, Input);
5038}
5039
5040/// Diagnose if arithmetic on the given ObjC pointer is illegal.
5041///
5042/// \return true on error
5044 SourceLocation opLoc,
5045 Expr *op) {
5046 assert(op->getType()->isObjCObjectPointerType());
5048 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5049 return false;
5050
5051 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
5053 << op->getSourceRange();
5054 return true;
5055}
5056
5058 auto *BaseNoParens = Base->IgnoreParens();
5059 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
5060 return MSProp->getPropertyDecl()->getType()->isArrayType();
5061 return isa<MSPropertySubscriptExpr>(BaseNoParens);
5062}
5063
5064// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5065// Typically this is DependentTy, but can sometimes be more precise.
5066//
5067// There are cases when we could determine a non-dependent type:
5068// - LHS and RHS may have non-dependent types despite being type-dependent
5069// (e.g. unbounded array static members of the current instantiation)
5070// - one may be a dependent-sized array with known element type
5071// - one may be a dependent-typed valid index (enum in current instantiation)
5072//
5073// We *always* return a dependent type, in such cases it is DependentTy.
5074// This avoids creating type-dependent expressions with non-dependent types.
5075// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5077 const ASTContext &Ctx) {
5078 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5079 QualType LTy = LHS->getType(), RTy = RHS->getType();
5081 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5082 if (const PointerType *PT = LTy->getAs<PointerType>())
5083 Result = PT->getPointeeType();
5084 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5085 Result = AT->getElementType();
5086 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5087 if (const PointerType *PT = RTy->getAs<PointerType>())
5088 Result = PT->getPointeeType();
5089 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5090 Result = AT->getElementType();
5091 }
5092 // Ensure we return a dependent type.
5093 return Result->isDependentType() ? Result : Ctx.DependentTy;
5094}
5095
5097 SourceLocation lbLoc,
5098 MultiExprArg ArgExprs,
5099 SourceLocation rbLoc) {
5100
5101 if (base && !base->getType().isNull() &&
5102 base->hasPlaceholderType(BuiltinType::ArraySection)) {
5103 auto *AS = cast<ArraySectionExpr>(base);
5104 if (AS->isOMPArraySection())
5106 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
5107 /*Length*/ nullptr,
5108 /*Stride=*/nullptr, rbLoc);
5109
5110 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
5111 SourceLocation(), /*Length*/ nullptr,
5112 rbLoc);
5113 }
5114
5115 // Since this might be a postfix expression, get rid of ParenListExprs.
5116 if (isa<ParenListExpr>(base)) {
5118 if (result.isInvalid())
5119 return ExprError();
5120 base = result.get();
5121 }
5122
5123 // Check if base and idx form a MatrixSubscriptExpr.
5124 //
5125 // Helper to check for comma expressions, which are not allowed as indices for
5126 // matrix subscript expressions.
5127 //
5128 // In C++23, we get multiple arguments instead of a comma expression.
5129 auto CheckAndReportCommaError = [&](Expr *E) {
5130 if (ArgExprs.size() > 1 ||
5131 (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp())) {
5132 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5133 << SourceRange(base->getBeginLoc(), rbLoc);
5134 return true;
5135 }
5136 return false;
5137 };
5138 // The matrix subscript operator ([][])is considered a single operator.
5139 // Separating the index expressions by parenthesis is not allowed.
5140 if (base && !base->getType().isNull() &&
5141 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5142 !isa<MatrixSubscriptExpr>(base)) {
5143 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5144 << SourceRange(base->getBeginLoc(), rbLoc);
5145 return ExprError();
5146 }
5147 // If the base is a MatrixSubscriptExpr, try to create a new
5148 // MatrixSubscriptExpr.
5149 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5150 if (matSubscriptE && matSubscriptE->isIncomplete()) {
5151 if (CheckAndReportCommaError(ArgExprs.front()))
5152 return ExprError();
5153
5154 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5155 matSubscriptE->getRowIdx(),
5156 ArgExprs.front(), rbLoc);
5157 }
5158 if (base->getType()->isWebAssemblyTableType()) {
5159 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5160 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5161 return ExprError();
5162 }
5163
5164 CheckInvalidBuiltinCountedByRef(base,
5166
5167 // Handle any non-overload placeholder types in the base and index
5168 // expressions. We can't handle overloads here because the other
5169 // operand might be an overloadable type, in which case the overload
5170 // resolution for the operator overload should get the first crack
5171 // at the overload.
5172 bool IsMSPropertySubscript = false;
5173 if (base->getType()->isNonOverloadPlaceholderType()) {
5174 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5175 if (!IsMSPropertySubscript) {
5176 ExprResult result = CheckPlaceholderExpr(base);
5177 if (result.isInvalid())
5178 return ExprError();
5179 base = result.get();
5180 }
5181 }
5182
5183 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5184 if (base->getType()->isMatrixType()) {
5185 if (CheckAndReportCommaError(ArgExprs.front()))
5186 return ExprError();
5187
5188 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5189 rbLoc);
5190 }
5191
5192 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5193 Expr *idx = ArgExprs[0];
5194 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5196 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5197 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5198 << SourceRange(base->getBeginLoc(), rbLoc);
5199 }
5200 }
5201
5202 if (ArgExprs.size() == 1 &&
5203 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5204 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5205 if (result.isInvalid())
5206 return ExprError();
5207 ArgExprs[0] = result.get();
5208 } else {
5209 if (CheckArgsForPlaceholders(ArgExprs))
5210 return ExprError();
5211 }
5212
5213 // Build an unanalyzed expression if either operand is type-dependent.
5214 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5215 (base->isTypeDependent() ||
5217 !isa<PackExpansionExpr>(ArgExprs[0])) {
5218 return new (Context) ArraySubscriptExpr(
5219 base, ArgExprs.front(),
5220 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5221 VK_LValue, OK_Ordinary, rbLoc);
5222 }
5223
5224 // MSDN, property (C++)
5225 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5226 // This attribute can also be used in the declaration of an empty array in a
5227 // class or structure definition. For example:
5228 // __declspec(property(get=GetX, put=PutX)) int x[];
5229 // The above statement indicates that x[] can be used with one or more array
5230 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5231 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5232 if (IsMSPropertySubscript) {
5233 if (ArgExprs.size() > 1) {
5234 Diag(base->getExprLoc(),
5235 diag::err_ms_property_subscript_expects_single_arg);
5236 return ExprError();
5237 }
5238
5239 // Build MS property subscript expression if base is MS property reference
5240 // or MS property subscript.
5241 return new (Context)
5242 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5243 VK_LValue, OK_Ordinary, rbLoc);
5244 }
5245
5246 // Use C++ overloaded-operator rules if either operand has record
5247 // type. The spec says to do this if either type is *overloadable*,
5248 // but enum types can't declare subscript operators or conversion
5249 // operators, so there's nothing interesting for overload resolution
5250 // to do if there aren't any record types involved.
5251 //
5252 // ObjC pointers have their own subscripting logic that is not tied
5253 // to overload resolution and so should not take this path.
5254 //
5255 // Issue a better diagnostic if we tried to pass multiple arguments to
5256 // a builtin subscript operator rather than diagnosing this as a generic
5257 // overload resolution failure.
5258 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5259 !base->getType()->isRecordType() &&
5260 !base->getType()->isObjCObjectPointerType()) {
5261 Diag(base->getExprLoc(), diag::err_ovl_builtin_subscript_expects_single_arg)
5262 << base->getType() << base->getSourceRange();
5263 return ExprError();
5264 }
5265
5267 ((base->getType()->isRecordType() ||
5268 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5269 ArgExprs[0]->getType()->isRecordType())))) {
5270 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5271 }
5272
5273 ExprResult Res =
5274 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5275
5276 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5277 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5278
5279 return Res;
5280}
5281
5284 InitializationKind Kind =
5286 InitializationSequence InitSeq(*this, Entity, Kind, E);
5287 return InitSeq.Perform(*this, Entity, Kind, E);
5288}
5289
5291 Expr *RowIdx,
5292 SourceLocation RBLoc) {
5294 if (BaseR.isInvalid())
5295 return BaseR;
5296 Base = BaseR.get();
5297
5298 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5299 if (RowR.isInvalid())
5300 return RowR;
5301 RowIdx = RowR.get();
5302
5303 // Build an unanalyzed expression if any of the operands is type-dependent.
5304 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5305 return new (Context)
5306 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5307
5308 // Check that IndexExpr is an integer expression. If it is a constant
5309 // expression, check that it is less than Dim (= the number of elements in the
5310 // corresponding dimension).
5311 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5312 bool IsColumnIdx) -> Expr * {
5313 if (!IndexExpr->getType()->isIntegerType() &&
5314 !IndexExpr->isTypeDependent()) {
5315 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5316 << IsColumnIdx;
5317 return nullptr;
5318 }
5319
5320 if (std::optional<llvm::APSInt> Idx =
5321 IndexExpr->getIntegerConstantExpr(Context)) {
5322 if ((*Idx < 0 || *Idx >= Dim)) {
5323 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5324 << IsColumnIdx << Dim;
5325 return nullptr;
5326 }
5327 }
5328
5329 ExprResult ConvExpr = IndexExpr;
5330 assert(!ConvExpr.isInvalid() &&
5331 "should be able to convert any integer type to size type");
5332 return ConvExpr.get();
5333 };
5334
5335 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5336 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5337 if (!RowIdx)
5338 return ExprError();
5339
5340 QualType RowVecQT =
5341 Context.getExtVectorType(MTy->getElementType(), MTy->getNumColumns());
5342
5343 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5344}
5345
5347 Expr *ColumnIdx,
5348 SourceLocation RBLoc) {
5350 if (BaseR.isInvalid())
5351 return BaseR;
5352 Base = BaseR.get();
5353
5354 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5355 if (RowR.isInvalid())
5356 return RowR;
5357 RowIdx = RowR.get();
5358
5359 if (!ColumnIdx)
5360 return new (Context) MatrixSubscriptExpr(
5361 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5362
5363 // Build an unanalyzed expression if any of the operands is type-dependent.
5364 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5365 ColumnIdx->isTypeDependent())
5366 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5367 Context.DependentTy, RBLoc);
5368
5369 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5370 if (ColumnR.isInvalid())
5371 return ColumnR;
5372 ColumnIdx = ColumnR.get();
5373
5374 // Check that IndexExpr is an integer expression. If it is a constant
5375 // expression, check that it is less than Dim (= the number of elements in the
5376 // corresponding dimension).
5377 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5378 bool IsColumnIdx) -> Expr * {
5379 if (!IndexExpr->getType()->isIntegerType() &&
5380 !IndexExpr->isTypeDependent()) {
5381 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5382 << IsColumnIdx;
5383 return nullptr;
5384 }
5385
5386 if (std::optional<llvm::APSInt> Idx =
5387 IndexExpr->getIntegerConstantExpr(Context)) {
5388 if ((*Idx < 0 || *Idx >= Dim)) {
5389 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5390 << IsColumnIdx << Dim;
5391 return nullptr;
5392 }
5393 }
5394
5395 ExprResult ConvExpr = IndexExpr;
5396 assert(!ConvExpr.isInvalid() &&
5397 "should be able to convert any integer type to size type");
5398 return ConvExpr.get();
5399 };
5400
5401 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5402 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5403 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5404 if (!RowIdx || !ColumnIdx)
5405 return ExprError();
5406
5407 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5408 MTy->getElementType(), RBLoc);
5409}
5410
5411void Sema::CheckAddressOfNoDeref(const Expr *E) {
5412 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5413 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5414
5415 // For expressions like `&(*s).b`, the base is recorded and what should be
5416 // checked.
5417 const MemberExpr *Member = nullptr;
5418 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5419 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5420
5421 LastRecord.PossibleDerefs.erase(StrippedExpr);
5422}
5423
5424void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5426 return;
5427
5428 QualType ResultTy = E->getType();
5429 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5430
5431 // Bail if the element is an array since it is not memory access.
5432 if (isa<ArrayType>(ResultTy))
5433 return;
5434
5435 if (ResultTy->hasAttr(attr::NoDeref)) {
5436 LastRecord.PossibleDerefs.insert(E);
5437 return;
5438 }
5439
5440 // Check if the base type is a pointer to a member access of a struct
5441 // marked with noderef.
5442 const Expr *Base = E->getBase();
5443 QualType BaseTy = Base->getType();
5444 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5445 // Not a pointer access
5446 return;
5447
5448 const MemberExpr *Member = nullptr;
5449 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5450 Member->isArrow())
5451 Base = Member->getBase();
5452
5453 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5454 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5455 LastRecord.PossibleDerefs.insert(E);
5456 }
5457}
5458
5461 Expr *Idx, SourceLocation RLoc) {
5462 Expr *LHSExp = Base;
5463 Expr *RHSExp = Idx;
5464
5467
5468 // Per C++ core issue 1213, the result is an xvalue if either operand is
5469 // a non-lvalue array, and an lvalue otherwise.
5470 if (getLangOpts().CPlusPlus11) {
5471 for (auto *Op : {LHSExp, RHSExp}) {
5472 Op = Op->IgnoreImplicit();
5473 if (Op->getType()->isArrayType() && !Op->isLValue())
5474 VK = VK_XValue;
5475 }
5476 }
5477
5478 // Perform default conversions.
5479 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5481 if (Result.isInvalid())
5482 return ExprError();
5483 LHSExp = Result.get();
5484 }
5486 if (Result.isInvalid())
5487 return ExprError();
5488 RHSExp = Result.get();
5489
5490 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5491
5492 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5493 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5494 // in the subscript position. As a result, we need to derive the array base
5495 // and index from the expression types.
5496 Expr *BaseExpr, *IndexExpr;
5497 QualType ResultType;
5498 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5499 BaseExpr = LHSExp;
5500 IndexExpr = RHSExp;
5501 ResultType =
5503 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5504 BaseExpr = LHSExp;
5505 IndexExpr = RHSExp;
5506 ResultType = PTy->getPointeeType();
5507 } else if (const ObjCObjectPointerType *PTy =
5508 LHSTy->getAs<ObjCObjectPointerType>()) {
5509 BaseExpr = LHSExp;
5510 IndexExpr = RHSExp;
5511
5512 // Use custom logic if this should be the pseudo-object subscript
5513 // expression.
5514 if (!LangOpts.isSubscriptPointerArithmetic())
5515 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5516 nullptr, nullptr);
5517
5518 ResultType = PTy->getPointeeType();
5519 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5520 // Handle the uncommon case of "123[Ptr]".
5521 BaseExpr = RHSExp;
5522 IndexExpr = LHSExp;
5523 ResultType = PTy->getPointeeType();
5524 } else if (const ObjCObjectPointerType *PTy =
5525 RHSTy->getAs<ObjCObjectPointerType>()) {
5526 // Handle the uncommon case of "123[Ptr]".
5527 BaseExpr = RHSExp;
5528 IndexExpr = LHSExp;
5529 ResultType = PTy->getPointeeType();
5530 if (!LangOpts.isSubscriptPointerArithmetic()) {
5531 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5532 << ResultType << BaseExpr->getSourceRange();
5533 return ExprError();
5534 }
5535 } else if (LHSTy->isSubscriptableVectorType()) {
5536 if (LHSTy->isBuiltinType() &&
5537 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5538 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5539 if (BTy->isSVEBool())
5540 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5541 << LHSExp->getSourceRange()
5542 << RHSExp->getSourceRange());
5543 ResultType = BTy->getSveEltType(Context);
5544 } else {
5545 const VectorType *VTy = LHSTy->getAs<VectorType>();
5546 ResultType = VTy->getElementType();
5547 }
5548 BaseExpr = LHSExp; // vectors: V[123]
5549 IndexExpr = RHSExp;
5550 // We apply C++ DR1213 to vector subscripting too.
5551 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5552 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5553 if (Materialized.isInvalid())
5554 return ExprError();
5555 LHSExp = Materialized.get();
5556 }
5557 VK = LHSExp->getValueKind();
5558 if (VK != VK_PRValue)
5559 OK = OK_VectorComponent;
5560
5561 QualType BaseType = BaseExpr->getType();
5562 Qualifiers BaseQuals = BaseType.getQualifiers();
5563 Qualifiers MemberQuals = ResultType.getQualifiers();
5564 Qualifiers Combined = BaseQuals + MemberQuals;
5565 if (Combined != MemberQuals)
5566 ResultType = Context.getQualifiedType(ResultType, Combined);
5567 } else if (LHSTy->isArrayType()) {
5568 // If we see an array that wasn't promoted by
5569 // DefaultFunctionArrayLvalueConversion, it must be an array that
5570 // wasn't promoted because of the C90 rule that doesn't
5571 // allow promoting non-lvalue arrays. Warn, then
5572 // force the promotion here.
5573 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5574 << LHSExp->getSourceRange();
5575 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5576 CK_ArrayToPointerDecay).get();
5577 LHSTy = LHSExp->getType();
5578
5579 BaseExpr = LHSExp;
5580 IndexExpr = RHSExp;
5581 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5582 } else if (RHSTy->isArrayType()) {
5583 // Same as previous, except for 123[f().a] case
5584 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5585 << RHSExp->getSourceRange();
5586 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5587 CK_ArrayToPointerDecay).get();
5588 RHSTy = RHSExp->getType();
5589
5590 BaseExpr = RHSExp;
5591 IndexExpr = LHSExp;
5592 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5593 } else {
5594 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5595 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5596 }
5597 // C99 6.5.2.1p1
5598 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5599 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5600 << IndexExpr->getSourceRange());
5601
5602 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5603 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5604 !IndexExpr->isTypeDependent()) {
5605 std::optional<llvm::APSInt> IntegerContantExpr =
5607 if (!IntegerContantExpr.has_value() ||
5608 IntegerContantExpr.value().isNegative())
5609 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5610 }
5611
5612 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5613 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5614 // type. Note that Functions are not objects, and that (in C99 parlance)
5615 // incomplete types are not object types.
5616 if (ResultType->isFunctionType()) {
5617 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5618 << ResultType << BaseExpr->getSourceRange();
5619 return ExprError();
5620 }
5621
5622 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5623 // GNU extension: subscripting on pointer to void
5624 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5625 << BaseExpr->getSourceRange();
5626
5627 // C forbids expressions of unqualified void type from being l-values.
5628 // See IsCForbiddenLValueType.
5629 if (!ResultType.hasQualifiers())
5630 VK = VK_PRValue;
5631 } else if (!ResultType->isDependentType() &&
5632 !ResultType.isWebAssemblyReferenceType() &&
5634 LLoc, ResultType,
5635 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5636 return ExprError();
5637
5638 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5639 !ResultType.isCForbiddenLValueType());
5640
5642 FunctionScopes.size() > 1) {
5643 if (auto *TT =
5644 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5645 for (auto I = FunctionScopes.rbegin(),
5646 E = std::prev(FunctionScopes.rend());
5647 I != E; ++I) {
5648 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5649 if (CSI == nullptr)
5650 break;
5651 DeclContext *DC = nullptr;
5652 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5653 DC = LSI->CallOperator;
5654 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5655 DC = CRSI->TheCapturedDecl;
5656 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5657 DC = BSI->TheDecl;
5658 if (DC) {
5659 if (DC->containsDecl(TT->getDecl()))
5660 break;
5662 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5663 }
5664 }
5665 }
5666 }
5667
5668 return new (Context)
5669 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5670}
5671
5673 ParmVarDecl *Param, Expr *RewrittenInit,
5674 bool SkipImmediateInvocations) {
5675 if (Param->hasUnparsedDefaultArg()) {
5676 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5677 // If we've already cleared out the location for the default argument,
5678 // that means we're parsing it right now.
5679 if (!UnparsedDefaultArgLocs.count(Param)) {
5680 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5681 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5682 Param->setInvalidDecl();
5683 return true;
5684 }
5685
5686 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5687 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5689 diag::note_default_argument_declared_here);
5690 return true;
5691 }
5692
5693 if (Param->hasUninstantiatedDefaultArg()) {
5694 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5695 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5696 return true;
5697 }
5698
5699 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5700 assert(Init && "default argument but no initializer?");
5701
5702 // If the default expression creates temporaries, we need to
5703 // push them to the current stack of expression temporaries so they'll
5704 // be properly destroyed.
5705 // FIXME: We should really be rebuilding the default argument with new
5706 // bound temporaries; see the comment in PR5810.
5707 // We don't need to do that with block decls, though, because
5708 // blocks in default argument expression can never capture anything.
5709 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5710 // Set the "needs cleanups" bit regardless of whether there are
5711 // any explicit objects.
5712 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5713 // Append all the objects to the cleanup list. Right now, this
5714 // should always be a no-op, because blocks in default argument
5715 // expressions should never be able to capture anything.
5716 assert(!InitWithCleanup->getNumObjects() &&
5717 "default argument expression has capturing blocks?");
5718 }
5719 // C++ [expr.const]p15.1:
5720 // An expression or conversion is in an immediate function context if it is
5721 // potentially evaluated and [...] its innermost enclosing non-block scope
5722 // is a function parameter scope of an immediate function.
5724 *this,
5728 Param);
5729 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5730 SkipImmediateInvocations;
5731 runWithSufficientStackSpace(CallLoc, [&] {
5732 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5733 });
5734 return false;
5735}
5736
5741 }
5742
5743 bool HasImmediateCalls = false;
5744
5745 bool VisitCallExpr(CallExpr *E) override {
5746 if (const FunctionDecl *FD = E->getDirectCallee())
5747 HasImmediateCalls |= FD->isImmediateFunction();
5749 }
5750
5752 if (const FunctionDecl *FD = E->getConstructor())
5753 HasImmediateCalls |= FD->isImmediateFunction();
5755 }
5756
5757 // SourceLocExpr are not immediate invocations
5758 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5759 // need to be rebuilt so that they refer to the correct SourceLocation and
5760 // DeclContext.
5762 HasImmediateCalls = true;
5764 }
5765
5766 // A nested lambda might have parameters with immediate invocations
5767 // in their default arguments.
5768 // The compound statement is not visited (as it does not constitute a
5769 // subexpression).
5770 // FIXME: We should consider visiting and transforming captures
5771 // with init expressions.
5772 bool VisitLambdaExpr(LambdaExpr *E) override {
5773 return VisitCXXMethodDecl(E->getCallOperator());
5774 }
5775
5777 return TraverseStmt(E->getExpr());
5778 }
5779
5781 return TraverseStmt(E->getExpr());
5782 }
5783};
5784
5786 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5789
5790 bool AlwaysRebuild() { return true; }
5791
5792 // Lambda can only have immediate invocations in the default
5793 // args of their parameters, which is transformed upon calling the closure.
5794 // The body is not a subexpression, so we have nothing to do.
5795 // FIXME: Immediate calls in capture initializers should be transformed.
5798
5799 // Make sure we don't rebuild the this pointer as it would
5800 // cause it to incorrectly point it to the outermost class
5801 // in the case of nested struct initialization.
5803
5804 // Rewrite to source location to refer to the context in which they are used.
5806 DeclContext *DC = E->getParentContext();
5807 if (DC == SemaRef.CurContext)
5808 return E;
5809
5810 // FIXME: During instantiation, because the rebuild of defaults arguments
5811 // is not always done in the context of the template instantiator,
5812 // we run the risk of producing a dependent source location
5813 // that would never be rebuilt.
5814 // This usually happens during overload resolution, or in contexts
5815 // where the value of the source location does not matter.
5816 // However, we should find a better way to deal with source location
5817 // of function templates.
5818 if (!SemaRef.CurrentInstantiationScope ||
5819 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5820 DC = SemaRef.CurContext;
5821
5822 return getDerived().RebuildSourceLocExpr(
5823 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5824 }
5825};
5826
5828 FunctionDecl *FD, ParmVarDecl *Param,
5829 Expr *Init) {
5830 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5831
5832 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5833 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5834 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5835 InitializationContext =
5837 if (!InitializationContext.has_value())
5838 InitializationContext.emplace(CallLoc, Param, CurContext);
5839
5840 if (!Init && !Param->hasUnparsedDefaultArg()) {
5841 // Mark that we are replacing a default argument first.
5842 // If we are instantiating a template we won't have to
5843 // retransform immediate calls.
5844 // C++ [expr.const]p15.1:
5845 // An expression or conversion is in an immediate function context if it
5846 // is potentially evaluated and [...] its innermost enclosing non-block
5847 // scope is a function parameter scope of an immediate function.
5849 *this,
5853 Param);
5854
5855 if (Param->hasUninstantiatedDefaultArg()) {
5856 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5857 return ExprError();
5858 }
5859 // CWG2631
5860 // An immediate invocation that is not evaluated where it appears is
5861 // evaluated and checked for whether it is a constant expression at the
5862 // point where the enclosing initializer is used in a function call.
5864 if (!NestedDefaultChecking)
5865 V.TraverseDecl(Param);
5866
5867 // Rewrite the call argument that was created from the corresponding
5868 // parameter's default argument.
5869 if (V.HasImmediateCalls ||
5870 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5871 if (V.HasImmediateCalls)
5872 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5873 CallLoc, Param, CurContext};
5874 // Pass down lifetime extending flag, and collect temporaries in
5875 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5879 ExprResult Res;
5880 runWithSufficientStackSpace(CallLoc, [&] {
5881 Res = Immediate.TransformInitializer(Param->getInit(),
5882 /*NotCopy=*/false);
5883 });
5884 if (Res.isInvalid())
5885 return ExprError();
5886 Res = ConvertParamDefaultArgument(Param, Res.get(),
5887 Res.get()->getBeginLoc());
5888 if (Res.isInvalid())
5889 return ExprError();
5890 Init = Res.get();
5891 }
5892 }
5893
5895 CallLoc, FD, Param, Init,
5896 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5897 return ExprError();
5898
5899 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5900 Init, InitializationContext->Context);
5901}
5902
5904 FieldDecl *Field) {
5905 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5906 return Pattern;
5907 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5908 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5910 ClassPattern->lookup(Field->getDeclName());
5911 auto Rng = llvm::make_filter_range(
5912 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5913 if (Rng.empty())
5914 return nullptr;
5915 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5916 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5917 // && "Duplicated instantiation pattern for field decl");
5918 return cast<FieldDecl>(*Rng.begin());
5919}
5920
5921ExprResult Sema::BuildCXXDefaultInitInternal(SourceLocation Loc,
5922 FieldDecl *Field,
5923 const InitializedEntity &Entity,
5924 bool NestedDefaultChecking,
5925 bool NeedRebuild) {
5926 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5927
5928 if (!Field->getInClassInitializer() &&
5929 isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5930 // Maybe we haven't instantiated the in-class initializer. Go check the
5931 // pattern FieldDecl to see if it has one.
5932 FieldDecl *Pattern =
5934 assert(Pattern && "We must have set the Pattern!");
5935 if (!Pattern->hasInClassInitializer() ||
5936 InstantiateInClassInitializer(Loc, Field, Pattern,
5938 return ExprError();
5939 }
5940
5941 Expr *InClassInit = Field->getInClassInitializer();
5942 if (!InClassInit) {
5943 // DR1351:
5944 // If the brace-or-equal-initializer of a non-static data member
5945 // invokes a defaulted default constructor of its class or of an
5946 // enclosing class in a potentially evaluated subexpression, the
5947 // program is ill-formed.
5948 //
5949 // This resolution is unworkable: the exception specification of the
5950 // default constructor can be needed in an unevaluated context, in
5951 // particular, in the operand of a noexcept-expression, and we can be
5952 // unable to compute an exception specification for an enclosed class.
5953 //
5954 // Any attempt to resolve the exception specification of a defaulted default
5955 // constructor before the initializer is lexically complete will ultimately
5956 // come here at which point we can diagnose it.
5957 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5958 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5959 << OutermostClass << Field;
5960 Diag(Field->getEndLoc(),
5961 diag::note_default_member_initializer_not_yet_parsed);
5962 // Recover by marking the field invalid, unless we're in a SFINAE context.
5963 if (!isSFINAEContext())
5964 Field->setInvalidDecl();
5965 return ExprError();
5966 }
5967
5968 // CWG2631
5969 // An immediate invocation that is not evaluated where it appears is
5970 // evaluated and checked for whether it is a constant expression at the
5971 // point where the enclosing initializer is used in a [...] a constructor
5972 // definition, or an aggregate initialization.
5973 ImmediateCallVisitor V(getASTContext());
5974 if (!NestedDefaultChecking)
5975 V.TraverseDecl(Field);
5976
5977 // CWG1815
5978 // Support lifetime extension of temporary created by aggregate
5979 // initialization using a default member initializer. We should rebuild
5980 // the initializer in a lifetime extension context if the initializer
5981 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5982 // extension code recurses into the default initializer and does lifetime
5983 // extension when warranted.
5984 bool ContainsAnyTemporaries = isa<ExprWithCleanups>(InClassInit);
5985 Expr *Init = InClassInit;
5986 if (!InClassInit->containsErrors() &&
5987 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5988 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5989 CurContext};
5990 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5991 NestedDefaultChecking;
5992 // Pass down lifetime extending flag, and collect temporaries in
5993 // CreateMaterializeTemporaryExpr when we rewrite the initializer.
5996
5997 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5998 ExprResult Res;
6000 Res = Immediate.TransformInitializer(InClassInit,
6001 /*CXXDirectInit=*/false);
6002 });
6003 if (!Res.isInvalid())
6004 Res = ConvertMemberDefaultInitExpression(Field, Entity, Res.get(), Loc);
6005 if (Res.isInvalid()) {
6006 Field->setInvalidDecl();
6007 return ExprError();
6008 }
6009 Init = Res.get();
6010 }
6011
6012 if (!NestedDefaultChecking)
6014 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/false);
6015 });
6016 return Init;
6017}
6018
6020 FieldDecl *Field) {
6021 assert(Field->hasInClassInitializer());
6022
6023 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6024
6025 // C++11 [class.base.init]p7:
6026 // The initialization of each base and member constitutes a
6027 // full-expression.
6028 // So this initializer gets an evaluation context of its own, and is finished
6029 // as a full-expression below.
6032 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6033
6035 if (!InitContext)
6036 InitContext.emplace(Loc, Field, CurContext);
6037
6038 // [class.temporary]/p7:
6039 // If such a temporary object would otherwise be destroyed at the end of the
6040 // for-range-initializer full-expression, the object persists for the lifetime
6041 // of the reference initialized by the for-range-initializer.
6042 //
6043 // A default member initializer used by a constructor is a separate
6044 // full-expression, we don't need extend temporaries lifetime in this
6045 // situation, the NeedRebuild will always false.
6046 ExprResult Init = BuildCXXDefaultInitInternal(
6047 Loc, Field,
6049 NestedDefaultChecking, /*NeedRebuild=*/false);
6050 if (Init.isInvalid())
6051 return ExprError();
6052
6053 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue=*/false);
6054 if (Init.isInvalid()) {
6055 Field->setInvalidDecl();
6056 return ExprError();
6057 }
6058
6060 Context, InitContext->Loc, Field, InitContext->Context,
6061 Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6062}
6063
6066 const InitializedEntity &MemberEntity) {
6067 assert(Field->hasInClassInitializer());
6068
6069 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6070
6071 // Unlike a mem-initializer, this initializer is a subexpression of the
6072 // full-expression containing the aggregate initialization. It is evaluated
6073 // exactly as that full-expression is, so inherit the enclosing context kind
6074 // rather than forcing a potentially evaluated one.
6076 *this, currentEvaluationContext().Context, Field);
6077 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6078
6080 if (!InitContext)
6081 InitContext.emplace(Loc, Field, CurContext);
6082
6083 // [class.temporary]/p7:
6084 // If such a temporary object would otherwise be destroyed at the end of the
6085 // for-range-initializer full-expression, the object persists for the lifetime
6086 // of the reference initialized by the for-range-initializer.
6087 //
6088 // A default member initializer used by an aggregate initialization belongs to
6089 // the full-expression containing the aggregate initialization. we need extend
6090 // temporaries lifetime in this situation, the NeedRebuild will always true.
6091
6092 // CWG1815: always rebuild, never share the AST built when the field was
6093 // declared. Only a copy rebuilt here has its MaterializeTemporaryExprs
6094 // collected in this context, which is what lets the aggregate initialization
6095 // lifetime-extend them; sharing one AST would also make several uses of the
6096 // same field fight over its extension. A mem-initializer has no such need,
6097 // as its temporaries die at the end of the initializer itself.
6098 ExprResult Init = BuildCXXDefaultInitInternal(
6099 Loc, Field, MemberEntity, NestedDefaultChecking, /*NeedRebuild=*/true);
6100 if (Init.isInvalid())
6101 return ExprError();
6102
6103 // Deliberately not finished as a full-expression: leaving the temporaries it
6104 // created on ExprCleanupObjects lets PopExpressionEvaluationContext merge
6105 // them into the enclosing context, which eventually wraps them all in a
6106 // single ExprWithCleanups. They are then destroyed at the end of the
6107 // containing full-expression, in reverse construction order.
6108
6110 Context, InitContext->Loc, Field, InitContext->Context,
6111 Init.get() == Field->getInClassInitializer() ? nullptr : Init.get());
6112}
6113
6115 const FunctionProtoType *Proto,
6116 Expr *Fn) {
6117 if (Proto && Proto->isVariadic()) {
6118 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6120 else if (Fn && Fn->getType()->isBlockPointerType())
6122 else if (FDecl) {
6123 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6124 if (Method->isInstance())
6126 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6129 }
6131}
6132
6133namespace {
6134class FunctionCallCCC final : public FunctionCallFilterCCC {
6135public:
6136 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6137 unsigned NumArgs, MemberExpr *ME)
6138 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6139 FunctionName(FuncName) {}
6140
6141 bool ValidateCandidate(const TypoCorrection &candidate) override {
6142 if (!candidate.getCorrectionSpecifier() ||
6143 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6144 return false;
6145 }
6146
6148 }
6149
6150 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6151 return std::make_unique<FunctionCallCCC>(*this);
6152 }
6153
6154private:
6155 const IdentifierInfo *const FunctionName;
6156};
6157}
6158
6160 FunctionDecl *FDecl,
6161 ArrayRef<Expr *> Args) {
6162 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6163 DeclarationName FuncName = FDecl->getDeclName();
6164 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6165
6166 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6167 if (TypoCorrection Corrected = S.CorrectTypo(
6169 S.getScopeForContext(S.CurContext), nullptr, CCC,
6171 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6172 if (Corrected.isOverloaded()) {
6175 for (NamedDecl *CD : Corrected) {
6176 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6178 OCS);
6179 }
6180 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6181 case OR_Success:
6182 ND = Best->FoundDecl;
6183 Corrected.setCorrectionDecl(ND);
6184 break;
6185 default:
6186 break;
6187 }
6188 }
6189 ND = ND->getUnderlyingDecl();
6191 return Corrected;
6192 }
6193 }
6194 return TypoCorrection();
6195}
6196
6197// [C++26][[expr.unary.op]/p4
6198// A pointer to member is only formed when an explicit &
6199// is used and its operand is a qualified-id not enclosed in parentheses.
6201 if (!isa<ParenExpr>(Fn))
6202 return false;
6203
6204 Fn = Fn->IgnoreParens();
6205
6206 auto *UO = dyn_cast<UnaryOperator>(Fn);
6207 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6208 return false;
6209 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
6210 return DRE->hasQualifier();
6211 }
6212 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
6213 return bool(OVL->getQualifier());
6214 return false;
6215}
6216
6217bool
6219 FunctionDecl *FDecl,
6220 const FunctionProtoType *Proto,
6221 ArrayRef<Expr *> Args,
6222 SourceLocation RParenLoc,
6223 bool IsExecConfig) {
6224 // Bail out early if calling a builtin with custom typechecking.
6225 // For HLSL builtin aliases, argument conversion is still needed because
6226 // overload resolution may have selected a conversion sequence (e.g.,
6227 // vector-to-scalar truncation) that must be applied before the custom
6228 // type checker runs.
6229 if (FDecl)
6230 if (unsigned ID = FDecl->getBuiltinID())
6231 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6232 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6233 return false;
6234
6235 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6236 // assignment, to the types of the corresponding parameter, ...
6237
6238 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6239 bool HasExplicitObjectParameter =
6240 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6241 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6242 unsigned NumParams = Proto->getNumParams();
6243 bool Invalid = false;
6244 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6245 unsigned FnKind = Fn->getType()->isBlockPointerType()
6246 ? 1 /* block */
6247 : (IsExecConfig ? 3 /* kernel function (exec config) */
6248 : 0 /* function */);
6249
6250 // If too few arguments are available (and we don't have default
6251 // arguments for the remaining parameters), don't make the call.
6252 if (Args.size() < NumParams) {
6253 if (Args.size() < MinArgs) {
6254 TypoCorrection TC;
6255 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6256 unsigned diag_id =
6257 MinArgs == NumParams && !Proto->isVariadic()
6258 ? diag::err_typecheck_call_too_few_args_suggest
6259 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6261 TC, PDiag(diag_id)
6262 << FnKind << MinArgs - ExplicitObjectParameterOffset
6263 << static_cast<unsigned>(Args.size()) -
6264 ExplicitObjectParameterOffset
6265 << HasExplicitObjectParameter << TC.getCorrectionRange());
6266 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6267 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6268 ->getDeclName())
6269 Diag(RParenLoc,
6270 MinArgs == NumParams && !Proto->isVariadic()
6271 ? diag::err_typecheck_call_too_few_args_one
6272 : diag::err_typecheck_call_too_few_args_at_least_one)
6273 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6274 << HasExplicitObjectParameter << Fn->getSourceRange();
6275 else
6276 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6277 ? diag::err_typecheck_call_too_few_args
6278 : diag::err_typecheck_call_too_few_args_at_least)
6279 << FnKind << MinArgs - ExplicitObjectParameterOffset
6280 << static_cast<unsigned>(Args.size()) -
6281 ExplicitObjectParameterOffset
6282 << HasExplicitObjectParameter << Fn->getSourceRange();
6283
6284 // Emit the location of the prototype.
6285 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6286 Diag(FDecl->getLocation(), diag::note_callee_decl)
6287 << FDecl << FDecl->getParametersSourceRange();
6288
6289 return true;
6290 }
6291 // We reserve space for the default arguments when we create
6292 // the call expression, before calling ConvertArgumentsForCall.
6293 assert((Call->getNumArgs() == NumParams) &&
6294 "We should have reserved space for the default arguments before!");
6295 }
6296
6297 // If too many are passed and not variadic, error on the extras and drop
6298 // them.
6299 if (Args.size() > NumParams) {
6300 if (!Proto->isVariadic()) {
6301 TypoCorrection TC;
6302 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6303 unsigned diag_id =
6304 MinArgs == NumParams && !Proto->isVariadic()
6305 ? diag::err_typecheck_call_too_many_args_suggest
6306 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6308 TC, PDiag(diag_id)
6309 << FnKind << NumParams - ExplicitObjectParameterOffset
6310 << static_cast<unsigned>(Args.size()) -
6311 ExplicitObjectParameterOffset
6312 << HasExplicitObjectParameter << TC.getCorrectionRange());
6313 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6314 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6315 ->getDeclName())
6316 Diag(Args[NumParams]->getBeginLoc(),
6317 MinArgs == NumParams
6318 ? diag::err_typecheck_call_too_many_args_one
6319 : diag::err_typecheck_call_too_many_args_at_most_one)
6320 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6321 << static_cast<unsigned>(Args.size()) -
6322 ExplicitObjectParameterOffset
6323 << HasExplicitObjectParameter << Fn->getSourceRange()
6324 << SourceRange(Args[NumParams]->getBeginLoc(),
6325 Args.back()->getEndLoc());
6326 else
6327 Diag(Args[NumParams]->getBeginLoc(),
6328 MinArgs == NumParams
6329 ? diag::err_typecheck_call_too_many_args
6330 : diag::err_typecheck_call_too_many_args_at_most)
6331 << FnKind << NumParams - ExplicitObjectParameterOffset
6332 << static_cast<unsigned>(Args.size()) -
6333 ExplicitObjectParameterOffset
6334 << HasExplicitObjectParameter << Fn->getSourceRange()
6335 << SourceRange(Args[NumParams]->getBeginLoc(),
6336 Args.back()->getEndLoc());
6337
6338 // Emit the location of the prototype.
6339 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6340 Diag(FDecl->getLocation(), diag::note_callee_decl)
6341 << FDecl << FDecl->getParametersSourceRange();
6342
6343 // This deletes the extra arguments.
6344 Call->shrinkNumArgs(NumParams);
6345 return true;
6346 }
6347 }
6348 SmallVector<Expr *, 8> AllArgs;
6349 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6350
6351 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6352 AllArgs, CallType);
6353 if (Invalid)
6354 return true;
6355 unsigned TotalNumArgs = AllArgs.size();
6356 for (unsigned i = 0; i < TotalNumArgs; ++i)
6357 Call->setArg(i, AllArgs[i]);
6358
6359 Call->computeDependence();
6360 return false;
6361}
6362
6364 const FunctionProtoType *Proto,
6365 unsigned FirstParam, ArrayRef<Expr *> Args,
6366 SmallVectorImpl<Expr *> &AllArgs,
6367 VariadicCallType CallType, bool AllowExplicit,
6368 bool IsListInitialization) {
6369 unsigned NumParams = Proto->getNumParams();
6370 bool Invalid = false;
6371 size_t ArgIx = 0;
6372 // Continue to check argument types (even if we have too few/many args).
6373 for (unsigned i = FirstParam; i < NumParams; i++) {
6374 QualType ProtoArgType = Proto->getParamType(i);
6375
6376 Expr *Arg;
6377 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6378 if (ArgIx < Args.size()) {
6379 Arg = Args[ArgIx++];
6380
6381 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6382 diag::err_call_incomplete_argument, Arg))
6383 return true;
6384
6385 // Strip the unbridged-cast placeholder expression off, if applicable.
6386 bool CFAudited = false;
6387 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6388 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6389 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6390 Arg = ObjC().stripARCUnbridgedCast(Arg);
6391 else if (getLangOpts().ObjCAutoRefCount &&
6392 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6393 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6394 CFAudited = true;
6395
6396 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6397 ProtoArgType->isBlockPointerType())
6398 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6399 BE->getBlockDecl()->setDoesNotEscape();
6400 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6402 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6403 if (ArgExpr.isInvalid())
6404 return true;
6405 Arg = ArgExpr.getAs<Expr>();
6406 }
6407
6408 InitializedEntity Entity =
6410 ProtoArgType)
6412 Context, ProtoArgType, Proto->isParamConsumed(i));
6413
6414 // Remember that parameter belongs to a CF audited API.
6415 if (CFAudited)
6416 Entity.setParameterCFAudited();
6417
6418 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6419 // function boundaries is a common oversight.
6420 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6421 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6422 bool isPedantic =
6423 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6424 Diag(Arg->getExprLoc(),
6425 isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6426 : diag::warn_obt_discarded_at_function_boundary)
6427 << Arg->getType() << ProtoArgType;
6428 }
6429
6431 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6432 if (ArgE.isInvalid())
6433 return true;
6434
6435 Arg = ArgE.getAs<Expr>();
6436 } else {
6437 assert(Param && "can't use default arguments without a known callee");
6438
6439 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6440 if (ArgExpr.isInvalid())
6441 return true;
6442
6443 Arg = ArgExpr.getAs<Expr>();
6444 }
6445
6446 // Check for array bounds violations for each argument to the call. This
6447 // check only triggers warnings when the argument isn't a more complex Expr
6448 // with its own checking, such as a BinaryOperator.
6449 CheckArrayAccess(Arg);
6450
6451 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6452 CheckStaticArrayArgument(CallLoc, Param, Arg);
6453
6454 AllArgs.push_back(Arg);
6455 }
6456
6457 // If this is a variadic call, handle args passed through "...".
6458 if (CallType != VariadicCallType::DoesNotApply) {
6459 // Assume that extern "C" functions with variadic arguments that
6460 // return __unknown_anytype aren't *really* variadic.
6461 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6462 FDecl->isExternC()) {
6463 for (Expr *A : Args.slice(ArgIx)) {
6464 QualType paramType; // ignored
6465 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6466 Invalid |= arg.isInvalid();
6467 AllArgs.push_back(arg.get());
6468 }
6469
6470 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6471 } else {
6472 for (Expr *A : Args.slice(ArgIx)) {
6473 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6474 Invalid |= Arg.isInvalid();
6475 AllArgs.push_back(Arg.get());
6476 }
6477 }
6478
6479 // Check for array bounds violations.
6480 for (Expr *A : Args.slice(ArgIx))
6481 CheckArrayAccess(A);
6482 }
6483 return Invalid;
6484}
6485
6487 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6488 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6489 TL = DTL.getOriginalLoc();
6490 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6491 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6492 << ATL.getLocalSourceRange();
6493}
6494
6495void
6497 ParmVarDecl *Param,
6498 const Expr *ArgExpr) {
6499 // Static array parameters are not supported in C++.
6500 if (!Param || getLangOpts().CPlusPlus)
6501 return;
6502
6503 QualType OrigTy = Param->getOriginalType();
6504
6505 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6506 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6507 return;
6508
6509 if (ArgExpr->isNullPointerConstant(Context,
6511 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6512 DiagnoseCalleeStaticArrayParam(*this, Param);
6513 return;
6514 }
6515
6516 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6517 if (!CAT)
6518 return;
6519
6520 const ConstantArrayType *ArgCAT =
6521 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6522 if (!ArgCAT)
6523 return;
6524
6525 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6526 ArgCAT->getElementType())) {
6527 if (ArgCAT->getSize().ult(CAT->getSize())) {
6528 Diag(CallLoc, diag::warn_static_array_too_small)
6529 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6530 << (unsigned)CAT->getZExtSize() << 0;
6531 DiagnoseCalleeStaticArrayParam(*this, Param);
6532 }
6533 return;
6534 }
6535
6536 std::optional<CharUnits> ArgSize =
6538 std::optional<CharUnits> ParmSize =
6540 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6541 Diag(CallLoc, diag::warn_static_array_too_small)
6542 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6543 << (unsigned)ParmSize->getQuantity() << 1;
6544 DiagnoseCalleeStaticArrayParam(*this, Param);
6545 }
6546}
6547
6548/// Given a function expression of unknown-any type, try to rebuild it
6549/// to have a function type.
6551
6552/// Is the given type a placeholder that we need to lower out
6553/// immediately during argument processing?
6555 // Placeholders are never sugared.
6556 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6557 if (!placeholder) return false;
6558
6559 switch (placeholder->getKind()) {
6560 // Ignore all the non-placeholder types.
6561#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6562 case BuiltinType::Id:
6563#include "clang/Basic/OpenCLImageTypes.def"
6564#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6565 case BuiltinType::Id:
6566#include "clang/Basic/OpenCLExtensionTypes.def"
6567 // In practice we'll never use this, since all SVE types are sugared
6568 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6569#define SVE_TYPE(Name, Id, SingletonId) \
6570 case BuiltinType::Id:
6571#include "clang/Basic/AArch64ACLETypes.def"
6572#define PPC_VECTOR_TYPE(Name, Id, Size) \
6573 case BuiltinType::Id:
6574#include "clang/Basic/PPCTypes.def"
6575#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6576#include "clang/Basic/RISCVVTypes.def"
6577#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6578#include "clang/Basic/WebAssemblyReferenceTypes.def"
6579#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6580#include "clang/Basic/AMDGPUTypes.def"
6581#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6582#include "clang/Basic/HLSLIntangibleTypes.def"
6583#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6584#include "clang/Basic/SPIRVTypes.def"
6585#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6586#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6587#include "clang/AST/BuiltinTypes.def"
6588 return false;
6589
6590 case BuiltinType::UnresolvedTemplate:
6591 // We cannot lower out overload sets; they might validly be resolved
6592 // by the call machinery.
6593 case BuiltinType::Overload:
6594 return false;
6595
6596 // Unbridged casts in ARC can be handled in some call positions and
6597 // should be left in place.
6598 case BuiltinType::ARCUnbridgedCast:
6599 return false;
6600
6601 // Pseudo-objects should be converted as soon as possible.
6602 case BuiltinType::PseudoObject:
6603 return true;
6604
6605 // The debugger mode could theoretically but currently does not try
6606 // to resolve unknown-typed arguments based on known parameter types.
6607 case BuiltinType::UnknownAny:
6608 return true;
6609
6610 // These are always invalid as call arguments and should be reported.
6611 case BuiltinType::BoundMember:
6612 case BuiltinType::BuiltinFn:
6613 case BuiltinType::IncompleteMatrixIdx:
6614 case BuiltinType::ArraySection:
6615 case BuiltinType::OMPArrayShaping:
6616 case BuiltinType::OMPIterator:
6617 return true;
6618
6619 }
6620 llvm_unreachable("bad builtin type kind");
6621}
6622
6624 // Apply this processing to all the arguments at once instead of
6625 // dying at the first failure.
6626 bool hasInvalid = false;
6627 for (size_t i = 0, e = args.size(); i != e; i++) {
6628 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6629 ExprResult result = CheckPlaceholderExpr(args[i]);
6630 if (result.isInvalid()) hasInvalid = true;
6631 else args[i] = result.get();
6632 }
6633 }
6634 return hasInvalid;
6635}
6636
6637/// If a builtin function has a pointer argument with no explicit address
6638/// space, then it should be able to accept a pointer to any address
6639/// space as input. In order to do this, we need to replace the
6640/// standard builtin declaration with one that uses the same address space
6641/// as the call.
6642///
6643/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6644/// it does not contain any pointer arguments without
6645/// an address space qualifer. Otherwise the rewritten
6646/// FunctionDecl is returned.
6647/// TODO: Handle pointer return types.
6649 FunctionDecl *FDecl,
6650 MultiExprArg ArgExprs) {
6651
6652 QualType DeclType = FDecl->getType();
6653 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6654
6655 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6656 ArgExprs.size() < FT->getNumParams())
6657 return nullptr;
6658
6659 bool NeedsNewDecl = false;
6660 unsigned i = 0;
6661 SmallVector<QualType, 8> OverloadParams;
6662
6663 {
6664 // The lvalue conversions in this loop are only for type resolution and
6665 // don't actually occur.
6668 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6669
6670 for (QualType ParamType : FT->param_types()) {
6671
6672 // Convert array arguments to pointer to simplify type lookup.
6673 ExprResult ArgRes =
6675 if (ArgRes.isInvalid())
6676 return nullptr;
6677 Expr *Arg = ArgRes.get();
6678 QualType ArgType = Arg->getType();
6679 if (!ParamType->isPointerType() ||
6680 ParamType->getPointeeType().hasAddressSpace() ||
6681 !ArgType->isPointerType() ||
6682 !ArgType->getPointeeType().hasAddressSpace() ||
6683 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6684 OverloadParams.push_back(ParamType);
6685 continue;
6686 }
6687
6688 QualType PointeeType = ParamType->getPointeeType();
6689 NeedsNewDecl = true;
6690 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6691
6692 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6693 OverloadParams.push_back(Context.getPointerType(PointeeType));
6694 }
6695 }
6696
6697 if (!NeedsNewDecl)
6698 return nullptr;
6699
6701 EPI.Variadic = FT->isVariadic();
6702 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6703 OverloadParams, EPI);
6704 DeclContext *Parent = FDecl->getParent();
6705 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6706 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6707 FDecl->getIdentifier(), OverloadTy,
6708 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6709 false,
6710 /*hasPrototype=*/true);
6712 FT = cast<FunctionProtoType>(OverloadTy);
6713 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6714 QualType ParamType = FT->getParamType(i);
6715 ParmVarDecl *Parm =
6716 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6717 SourceLocation(), nullptr, ParamType,
6718 /*TInfo=*/nullptr, SC_None, nullptr);
6719 Parm->setScopeInfo(0, i);
6720 Params.push_back(Parm);
6721 }
6722 OverloadDecl->setParams(Params);
6723 // We cannot merge host/device attributes of redeclarations. They have to
6724 // be consistent when created.
6725 if (Sema->LangOpts.CUDA) {
6726 if (FDecl->hasAttr<CUDAHostAttr>())
6727 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6728 if (FDecl->hasAttr<CUDADeviceAttr>())
6729 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6730 }
6731 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6732 return OverloadDecl;
6733}
6734
6735static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6736 FunctionDecl *Callee,
6737 MultiExprArg ArgExprs) {
6738 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6739 // similar attributes) really don't like it when functions are called with an
6740 // invalid number of args.
6741 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6742 /*PartialOverloading=*/false) &&
6743 !Callee->isVariadic())
6744 return;
6745 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6746 return;
6747
6748 if (const EnableIfAttr *Attr =
6749 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6750 S.Diag(Fn->getBeginLoc(),
6751 isa<CXXMethodDecl>(Callee)
6752 ? diag::err_ovl_no_viable_member_function_in_call
6753 : diag::err_ovl_no_viable_function_in_call)
6754 << Callee << Callee->getSourceRange();
6755 S.Diag(Callee->getLocation(),
6756 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6757 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6758 return;
6759 }
6760}
6761
6763 const UnresolvedMemberExpr *const UME, Sema &S) {
6764
6765 const auto GetFunctionLevelDCIfCXXClass =
6766 [](Sema &S) -> const CXXRecordDecl * {
6767 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6768 if (!DC || !DC->getParent())
6769 return nullptr;
6770
6771 // If the call to some member function was made from within a member
6772 // function body 'M' return return 'M's parent.
6773 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6774 return MD->getParent()->getCanonicalDecl();
6775 // else the call was made from within a default member initializer of a
6776 // class, so return the class.
6777 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6778 return RD->getCanonicalDecl();
6779 return nullptr;
6780 };
6781 // If our DeclContext is neither a member function nor a class (in the
6782 // case of a lambda in a default member initializer), we can't have an
6783 // enclosing 'this'.
6784
6785 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6786 if (!CurParentClass)
6787 return false;
6788
6789 // The naming class for implicit member functions call is the class in which
6790 // name lookup starts.
6791 const CXXRecordDecl *const NamingClass =
6793 assert(NamingClass && "Must have naming class even for implicit access");
6794
6795 // If the unresolved member functions were found in a 'naming class' that is
6796 // related (either the same or derived from) to the class that contains the
6797 // member function that itself contained the implicit member access.
6798
6799 return CurParentClass == NamingClass ||
6800 CurParentClass->isDerivedFrom(NamingClass);
6801}
6802
6803static void
6805 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6806
6807 if (!UME)
6808 return;
6809
6810 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6811 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6812 // already been captured, or if this is an implicit member function call (if
6813 // it isn't, an attempt to capture 'this' should already have been made).
6814 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6815 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6816 return;
6817
6818 // Check if the naming class in which the unresolved members were found is
6819 // related (same as or is a base of) to the enclosing class.
6820
6822 return;
6823
6824
6825 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6826 // If the enclosing function is not dependent, then this lambda is
6827 // capture ready, so if we can capture this, do so.
6828 if (!EnclosingFunctionCtx->isDependentContext()) {
6829 // If the current lambda and all enclosing lambdas can capture 'this' -
6830 // then go ahead and capture 'this' (since our unresolved overload set
6831 // contains at least one non-static member function).
6832 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6833 S.CheckCXXThisCapture(CallLoc);
6834 } else if (S.CurContext->isDependentContext()) {
6835 // ... since this is an implicit member reference, that might potentially
6836 // involve a 'this' capture, mark 'this' for potential capture in
6837 // enclosing lambdas.
6838 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6839 CurLSI->addPotentialThisCapture(CallLoc);
6840 }
6841}
6842
6843// Once a call is fully resolved, warn for unqualified calls to specific
6844// C++ standard functions, like move and forward.
6846 const CallExpr *Call) {
6847 // We are only checking unary move and forward so exit early here.
6848 if (Call->getNumArgs() != 1)
6849 return;
6850
6851 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6852 if (!E || isa<UnresolvedLookupExpr>(E))
6853 return;
6854 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6855 if (!DRE || !DRE->getLocation().isValid())
6856 return;
6857
6858 if (DRE->getQualifier())
6859 return;
6860
6861 const FunctionDecl *FD = Call->getDirectCallee();
6862 if (!FD)
6863 return;
6864
6865 // Only warn for some functions deemed more frequent or problematic.
6866 unsigned BuiltinID = FD->getBuiltinID();
6867 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6868 return;
6869
6870 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6872 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6873}
6874
6876 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6877 Expr *ExecConfig) {
6879 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6880 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6881 if (Call.isInvalid())
6882 return Call;
6883
6884 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6885 // language modes.
6886 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6887 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6888 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6889 << ULE->getName();
6890 }
6891
6892 if (LangOpts.OpenMP)
6893 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6894 ExecConfig);
6895 if (LangOpts.CPlusPlus) {
6896 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6898
6899 // If we previously found that the id-expression of this call refers to a
6900 // consteval function but the call is dependent, we should not treat is an
6901 // an invalid immediate call.
6902 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6903 DRE && Call.get()->isValueDependent()) {
6905 }
6906 }
6907 return Call;
6908}
6909
6910// Any type that could be used to form a callable expression
6911static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6912 QualType T = E->getType();
6913 if (T->isDependentType())
6914 return true;
6915
6916 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6917 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6918 T->isFunctionType() || T->isFunctionReferenceType() ||
6919 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6920 T->isBlockPointerType() || T->isRecordType() || T->isUndeducedType())
6921 return true;
6922
6925}
6926
6928 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6929 Expr *ExecConfig, bool IsExecConfig,
6930 bool AllowRecovery) {
6931 // Since this might be a postfix expression, get rid of ParenListExprs.
6933 if (Result.isInvalid()) return ExprError();
6934 Fn = Result.get();
6935
6936 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6937 // later, when we check boolean conditions, for now we merely forward it
6938 // without any additional checking.
6939 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6940 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6941 const auto *FD = cast<FunctionDecl>(Fn->getReferencedDeclOfCallee());
6942
6943 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6944 QualType FnPtrTy = Context.getPointerType(FD->getType());
6945 Expr *R = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6946 return CallExpr::Create(
6947 Context, R, ArgExprs, Context.AMDGPUFeaturePredicateTy,
6949 }
6950 }
6951
6952 if (CheckArgsForPlaceholders(ArgExprs))
6953 return ExprError();
6954
6955 // The result of __builtin_counted_by_ref cannot be used as a function
6956 // argument. It allows leaking and modification of bounds safety information.
6957 for (const Expr *Arg : ArgExprs)
6958 if (CheckInvalidBuiltinCountedByRef(Arg,
6960 return ExprError();
6961
6962 if (getLangOpts().CPlusPlus) {
6963 // If this is a pseudo-destructor expression, build the call immediately.
6965 if (!ArgExprs.empty()) {
6966 // Pseudo-destructor calls should not have any arguments.
6967 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6969 SourceRange(ArgExprs.front()->getBeginLoc(),
6970 ArgExprs.back()->getEndLoc()));
6971 }
6972
6973 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6974 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6975 }
6976 if (Fn->getType() == Context.PseudoObjectTy) {
6977 ExprResult result = CheckPlaceholderExpr(Fn);
6978 if (result.isInvalid()) return ExprError();
6979 Fn = result.get();
6980 }
6981
6982 // Determine whether this is a dependent call inside a C++ template,
6983 // in which case we won't do any semantic analysis now.
6984 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6985 if (ExecConfig) {
6987 cast<CallExpr>(ExecConfig), ArgExprs,
6988 Context.DependentTy, VK_PRValue,
6989 RParenLoc, CurFPFeatureOverrides());
6990 } else {
6991
6993 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6994 Fn->getBeginLoc());
6995
6996 // If the type of the function itself is not dependent
6997 // check that it is a reasonable as a function, as type deduction
6998 // later assume the CallExpr has a sensible TYPE.
6999 if (!MayBeFunctionType(Context, Fn))
7000 return ExprError(
7001 Diag(LParenLoc, diag::err_typecheck_call_not_function)
7002 << Fn->getType() << Fn->getSourceRange());
7003
7004 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7005 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7006 }
7007 }
7008
7009 // Determine whether this is a call to an object (C++ [over.call.object]).
7010 if (Fn->getType()->isRecordType())
7011 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
7012 RParenLoc);
7013
7014 if (Fn->getType() == Context.UnknownAnyTy) {
7015 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7016 if (result.isInvalid()) return ExprError();
7017 Fn = result.get();
7018 }
7019
7020 if (Fn->getType() == Context.BoundMemberTy) {
7021 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7022 RParenLoc, ExecConfig, IsExecConfig,
7023 AllowRecovery);
7024 }
7025 }
7026
7027 // Check for overloaded calls. This can happen even in C due to extensions.
7028 if (Fn->getType() == Context.OverloadTy) {
7030
7031 // We aren't supposed to apply this logic if there's an '&' involved.
7034 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7035 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7036 OverloadExpr *ovl = find.Expression;
7037 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
7039 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7040 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
7041 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7042 RParenLoc, ExecConfig, IsExecConfig,
7043 AllowRecovery);
7044 }
7045 }
7046
7047 // If we're directly calling a function, get the appropriate declaration.
7048 if (Fn->getType() == Context.UnknownAnyTy) {
7049 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7050 if (result.isInvalid()) return ExprError();
7051 Fn = result.get();
7052 }
7053
7054 Expr *NakedFn = Fn->IgnoreParens();
7055
7056 bool CallingNDeclIndirectly = false;
7057 NamedDecl *NDecl = nullptr;
7058 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
7059 if (UnOp->getOpcode() == UO_AddrOf) {
7060 CallingNDeclIndirectly = true;
7061 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7062 }
7063 }
7064
7065 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
7066 NDecl = DRE->getDecl();
7067
7068 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
7069 if (FDecl && FDecl->getBuiltinID()) {
7070 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
7071 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
7072 if (Context.BuiltinInfo.isTSBuiltin(FDecl->getBuiltinID()) &&
7073 !Context.BuiltinInfo.isAuxBuiltinID(FDecl->getBuiltinID())) {
7075 getFunctionLevelDeclContext(/*AllowLambda=*/true)));
7076 }
7077 }
7078
7079 // Rewrite the function decl for this builtin by replacing parameters
7080 // with no explicit address space with the address space of the arguments
7081 // in ArgExprs.
7082 if ((FDecl =
7083 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
7084 NDecl = FDecl;
7086 Context, DRE->getQualifierLoc(), SourceLocation(), FDecl, false,
7087 SourceLocation(), Fn->getType() /* BuiltinFnTy */,
7088 Fn->getValueKind(), FDecl, nullptr, DRE->isNonOdrUse());
7089 }
7090 }
7091 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
7092 NDecl = ME->getMemberDecl();
7093
7094 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
7095 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7096 FD, /*Complain=*/true, Fn->getBeginLoc()))
7097 return ExprError();
7098
7099 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
7100
7101 // If this expression is a call to a builtin function in HIP compilation,
7102 // allow a pointer-type argument to default address space to be passed as a
7103 // pointer-type parameter to a non-default address space. If Arg is declared
7104 // in the default address space and Param is declared in a non-default
7105 // address space, perform an implicit address space cast to the parameter
7106 // type.
7107 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
7108 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
7109 ++Idx) {
7110 ParmVarDecl *Param = FD->getParamDecl(Idx);
7111 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7112 !ArgExprs[Idx]->getType()->isPointerType())
7113 continue;
7114
7115 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7116 auto ArgTy = ArgExprs[Idx]->getType();
7117 auto ArgPtTy = ArgTy->getPointeeType();
7118 auto ArgAS = ArgPtTy.getAddressSpace();
7119
7120 // Add address space cast if target address spaces are different
7121 bool NeedImplicitASC =
7122 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7123 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7124 // or from specific AS which has target AS matching that of Param.
7126 if (!NeedImplicitASC)
7127 continue;
7128
7129 // First, ensure that the Arg is an RValue.
7130 if (ArgExprs[Idx]->isGLValue()) {
7131 ExprResult Res = DefaultLvalueConversion(ArgExprs[Idx]);
7132 if (Res.isInvalid())
7133 return ExprError();
7134 ArgExprs[Idx] = Res.get();
7135 }
7136
7137 // Construct a new arg type with address space of Param
7138 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7139 ArgPtQuals.setAddressSpace(ParamAS);
7140 auto NewArgPtTy =
7141 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7142 auto NewArgTy =
7143 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7144 ArgTy.getQualifiers());
7145
7146 // Finally perform an implicit address space cast
7147 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7148 CK_AddressSpaceConversion)
7149 .get();
7150 }
7151 }
7152 }
7153
7154 if (Context.isDependenceAllowed() &&
7155 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7156 assert(!getLangOpts().CPlusPlus);
7157 assert((Fn->containsErrors() ||
7158 llvm::any_of(ArgExprs,
7159 [](clang::Expr *E) { return E->containsErrors(); })) &&
7160 "should only occur in error-recovery path.");
7161 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7162 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7163 }
7164 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7165 ExecConfig, IsExecConfig);
7166}
7167
7169 MultiExprArg CallArgs) {
7170 std::string Name = Context.BuiltinInfo.getName(Id);
7171 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7173 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7174
7175 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7176 assert(BuiltInDecl && "failed to find builtin declaration");
7177
7178 ExprResult DeclRef =
7179 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7180 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7181
7183 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7184
7185 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7186 return Call.get();
7187}
7188
7190 SourceLocation BuiltinLoc,
7191 SourceLocation RParenLoc) {
7192 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7193 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7194}
7195
7197 SourceLocation BuiltinLoc,
7198 SourceLocation RParenLoc) {
7201 QualType SrcTy = E->getType();
7202 if (!SrcTy->isDependentType() &&
7203 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7204 return ExprError(
7205 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7206 << DestTy << SrcTy << E->getSourceRange());
7207 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7208}
7209
7211 SourceLocation BuiltinLoc,
7212 SourceLocation RParenLoc) {
7213 TypeSourceInfo *TInfo;
7214 GetTypeFromParser(ParsedDestTy, &TInfo);
7215 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7216}
7217
7219 SourceLocation LParenLoc,
7220 ArrayRef<Expr *> Args,
7221 SourceLocation RParenLoc, Expr *Config,
7222 bool IsExecConfig, ADLCallKind UsesADL) {
7223 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7224 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7225
7226 auto IsSJLJ = [&] {
7227 switch (BuiltinID) {
7228 case Builtin::BI__builtin_longjmp:
7229 case Builtin::BI__builtin_setjmp:
7230 case Builtin::BI__sigsetjmp:
7231 case Builtin::BI_longjmp:
7232 case Builtin::BI_setjmp:
7233 case Builtin::BIlongjmp:
7234 case Builtin::BIsetjmp:
7235 case Builtin::BIsiglongjmp:
7236 case Builtin::BIsigsetjmp:
7237 return true;
7238 default:
7239 return false;
7240 }
7241 };
7242
7243 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7244 if (!CurrentDefer.empty() && IsSJLJ()) {
7245 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7246 // for more than just blocks (e.g. lambdas, nested classes...).
7247 Scope *DeferParent = CurrentDefer.back().first;
7248 Scope *Block = CurScope->getBlockParent();
7249 if (DeferParent->Contains(*CurScope) &&
7250 (!Block || !DeferParent->Contains(*Block)))
7251 Diag(Fn->getExprLoc(), diag::err_defer_invalid_sjlj) << FDecl;
7252 }
7253
7254 // Functions with 'interrupt' attribute cannot be called directly.
7255 if (FDecl) {
7256 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7257 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7258 return ExprError();
7259 }
7260 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7261 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
7262 return ExprError();
7263 }
7264 }
7265
7266 // X86 interrupt handlers may only call routines with attribute
7267 // no_caller_saved_registers since there is no efficient way to
7268 // save and restore the non-GPR state.
7269 if (auto *Caller = getCurFunctionDecl()) {
7270 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7271 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7272 const TargetInfo &TI = Context.getTargetInfo();
7273 bool HasNonGPRRegisters =
7274 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
7275 if (HasNonGPRRegisters &&
7276 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7277 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
7278 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7279 if (FDecl)
7280 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7281 }
7282 }
7283 }
7284
7285 // Extract the return type from the builtin function pointer type.
7286 QualType ResultTy;
7287 if (BuiltinID)
7288 ResultTy = FDecl->getCallResultType();
7289 else
7290 ResultTy = Context.BoolTy;
7291
7292 // Promote the function operand.
7293 // We special-case function promotion here because we only allow promoting
7294 // builtin functions to function pointers in the callee of a call.
7296 if (BuiltinID &&
7297 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7298 // FIXME Several builtins still have setType in
7299 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7300 // Builtins.td to ensure they are correct before removing setType calls.
7301 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7302 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7303 } else
7305 if (Result.isInvalid())
7306 return ExprError();
7307 Fn = Result.get();
7308
7309 // Check for a valid function type, but only if it is not a builtin which
7310 // requires custom type checking. These will be handled by
7311 // CheckBuiltinFunctionCall below just after creation of the call expression.
7312 const FunctionType *FuncT = nullptr;
7313 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7314 retry:
7315 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7316 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7317 // have type pointer to function".
7318 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7319 if (!FuncT)
7320 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7321 << Fn->getType() << Fn->getSourceRange());
7322 } else if (const BlockPointerType *BPT =
7323 Fn->getType()->getAs<BlockPointerType>()) {
7324 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7325 } else {
7326 // Handle calls to expressions of unknown-any type.
7327 if (Fn->getType() == Context.UnknownAnyTy) {
7328 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7329 if (rewrite.isInvalid())
7330 return ExprError();
7331 Fn = rewrite.get();
7332 goto retry;
7333 }
7334
7335 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7336 << Fn->getType() << Fn->getSourceRange());
7337 }
7338 }
7339
7340 // Get the number of parameters in the function prototype, if any.
7341 // We will allocate space for max(Args.size(), NumParams) arguments
7342 // in the call expression.
7343 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7344 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7345
7346 CallExpr *TheCall;
7347 if (Config) {
7348 assert(UsesADL == ADLCallKind::NotADL &&
7349 "CUDAKernelCallExpr should not use ADL");
7350 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7351 Args, ResultTy, VK_PRValue, RParenLoc,
7352 CurFPFeatureOverrides(), NumParams);
7353 } else {
7354 TheCall =
7355 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7356 CurFPFeatureOverrides(), NumParams, UsesADL);
7357 }
7358
7359 // Bail out early if calling a builtin with custom type checking.
7360 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7361 // For HLSL builtin aliases, the call was resolved via overload resolution
7362 // which may have selected a conversion sequence (e.g., vector-to-scalar
7363 // truncation). Convert arguments to match the declared prototype before
7364 // the custom type checker runs, otherwise the builtin will operate on
7365 // the unconverted argument types.
7366 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7367 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7368 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, P, Args, RParenLoc,
7369 IsExecConfig))
7370 return ExprError();
7371 }
7372 }
7373 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7374 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
7375 E = CheckForImmediateInvocation(E, FDecl);
7376 return E;
7377 }
7378
7379 if (getLangOpts().CUDA) {
7380 if (Config) {
7381 // CUDA: Kernel calls must be to global functions
7382 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7383 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7384 << FDecl << Fn->getSourceRange());
7385
7386 // CUDA: Kernel function must have 'void' return type
7387 if (!FuncT->getReturnType()->isVoidType() &&
7388 !FuncT->getReturnType()->getAs<AutoType>() &&
7390 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7391 << Fn->getType() << Fn->getSourceRange());
7392 } else {
7393 // CUDA: Calls to global functions must be configured
7394 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7395 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7396 << FDecl << Fn->getSourceRange());
7397 }
7398 }
7399
7400 // Check for a valid return type
7401 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7402 FDecl))
7403 return ExprError();
7404
7405 // We know the result type of the call, set it.
7406 TheCall->setType(FuncT->getCallResultType(Context));
7408
7409 // WebAssembly tables can't be used as arguments.
7410 if (Context.getTargetInfo().getTriple().isWasm()) {
7411 for (const Expr *Arg : Args) {
7412 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7413 return ExprError(Diag(Arg->getExprLoc(),
7414 diag::err_wasm_table_as_function_parameter));
7415 }
7416 }
7417 }
7418
7419 // Check read_image{i|ui} sampler argument before ConvertArgumentsForCall
7420 // replaces sampler DeclRefExprs with their integer initializers.
7421 if (getLangOpts().OpenCL && FDecl) {
7422 OpenCL().checkBuiltinReadImage(FDecl, TheCall);
7423 }
7424
7425 if (Proto) {
7426 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7427 IsExecConfig))
7428 return ExprError();
7429 } else {
7430 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7431
7432 if (FDecl) {
7433 // Check if we have too few/too many template arguments, based
7434 // on our knowledge of the function definition.
7435 const FunctionDecl *Def = nullptr;
7436 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7437 Proto = Def->getType()->getAs<FunctionProtoType>();
7438 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7439 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7440 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7441 }
7442
7443 // If the function we're calling isn't a function prototype, but we have
7444 // a function prototype from a prior declaratiom, use that prototype.
7445 if (!FDecl->hasPrototype())
7446 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7447 }
7448
7449 // If we still haven't found a prototype to use but there are arguments to
7450 // the call, diagnose this as calling a function without a prototype.
7451 // However, if we found a function declaration, check to see if
7452 // -Wdeprecated-non-prototype was disabled where the function was declared.
7453 // If so, we will silence the diagnostic here on the assumption that this
7454 // interface is intentional and the user knows what they're doing. We will
7455 // also silence the diagnostic if there is a function declaration but it
7456 // was implicitly defined (the user already gets diagnostics about the
7457 // creation of the implicit function declaration, so the additional warning
7458 // is not helpful).
7459 if (!Proto && !Args.empty() &&
7460 (!FDecl || (!FDecl->isImplicit() &&
7461 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7462 FDecl->getLocation()))))
7463 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7464 << (FDecl != nullptr) << FDecl;
7465
7466 // Promote the arguments (C99 6.5.2.2p6).
7467 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7468 Expr *Arg = Args[i];
7469
7470 if (Proto && i < Proto->getNumParams()) {
7472 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7473 ExprResult ArgE =
7475 if (ArgE.isInvalid())
7476 return true;
7477
7478 Arg = ArgE.getAs<Expr>();
7479
7480 } else {
7482
7483 if (ArgE.isInvalid())
7484 return true;
7485
7486 Arg = ArgE.getAs<Expr>();
7487 }
7488
7489 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7490 diag::err_call_incomplete_argument, Arg))
7491 return ExprError();
7492
7493 TheCall->setArg(i, Arg);
7494 }
7495 TheCall->computeDependence();
7496 }
7497
7498 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7499 if (Method->isImplicitObjectMemberFunction())
7500 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7501 << Fn->getSourceRange() << 0);
7502
7503 // Check for sentinels
7504 if (NDecl)
7505 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7506
7507 // Warn for unions passing across security boundary (CMSE).
7508 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7509 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7510 if (const auto *RT =
7511 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7512 if (RT->getDecl()->isOrContainsUnion())
7513 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7514 << 0 << i;
7515 }
7516 }
7517 }
7518
7519 // Do special checking on direct calls to functions.
7520 if (FDecl) {
7521 if (CheckFunctionCall(FDecl, TheCall, Proto))
7522 return ExprError();
7523
7524 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7525 checkFortifiedLibcArgument(FDecl, TheCall);
7526
7527 if (BuiltinID)
7528 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7529 } else if (NDecl) {
7530 if (CheckPointerCall(NDecl, TheCall, Proto))
7531 return ExprError();
7532 } else {
7533 if (CheckOtherCall(TheCall, Proto))
7534 return ExprError();
7535 }
7536
7537 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7538}
7539
7542 SourceLocation RParenLoc, Expr *InitExpr) {
7543 assert(Ty && "ActOnCompoundLiteral(): missing type");
7544 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7545
7546 TypeSourceInfo *TInfo;
7547 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7548 if (!TInfo)
7549 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7550
7551 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7552}
7553
7556 SourceLocation RParenLoc, Expr *LiteralExpr) {
7557 QualType literalType = TInfo->getType();
7558
7559 if (literalType->isArrayType()) {
7561 LParenLoc, Context.getBaseElementType(literalType),
7562 diag::err_array_incomplete_or_sizeless_type,
7563 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7564 return ExprError();
7565 if (literalType->isVariableArrayType()) {
7566 // C23 6.7.10p4: An entity of variable length array type shall not be
7567 // initialized except by an empty initializer.
7568 //
7569 // The C extension warnings are issued from ParseBraceInitializer() and
7570 // do not need to be issued here. However, we continue to issue an error
7571 // in the case there are initializers or we are compiling C++. We allow
7572 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7573 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7574 // FIXME: should we allow this construct in C++ when it makes sense to do
7575 // so?
7576 //
7577 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7578 // shall specify an object type or an array of unknown size, but not a
7579 // variable length array type. This seems odd, as it allows 'int a[size] =
7580 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7581 // says, this is what's implemented here for C (except for the extension
7582 // that permits constant foldable size arrays)
7583
7584 auto diagID = LangOpts.CPlusPlus
7585 ? diag::err_variable_object_no_init
7586 : diag::err_compound_literal_with_vla_type;
7587 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7588 diagID))
7589 return ExprError();
7590 }
7591 } else if (!literalType->isDependentType() &&
7592 RequireCompleteType(LParenLoc, literalType,
7593 diag::err_typecheck_decl_incomplete_type,
7594 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7595 return ExprError();
7596
7597 InitializedEntity Entity
7601 SourceRange(LParenLoc, RParenLoc),
7602 /*InitList=*/true);
7603 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7604 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7605 &literalType);
7606 if (Result.isInvalid())
7607 return ExprError();
7608 LiteralExpr = Result.get();
7609
7610 // We treat the compound literal as being at file scope if it's not in a
7611 // function or method body, or within the function's prototype scope. This
7612 // means the following compound literal is not at file scope:
7613 // void func(char *para[(int [1]){ 0 }[0]);
7614 const Scope *S = getCurScope();
7615 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7616 !S->isInCFunctionScope() &&
7617 (!S || !S->isFunctionPrototypeScope());
7618
7619 // In C, compound literals are l-values for some reason.
7620 // For GCC compatibility, in C++, file-scope array compound literals with
7621 // constant initializers are also l-values, and compound literals are
7622 // otherwise prvalues.
7623 //
7624 // (GCC also treats C++ list-initialized file-scope array prvalues with
7625 // constant initializers as l-values, but that's non-conforming, so we don't
7626 // follow it there.)
7627 //
7628 // FIXME: It would be better to handle the lvalue cases as materializing and
7629 // lifetime-extending a temporary object, but our materialized temporaries
7630 // representation only supports lifetime extension from a variable, not "out
7631 // of thin air".
7632 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7633 // is bound to the result of applying array-to-pointer decay to the compound
7634 // literal.
7635 // FIXME: GCC supports compound literals of reference type, which should
7636 // obviously have a value kind derived from the kind of reference involved.
7638 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7639 ? VK_PRValue
7640 : VK_LValue;
7641
7642 // C99 6.5.2.5
7643 // "If the compound literal occurs outside the body of a function, the
7644 // initializer list shall consist of constant expressions."
7645 if (IsFileScope)
7646 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7647 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7648 Expr *Init = ILE->getInit(i);
7649 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7650 !Init->isConstantInitializer(Context)) {
7651 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7652 << Init->getSourceBitField();
7653 return ExprError();
7654 }
7655
7656 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7657 }
7658
7659 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7660 LiteralExpr, IsFileScope);
7661 if (IsFileScope) {
7662 if (!LiteralExpr->isTypeDependent() &&
7663 !LiteralExpr->isValueDependent() &&
7664 !literalType->isDependentType()) // C99 6.5.2.5p3
7665 if (CheckForConstantInitializer(LiteralExpr))
7666 return ExprError();
7667 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7668 literalType.getAddressSpace() != LangAS::Default) {
7669 // Embedded-C extensions to C99 6.5.2.5:
7670 // "If the compound literal occurs inside the body of a function, the
7671 // type name shall not be qualified by an address-space qualifier."
7672 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7673 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7674 return ExprError();
7675 }
7676
7677 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7678 // Compound literals that have automatic storage duration are destroyed at
7679 // the end of the scope in C; in C++, they're just temporaries.
7680
7681 // Emit diagnostics if it is or contains a C union type that is non-trivial
7682 // to destruct.
7687
7688 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7689 Cleanup.setExprNeedsCleanups(true);
7690 ExprCleanupObjects.push_back(E);
7691 if (literalType.isDestructedType()) {
7693 }
7694 }
7695
7698 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7699 E->getInitializer()->getExprLoc());
7700
7701 return MaybeBindToTemporary(E);
7702}
7703
7706 SourceLocation RBraceLoc) {
7707 // Only produce each kind of designated initialization diagnostic once.
7708 SourceLocation FirstDesignator;
7709 bool DiagnosedArrayDesignator = false;
7710 bool DiagnosedNestedDesignator = false;
7711 bool DiagnosedMixedDesignator = false;
7712
7713 // Check that any designated initializers are syntactically valid in the
7714 // current language mode.
7715 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7716 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7717 if (FirstDesignator.isInvalid())
7718 FirstDesignator = DIE->getBeginLoc();
7719
7720 if (!getLangOpts().CPlusPlus)
7721 break;
7722
7723 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7724 DiagnosedNestedDesignator = true;
7725 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7726 << DIE->getDesignatorsSourceRange();
7727 }
7728
7729 for (auto &Desig : DIE->designators()) {
7730 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7731 DiagnosedArrayDesignator = true;
7732 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7733 << Desig.getSourceRange();
7734 }
7735 }
7736
7737 if (!DiagnosedMixedDesignator &&
7738 !isa<DesignatedInitExpr>(InitArgList[0])) {
7739 DiagnosedMixedDesignator = true;
7740 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7741 << DIE->getSourceRange();
7742 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7743 << InitArgList[0]->getSourceRange();
7744 }
7745 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7746 isa<DesignatedInitExpr>(InitArgList[0])) {
7747 DiagnosedMixedDesignator = true;
7748 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7749 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7750 << DIE->getSourceRange();
7751 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7752 << InitArgList[I]->getSourceRange();
7753 }
7754 }
7755
7756 if (FirstDesignator.isValid()) {
7757 // Only diagnose designated initiaization as a C++20 extension if we didn't
7758 // already diagnose use of (non-C++20) C99 designator syntax.
7759 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7760 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7761 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7762 ? diag::warn_cxx17_compat_designated_init
7763 : diag::ext_cxx_designated_init);
7764 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7765 Diag(FirstDesignator, diag::ext_designated_init);
7766 }
7767 }
7768
7769 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7770}
7771
7773 MultiExprArg InitArgList,
7774 SourceLocation RBraceLoc, bool IsExplicit) {
7775 // Semantic analysis for initializers is done by ActOnDeclarator() and
7776 // CheckInitializer() - it requires knowledge of the object being initialized.
7777
7778 // Immediately handle non-overload placeholders. Overloads can be
7779 // resolved contextually, but everything else here can't.
7780 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7781 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7782 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7783
7784 // Ignore failures; dropping the entire initializer list because
7785 // of one failure would be terrible for indexing/etc.
7786 if (result.isInvalid()) continue;
7787
7788 InitArgList[I] = result.get();
7789 }
7790 }
7791
7792 InitListExpr *E = new (Context)
7793 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7794 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7795 return E;
7796}
7797
7799 assert(E.get()->getType()->isBlockPointerType());
7800 assert(E.get()->isPRValue());
7801
7802 // Only do this in an r-value context.
7803 if (!getLangOpts().ObjCAutoRefCount) return;
7804
7806 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7807 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7808 Cleanup.setExprNeedsCleanups(true);
7809}
7810
7812 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7813 // Also, callers should have filtered out the invalid cases with
7814 // pointers. Everything else should be possible.
7815
7816 QualType SrcTy = Src.get()->getType();
7817 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7818 return CK_NoOp;
7819
7820 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7822 llvm_unreachable("member pointer type in C");
7823
7824 case Type::STK_CPointer:
7827 switch (DestTy->getScalarTypeKind()) {
7828 case Type::STK_CPointer: {
7829 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7830 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7831 if (SrcAS != DestAS)
7832 return CK_AddressSpaceConversion;
7833 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7834 return CK_NoOp;
7835 return CK_BitCast;
7836 }
7838 return (SrcKind == Type::STK_BlockPointer
7839 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7841 if (SrcKind == Type::STK_ObjCObjectPointer)
7842 return CK_BitCast;
7843 if (SrcKind == Type::STK_CPointer)
7844 return CK_CPointerToObjCPointerCast;
7846 return CK_BlockPointerToObjCPointerCast;
7847 case Type::STK_Bool:
7848 return CK_PointerToBoolean;
7849 case Type::STK_Integral:
7850 return CK_PointerToIntegral;
7851 case Type::STK_Floating:
7856 llvm_unreachable("illegal cast from pointer");
7857 }
7858 llvm_unreachable("Should have returned before this");
7859
7861 switch (DestTy->getScalarTypeKind()) {
7863 return CK_FixedPointCast;
7864 case Type::STK_Bool:
7865 return CK_FixedPointToBoolean;
7866 case Type::STK_Integral:
7867 return CK_FixedPointToIntegral;
7868 case Type::STK_Floating:
7869 return CK_FixedPointToFloating;
7872 Diag(Src.get()->getExprLoc(),
7873 diag::err_unimplemented_conversion_with_fixed_point_type)
7874 << DestTy;
7875 return CK_IntegralCast;
7876 case Type::STK_CPointer:
7880 llvm_unreachable("illegal cast to pointer type");
7881 }
7882 llvm_unreachable("Should have returned before this");
7883
7884 case Type::STK_Bool: // casting from bool is like casting from an integer
7885 case Type::STK_Integral:
7886 switch (DestTy->getScalarTypeKind()) {
7887 case Type::STK_CPointer:
7892 return CK_NullToPointer;
7893 return CK_IntegralToPointer;
7894 case Type::STK_Bool:
7895 return CK_IntegralToBoolean;
7896 case Type::STK_Integral:
7897 return CK_IntegralCast;
7898 case Type::STK_Floating:
7899 return CK_IntegralToFloating;
7901 Src = ImpCastExprToType(Src.get(),
7902 DestTy->castAs<ComplexType>()->getElementType(),
7903 CK_IntegralCast);
7904 return CK_IntegralRealToComplex;
7906 Src = ImpCastExprToType(Src.get(),
7907 DestTy->castAs<ComplexType>()->getElementType(),
7908 CK_IntegralToFloating);
7909 return CK_FloatingRealToComplex;
7911 llvm_unreachable("member pointer type in C");
7913 return CK_IntegralToFixedPoint;
7914 }
7915 llvm_unreachable("Should have returned before this");
7916
7917 case Type::STK_Floating:
7918 switch (DestTy->getScalarTypeKind()) {
7919 case Type::STK_Floating:
7920 return CK_FloatingCast;
7921 case Type::STK_Bool:
7922 return CK_FloatingToBoolean;
7923 case Type::STK_Integral:
7924 return CK_FloatingToIntegral;
7926 Src = ImpCastExprToType(Src.get(),
7927 DestTy->castAs<ComplexType>()->getElementType(),
7928 CK_FloatingCast);
7929 return CK_FloatingRealToComplex;
7931 Src = ImpCastExprToType(Src.get(),
7932 DestTy->castAs<ComplexType>()->getElementType(),
7933 CK_FloatingToIntegral);
7934 return CK_IntegralRealToComplex;
7935 case Type::STK_CPointer:
7938 llvm_unreachable("valid float->pointer cast?");
7940 llvm_unreachable("member pointer type in C");
7942 return CK_FloatingToFixedPoint;
7943 }
7944 llvm_unreachable("Should have returned before this");
7945
7947 switch (DestTy->getScalarTypeKind()) {
7949 return CK_FloatingComplexCast;
7951 return CK_FloatingComplexToIntegralComplex;
7952 case Type::STK_Floating: {
7953 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7954 if (Context.hasSameType(ET, DestTy))
7955 return CK_FloatingComplexToReal;
7956 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7957 return CK_FloatingCast;
7958 }
7959 case Type::STK_Bool:
7960 return CK_FloatingComplexToBoolean;
7961 case Type::STK_Integral:
7962 Src = ImpCastExprToType(Src.get(),
7963 SrcTy->castAs<ComplexType>()->getElementType(),
7964 CK_FloatingComplexToReal);
7965 return CK_FloatingToIntegral;
7966 case Type::STK_CPointer:
7969 llvm_unreachable("valid complex float->pointer cast?");
7971 llvm_unreachable("member pointer type in C");
7973 Diag(Src.get()->getExprLoc(),
7974 diag::err_unimplemented_conversion_with_fixed_point_type)
7975 << SrcTy;
7976 return CK_IntegralCast;
7977 }
7978 llvm_unreachable("Should have returned before this");
7979
7981 switch (DestTy->getScalarTypeKind()) {
7983 return CK_IntegralComplexToFloatingComplex;
7985 return CK_IntegralComplexCast;
7986 case Type::STK_Integral: {
7987 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7988 if (Context.hasSameType(ET, DestTy))
7989 return CK_IntegralComplexToReal;
7990 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7991 return CK_IntegralCast;
7992 }
7993 case Type::STK_Bool:
7994 return CK_IntegralComplexToBoolean;
7995 case Type::STK_Floating:
7996 Src = ImpCastExprToType(Src.get(),
7997 SrcTy->castAs<ComplexType>()->getElementType(),
7998 CK_IntegralComplexToReal);
7999 return CK_IntegralToFloating;
8000 case Type::STK_CPointer:
8003 llvm_unreachable("valid complex int->pointer cast?");
8005 llvm_unreachable("member pointer type in C");
8007 Diag(Src.get()->getExprLoc(),
8008 diag::err_unimplemented_conversion_with_fixed_point_type)
8009 << SrcTy;
8010 return CK_IntegralCast;
8011 }
8012 llvm_unreachable("Should have returned before this");
8013 }
8014
8015 llvm_unreachable("Unhandled scalar cast");
8016}
8017
8018static bool breakDownVectorType(QualType type, uint64_t &len,
8019 QualType &eltType) {
8020 // Vectors are simple.
8021 if (const VectorType *vecType = type->getAs<VectorType>()) {
8022 len = vecType->getNumElements();
8023 eltType = vecType->getElementType();
8024 assert(eltType->isScalarType() || eltType->isMFloat8Type());
8025 return true;
8026 }
8027
8028 // We allow lax conversion to and from non-vector types, but only if
8029 // they're real types (i.e. non-complex, non-pointer scalar types).
8030 if (!type->isRealType()) return false;
8031
8032 len = 1;
8033 eltType = type;
8034 return true;
8035}
8036
8038 assert(srcTy->isVectorType() || destTy->isVectorType());
8039
8040 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8041 if (!FirstType->isSVESizelessBuiltinType())
8042 return false;
8043
8044 const auto *VecTy = SecondType->getAs<VectorType>();
8045 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
8046 };
8047
8048 return ValidScalableConversion(srcTy, destTy) ||
8049 ValidScalableConversion(destTy, srcTy);
8050}
8051
8053 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8054 return false;
8055
8056 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8057 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8058
8059 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8060 matSrcType->getNumColumns() == matDestType->getNumColumns();
8061}
8062
8064 assert(DestTy->isVectorType() || SrcTy->isVectorType());
8065
8066 uint64_t SrcLen, DestLen;
8067 QualType SrcEltTy, DestEltTy;
8068 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
8069 return false;
8070 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
8071 return false;
8072
8073 // ASTContext::getTypeSize will return the size rounded up to a
8074 // power of 2, so instead of using that, we need to use the raw
8075 // element size multiplied by the element count.
8076 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
8077 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
8078
8079 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8080}
8081
8083 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
8084 "expected at least one type to be a vector here");
8085
8086 bool IsSrcTyAltivec =
8087 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8089 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8091 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8093
8094 bool IsDestTyAltivec = DestTy->isVectorType() &&
8095 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8097 (DestTy->castAs<VectorType>()->getVectorKind() ==
8099 (DestTy->castAs<VectorType>()->getVectorKind() ==
8101
8102 return (IsSrcTyAltivec || IsDestTyAltivec);
8103}
8104
8106 assert(destTy->isVectorType() || srcTy->isVectorType());
8107
8108 // Disallow lax conversions between scalars and ExtVectors (these
8109 // conversions are allowed for other vector types because common headers
8110 // depend on them). Most scalar OP ExtVector cases are handled by the
8111 // splat path anyway, which does what we want (convert, not bitcast).
8112 // What this rules out for ExtVectors is crazy things like char4*float.
8113 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8114 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8115
8116 return areVectorTypesSameSize(srcTy, destTy);
8117}
8118
8120 assert(destTy->isVectorType() || srcTy->isVectorType());
8121
8122 switch (Context.getLangOpts().getLaxVectorConversions()) {
8124 return false;
8125
8127 if (!srcTy->isIntegralOrEnumerationType()) {
8128 auto *Vec = srcTy->getAs<VectorType>();
8129 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8130 return false;
8131 }
8132 if (!destTy->isIntegralOrEnumerationType()) {
8133 auto *Vec = destTy->getAs<VectorType>();
8134 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8135 return false;
8136 }
8137 // OK, integer (vector) -> integer (vector) bitcast.
8138 break;
8139
8141 break;
8142 }
8143
8144 return areLaxCompatibleVectorTypes(srcTy, destTy);
8145}
8146
8148 CastKind &Kind) {
8149 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8150 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8151 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8152 << DestTy << SrcTy << R;
8153 }
8154 } else if (SrcTy->isMatrixType()) {
8155 return Diag(R.getBegin(),
8156 diag::err_invalid_conversion_between_matrix_and_type)
8157 << SrcTy << DestTy << R;
8158 } else if (DestTy->isMatrixType()) {
8159 return Diag(R.getBegin(),
8160 diag::err_invalid_conversion_between_matrix_and_type)
8161 << DestTy << SrcTy << R;
8162 }
8163
8164 Kind = CK_MatrixCast;
8165 return false;
8166}
8167
8169 CastKind &Kind) {
8170 assert(VectorTy->isVectorType() && "Not a vector type!");
8171
8172 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8173 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8174 return Diag(R.getBegin(),
8175 Ty->isVectorType() ?
8176 diag::err_invalid_conversion_between_vectors :
8177 diag::err_invalid_conversion_between_vector_and_integer)
8178 << VectorTy << Ty << R;
8179 } else
8180 return Diag(R.getBegin(),
8181 diag::err_invalid_conversion_between_vector_and_scalar)
8182 << VectorTy << Ty << R;
8183
8184 Kind = CK_BitCast;
8185 return false;
8186}
8187
8189 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8190
8191 if (DestElemTy == SplattedExpr->getType())
8192 return SplattedExpr;
8193
8194 assert(DestElemTy->isFloatingType() ||
8195 DestElemTy->isIntegralOrEnumerationType());
8196
8197 CastKind CK;
8198 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8199 // OpenCL requires that we convert `true` boolean expressions to -1, but
8200 // only when splatting vectors.
8201 if (DestElemTy->isFloatingType()) {
8202 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8203 // in two steps: boolean to signed integral, then to floating.
8204 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8205 CK_BooleanToSignedIntegral);
8206 SplattedExpr = CastExprRes.get();
8207 CK = CK_IntegralToFloating;
8208 } else {
8209 CK = CK_BooleanToSignedIntegral;
8210 }
8211 } else {
8212 ExprResult CastExprRes = SplattedExpr;
8213 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8214 if (CastExprRes.isInvalid())
8215 return ExprError();
8216 SplattedExpr = CastExprRes.get();
8217 }
8218 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8219}
8220
8222 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8223
8224 if (DestElemTy == SplattedExpr->getType())
8225 return SplattedExpr;
8226
8227 assert(DestElemTy->isFloatingType() ||
8228 DestElemTy->isIntegralOrEnumerationType());
8229
8230 ExprResult CastExprRes = SplattedExpr;
8231 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
8232 if (CastExprRes.isInvalid())
8233 return ExprError();
8234 SplattedExpr = CastExprRes.get();
8235
8236 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8237}
8238
8240 Expr *CastExpr, CastKind &Kind) {
8241 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8242
8243 QualType SrcTy = CastExpr->getType();
8244
8245 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8246 // an ExtVectorType.
8247 // In OpenCL, casts between vectors of different types are not allowed.
8248 // (See OpenCL 6.2).
8249 if (SrcTy->isVectorType()) {
8250 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8251 (getLangOpts().OpenCL &&
8252 !Context.hasSameUnqualifiedType(DestTy, SrcTy) &&
8253 !Context.areCompatibleVectorTypes(DestTy, SrcTy))) {
8254 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8255 << DestTy << SrcTy << R;
8256 return ExprError();
8257 }
8258 Kind = CK_BitCast;
8259 return CastExpr;
8260 }
8261
8262 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8263 // conversion will take place first from scalar to elt type, and then
8264 // splat from elt type to vector.
8265 if (SrcTy->isPointerType())
8266 return Diag(R.getBegin(),
8267 diag::err_invalid_conversion_between_vector_and_scalar)
8268 << DestTy << SrcTy << R;
8269
8270 Kind = CK_VectorSplat;
8271 return prepareVectorSplat(DestTy, CastExpr);
8272}
8273
8274/// Check that a call to alloc_size function specifies sufficient space for the
8275/// destination type.
8276static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8277 const Expr *E) {
8278 QualType SourceType = E->getType();
8279 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8280 DestType == SourceType)
8281 return;
8282
8283 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
8284 if (!CE)
8285 return;
8286
8287 // Find the total size allocated by the function call.
8288 if (!CE->getCalleeAllocSizeAttr())
8289 return;
8290 std::optional<llvm::APInt> AllocSize =
8291 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
8292 // Allocations of size zero are permitted as a special case. They are usually
8293 // done intentionally.
8294 if (!AllocSize || AllocSize->isZero())
8295 return;
8296 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
8297
8298 QualType TargetType = DestType->getPointeeType();
8299 // Find the destination size. As a special case function types have size of
8300 // one byte to match the sizeof operator behavior.
8301 auto LhsSize = TargetType->isFunctionType()
8302 ? CharUnits::One()
8303 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
8304 if (LhsSize && Size < LhsSize)
8305 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
8306 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8307}
8308
8311 Declarator &D, ParsedType &Ty,
8312 SourceLocation RParenLoc, Expr *CastExpr) {
8313 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8314 "ActOnCastExpr(): missing type or expr");
8315
8317 if (D.isInvalidType())
8318 return ExprError();
8319
8320 if (getLangOpts().CPlusPlus) {
8321 // Check that there are no default arguments (C++ only).
8323 }
8324
8326
8327 QualType castType = castTInfo->getType();
8328 Ty = CreateParsedType(castType, castTInfo);
8329
8330 bool isVectorLiteral = false;
8331
8332 // Check for an altivec or OpenCL literal,
8333 // i.e. all the elements are integer constants.
8334 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8335 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8336 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8337 && castType->isVectorType() && (PE || PLE)) {
8338 if (PLE && PLE->getNumExprs() == 0) {
8339 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8340 return ExprError();
8341 }
8342 if (PE || PLE->getNumExprs() == 1) {
8343 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8344 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8345 isVectorLiteral = true;
8346 }
8347 else
8348 isVectorLiteral = true;
8349 }
8350
8351 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8352 // then handle it as such.
8353 if (isVectorLiteral)
8354 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8355
8356 // If the Expr being casted is a ParenListExpr, handle it specially.
8357 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8358 // sequence of BinOp comma operators.
8361 if (Result.isInvalid()) return ExprError();
8362 CastExpr = Result.get();
8363 }
8364
8365 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8366 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8367
8369
8371
8373
8374 CheckSufficientAllocSize(*this, castType, CastExpr);
8375
8376 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8377}
8378
8380 SourceLocation RParenLoc, Expr *E,
8381 TypeSourceInfo *TInfo) {
8382 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8383 "Expected paren or paren list expression");
8384
8385 Expr **exprs;
8386 unsigned numExprs;
8387 Expr *subExpr;
8388 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8389 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8390 LiteralLParenLoc = PE->getLParenLoc();
8391 LiteralRParenLoc = PE->getRParenLoc();
8392 exprs = PE->getExprs();
8393 numExprs = PE->getNumExprs();
8394 } else { // isa<ParenExpr> by assertion at function entrance
8395 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8396 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8397 subExpr = cast<ParenExpr>(E)->getSubExpr();
8398 exprs = &subExpr;
8399 numExprs = 1;
8400 }
8401
8402 QualType Ty = TInfo->getType();
8403 assert(Ty->isVectorType() && "Expected vector type");
8404
8405 SmallVector<Expr *, 8> initExprs;
8406 const VectorType *VTy = Ty->castAs<VectorType>();
8407 unsigned numElems = VTy->getNumElements();
8408
8409 // '(...)' form of vector initialization in AltiVec: the number of
8410 // initializers must be one or must match the size of the vector.
8411 // If a single value is specified in the initializer then it will be
8412 // replicated to all the components of the vector
8414 VTy->getElementType()))
8415 return ExprError();
8417 // The number of initializers must be one or must match the size of the
8418 // vector. If a single value is specified in the initializer then it will
8419 // be replicated to all the components of the vector
8420 if (numExprs == 1) {
8421 QualType ElemTy = VTy->getElementType();
8422 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8423 if (Literal.isInvalid())
8424 return ExprError();
8425 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8426 PrepareScalarCast(Literal, ElemTy));
8427 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8428 }
8429 else if (numExprs < numElems) {
8430 Diag(E->getExprLoc(),
8431 diag::err_incorrect_number_of_vector_initializers);
8432 return ExprError();
8433 }
8434 else
8435 initExprs.append(exprs, exprs + numExprs);
8436 }
8437 else {
8438 // For OpenCL, when the number of initializers is a single value,
8439 // it will be replicated to all components of the vector.
8441 numExprs == 1) {
8442 QualType SrcTy = exprs[0]->getType();
8443 if (!SrcTy->isArithmeticType()) {
8444 Diag(exprs[0]->getBeginLoc(), diag::err_typecheck_convert_incompatible)
8445 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8446 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8447 return ExprError();
8448 }
8449 QualType ElemTy = VTy->getElementType();
8450 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8451 if (Literal.isInvalid())
8452 return ExprError();
8453 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8454 PrepareScalarCast(Literal, ElemTy));
8455 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8456 }
8457
8458 initExprs.append(exprs, exprs + numExprs);
8459 }
8460 // FIXME: This means that pretty-printing the final AST will produce curly
8461 // braces instead of the original commas.
8462 InitListExpr *initE =
8463 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8464 LiteralRParenLoc, /*isExplicit=*/false);
8465 initE->setType(Ty);
8466 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8467}
8468
8471 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8472 if (!E)
8473 return OrigExpr;
8474
8475 ExprResult Result(E->getExpr(0));
8476
8477 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8478 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8479 E->getExpr(i));
8480
8481 if (Result.isInvalid()) return ExprError();
8482
8483 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8484}
8485
8491
8493 unsigned NumUserSpecifiedExprs,
8494 SourceLocation InitLoc,
8495 SourceLocation LParenLoc,
8496 SourceLocation RParenLoc) {
8497 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8498 InitLoc, LParenLoc, RParenLoc);
8499}
8500
8501bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8502 SourceLocation QuestionLoc) {
8503 const Expr *NullExpr = LHSExpr;
8504 const Expr *NonPointerExpr = RHSExpr;
8508
8509 if (NullKind == Expr::NPCK_NotNull) {
8510 NullExpr = RHSExpr;
8511 NonPointerExpr = LHSExpr;
8512 NullKind =
8515 }
8516
8517 if (NullKind == Expr::NPCK_NotNull)
8518 return false;
8519
8520 if (NullKind == Expr::NPCK_ZeroExpression)
8521 return false;
8522
8523 if (NullKind == Expr::NPCK_ZeroLiteral) {
8524 // In this case, check to make sure that we got here from a "NULL"
8525 // string in the source code.
8526 NullExpr = NullExpr->IgnoreParenImpCasts();
8527 SourceLocation loc = NullExpr->getExprLoc();
8528 if (!findMacroSpelling(loc, "NULL"))
8529 return false;
8530 }
8531
8532 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8533 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8534 << NonPointerExpr->getType() << DiagType
8535 << NonPointerExpr->getSourceRange();
8536 return true;
8537}
8538
8539/// Return false if the condition expression is valid, true otherwise.
8540static bool checkCondition(Sema &S, const Expr *Cond,
8541 SourceLocation QuestionLoc) {
8542 QualType CondTy = Cond->getType();
8543
8544 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8545 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8546 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8547 << CondTy << Cond->getSourceRange();
8548 return true;
8549 }
8550
8551 // C99 6.5.15p2
8552 if (CondTy->isScalarType()) return false;
8553
8554 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8555 << CondTy << Cond->getSourceRange();
8556 return true;
8557}
8558
8559/// Return false if the NullExpr can be promoted to PointerTy,
8560/// true otherwise.
8562 QualType PointerTy) {
8563 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8564 !NullExpr.get()->isNullPointerConstant(S.Context,
8566 return true;
8567
8568 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8569 return false;
8570}
8571
8572/// Checks compatibility between two pointers and return the resulting
8573/// type.
8575 ExprResult &RHS,
8576 SourceLocation Loc) {
8577 QualType LHSTy = LHS.get()->getType();
8578 QualType RHSTy = RHS.get()->getType();
8579
8580 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8581 // Two identical pointers types are always compatible.
8582 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8583 }
8584
8585 QualType lhptee, rhptee;
8586
8587 // Get the pointee types.
8588 bool IsBlockPointer = false;
8589 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8590 lhptee = LHSBTy->getPointeeType();
8591 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8592 IsBlockPointer = true;
8593 } else {
8594 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8595 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8596 }
8597
8598 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8599 // differently qualified versions of compatible types, the result type is
8600 // a pointer to an appropriately qualified version of the composite
8601 // type.
8602
8603 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8604 // clause doesn't make sense for our extensions. E.g. address space 2 should
8605 // be incompatible with address space 3: they may live on different devices or
8606 // anything.
8607 Qualifiers lhQual = lhptee.getQualifiers();
8608 Qualifiers rhQual = rhptee.getQualifiers();
8609
8610 LangAS ResultAddrSpace = LangAS::Default;
8611 LangAS LAddrSpace = lhQual.getAddressSpace();
8612 LangAS RAddrSpace = rhQual.getAddressSpace();
8613
8614 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8615 // spaces is disallowed.
8616 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8617 ResultAddrSpace = LAddrSpace;
8618 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8619 ResultAddrSpace = RAddrSpace;
8620 else {
8621 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8622 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8623 << RHS.get()->getSourceRange();
8624 return QualType();
8625 }
8626
8627 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8628 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8629 lhQual.removeCVRQualifiers();
8630 rhQual.removeCVRQualifiers();
8631
8632 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8633 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8634 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8635 << RHS.get()->getSourceRange();
8636 return QualType();
8637 }
8638
8639 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8640 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8641 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8642 // qual types are compatible iff
8643 // * corresponded types are compatible
8644 // * CVR qualifiers are equal
8645 // * address spaces are equal
8646 // Thus for conditional operator we merge CVR and address space unqualified
8647 // pointees and if there is a composite type we return a pointer to it with
8648 // merged qualifiers.
8649 LHSCastKind =
8650 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8651 RHSCastKind =
8652 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8653 lhQual.removeAddressSpace();
8654 rhQual.removeAddressSpace();
8655
8656 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8657 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8658
8659 QualType CompositeTy = S.Context.mergeTypes(
8660 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8661 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8662
8663 if (CompositeTy.isNull()) {
8664 // In this situation, we assume void* type. No especially good
8665 // reason, but this is what gcc does, and we do have to pick
8666 // to get a consistent AST.
8667 QualType incompatTy;
8668 incompatTy = S.Context.getPointerType(
8669 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8670 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8671 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8672
8673 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8674 // for casts between types with incompatible address space qualifiers.
8675 // For the following code the compiler produces casts between global and
8676 // local address spaces of the corresponded innermost pointees:
8677 // local int *global *a;
8678 // global int *global *b;
8679 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8680 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8681 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8682 << RHS.get()->getSourceRange();
8683
8684 return incompatTy;
8685 }
8686
8687 // The pointer types are compatible.
8688 // In case of OpenCL ResultTy should have the address space qualifier
8689 // which is a superset of address spaces of both the 2nd and the 3rd
8690 // operands of the conditional operator.
8691 QualType ResultTy = [&, ResultAddrSpace]() {
8692 if (S.getLangOpts().OpenCL) {
8693 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8694 CompositeQuals.setAddressSpace(ResultAddrSpace);
8695 return S.Context
8696 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8697 .withCVRQualifiers(MergedCVRQual);
8698 }
8699 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8700 }();
8701 if (IsBlockPointer)
8702 ResultTy = S.Context.getBlockPointerType(ResultTy);
8703 else
8704 ResultTy = S.Context.getPointerType(ResultTy);
8705
8706 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8707 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8708 return ResultTy;
8709}
8710
8711/// Return the resulting type when the operands are both block pointers.
8713 ExprResult &LHS,
8714 ExprResult &RHS,
8715 SourceLocation Loc) {
8716 QualType LHSTy = LHS.get()->getType();
8717 QualType RHSTy = RHS.get()->getType();
8718
8719 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8720 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8722 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8723 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8724 return destType;
8725 }
8726 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8727 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8728 << RHS.get()->getSourceRange();
8729 return QualType();
8730 }
8731
8732 // We have 2 block pointer types.
8733 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8734}
8735
8736/// Return the resulting type when the operands are both pointers.
8737static QualType
8739 ExprResult &RHS,
8740 SourceLocation Loc) {
8741 // get the pointer types
8742 QualType LHSTy = LHS.get()->getType();
8743 QualType RHSTy = RHS.get()->getType();
8744
8745 // get the "pointed to" types
8746 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8747 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8748
8749 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8750 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8751 // Figure out necessary qualifiers (C99 6.5.15p6)
8752 QualType destPointee
8753 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8754 QualType destType = S.Context.getPointerType(destPointee);
8755 // Add qualifiers if necessary.
8756 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8757 // Promote to void*.
8758 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8759 return destType;
8760 }
8761 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8762 QualType destPointee
8763 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8764 QualType destType = S.Context.getPointerType(destPointee);
8765 // Add qualifiers if necessary.
8766 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8767 // Promote to void*.
8768 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8769 return destType;
8770 }
8771
8772 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8773}
8774
8775/// Return false if the first expression is not an integer and the second
8776/// expression is not a pointer, true otherwise.
8778 Expr* PointerExpr, SourceLocation Loc,
8779 bool IsIntFirstExpr) {
8780 if (!PointerExpr->getType()->isPointerType() ||
8781 !Int.get()->getType()->isIntegerType())
8782 return false;
8783
8784 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8785 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8786
8787 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8788 << Expr1->getType() << Expr2->getType()
8789 << Expr1->getSourceRange() << Expr2->getSourceRange();
8790 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8791 CK_IntegralToPointer);
8792 return true;
8793}
8794
8795/// Simple conversion between integer and floating point types.
8796///
8797/// Used when handling the OpenCL conditional operator where the
8798/// condition is a vector while the other operands are scalar.
8799///
8800/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8801/// types are either integer or floating type. Between the two
8802/// operands, the type with the higher rank is defined as the "result
8803/// type". The other operand needs to be promoted to the same type. No
8804/// other type promotion is allowed. We cannot use
8805/// UsualArithmeticConversions() for this purpose, since it always
8806/// promotes promotable types.
8808 ExprResult &RHS,
8809 SourceLocation QuestionLoc) {
8811 if (LHS.isInvalid())
8812 return QualType();
8814 if (RHS.isInvalid())
8815 return QualType();
8816
8817 // For conversion purposes, we ignore any qualifiers.
8818 // For example, "const float" and "float" are equivalent.
8819 QualType LHSType =
8821 QualType RHSType =
8823
8824 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8825 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8826 << LHSType << LHS.get()->getSourceRange();
8827 return QualType();
8828 }
8829
8830 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8831 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8832 << RHSType << RHS.get()->getSourceRange();
8833 return QualType();
8834 }
8835
8836 // If both types are identical, no conversion is needed.
8837 if (LHSType == RHSType)
8838 return LHSType;
8839
8840 // Now handle "real" floating types (i.e. float, double, long double).
8841 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8842 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8843 /*IsCompAssign = */ false);
8844
8845 // Finally, we have two differing integer types.
8847 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8848}
8849
8850/// Convert scalar operands to a vector that matches the
8851/// condition in length.
8852///
8853/// Used when handling the OpenCL conditional operator where the
8854/// condition is a vector while the other operands are scalar.
8855///
8856/// We first compute the "result type" for the scalar operands
8857/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8858/// into a vector of that type where the length matches the condition
8859/// vector type. s6.11.6 requires that the element types of the result
8860/// and the condition must have the same number of bits.
8861static QualType
8863 QualType CondTy, SourceLocation QuestionLoc) {
8864 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8865 if (ResTy.isNull()) return QualType();
8866
8867 const VectorType *CV = CondTy->getAs<VectorType>();
8868 assert(CV);
8869
8870 // Determine the vector result type
8871 unsigned NumElements = CV->getNumElements();
8872 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8873
8874 // Ensure that all types have the same number of bits
8876 != S.Context.getTypeSize(ResTy)) {
8877 // Since VectorTy is created internally, it does not pretty print
8878 // with an OpenCL name. Instead, we just print a description.
8879 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8880 SmallString<64> Str;
8881 llvm::raw_svector_ostream OS(Str);
8882 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8883 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8884 << CondTy << OS.str();
8885 return QualType();
8886 }
8887
8888 // Convert operands to the vector result type
8889 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8890 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8891
8892 return VectorTy;
8893}
8894
8895/// Return false if this is a valid OpenCL condition vector
8897 SourceLocation QuestionLoc) {
8898 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8899 // integral type.
8900 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8901 assert(CondTy);
8902 QualType EleTy = CondTy->getElementType();
8903 if (EleTy->isIntegerType()) return false;
8904
8905 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8906 << Cond->getType() << Cond->getSourceRange();
8907 return true;
8908}
8909
8910/// Return false if the vector condition type and the vector
8911/// result type are compatible.
8912///
8913/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8914/// number of elements, and their element types have the same number
8915/// of bits.
8916static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8917 SourceLocation QuestionLoc) {
8918 const VectorType *CV = CondTy->getAs<VectorType>();
8919 const VectorType *RV = VecResTy->getAs<VectorType>();
8920 assert(CV && RV);
8921
8922 if (CV->getNumElements() != RV->getNumElements()) {
8923 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8924 << CondTy << VecResTy;
8925 return true;
8926 }
8927
8928 QualType CVE = CV->getElementType();
8929 QualType RVE = RV->getElementType();
8930
8931 // Boolean vectors are permitted outside of OpenCL mode.
8932 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8933 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8934 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8935 << CondTy << VecResTy;
8936 return true;
8937 }
8938
8939 return false;
8940}
8941
8942/// Return the resulting type for the conditional operator in
8943/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8944/// s6.3.i) when the condition is a vector type.
8945static QualType
8947 ExprResult &LHS, ExprResult &RHS,
8948 SourceLocation QuestionLoc) {
8950 if (Cond.isInvalid())
8951 return QualType();
8952 QualType CondTy = Cond.get()->getType();
8953
8954 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8955 return QualType();
8956
8957 // If either operand is a vector then find the vector type of the
8958 // result as specified in OpenCL v1.1 s6.3.i.
8959 if (LHS.get()->getType()->isVectorType() ||
8960 RHS.get()->getType()->isVectorType()) {
8961 bool IsBoolVecLang =
8962 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8963 QualType VecResTy =
8964 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8965 /*isCompAssign*/ false,
8966 /*AllowBothBool*/ true,
8967 /*AllowBoolConversions*/ false,
8968 /*AllowBooleanOperation*/ IsBoolVecLang,
8969 /*ReportInvalid*/ true);
8970 if (VecResTy.isNull())
8971 return QualType();
8972 // The result type must match the condition type as specified in
8973 // OpenCL v1.1 s6.11.6.
8974 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8975 return QualType();
8976 return VecResTy;
8977 }
8978
8979 // Both operands are scalar.
8980 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8981}
8982
8983/// Return true if the Expr is block type
8984static bool checkBlockType(Sema &S, const Expr *E) {
8985 if (E->getType()->isBlockPointerType()) {
8986 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8987 return true;
8988 }
8989
8990 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8991 QualType Ty = CE->getCallee()->getType();
8992 if (Ty->isBlockPointerType()) {
8993 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8994 return true;
8995 }
8996 }
8997 return false;
8998}
8999
9000/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9001/// In that case, LHS = cond.
9002/// C99 6.5.15
9005 ExprObjectKind &OK,
9006 SourceLocation QuestionLoc) {
9007
9008 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
9009 if (!LHSResult.isUsable()) return QualType();
9010 LHS = LHSResult;
9011
9012 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
9013 if (!RHSResult.isUsable()) return QualType();
9014 RHS = RHSResult;
9015
9016 // C++ is sufficiently different to merit its own checker.
9017 if (getLangOpts().CPlusPlus)
9018 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
9019
9020 VK = VK_PRValue;
9021 OK = OK_Ordinary;
9022
9023 if (Context.isDependenceAllowed() &&
9024 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
9025 RHS.get()->isTypeDependent())) {
9026 assert(!getLangOpts().CPlusPlus);
9027 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
9028 RHS.get()->containsErrors()) &&
9029 "should only occur in error-recovery path.");
9030 return Context.DependentTy;
9031 }
9032
9033 // The OpenCL operator with a vector condition is sufficiently
9034 // different to merit its own checker.
9035 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
9036 Cond.get()->getType()->isExtVectorType())
9037 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
9038
9039 // First, check the condition.
9040 Cond = UsualUnaryConversions(Cond.get());
9041 if (Cond.isInvalid())
9042 return QualType();
9043 if (checkCondition(*this, Cond.get(), QuestionLoc))
9044 return QualType();
9045
9046 // Handle vectors.
9047 if (LHS.get()->getType()->isVectorType() ||
9048 RHS.get()->getType()->isVectorType())
9049 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
9050 /*AllowBothBool*/ true,
9051 /*AllowBoolConversions*/ false,
9052 /*AllowBooleanOperation*/ false,
9053 /*ReportInvalid*/ true);
9054
9055 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
9057 if (LHS.isInvalid() || RHS.isInvalid())
9058 return QualType();
9059
9060 // WebAssembly tables are not allowed as conditional LHS or RHS.
9061 QualType LHSTy = LHS.get()->getType();
9062 QualType RHSTy = RHS.get()->getType();
9063 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
9064 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
9065 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9066 return QualType();
9067 }
9068
9069 // Diagnose attempts to convert between __ibm128, __float128 and long double
9070 // where such conversions currently can't be handled.
9071 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
9072 Diag(QuestionLoc,
9073 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
9074 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9075 return QualType();
9076 }
9077
9078 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9079 // selection operator (?:).
9080 if (getLangOpts().OpenCL &&
9081 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
9082 return QualType();
9083 }
9084
9085 // If both operands have arithmetic type, do the usual arithmetic conversions
9086 // to find a common type: C99 6.5.15p3,5.
9087 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
9088 // Disallow invalid arithmetic conversions, such as those between bit-
9089 // precise integers types of different sizes, or between a bit-precise
9090 // integer and another type.
9091 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9092 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9093 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9094 << RHS.get()->getSourceRange();
9095 return QualType();
9096 }
9097
9098 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
9099 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
9100
9101 return ResTy;
9102 }
9103
9104 // If both operands are the same structure or union type, the result is that
9105 // type.
9106 // FIXME: Type of conditional expression must be complete in C mode.
9107 if (LHSTy->isRecordType() &&
9108 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
9109 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
9110 RHSTy.getUnqualifiedType());
9111
9112 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9113 // The following || allows only one side to be void (a GCC-ism).
9114 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9115 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9116 // UsualArithmeticConversions already handled the case where both sides
9117 // are the same type.
9118 } else if (RHSTy->isVoidType()) {
9119 ResTy = RHSTy;
9120 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9121 << RHS.get()->getSourceRange();
9122 } else {
9123 ResTy = LHSTy;
9124 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9125 << LHS.get()->getSourceRange();
9126 }
9127 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
9128 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
9129 return ResTy;
9130 }
9131
9132 // C23 6.5.15p7:
9133 // ... if both the second and third operands have nullptr_t type, the
9134 // result also has that type.
9135 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
9136 return ResTy;
9137
9138 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9139 // the type of the other operand."
9140 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
9141 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
9142
9143 // All objective-c pointer type analysis is done here.
9144 QualType compositeType =
9145 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9146 if (LHS.isInvalid() || RHS.isInvalid())
9147 return QualType();
9148 if (!compositeType.isNull())
9149 return compositeType;
9150
9151
9152 // Handle block pointer types.
9153 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9154 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9155 QuestionLoc);
9156
9157 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9158 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9159 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9160 QuestionLoc);
9161
9162 // GCC compatibility: soften pointer/integer mismatch. Note that
9163 // null pointers have been filtered out by this point.
9164 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9165 /*IsIntFirstExpr=*/true))
9166 return RHSTy;
9167 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9168 /*IsIntFirstExpr=*/false))
9169 return LHSTy;
9170
9171 // Emit a better diagnostic if one of the expressions is a null pointer
9172 // constant and the other is not a pointer type. In this case, the user most
9173 // likely forgot to take the address of the other expression.
9174 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9175 return QualType();
9176
9177 // Finally, if the LHS and RHS types are canonically the same type, we can
9178 // use the common sugared type.
9179 if (Context.hasSameType(LHSTy, RHSTy))
9180 return Context.getCommonSugaredType(LHSTy, RHSTy);
9181
9182 // Otherwise, the operands are not compatible.
9183 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9184 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9185 << RHS.get()->getSourceRange();
9186 return QualType();
9187}
9188
9189/// SuggestParentheses - Emit a note with a fixit hint that wraps
9190/// ParenRange in parentheses.
9192 const PartialDiagnostic &Note,
9193 SourceRange ParenRange) {
9194 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9195 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9196 EndLoc.isValid()) {
9197 Self.Diag(Loc, Note)
9198 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9199 << FixItHint::CreateInsertion(EndLoc, ")");
9200 } else {
9201 // We can't display the parentheses, so just show the bare note.
9202 Self.Diag(Loc, Note) << ParenRange;
9203 }
9204}
9205
9207 return BinaryOperator::isAdditiveOp(Opc) ||
9209 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9210 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9211 // not any of the logical operators. Bitwise-xor is commonly used as a
9212 // logical-xor because there is no logical-xor operator. The logical
9213 // operators, including uses of xor, have a high false positive rate for
9214 // precedence warnings.
9215}
9216
9217/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9218/// expression, either using a built-in or overloaded operator,
9219/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9220/// expression.
9221static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9222 const Expr **RHSExprs) {
9223 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9224 E = E->IgnoreImpCasts();
9226 E = E->IgnoreImpCasts();
9227 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9228 E = MTE->getSubExpr();
9229 E = E->IgnoreImpCasts();
9230 }
9231
9232 // Built-in binary operator.
9233 if (const auto *OP = dyn_cast<BinaryOperator>(E);
9234 OP && IsArithmeticOp(OP->getOpcode())) {
9235 *Opcode = OP->getOpcode();
9236 *RHSExprs = OP->getRHS();
9237 return true;
9238 }
9239
9240 // Overloaded operator.
9241 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9242 if (Call->getNumArgs() != 2)
9243 return false;
9244
9245 // Make sure this is really a binary operator that is safe to pass into
9246 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9247 OverloadedOperatorKind OO = Call->getOperator();
9248 if (OO < OO_Plus || OO > OO_Arrow ||
9249 OO == OO_PlusPlus || OO == OO_MinusMinus)
9250 return false;
9251
9253 if (IsArithmeticOp(OpKind)) {
9254 *Opcode = OpKind;
9255 *RHSExprs = Call->getArg(1);
9256 return true;
9257 }
9258 }
9259
9260 return false;
9261}
9262
9263/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9264/// or is a logical expression such as (x==y) which has int type, but is
9265/// commonly interpreted as boolean.
9266static bool ExprLooksBoolean(const Expr *E) {
9267 E = E->IgnoreParenImpCasts();
9268
9269 if (E->getType()->isBooleanType())
9270 return true;
9271 if (const auto *OP = dyn_cast<BinaryOperator>(E))
9272 return OP->isComparisonOp() || OP->isLogicalOp();
9273 if (const auto *OP = dyn_cast<UnaryOperator>(E))
9274 return OP->getOpcode() == UO_LNot;
9275 if (E->getType()->isPointerType())
9276 return true;
9277 // FIXME: What about overloaded operator calls returning "unspecified boolean
9278 // type"s (commonly pointer-to-members)?
9279
9280 return false;
9281}
9282
9283/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9284/// and binary operator are mixed in a way that suggests the programmer assumed
9285/// the conditional operator has higher precedence, for example:
9286/// "int x = a + someBinaryCondition ? 1 : 2".
9288 Expr *Condition, const Expr *LHSExpr,
9289 const Expr *RHSExpr) {
9290 BinaryOperatorKind CondOpcode;
9291 const Expr *CondRHS;
9292
9293 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9294 return;
9295 if (!ExprLooksBoolean(CondRHS))
9296 return;
9297
9298 // The condition is an arithmetic binary expression, with a right-
9299 // hand side that looks boolean, so warn.
9300
9301 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9302 ? diag::warn_precedence_bitwise_conditional
9303 : diag::warn_precedence_conditional;
9304
9305 Self.Diag(OpLoc, DiagID)
9306 << Condition->getSourceRange()
9307 << BinaryOperator::getOpcodeStr(CondOpcode);
9308
9310 Self, OpLoc,
9311 Self.PDiag(diag::note_precedence_silence)
9312 << BinaryOperator::getOpcodeStr(CondOpcode),
9313 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9314
9315 SuggestParentheses(Self, OpLoc,
9316 Self.PDiag(diag::note_precedence_conditional_first),
9317 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9318}
9319
9320/// Compute the nullability of a conditional expression.
9322 QualType LHSTy, QualType RHSTy,
9323 ASTContext &Ctx) {
9324 if (!ResTy->isAnyPointerType())
9325 return ResTy;
9326
9327 auto GetNullability = [](QualType Ty) {
9328 NullabilityKindOrNone Kind = Ty->getNullability();
9329 if (Kind) {
9330 // For our purposes, treat _Nullable_result as _Nullable.
9333 return *Kind;
9334 }
9336 };
9337
9338 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9339 NullabilityKind MergedKind;
9340
9341 // Compute nullability of a binary conditional expression.
9342 if (IsBin) {
9343 if (LHSKind == NullabilityKind::NonNull)
9344 MergedKind = NullabilityKind::NonNull;
9345 else
9346 MergedKind = RHSKind;
9347 // Compute nullability of a normal conditional expression.
9348 } else {
9349 if (LHSKind == NullabilityKind::Nullable ||
9350 RHSKind == NullabilityKind::Nullable)
9351 MergedKind = NullabilityKind::Nullable;
9352 else if (LHSKind == NullabilityKind::NonNull)
9353 MergedKind = RHSKind;
9354 else if (RHSKind == NullabilityKind::NonNull)
9355 MergedKind = LHSKind;
9356 else
9357 MergedKind = NullabilityKind::Unspecified;
9358 }
9359
9360 // Return if ResTy already has the correct nullability.
9361 if (GetNullability(ResTy) == MergedKind)
9362 return ResTy;
9363
9364 // Strip all nullability from ResTy.
9365 while (ResTy->getNullability())
9366 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9367
9368 // Create a new AttributedType with the new nullability kind.
9369 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
9370}
9371
9373 SourceLocation ColonLoc,
9374 Expr *CondExpr, Expr *LHSExpr,
9375 Expr *RHSExpr) {
9376 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9377 // was the condition.
9378 OpaqueValueExpr *opaqueValue = nullptr;
9379 Expr *commonExpr = nullptr;
9380 if (!LHSExpr) {
9381 commonExpr = CondExpr;
9382 // Lower out placeholder types first. This is important so that we don't
9383 // try to capture a placeholder. This happens in few cases in C++; such
9384 // as Objective-C++'s dictionary subscripting syntax.
9385 if (commonExpr->hasPlaceholderType()) {
9386 ExprResult result = CheckPlaceholderExpr(commonExpr);
9387 if (!result.isUsable()) return ExprError();
9388 commonExpr = result.get();
9389 }
9390 // We usually want to apply unary conversions *before* saving, except
9391 // in the special case of a C++ l-value conditional.
9392 if (!(getLangOpts().CPlusPlus
9393 && !commonExpr->isTypeDependent()
9394 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9395 && commonExpr->isGLValue()
9396 && commonExpr->isOrdinaryOrBitFieldObject()
9397 && RHSExpr->isOrdinaryOrBitFieldObject()
9398 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9399 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9400 if (commonRes.isInvalid())
9401 return ExprError();
9402 commonExpr = commonRes.get();
9403 }
9404
9405 // If the common expression is a class or array prvalue, materialize it
9406 // so that we can safely refer to it multiple times.
9407 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9408 commonExpr->getType()->isArrayType())) {
9409 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9410 if (MatExpr.isInvalid())
9411 return ExprError();
9412 commonExpr = MatExpr.get();
9413 }
9414
9415 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9416 commonExpr->getType(),
9417 commonExpr->getValueKind(),
9418 commonExpr->getObjectKind(),
9419 commonExpr);
9420 LHSExpr = CondExpr = opaqueValue;
9421 }
9422
9423 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9426 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9427 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9428 VK, OK, QuestionLoc);
9429 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9430 RHS.isInvalid())
9431 return ExprError();
9432
9433 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9434 RHS.get());
9435
9436 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9437
9438 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9439 Context);
9440
9441 if (!commonExpr)
9442 return new (Context)
9443 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9444 RHS.get(), result, VK, OK);
9445
9447 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9448 ColonLoc, result, VK, OK);
9449}
9450
9452 unsigned FromAttributes = 0, ToAttributes = 0;
9453 if (const auto *FromFn =
9454 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9455 FromAttributes =
9456 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9457 if (const auto *ToFn =
9458 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9459 ToAttributes =
9460 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9461
9462 return FromAttributes != ToAttributes;
9463}
9464
9465// checkPointerTypesForAssignment - This is a very tricky routine (despite
9466// being closely modeled after the C99 spec:-). The odd characteristic of this
9467// routine is it effectively iqnores the qualifiers on the top level pointee.
9468// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9469// FIXME: add a couple examples in this comment.
9471 QualType LHSType,
9472 QualType RHSType,
9473 SourceLocation Loc) {
9474 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9475 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9476
9477 // get the "pointed to" type (ignoring qualifiers at the top level)
9478 const Type *lhptee, *rhptee;
9479 Qualifiers lhq, rhq;
9480 std::tie(lhptee, lhq) =
9481 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9482 std::tie(rhptee, rhq) =
9483 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9484
9486
9487 // C99 6.5.16.1p1: This following citation is common to constraints
9488 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9489 // qualifiers of the type *pointed to* by the right;
9490
9491 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9492 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9494 // Ignore lifetime for further calculation.
9495 lhq.removeObjCLifetime();
9496 rhq.removeObjCLifetime();
9497 }
9498
9499 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9500 // Treat address-space mismatches as fatal.
9501 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9503
9504 // It's okay to add or remove GC or lifetime qualifiers when converting to
9505 // and from void*.
9508 S.getASTContext()) &&
9509 (lhptee->isVoidType() || rhptee->isVoidType()))
9510 ; // keep old
9511
9512 // Treat lifetime mismatches as fatal.
9513 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9515
9516 // Treat pointer-auth mismatches as fatal.
9517 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9519
9520 // For GCC/MS compatibility, other qualifier mismatches are treated
9521 // as still compatible in C.
9522 else
9524 }
9525
9526 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9527 // incomplete type and the other is a pointer to a qualified or unqualified
9528 // version of void...
9529 if (lhptee->isVoidType()) {
9530 if (rhptee->isIncompleteOrObjectType())
9531 return ConvTy;
9532
9533 // As an extension, we allow cast to/from void* to function pointer.
9534 assert(rhptee->isFunctionType());
9536 }
9537
9538 if (rhptee->isVoidType()) {
9539 // In C, void * to another pointer type is compatible, but we want to note
9540 // that there will be an implicit conversion happening here.
9541 if (lhptee->isIncompleteOrObjectType())
9542 return ConvTy == AssignConvertType::Compatible &&
9543 !S.getLangOpts().CPlusPlus
9545 : ConvTy;
9546
9547 // As an extension, we allow cast to/from void* to function pointer.
9548 assert(lhptee->isFunctionType());
9550 }
9551
9552 if (!S.Diags.isIgnored(
9553 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9554 Loc) &&
9555 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9556 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9558
9559 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9560 // unqualified versions of compatible types, ...
9561 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9562
9563 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9564 if (!S.Context.hasSameType(ltrans, rtrans)) {
9565 QualType LUnderlying =
9566 ltrans->isOverflowBehaviorType()
9567 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9568 : ltrans;
9569 QualType RUnderlying =
9570 rtrans->isOverflowBehaviorType()
9571 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9572 : rtrans;
9573
9574 if (S.Context.hasSameType(LUnderlying, RUnderlying))
9576
9577 ltrans = LUnderlying;
9578 rtrans = RUnderlying;
9579 }
9580 }
9581
9582 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9583 // Check if the pointee types are compatible ignoring the sign.
9584 // We explicitly check for char so that we catch "char" vs
9585 // "unsigned char" on systems where "char" is unsigned.
9586 if (lhptee->isCharType())
9587 ltrans = S.Context.UnsignedCharTy;
9588 else if (lhptee->hasSignedIntegerRepresentation())
9589 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9590
9591 if (rhptee->isCharType())
9592 rtrans = S.Context.UnsignedCharTy;
9593 else if (rhptee->hasSignedIntegerRepresentation())
9594 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9595
9596 if (ltrans == rtrans) {
9597 // Types are compatible ignoring the sign. Qualifier incompatibility
9598 // takes priority over sign incompatibility because the sign
9599 // warning can be disabled.
9600 if (!S.IsAssignConvertCompatible(ConvTy))
9601 return ConvTy;
9602
9604 }
9605
9606 // If we are a multi-level pointer, it's possible that our issue is simply
9607 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9608 // the eventual target type is the same and the pointers have the same
9609 // level of indirection, this must be the issue.
9610 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9611 do {
9612 std::tie(lhptee, lhq) =
9613 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9614 std::tie(rhptee, rhq) =
9615 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9616
9617 // Inconsistent address spaces at this point is invalid, even if the
9618 // address spaces would be compatible.
9619 // FIXME: This doesn't catch address space mismatches for pointers of
9620 // different nesting levels, like:
9621 // __local int *** a;
9622 // int ** b = a;
9623 // It's not clear how to actually determine when such pointers are
9624 // invalidly incompatible.
9625 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9626 return AssignConvertType::
9627 IncompatibleNestedPointerAddressSpaceMismatch;
9628
9629 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9630
9631 if (lhptee == rhptee)
9633 }
9634
9635 // General pointer incompatibility takes priority over qualifiers.
9636 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9639 }
9640 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9641 // hasSameType, so we can skip further checks.
9642 const auto *LFT = ltrans->getAs<FunctionType>();
9643 const auto *RFT = rtrans->getAs<FunctionType>();
9644 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9645 // The invocation of IsFunctionConversion below will try to transform rtrans
9646 // to obtain an exact match for ltrans. This should not fail because of
9647 // mismatches in result type and parameter types, they were already checked
9648 // by typesAreCompatible above. So we will recreate rtrans (or where
9649 // appropriate ltrans) using the result type and parameter types from ltrans
9650 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9651 const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);
9652 const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);
9653 if (LFPT && RFPT) {
9654 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9655 LFPT->getParamTypes(),
9656 RFPT->getExtProtoInfo());
9657 } else if (LFPT) {
9659 EPI.ExtInfo = RFT->getExtInfo();
9660 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9661 LFPT->getParamTypes(), EPI);
9662 } else if (RFPT) {
9663 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9664 // all of its ExtProtoInfo. Transform ltrans instead.
9666 EPI.ExtInfo = LFT->getExtInfo();
9667 ltrans = S.Context.getFunctionType(RFPT->getReturnType(),
9668 RFPT->getParamTypes(), EPI);
9669 } else {
9670 rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),
9671 RFT->getExtInfo());
9672 }
9673 if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&
9674 !S.IsFunctionConversion(rtrans, ltrans))
9676 }
9677 return ConvTy;
9678}
9679
9680/// checkBlockPointerTypesForAssignment - This routine determines whether two
9681/// block pointer types are compatible or whether a block and normal pointer
9682/// are compatible. It is more restrict than comparing two function pointer
9683// types.
9685 QualType LHSType,
9686 QualType RHSType) {
9687 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9688 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9689
9690 QualType lhptee, rhptee;
9691
9692 // get the "pointed to" type (ignoring qualifiers at the top level)
9693 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9694 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9695
9696 // In C++, the types have to match exactly.
9697 if (S.getLangOpts().CPlusPlus)
9699
9701
9702 // For blocks we enforce that qualifiers are identical.
9703 Qualifiers LQuals = lhptee.getLocalQualifiers();
9704 Qualifiers RQuals = rhptee.getLocalQualifiers();
9705 if (S.getLangOpts().OpenCL) {
9706 LQuals.removeAddressSpace();
9707 RQuals.removeAddressSpace();
9708 }
9709 if (LQuals != RQuals)
9711
9712 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9713 // assignment.
9714 // The current behavior is similar to C++ lambdas. A block might be
9715 // assigned to a variable iff its return type and parameters are compatible
9716 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9717 // an assignment. Presumably it should behave in way that a function pointer
9718 // assignment does in C, so for each parameter and return type:
9719 // * CVR and address space of LHS should be a superset of CVR and address
9720 // space of RHS.
9721 // * unqualified types should be compatible.
9722 if (S.getLangOpts().OpenCL) {
9724 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9725 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9727 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9729
9730 return ConvTy;
9731}
9732
9733/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9734/// for assignment compatibility.
9736 QualType LHSType,
9737 QualType RHSType) {
9738 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9739 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9740
9741 if (LHSType->isObjCBuiltinType()) {
9742 // Class is not compatible with ObjC object pointers.
9743 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9744 !RHSType->isObjCQualifiedClassType())
9747 }
9748 if (RHSType->isObjCBuiltinType()) {
9749 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9750 !LHSType->isObjCQualifiedClassType())
9753 }
9754 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9755 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9756
9757 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9758 // make an exception for id<P>
9759 !LHSType->isObjCQualifiedIdType())
9761
9762 if (S.Context.typesAreCompatible(LHSType, RHSType))
9764 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9767}
9768
9770 QualType LHSType,
9771 QualType RHSType) {
9772 // Fake up an opaque expression. We don't actually care about what
9773 // cast operations are required, so if CheckAssignmentConstraints
9774 // adds casts to this they'll be wasted, but fortunately that doesn't
9775 // usually happen on valid code.
9776 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9777 ExprResult RHSPtr = &RHSExpr;
9778 CastKind K;
9779
9780 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9781}
9782
9783/// This helper function returns true if QT is a vector type that has element
9784/// type ElementType.
9785static bool isVector(QualType QT, QualType ElementType) {
9786 if (const VectorType *VT = QT->getAs<VectorType>())
9787 return VT->getElementType().getCanonicalType() == ElementType;
9788 return false;
9789}
9790
9791/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9792/// has code to accommodate several GCC extensions when type checking
9793/// pointers. Here are some objectionable examples that GCC considers warnings:
9794///
9795/// int a, *pint;
9796/// short *pshort;
9797/// struct foo *pfoo;
9798///
9799/// pint = pshort; // warning: assignment from incompatible pointer type
9800/// a = pint; // warning: assignment makes integer from pointer without a cast
9801/// pint = a; // warning: assignment makes pointer from integer without a cast
9802/// pint = pfoo; // warning: assignment from incompatible pointer type
9803///
9804/// As a result, the code for dealing with pointers is more complex than the
9805/// C99 spec dictates.
9806///
9807/// Sets 'Kind' for any result kind except Incompatible.
9809 ExprResult &RHS,
9810 CastKind &Kind,
9811 bool ConvertRHS) {
9812 QualType RHSType = RHS.get()->getType();
9813 QualType OrigLHSType = LHSType;
9814
9815 // Get canonical types. We're not formatting these types, just comparing
9816 // them.
9817 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9818 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9819
9820 // Common case: no conversion required.
9821 if (LHSType == RHSType) {
9822 Kind = CK_NoOp;
9824 }
9825
9826 // If the LHS has an __auto_type, there are no additional type constraints
9827 // to be worried about.
9828 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9829 if (AT->isGNUAutoType()) {
9830 Kind = CK_NoOp;
9832 }
9833 }
9834
9835 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHSType, RHSType);
9836 switch (OBTResult) {
9838 Kind = CK_NoOp;
9841 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9845 break;
9846 }
9847
9848 // Check for incompatible OBT types in pointer pointee types
9849 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9850 QualType LHSPointee = LHSType->getPointeeType();
9851 QualType RHSPointee = RHSType->getPointeeType();
9852 if ((LHSPointee->isOverflowBehaviorType() ||
9853 RHSPointee->isOverflowBehaviorType()) &&
9854 !Context.areCompatibleOverflowBehaviorTypes(LHSPointee, RHSPointee)) {
9855 Kind = CK_NoOp;
9857 }
9858 }
9859
9860 // If we have an atomic type, try a non-atomic assignment, then just add an
9861 // atomic qualification step.
9862 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9864 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9866 return Result;
9867 if (Kind != CK_NoOp && ConvertRHS)
9868 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9869 Kind = CK_NonAtomicToAtomic;
9870 return Result;
9871 }
9872
9873 // If the left-hand side is a reference type, then we are in a
9874 // (rare!) case where we've allowed the use of references in C,
9875 // e.g., as a parameter type in a built-in function. In this case,
9876 // just make sure that the type referenced is compatible with the
9877 // right-hand side type. The caller is responsible for adjusting
9878 // LHSType so that the resulting expression does not have reference
9879 // type.
9880 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9881 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9882 Kind = CK_LValueBitCast;
9884 }
9886 }
9887
9888 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9889 // of an ExtVector type to the same ExtVector type.
9890 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9891 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9892 // Implicit conversions require the same number of elements.
9893 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9895
9896 if (LHSType->isExtVectorBoolType() &&
9897 RHSExtType->getElementType()->isIntegerType()) {
9898 Kind = CK_IntegralToBoolean;
9900 }
9901 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9902 if (Context.getLangOpts().OpenCL &&
9903 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9904 Kind = CK_BitCast;
9906 }
9908 }
9909 if (RHSType->isArithmeticType()) {
9910 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9911 if (ConvertRHS)
9912 RHS = prepareVectorSplat(LHSType, RHS.get());
9913 Kind = CK_VectorSplat;
9915 }
9916 }
9917
9918 // Conversions to or from vector type.
9919 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9920 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9921 // Allow assignments of an AltiVec vector type to an equivalent GCC
9922 // vector type and vice versa
9923 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9924 Kind = CK_BitCast;
9926 }
9927
9928 // If we are allowing lax vector conversions, and LHS and RHS are both
9929 // vectors, the total size only needs to be the same. This is a bitcast;
9930 // no bits are changed but the result type is different.
9931 if (isLaxVectorConversion(RHSType, LHSType)) {
9932 // The default for lax vector conversions with Altivec vectors will
9933 // change, so if we are converting between vector types where
9934 // at least one is an Altivec vector, emit a warning.
9935 if (Context.getTargetInfo().getTriple().isPPC() &&
9936 anyAltivecTypes(RHSType, LHSType) &&
9937 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9938 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9939 << RHSType << LHSType;
9940 Kind = CK_BitCast;
9942 }
9943 }
9944
9945 // When the RHS comes from another lax conversion (e.g. binops between
9946 // scalars and vectors) the result is canonicalized as a vector. When the
9947 // LHS is also a vector, the lax is allowed by the condition above. Handle
9948 // the case where LHS is a scalar.
9949 if (LHSType->isScalarType()) {
9950 const VectorType *VecType = RHSType->getAs<VectorType>();
9951 if (VecType && VecType->getNumElements() == 1 &&
9952 isLaxVectorConversion(RHSType, LHSType)) {
9953 if (Context.getTargetInfo().getTriple().isPPC() &&
9955 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9957 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9958 << RHSType << LHSType;
9959 ExprResult *VecExpr = &RHS;
9960 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9961 Kind = CK_BitCast;
9963 }
9964 }
9965
9966 // Allow assignments between fixed-length and sizeless SVE vectors.
9967 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9968 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9969 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9970 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9971 Kind = CK_BitCast;
9973 }
9974
9975 // Allow assignments between fixed-length and sizeless RVV vectors.
9976 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9977 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9978 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9979 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9980 Kind = CK_BitCast;
9982 }
9983 }
9984
9986 }
9987
9988 // Diagnose attempts to convert between __ibm128, __float128 and long double
9989 // where such conversions currently can't be handled.
9990 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9992
9993 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9994 // discards the imaginary part.
9995 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9996 !LHSType->getAs<ComplexType>())
9998
9999 // Arithmetic conversions.
10000 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
10001 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
10002 if (ConvertRHS)
10003 Kind = PrepareScalarCast(RHS, LHSType);
10005 }
10006
10007 // Conversions to normal pointers.
10008 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
10009 // U* -> T*
10010 if (isa<PointerType>(RHSType)) {
10011 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10012 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
10013 if (AddrSpaceL != AddrSpaceR)
10014 Kind = CK_AddressSpaceConversion;
10015 else if (Context.hasCvrSimilarType(RHSType, LHSType))
10016 Kind = CK_NoOp;
10017 else
10018 Kind = CK_BitCast;
10019 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
10020 RHS.get()->getBeginLoc());
10021 }
10022
10023 // int -> T*
10024 if (RHSType->isIntegerType()) {
10025 Kind = CK_IntegralToPointer; // FIXME: null?
10027 }
10028
10029 // C pointers are not compatible with ObjC object pointers,
10030 // with two exceptions:
10031 if (isa<ObjCObjectPointerType>(RHSType)) {
10032 // - conversions to void*
10033 if (LHSPointer->getPointeeType()->isVoidType()) {
10034 Kind = CK_BitCast;
10036 }
10037
10038 // - conversions from 'Class' to the redefinition type
10039 if (RHSType->isObjCClassType() &&
10040 Context.hasSameType(LHSType,
10041 Context.getObjCClassRedefinitionType())) {
10042 Kind = CK_BitCast;
10044 }
10045
10046 Kind = CK_BitCast;
10048 }
10049
10050 // U^ -> void*
10051 if (RHSType->getAs<BlockPointerType>()) {
10052 if (LHSPointer->getPointeeType()->isVoidType()) {
10053 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10054 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10055 ->getPointeeType()
10056 .getAddressSpace();
10057 Kind =
10058 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10060 }
10061 }
10062
10064 }
10065
10066 // Conversions to block pointers.
10067 if (isa<BlockPointerType>(LHSType)) {
10068 // U^ -> T^
10069 if (RHSType->isBlockPointerType()) {
10070 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10071 ->getPointeeType()
10072 .getAddressSpace();
10073 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10074 ->getPointeeType()
10075 .getAddressSpace();
10076 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10077 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
10078 }
10079
10080 // int or null -> T^
10081 if (RHSType->isIntegerType()) {
10082 Kind = CK_IntegralToPointer; // FIXME: null
10084 }
10085
10086 // id -> T^
10087 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10088 Kind = CK_AnyPointerToBlockPointerCast;
10090 }
10091
10092 // void* -> T^
10093 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10094 if (RHSPT->getPointeeType()->isVoidType()) {
10095 Kind = CK_AnyPointerToBlockPointerCast;
10097 }
10098
10100 }
10101
10102 // Conversions to Objective-C pointers.
10103 if (isa<ObjCObjectPointerType>(LHSType)) {
10104 // A* -> B*
10105 if (RHSType->isObjCObjectPointerType()) {
10106 Kind = CK_BitCast;
10107 AssignConvertType result =
10108 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
10109 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10111 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10113 return result;
10114 }
10115
10116 // int or null -> A*
10117 if (RHSType->isIntegerType()) {
10118 Kind = CK_IntegralToPointer; // FIXME: null
10120 }
10121
10122 // In general, C pointers are not compatible with ObjC object pointers,
10123 // with two exceptions:
10124 if (isa<PointerType>(RHSType)) {
10125 Kind = CK_CPointerToObjCPointerCast;
10126
10127 // - conversions from 'void*'
10128 if (RHSType->isVoidPointerType()) {
10130 }
10131
10132 // - conversions to 'Class' from its redefinition type
10133 if (LHSType->isObjCClassType() &&
10134 Context.hasSameType(RHSType,
10135 Context.getObjCClassRedefinitionType())) {
10137 }
10138
10140 }
10141
10142 // Only under strict condition T^ is compatible with an Objective-C pointer.
10143 if (RHSType->isBlockPointerType() &&
10145 if (ConvertRHS)
10147 Kind = CK_BlockPointerToObjCPointerCast;
10149 }
10150
10152 }
10153
10154 // Conversion to nullptr_t (C23 only)
10155 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10158 // null -> nullptr_t
10159 Kind = CK_NullToPointer;
10161 }
10162
10163 // Conversions from pointers that are not covered by the above.
10164 if (isa<PointerType>(RHSType)) {
10165 // T* -> _Bool
10166 if (LHSType == Context.BoolTy) {
10167 Kind = CK_PointerToBoolean;
10169 }
10170
10171 // T* -> int
10172 if (LHSType->isIntegerType()) {
10173 Kind = CK_PointerToIntegral;
10175 }
10176
10178 }
10179
10180 // Conversions from Objective-C pointers that are not covered by the above.
10181 if (isa<ObjCObjectPointerType>(RHSType)) {
10182 // T* -> _Bool
10183 if (LHSType == Context.BoolTy) {
10184 Kind = CK_PointerToBoolean;
10186 }
10187
10188 // T* -> int
10189 if (LHSType->isIntegerType()) {
10190 Kind = CK_PointerToIntegral;
10192 }
10193
10195 }
10196
10197 // struct A -> struct B
10198 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10199 if (Context.typesAreCompatible(LHSType, RHSType)) {
10200 Kind = CK_NoOp;
10202 }
10203 }
10204
10205 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10206 Kind = CK_IntToOCLSampler;
10208 }
10209
10211}
10212
10213/// Constructs a transparent union from an expression that is
10214/// used to initialize the transparent union.
10216 ExprResult &EResult, QualType UnionType,
10217 FieldDecl *Field) {
10218 // Build an initializer list that designates the appropriate member
10219 // of the transparent union.
10220 Expr *E = EResult.get();
10222 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10223 Initializer->setType(UnionType);
10224 Initializer->setInitializedFieldInUnion(Field);
10225
10226 // Build a compound literal constructing a value of the transparent
10227 // union type from this initializer list.
10228 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10229 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10230 VK_PRValue, Initializer, false);
10231}
10232
10235 ExprResult &RHS) {
10236 QualType RHSType = RHS.get()->getType();
10237
10238 // If the ArgType is a Union type, we want to handle a potential
10239 // transparent_union GCC extension.
10240 const RecordType *UT = ArgType->getAsUnionType();
10241 if (!UT)
10243
10244 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10245 if (!UD->hasAttr<TransparentUnionAttr>())
10247
10248 // The field to initialize within the transparent union.
10249 FieldDecl *InitField = nullptr;
10250 // It's compatible if the expression matches any of the fields.
10251 for (auto *it : UD->fields()) {
10252 if (it->getType()->isPointerType()) {
10253 // If the transparent union contains a pointer type, we allow:
10254 // 1) void pointer
10255 // 2) null pointer constant
10256 if (RHSType->isPointerType())
10257 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10258 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10259 InitField = it;
10260 break;
10261 }
10262
10265 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10266 CK_NullToPointer);
10267 InitField = it;
10268 break;
10269 }
10270 }
10271
10272 CastKind Kind;
10273 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
10275 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10276 InitField = it;
10277 break;
10278 }
10279 }
10280
10281 if (!InitField)
10283
10284 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10286}
10287
10289 ExprResult &CallerRHS,
10290 bool Diagnose,
10291 bool DiagnoseCFAudited,
10292 bool ConvertRHS) {
10293 // We need to be able to tell the caller whether we diagnosed a problem, if
10294 // they ask us to issue diagnostics.
10295 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10296
10297 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10298 // we can't avoid *all* modifications at the moment, so we need some somewhere
10299 // to put the updated value.
10300 ExprResult LocalRHS = CallerRHS;
10301 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10302
10303 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10304 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10305 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10306 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10307 Diag(RHS.get()->getExprLoc(),
10308 diag::warn_noderef_to_dereferenceable_pointer)
10309 << RHS.get()->getSourceRange();
10310 }
10311 }
10312 }
10313
10314 if (getLangOpts().CPlusPlus) {
10315 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10316 // C++ 5.17p3: If the left operand is not of class type, the
10317 // expression is implicitly converted (C++ 4) to the
10318 // cv-unqualified type of the left operand.
10319 QualType RHSType = RHS.get()->getType();
10320 if (Diagnose) {
10321 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10323 } else {
10326 /*SuppressUserConversions=*/false,
10327 AllowedExplicit::None,
10328 /*InOverloadResolution=*/false,
10329 /*CStyle=*/false,
10330 /*AllowObjCWritebackConversion=*/false);
10331 if (ICS.isFailure())
10333 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10335 }
10336 if (RHS.isInvalid())
10339 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10340 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10342
10343 // Check if OBT is being discarded during assignment
10344 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10345 if (RHSType->isOverflowBehaviorType() &&
10346 !LHSType->isOverflowBehaviorType()) {
10348 }
10349
10350 return result;
10351 }
10352
10353 // FIXME: Currently, we fall through and treat C++ classes like C
10354 // structures.
10355 // FIXME: We also fall through for atomics; not sure what should
10356 // happen there, though.
10357 } else if (RHS.get()->getType() == Context.OverloadTy) {
10358 // As a set of extensions to C, we support overloading on functions. These
10359 // functions need to be resolved here.
10360 DeclAccessPair DAP;
10362 RHS.get(), LHSType, /*Complain=*/false, DAP))
10363 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10364 else
10366 }
10367
10368 // For HLSL records, insert derived-to-base conversion if needed.
10369 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10370 QualType RHSType = RHS.get()->getType();
10371 if (!Context.hasSameUnqualifiedType(RHSType, LHSType)) {
10372 CXXBasePaths Paths;
10373 if (IsDerivedFrom(RHS.get()->getBeginLoc(), RHSType, LHSType, Paths)) {
10374 CXXCastPath CastPath;
10375 BuildBasePathArray(Paths, CastPath);
10376 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_DerivedToBase, VK_LValue,
10377 &CastPath);
10378 }
10379 }
10380 }
10381
10382 // This check seems unnatural, however it is necessary to ensure the proper
10383 // conversion of functions/arrays. If the conversion were done for all
10384 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10385 // expressions that suppress this implicit conversion (&, sizeof). This needs
10386 // to happen before we check for null pointer conversions because C does not
10387 // undergo the same implicit conversions as C++ does above (by the calls to
10388 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10389 // lvalue to rvalue cast before checking for null pointer constraints. This
10390 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10391 //
10392 // Suppress this for references: C++ 8.5.3p5.
10393 if (!LHSType->isReferenceType()) {
10394 // FIXME: We potentially allocate here even if ConvertRHS is false.
10396 if (RHS.isInvalid())
10398 }
10399
10400 // The constraints are expressed in terms of the atomic, qualified, or
10401 // unqualified type of the LHS.
10402 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10403
10404 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10405 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10406 if ((LHSTypeAfterConversion->isPointerType() ||
10407 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10408 LHSTypeAfterConversion->isBlockPointerType()) &&
10409 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10413 if (Diagnose || ConvertRHS) {
10414 CastKind Kind;
10415 CXXCastPath Path;
10416 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10417 /*IgnoreBaseAccess=*/false, Diagnose);
10418
10419 // If there is a conversion of some kind, check to see what kind of
10420 // pointer conversion happened so we can diagnose a C++ compatibility
10421 // diagnostic if the conversion is invalid. This only matters if the RHS
10422 // is some kind of void pointer. We have a carve-out when the RHS is from
10423 // a macro expansion because the use of a macro may indicate different
10424 // code between C and C++. Consider: char *s = NULL; where NULL is
10425 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10426 // C++, which is valid in C++.
10427 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10428 !RHS.get()->getBeginLoc().isMacroID()) {
10429 QualType CanRHS =
10431 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10432 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10433 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
10434 RHS.get()->getExprLoc());
10435 // Anything that's not considered perfectly compatible would be
10436 // incompatible in C++.
10439 }
10440 }
10441
10442 if (ConvertRHS)
10443 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10444 }
10445 return Ret;
10446 }
10447 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10448 // unqualified bool, and the right operand is a pointer or its type is
10449 // nullptr_t.
10450 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10451 RHS.get()->getType()->isNullPtrType()) {
10452 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10453 // only handles nullptr -> _Bool due to needing an extra conversion
10454 // step.
10455 // We model this by converting from nullptr -> void * and then let the
10456 // conversion from void * -> _Bool happen naturally.
10457 if (Diagnose || ConvertRHS) {
10458 CastKind Kind;
10459 CXXCastPath Path;
10460 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10461 /*IgnoreBaseAccess=*/false, Diagnose);
10462 if (ConvertRHS)
10463 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10464 &Path);
10465 }
10466 }
10467
10468 // OpenCL queue_t type assignment.
10469 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10471 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10473 }
10474
10475 CastKind Kind;
10476 AssignConvertType result =
10477 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10478
10479 // If assigning a void * created by an allocation function call to some other
10480 // type, check that the allocated size is sufficient for that type.
10481 if (result != AssignConvertType::Incompatible &&
10482 RHS.get()->getType()->isVoidPointerType())
10483 CheckSufficientAllocSize(*this, LHSType, RHS.get());
10484
10485 // C99 6.5.16.1p2: The value of the right operand is converted to the
10486 // type of the assignment expression.
10487 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10488 // so that we can use references in built-in functions even in C.
10489 // The getNonReferenceType() call makes sure that the resulting expression
10490 // does not have reference type.
10491 if (result != AssignConvertType::Incompatible &&
10492 RHS.get()->getType() != LHSType) {
10494 Expr *E = RHS.get();
10495
10496 // Check for various Objective-C errors. If we are not reporting
10497 // diagnostics and just checking for errors, e.g., during overload
10498 // resolution, return Incompatible to indicate the failure.
10499 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10500 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
10502 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10503 if (!Diagnose)
10505 }
10506 if (getLangOpts().ObjC &&
10507 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10508 E->getType(), E, Diagnose) ||
10509 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10510 if (!Diagnose)
10512 // Replace the expression with a corrected version and continue so we
10513 // can find further errors.
10514 RHS = E;
10516 }
10517
10518 if (ConvertRHS)
10519 RHS = ImpCastExprToType(E, Ty, Kind);
10520 }
10521
10522 return result;
10523}
10524
10525namespace {
10526/// The original operand to an operator, prior to the application of the usual
10527/// arithmetic conversions and converting the arguments of a builtin operator
10528/// candidate.
10529struct OriginalOperand {
10530 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10531 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10532 Op = MTE->getSubExpr();
10533 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10534 Op = BTE->getSubExpr();
10535 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10536 Orig = ICE->getSubExprAsWritten();
10537 Conversion = ICE->getConversionFunction();
10538 }
10539 }
10540
10541 QualType getType() const { return Orig->getType(); }
10542
10543 Expr *Orig;
10544 NamedDecl *Conversion;
10545};
10546}
10547
10549 ExprResult &RHS) {
10550 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10551
10552 Diag(Loc, diag::err_typecheck_invalid_operands)
10553 << OrigLHS.getType() << OrigRHS.getType()
10554 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10555
10556 // If a user-defined conversion was applied to either of the operands prior
10557 // to applying the built-in operator rules, tell the user about it.
10558 if (OrigLHS.Conversion) {
10559 Diag(OrigLHS.Conversion->getLocation(),
10560 diag::note_typecheck_invalid_operands_converted)
10561 << 0 << LHS.get()->getType();
10562 }
10563 if (OrigRHS.Conversion) {
10564 Diag(OrigRHS.Conversion->getLocation(),
10565 diag::note_typecheck_invalid_operands_converted)
10566 << 1 << RHS.get()->getType();
10567 }
10568
10569 return QualType();
10570}
10571
10573 ExprResult &RHS) {
10574 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10575 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10576
10577 bool LHSNatVec = LHSType->isVectorType();
10578 bool RHSNatVec = RHSType->isVectorType();
10579
10580 if (!(LHSNatVec && RHSNatVec)) {
10581 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10582 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10583 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10584 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10585 << Vector->getSourceRange();
10586 return QualType();
10587 }
10588
10589 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10590 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10591 << RHS.get()->getSourceRange();
10592
10593 return QualType();
10594}
10595
10596/// Try to convert a value of non-vector type to a vector type by converting
10597/// the type to the element type of the vector and then performing a splat.
10598/// If the language is OpenCL, we only use conversions that promote scalar
10599/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10600/// for float->int.
10601///
10602/// OpenCL V2.0 6.2.6.p2:
10603/// An error shall occur if any scalar operand type has greater rank
10604/// than the type of the vector element.
10605///
10606/// \param scalar - if non-null, actually perform the conversions
10607/// \return true if the operation fails (but without diagnosing the failure)
10609 QualType scalarTy,
10610 QualType vectorEltTy,
10611 QualType vectorTy,
10612 unsigned &DiagID) {
10613 // The conversion to apply to the scalar before splatting it,
10614 // if necessary.
10615 CastKind scalarCast = CK_NoOp;
10616
10617 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10618 scalarCast = CK_IntegralToBoolean;
10619 } else if (vectorEltTy->isIntegralType(S.Context)) {
10620 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10621 (scalarTy->isIntegerType() &&
10622 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10623 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10624 return true;
10625 }
10626 if (!scalarTy->isIntegralType(S.Context))
10627 return true;
10628 scalarCast = CK_IntegralCast;
10629 } else if (vectorEltTy->isRealFloatingType()) {
10630 if (scalarTy->isRealFloatingType()) {
10631 if (S.getLangOpts().OpenCL &&
10632 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10633 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10634 return true;
10635 }
10636 scalarCast = CK_FloatingCast;
10637 }
10638 else if (scalarTy->isIntegralType(S.Context))
10639 scalarCast = CK_IntegralToFloating;
10640 else
10641 return true;
10642 } else {
10643 return true;
10644 }
10645
10646 // Adjust scalar if desired.
10647 if (scalar) {
10648 if (scalarCast != CK_NoOp)
10649 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10650 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10651 }
10652 return false;
10653}
10654
10655/// Convert vector E to a vector with the same number of elements but different
10656/// element type.
10657static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10658 const auto *VecTy = E->getType()->getAs<VectorType>();
10659 assert(VecTy && "Expression E must be a vector");
10660 QualType NewVecTy =
10661 VecTy->isExtVectorType()
10662 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10663 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10664 VecTy->getVectorKind());
10665
10666 // Look through the implicit cast. Return the subexpression if its type is
10667 // NewVecTy.
10668 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10669 if (ICE->getSubExpr()->getType() == NewVecTy)
10670 return ICE->getSubExpr();
10671
10672 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10673 return S.ImpCastExprToType(E, NewVecTy, Cast);
10674}
10675
10676/// Test if a (constant) integer Int can be casted to another integer type
10677/// IntTy without losing precision.
10679 QualType OtherIntTy) {
10680 Expr *E = Int->get();
10682 return false;
10683
10684 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10685
10686 // Reject cases where the value of the Int is unknown as that would
10687 // possibly cause truncation, but accept cases where the scalar can be
10688 // demoted without loss of precision.
10689 Expr::EvalResult EVResult;
10690 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10691 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10692 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10693 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10694
10695 if (CstInt) {
10696 // If the scalar is constant and is of a higher order and has more active
10697 // bits that the vector element type, reject it.
10698 llvm::APSInt Result = EVResult.Val.getInt();
10699 unsigned NumBits = IntSigned
10700 ? (Result.isNegative() ? Result.getSignificantBits()
10701 : Result.getActiveBits())
10702 : Result.getActiveBits();
10703 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10704 return true;
10705
10706 // If the signedness of the scalar type and the vector element type
10707 // differs and the number of bits is greater than that of the vector
10708 // element reject it.
10709 return (IntSigned != OtherIntSigned &&
10710 NumBits > S.Context.getIntWidth(OtherIntTy));
10711 }
10712
10713 // Reject cases where the value of the scalar is not constant and it's
10714 // order is greater than that of the vector element type.
10715 return (Order < 0);
10716}
10717
10718/// Test if a (constant) integer Int can be casted to floating point type
10719/// FloatTy without losing precision.
10721 QualType FloatTy) {
10722 if (Int->get()->containsErrors())
10723 return false;
10724
10725 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10726
10727 // Determine if the integer constant can be expressed as a floating point
10728 // number of the appropriate type.
10729 Expr::EvalResult EVResult;
10730 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10731
10732 uint64_t Bits = 0;
10733 if (CstInt) {
10734 // Reject constants that would be truncated if they were converted to
10735 // the floating point type. Test by simple to/from conversion.
10736 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10737 // could be avoided if there was a convertFromAPInt method
10738 // which could signal back if implicit truncation occurred.
10739 llvm::APSInt Result = EVResult.Val.getInt();
10740 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10741 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10742 llvm::APFloat::rmTowardZero);
10743 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10745 bool Ignored = false;
10746 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10747 &Ignored);
10748 if (Result != ConvertBack)
10749 return true;
10750 } else {
10751 // Reject types that cannot be fully encoded into the mantissa of
10752 // the float.
10753 Bits = S.Context.getTypeSize(IntTy);
10754 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10755 S.Context.getFloatTypeSemantics(FloatTy));
10756 if (Bits > FloatPrec)
10757 return true;
10758 }
10759
10760 return false;
10761}
10762
10763/// Attempt to convert and splat Scalar into a vector whose types matches
10764/// Vector following GCC conversion rules. The rule is that implicit
10765/// conversion can occur when Scalar can be casted to match Vector's element
10766/// type without causing truncation of Scalar.
10768 ExprResult *Vector) {
10769 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10770 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10771 QualType VectorEltTy;
10772
10773 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10774 assert(!isa<ExtVectorType>(VT) &&
10775 "ExtVectorTypes should not be handled here!");
10776 VectorEltTy = VT->getElementType();
10777 } else if (VectorTy->isSveVLSBuiltinType()) {
10778 VectorEltTy =
10779 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10780 } else {
10781 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10782 }
10783
10784 // Reject cases where the vector element type or the scalar element type are
10785 // not integral or floating point types.
10786 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10787 return true;
10788
10789 // The conversion to apply to the scalar before splatting it,
10790 // if necessary.
10791 CastKind ScalarCast = CK_NoOp;
10792
10793 // Accept cases where the vector elements are integers and the scalar is
10794 // an integer.
10795 // FIXME: Notionally if the scalar was a floating point value with a precise
10796 // integral representation, we could cast it to an appropriate integer
10797 // type and then perform the rest of the checks here. GCC will perform
10798 // this conversion in some cases as determined by the input language.
10799 // We should accept it on a language independent basis.
10800 if (VectorEltTy->isIntegralType(S.Context) &&
10801 ScalarTy->isIntegralType(S.Context) &&
10802 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10803
10804 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10805 return true;
10806
10807 ScalarCast = CK_IntegralCast;
10808 } else if (VectorEltTy->isIntegralType(S.Context) &&
10809 ScalarTy->isRealFloatingType()) {
10810 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10811 ScalarCast = CK_FloatingToIntegral;
10812 else
10813 return true;
10814 } else if (VectorEltTy->isRealFloatingType()) {
10815 if (ScalarTy->isRealFloatingType()) {
10816
10817 // Reject cases where the scalar type is not a constant and has a higher
10818 // Order than the vector element type.
10819 llvm::APFloat Result(0.0);
10820
10821 // Determine whether this is a constant scalar. In the event that the
10822 // value is dependent (and thus cannot be evaluated by the constant
10823 // evaluator), skip the evaluation. This will then diagnose once the
10824 // expression is instantiated.
10825 bool CstScalar = Scalar->get()->isValueDependent() ||
10826 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10827 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10828 if (!CstScalar && Order < 0)
10829 return true;
10830
10831 // If the scalar cannot be safely casted to the vector element type,
10832 // reject it.
10833 if (CstScalar) {
10834 bool Truncated = false;
10835 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10836 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10837 if (Truncated)
10838 return true;
10839 }
10840
10841 ScalarCast = CK_FloatingCast;
10842 } else if (ScalarTy->isIntegralType(S.Context)) {
10843 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10844 return true;
10845
10846 ScalarCast = CK_IntegralToFloating;
10847 } else
10848 return true;
10849 } else if (ScalarTy->isEnumeralType())
10850 return true;
10851
10852 // Adjust scalar if desired.
10853 if (ScalarCast != CK_NoOp)
10854 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10855 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10856 return false;
10857}
10858
10860 SourceLocation Loc, bool IsCompAssign,
10861 bool AllowBothBool,
10862 bool AllowBoolConversions,
10863 bool AllowBoolOperation,
10864 bool ReportInvalid) {
10865 if (!IsCompAssign) {
10867 if (LHS.isInvalid())
10868 return QualType();
10869 }
10871 if (RHS.isInvalid())
10872 return QualType();
10873
10874 // For conversion purposes, we ignore any qualifiers.
10875 // For example, "const float" and "float" are equivalent.
10876 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10877 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10878
10879 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10880 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10881 assert(LHSVecType || RHSVecType);
10882
10883 if (getLangOpts().HLSL)
10884 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10885 IsCompAssign);
10886
10887 // Any operation with MFloat8 type is only possible with C intrinsics
10888 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10889 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10890 return InvalidOperands(Loc, LHS, RHS);
10891
10892 // AltiVec-style "vector bool op vector bool" combinations are allowed
10893 // for some operators but not others.
10894 if (!AllowBothBool && LHSVecType &&
10895 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10896 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10897 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10898
10899 // This operation may not be performed on boolean vectors.
10900 if (!AllowBoolOperation &&
10901 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10902 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10903
10904 // If the vector types are identical, return.
10905 if (Context.hasSameType(LHSType, RHSType))
10906 return Context.getCommonSugaredType(LHSType, RHSType);
10907
10908 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10909 if (LHSVecType && RHSVecType &&
10910 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10911 if (isa<ExtVectorType>(LHSVecType)) {
10912 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10913 return LHSType;
10914 }
10915
10916 if (!IsCompAssign)
10917 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10918 return RHSType;
10919 }
10920
10921 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10922 // can be mixed, with the result being the non-bool type. The non-bool
10923 // operand must have integer element type.
10924 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10925 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10926 (Context.getTypeSize(LHSVecType->getElementType()) ==
10927 Context.getTypeSize(RHSVecType->getElementType()))) {
10928 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10929 LHSVecType->getElementType()->isIntegerType() &&
10930 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10931 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10932 return LHSType;
10933 }
10934 if (!IsCompAssign &&
10935 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10936 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10937 RHSVecType->getElementType()->isIntegerType()) {
10938 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10939 return RHSType;
10940 }
10941 }
10942
10943 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10944 // invalid since the ambiguity can affect the ABI.
10945 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10946 unsigned &SVEorRVV) {
10947 const VectorType *VecType = SecondType->getAs<VectorType>();
10948 SVEorRVV = 0;
10949 if (FirstType->isSizelessBuiltinType() && VecType) {
10952 return true;
10958 SVEorRVV = 1;
10959 return true;
10960 }
10961 }
10962
10963 return false;
10964 };
10965
10966 unsigned SVEorRVV;
10967 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10968 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10969 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10970 << SVEorRVV << LHSType << RHSType;
10971 return QualType();
10972 }
10973
10974 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10975 // invalid since the ambiguity can affect the ABI.
10976 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10977 unsigned &SVEorRVV) {
10978 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10979 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10980
10981 SVEorRVV = 0;
10982 if (FirstVecType && SecondVecType) {
10983 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10984 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10985 SecondVecType->getVectorKind() ==
10987 return true;
10988 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10989 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10990 SecondVecType->getVectorKind() ==
10992 SecondVecType->getVectorKind() ==
10994 SecondVecType->getVectorKind() ==
10996 SVEorRVV = 1;
10997 return true;
10998 }
10999 }
11000 return false;
11001 }
11002
11003 if (SecondVecType &&
11004 SecondVecType->getVectorKind() == VectorKind::Generic) {
11005 if (FirstType->isSVESizelessBuiltinType())
11006 return true;
11007 if (FirstType->isRVVSizelessBuiltinType()) {
11008 SVEorRVV = 1;
11009 return true;
11010 }
11011 }
11012
11013 return false;
11014 };
11015
11016 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
11017 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
11018 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
11019 << SVEorRVV << LHSType << RHSType;
11020 return QualType();
11021 }
11022
11023 // If there's a vector type and a scalar, try to convert the scalar to
11024 // the vector element type and splat.
11025 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
11026 if (!RHSVecType) {
11027 if (isa<ExtVectorType>(LHSVecType)) {
11028 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
11029 LHSVecType->getElementType(), LHSType,
11030 DiagID))
11031 return LHSType;
11032 } else {
11033 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11034 return LHSType;
11035 }
11036 }
11037 if (!LHSVecType) {
11038 if (isa<ExtVectorType>(RHSVecType)) {
11039 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
11040 LHSType, RHSVecType->getElementType(),
11041 RHSType, DiagID))
11042 return RHSType;
11043 } else {
11044 if (LHS.get()->isLValue() ||
11045 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11046 return RHSType;
11047 }
11048 }
11049
11050 // FIXME: The code below also handles conversion between vectors and
11051 // non-scalars, we should break this down into fine grained specific checks
11052 // and emit proper diagnostics.
11053 QualType VecType = LHSVecType ? LHSType : RHSType;
11054 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
11055 QualType OtherType = LHSVecType ? RHSType : LHSType;
11056 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
11057 if (isLaxVectorConversion(OtherType, VecType)) {
11058 if (Context.getTargetInfo().getTriple().isPPC() &&
11059 anyAltivecTypes(RHSType, LHSType) &&
11060 !Context.areCompatibleVectorTypes(RHSType, LHSType))
11061 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
11062 // If we're allowing lax vector conversions, only the total (data) size
11063 // needs to be the same. For non compound assignment, if one of the types is
11064 // scalar, the result is always the vector type.
11065 if (!IsCompAssign) {
11066 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
11067 return VecType;
11068 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11069 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11070 // type. Note that this is already done by non-compound assignments in
11071 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11072 // <1 x T> -> T. The result is also a vector type.
11073 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
11074 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
11075 ExprResult *RHSExpr = &RHS;
11076 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
11077 return VecType;
11078 }
11079 }
11080
11081 // Okay, the expression is invalid.
11082
11083 // If there's a non-vector, non-real operand, diagnose that.
11084 if ((!RHSVecType && !RHSType->isRealType()) ||
11085 (!LHSVecType && !LHSType->isRealType())) {
11086 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11087 << LHSType << RHSType
11088 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11089 return QualType();
11090 }
11091
11092 // OpenCL V1.1 6.2.6.p1:
11093 // If the operands are of more than one vector type, then an error shall
11094 // occur. Implicit conversions between vector types are not permitted, per
11095 // section 6.2.1.
11096 if (getLangOpts().OpenCL &&
11097 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
11098 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
11099 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
11100 << RHSType;
11101 return QualType();
11102 }
11103
11104
11105 // If there is a vector type that is not a ExtVector and a scalar, we reach
11106 // this point if scalar could not be converted to the vector's element type
11107 // without truncation.
11108 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
11109 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
11110 QualType Scalar = LHSVecType ? RHSType : LHSType;
11111 QualType Vector = LHSVecType ? LHSType : RHSType;
11112 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11113 Diag(Loc,
11114 diag::err_typecheck_vector_not_convertable_implict_truncation)
11115 << ScalarOrVector << Scalar << Vector;
11116
11117 return QualType();
11118 }
11119
11120 // Otherwise, use the generic diagnostic.
11121 Diag(Loc, DiagID)
11122 << LHSType << RHSType
11123 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11124 return QualType();
11125}
11126
11128 SourceLocation Loc,
11129 bool IsCompAssign,
11130 ArithConvKind OperationKind) {
11131 if (!IsCompAssign) {
11133 if (LHS.isInvalid())
11134 return QualType();
11135 }
11137 if (RHS.isInvalid())
11138 return QualType();
11139
11140 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11141 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11142
11143 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11144 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11145
11146 unsigned DiagID = diag::err_typecheck_invalid_operands;
11147 if ((OperationKind == ArithConvKind::Arithmetic) &&
11148 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11149 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11150 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11151 << RHS.get()->getSourceRange();
11152 return QualType();
11153 }
11154
11155 if (Context.hasSameType(LHSType, RHSType))
11156 return LHSType;
11157
11158 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11159 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11160 return LHSType;
11161 }
11162 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11163 if (LHS.get()->isLValue() ||
11164 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11165 return RHSType;
11166 }
11167
11168 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11169 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11170 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11171 << LHSType << RHSType << LHS.get()->getSourceRange()
11172 << RHS.get()->getSourceRange();
11173 return QualType();
11174 }
11175
11176 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11177 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11178 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11179 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11180 << LHSType << RHSType << LHS.get()->getSourceRange()
11181 << RHS.get()->getSourceRange();
11182 return QualType();
11183 }
11184
11185 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11186 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11187 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11188 bool ScalarOrVector =
11189 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11190
11191 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11192 << ScalarOrVector << Scalar << Vector;
11193
11194 return QualType();
11195 }
11196
11197 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11198 << RHS.get()->getSourceRange();
11199 return QualType();
11200}
11201
11202// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11203// expression. These are mainly cases where the null pointer is used as an
11204// integer instead of a pointer.
11206 SourceLocation Loc, bool IsCompare) {
11207 // The canonical way to check for a GNU null is with isNullPointerConstant,
11208 // but we use a bit of a hack here for speed; this is a relatively
11209 // hot path, and isNullPointerConstant is slow.
11210 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11211 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11212
11213 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11214
11215 // Avoid analyzing cases where the result will either be invalid (and
11216 // diagnosed as such) or entirely valid and not something to warn about.
11217 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11218 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11219 return;
11220
11221 // Comparison operations would not make sense with a null pointer no matter
11222 // what the other expression is.
11223 if (!IsCompare) {
11224 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11225 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11226 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11227 return;
11228 }
11229
11230 // The rest of the operations only make sense with a null pointer
11231 // if the other expression is a pointer.
11232 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11233 NonNullType->canDecayToPointerType())
11234 return;
11235
11236 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11237 << LHSNull /* LHS is NULL */ << NonNullType
11238 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11239}
11240
11242 SourceLocation OpLoc) {
11243 // If the divisor is real, then this is real/real or complex/real division.
11244 // Either way there can be no precision loss.
11245 auto *CT = DivisorTy->getAs<ComplexType>();
11246 if (!CT)
11247 return;
11248
11249 QualType ElementType = CT->getElementType().getCanonicalType();
11250 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11252 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11253 return;
11254
11255 ASTContext &Ctx = S.getASTContext();
11256 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11257 const llvm::fltSemantics &ElementTypeSemantics =
11258 Ctx.getFloatTypeSemantics(ElementType);
11259 const llvm::fltSemantics &HigherElementTypeSemantics =
11260 Ctx.getFloatTypeSemantics(HigherElementType);
11261
11262 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11263 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11264 (HigherElementType == Ctx.LongDoubleTy &&
11265 !Ctx.getTargetInfo().hasLongDoubleType())) {
11266 // Retain the location of the first use of higher precision type.
11269 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11270 if (Type == HigherElementType) {
11271 Num++;
11272 return;
11273 }
11274 }
11275 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
11276 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
11277 }
11278}
11279
11281 SourceLocation Loc) {
11282 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11283 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11284 if (!LUE || !RUE)
11285 return;
11286 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11287 RUE->getKind() != UETT_SizeOf)
11288 return;
11289
11290 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11291 QualType LHSTy = LHSArg->getType();
11292 QualType RHSTy;
11293
11294 if (RUE->isArgumentType())
11295 RHSTy = RUE->getArgumentType().getNonReferenceType();
11296 else
11297 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11298
11299 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11300 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11301 return;
11302
11303 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11304 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11305 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11306 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11307 << LHSArgDecl;
11308 }
11309 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11310 QualType ArrayElemTy = ArrayTy->getElementType();
11311 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11312 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11313 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11314 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11315 return;
11316 S.Diag(Loc, diag::warn_division_sizeof_array)
11317 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11318 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11319 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11320 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11321 << LHSArgDecl;
11322 }
11323
11324 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11325 }
11326}
11327
11329 ExprResult &RHS,
11330 SourceLocation Loc, bool IsDiv) {
11331 // Check for division/remainder by zero.
11332 Expr::EvalResult RHSValue;
11333 if (!RHS.get()->isValueDependent() &&
11334 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11335 RHSValue.Val.getInt() == 0)
11336 S.DiagRuntimeBehavior(Loc, RHS.get(),
11337 S.PDiag(diag::warn_remainder_division_by_zero)
11338 << IsDiv << RHS.get()->getSourceRange());
11339}
11340
11341static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11342 const ExprResult &LHS, const ExprResult &RHS,
11343 BinaryOperatorKind Opc) {
11344 if (!LHS.isUsable() || !RHS.isUsable())
11345 return;
11346 const Expr *LHSExpr = LHS.get();
11347 const Expr *RHSExpr = RHS.get();
11348 const QualType LHSType = LHSExpr->getType();
11349 const QualType RHSType = RHSExpr->getType();
11350 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11351 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11352 if (!LHSIsScoped && !RHSIsScoped)
11353 return;
11354 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11355 return;
11356 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11357 return;
11358 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11359 return;
11360 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11361 SourceLocation BeginLoc = expr->getBeginLoc();
11362 QualType IntType = type->castAs<EnumType>()
11363 ->getDecl()
11364 ->getDefinitionOrSelf()
11365 ->getIntegerType();
11366 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11367 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
11368 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
11369 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
11370 };
11371 if (LHSIsScoped) {
11372 DiagnosticHelper(LHSExpr, LHSType);
11373 }
11374 if (RHSIsScoped) {
11375 DiagnosticHelper(RHSExpr, RHSType);
11376 }
11377}
11378
11380 SourceLocation Loc,
11381 BinaryOperatorKind Opc) {
11382 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11383 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11384
11385 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11386
11387 QualType LHSTy = LHS.get()->getType();
11388 QualType RHSTy = RHS.get()->getType();
11389 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11390 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11391 /*AllowBothBool*/ getLangOpts().AltiVec,
11392 /*AllowBoolConversions*/ false,
11393 /*AllowBooleanOperation*/ false,
11394 /*ReportInvalid*/ true);
11395 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11396 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11398 if (!IsDiv &&
11399 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11400 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11401 // For division, only matrix-by-scalar is supported. Other combinations with
11402 // matrix types are invalid.
11403 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11404 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11405
11407 LHS, RHS, Loc,
11409 if (LHS.isInvalid() || RHS.isInvalid())
11410 return QualType();
11411
11412 if (compType.isNull() || !compType->isArithmeticType()) {
11413 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11414 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11415 return ResultTy;
11416 }
11417 if (IsDiv) {
11418 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
11419 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11420 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11421 }
11422 return compType;
11423}
11424
11426 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11427 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11428
11429 // Note: This check is here to simplify the double exclusions of
11430 // scalar and vector HLSL checks. No getLangOpts().HLSL
11431 // is needed since all languages exlcude doubles.
11432 if (LHS.get()->getType()->isDoubleType() ||
11433 RHS.get()->getType()->isDoubleType() ||
11434 (LHS.get()->getType()->isVectorType() && LHS.get()
11435 ->getType()
11436 ->getAs<VectorType>()
11437 ->getElementType()
11438 ->isDoubleType()) ||
11439 (RHS.get()->getType()->isVectorType() && RHS.get()
11440 ->getType()
11441 ->getAs<VectorType>()
11442 ->getElementType()
11443 ->isDoubleType()))
11444 return InvalidOperands(Loc, LHS, RHS);
11445
11446 if (LHS.get()->getType()->isVectorType() ||
11447 RHS.get()->getType()->isVectorType()) {
11448 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11449 RHS.get()->getType()->hasIntegerRepresentation()) ||
11450 (getLangOpts().HLSL &&
11451 (LHS.get()->getType()->hasFloatingRepresentation() ||
11453 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11454 /*AllowBothBool*/ getLangOpts().AltiVec,
11455 /*AllowBoolConversions*/ false,
11456 /*AllowBooleanOperation*/ false,
11457 /*ReportInvalid*/ true);
11458 return InvalidOperands(Loc, LHS, RHS);
11459 }
11460
11461 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11462 RHS.get()->getType()->isSveVLSBuiltinType()) {
11463 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11465 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11467
11468 return InvalidOperands(Loc, LHS, RHS);
11469 }
11470
11472 LHS, RHS, Loc,
11474 if (LHS.isInvalid() || RHS.isInvalid())
11475 return QualType();
11476
11477 if (compType.isNull() ||
11478 (!compType->isIntegerType() &&
11479 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11480 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11481 diagnoseScopedEnums(*this, Loc, LHS, RHS,
11482 IsCompAssign ? BO_RemAssign : BO_Rem);
11483 return ResultTy;
11484 }
11485 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11486 return compType;
11487}
11488
11489/// Diagnose invalid arithmetic on two void pointers.
11491 Expr *LHSExpr, Expr *RHSExpr) {
11492 S.Diag(Loc, S.getLangOpts().CPlusPlus
11493 ? diag::err_typecheck_pointer_arith_void_type
11494 : diag::ext_gnu_void_ptr)
11495 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11496 << RHSExpr->getSourceRange();
11497}
11498
11499/// Diagnose invalid arithmetic on a void pointer.
11501 Expr *Pointer) {
11502 S.Diag(Loc, S.getLangOpts().CPlusPlus
11503 ? diag::err_typecheck_pointer_arith_void_type
11504 : diag::ext_gnu_void_ptr)
11505 << 0 /* one pointer */ << Pointer->getSourceRange();
11506}
11507
11508/// Diagnose invalid arithmetic on a null pointer.
11509///
11510/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11511/// idiom, which we recognize as a GNU extension.
11512///
11514 Expr *Pointer, bool IsGNUIdiom) {
11515 if (IsGNUIdiom)
11516 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11517 << Pointer->getSourceRange();
11518 else
11519 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11520 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11521}
11522
11523/// Diagnose invalid subraction on a null pointer.
11524///
11526 Expr *Pointer, bool BothNull) {
11527 // Null - null is valid in C++ [expr.add]p7
11528 if (BothNull && S.getLangOpts().CPlusPlus)
11529 return;
11530
11531 // Is this s a macro from a system header?
11533 return;
11534
11536 S.PDiag(diag::warn_pointer_sub_null_ptr)
11537 << S.getLangOpts().CPlusPlus
11538 << Pointer->getSourceRange());
11539}
11540
11541/// Diagnose invalid arithmetic on two function pointers.
11543 Expr *LHS, Expr *RHS) {
11544 assert(LHS->getType()->isAnyPointerType());
11545 assert(RHS->getType()->isAnyPointerType());
11546 S.Diag(Loc, S.getLangOpts().CPlusPlus
11547 ? diag::err_typecheck_pointer_arith_function_type
11548 : diag::ext_gnu_ptr_func_arith)
11549 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11550 // We only show the second type if it differs from the first.
11552 RHS->getType())
11553 << RHS->getType()->getPointeeType()
11554 << LHS->getSourceRange() << RHS->getSourceRange();
11555}
11556
11557/// Diagnose invalid arithmetic on a function pointer.
11559 Expr *Pointer) {
11560 assert(Pointer->getType()->isAnyPointerType());
11561 S.Diag(Loc, S.getLangOpts().CPlusPlus
11562 ? diag::err_typecheck_pointer_arith_function_type
11563 : diag::ext_gnu_ptr_func_arith)
11564 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11565 << 0 /* one pointer, so only one type */
11566 << Pointer->getSourceRange();
11567}
11568
11569/// Emit error if Operand is incomplete pointer type
11570///
11571/// \returns True if pointer has incomplete type
11573 Expr *Operand) {
11574 QualType ResType = Operand->getType();
11575 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11576 ResType = ResAtomicType->getValueType();
11577
11578 assert(ResType->isAnyPointerType());
11579 QualType PointeeTy = ResType->getPointeeType();
11580 return S.RequireCompleteSizedType(
11581 Loc, PointeeTy,
11582 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11583 Operand->getSourceRange());
11584}
11585
11586/// Check the validity of an arithmetic pointer operand.
11587///
11588/// If the operand has pointer type, this code will check for pointer types
11589/// which are invalid in arithmetic operations. These will be diagnosed
11590/// appropriately, including whether or not the use is supported as an
11591/// extension.
11592///
11593/// \returns True when the operand is valid to use (even if as an extension).
11595 Expr *Operand) {
11596 QualType ResType = Operand->getType();
11597 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11598 ResType = ResAtomicType->getValueType();
11599
11600 if (!ResType->isAnyPointerType()) return true;
11601
11602 QualType PointeeTy = ResType->getPointeeType();
11603 if (PointeeTy->isVoidType()) {
11604 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11605 return !S.getLangOpts().CPlusPlus;
11606 }
11607 if (PointeeTy->isFunctionType()) {
11608 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11609 return !S.getLangOpts().CPlusPlus;
11610 }
11611
11612 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11613
11614 return true;
11615}
11616
11617/// Check the validity of a binary arithmetic operation w.r.t. pointer
11618/// operands.
11619///
11620/// This routine will diagnose any invalid arithmetic on pointer operands much
11621/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11622/// for emitting a single diagnostic even for operations where both LHS and RHS
11623/// are (potentially problematic) pointers.
11624///
11625/// \returns True when the operand is valid to use (even if as an extension).
11627 Expr *LHSExpr, Expr *RHSExpr) {
11628 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11629 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11630 if (!isLHSPointer && !isRHSPointer) return true;
11631
11632 QualType LHSPointeeTy, RHSPointeeTy;
11633 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11634 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11635
11636 // if both are pointers check if operation is valid wrt address spaces
11637 if (isLHSPointer && isRHSPointer) {
11638 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11639 S.getASTContext())) {
11640 S.Diag(Loc,
11641 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11642 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11643 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11644 return false;
11645 }
11646 }
11647
11648 // Check for arithmetic on pointers to incomplete types.
11649 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11650 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11651 if (isLHSVoidPtr || isRHSVoidPtr) {
11652 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11653 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11654 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11655
11656 return !S.getLangOpts().CPlusPlus;
11657 }
11658
11659 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11660 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11661 if (isLHSFuncPtr || isRHSFuncPtr) {
11662 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11663 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11664 RHSExpr);
11665 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11666
11667 return !S.getLangOpts().CPlusPlus;
11668 }
11669
11670 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11671 return false;
11672 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11673 return false;
11674
11675 return true;
11676}
11677
11678/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11679/// literal.
11681 Expr *LHSExpr, Expr *RHSExpr) {
11682 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11683 Expr* IndexExpr = RHSExpr;
11684 if (!StrExpr) {
11685 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11686 IndexExpr = LHSExpr;
11687 }
11688
11689 bool IsStringPlusInt = StrExpr &&
11691 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11692 return;
11693
11694 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11695 Self.Diag(OpLoc, diag::warn_string_plus_int)
11696 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11697
11698 // Only print a fixit for "str" + int, not for int + "str".
11699 if (IndexExpr == RHSExpr) {
11700 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11701 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11702 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11704 << FixItHint::CreateInsertion(EndLoc, "]");
11705 } else
11706 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11707}
11708
11709/// Emit a warning when adding a char literal to a string.
11711 Expr *LHSExpr, Expr *RHSExpr) {
11712 const Expr *StringRefExpr = LHSExpr;
11713 const CharacterLiteral *CharExpr =
11714 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11715
11716 if (!CharExpr) {
11717 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11718 StringRefExpr = RHSExpr;
11719 }
11720
11721 if (!CharExpr || !StringRefExpr)
11722 return;
11723
11724 const QualType StringType = StringRefExpr->getType();
11725
11726 // Return if not a PointerType.
11727 if (!StringType->isAnyPointerType())
11728 return;
11729
11730 // Return if not a CharacterType.
11731 if (!StringType->getPointeeType()->isAnyCharacterType())
11732 return;
11733
11734 ASTContext &Ctx = Self.getASTContext();
11735 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11736
11737 const QualType CharType = CharExpr->getType();
11738 if (!CharType->isAnyCharacterType() &&
11739 CharType->isIntegerType() &&
11740 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11741 Self.Diag(OpLoc, diag::warn_string_plus_char)
11742 << DiagRange << Ctx.CharTy;
11743 } else {
11744 Self.Diag(OpLoc, diag::warn_string_plus_char)
11745 << DiagRange << CharExpr->getType();
11746 }
11747
11748 // Only print a fixit for str + char, not for char + str.
11749 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11750 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11751 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11752 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11754 << FixItHint::CreateInsertion(EndLoc, "]");
11755 } else {
11756 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11757 }
11758}
11759
11760/// Emit error when two pointers are incompatible.
11762 Expr *LHSExpr, Expr *RHSExpr) {
11763 assert(LHSExpr->getType()->isAnyPointerType());
11764 assert(RHSExpr->getType()->isAnyPointerType());
11765 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11766 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11767 << RHSExpr->getSourceRange();
11768}
11769
11770// C99 6.5.6
11773 QualType* CompLHSTy) {
11774 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11775
11776 if (LHS.get()->getType()->isVectorType() ||
11777 RHS.get()->getType()->isVectorType()) {
11778 QualType compType =
11779 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11780 /*AllowBothBool*/ getLangOpts().AltiVec,
11781 /*AllowBoolConversions*/ getLangOpts().ZVector,
11782 /*AllowBooleanOperation*/ false,
11783 /*ReportInvalid*/ true);
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 /*ReportInvalid*/ true);
11931 if (CompLHSTy) *CompLHSTy = compType;
11932 return compType;
11933 }
11934
11935 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11936 RHS.get()->getType()->isSveVLSBuiltinType()) {
11937 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11939 if (CompLHSTy)
11940 *CompLHSTy = compType;
11941 return compType;
11942 }
11943
11944 if (LHS.get()->getType()->isConstantMatrixType() ||
11945 RHS.get()->getType()->isConstantMatrixType()) {
11946 QualType compType =
11947 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11948 if (CompLHSTy)
11949 *CompLHSTy = compType;
11950 return compType;
11951 }
11952
11954 LHS, RHS, Loc,
11956 if (LHS.isInvalid() || RHS.isInvalid())
11957 return QualType();
11958
11959 // Enforce type constraints: C99 6.5.6p3.
11960
11961 // Handle the common case first (both operands are arithmetic).
11962 if (!compType.isNull() && compType->isArithmeticType()) {
11963 if (CompLHSTy) *CompLHSTy = compType;
11964 return compType;
11965 }
11966
11967 // Either ptr - int or ptr - ptr.
11968 if (LHS.get()->getType()->isAnyPointerType()) {
11969 QualType lpointee = LHS.get()->getType()->getPointeeType();
11970
11971 // Diagnose bad cases where we step over interface counts.
11972 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11973 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11974 return QualType();
11975
11976 // Arithmetic on label addresses is normally allowed, except when we add
11977 // a ptrauth signature to the addresses.
11978 if (isa<AddrLabelExpr>(LHS.get()) &&
11979 getLangOpts().PointerAuthIndirectGotos) {
11980 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11981 << /*subtraction*/ 0;
11982 return QualType();
11983 }
11984
11985 // The result type of a pointer-int computation is the pointer type.
11986 if (RHS.get()->getType()->isIntegerType()) {
11987 // Subtracting from a null pointer should produce a warning.
11988 // The last argument to the diagnose call says this doesn't match the
11989 // GNU int-to-pointer idiom.
11992 // In C++ adding zero to a null pointer is defined.
11993 Expr::EvalResult KnownVal;
11994 if (!getLangOpts().CPlusPlus ||
11995 (!RHS.get()->isValueDependent() &&
11996 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11997 KnownVal.Val.getInt() != 0))) {
11998 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11999 }
12000 }
12001
12002 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
12003 return QualType();
12004
12005 // Check array bounds for pointer arithemtic
12006 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
12007 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
12008
12009 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12010 return LHS.get()->getType();
12011 }
12012
12013 // Handle pointer-pointer subtractions.
12014 if (const PointerType *RHSPTy
12015 = RHS.get()->getType()->getAs<PointerType>()) {
12016 QualType rpointee = RHSPTy->getPointeeType();
12017
12018 if (getLangOpts().CPlusPlus) {
12019 // Pointee types must be the same: C++ [expr.add]
12020 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
12021 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
12022 }
12023 } else {
12024 // Pointee types must be compatible C99 6.5.6p3
12025 if (!Context.typesAreCompatible(
12026 Context.getCanonicalType(lpointee).getUnqualifiedType(),
12027 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
12028 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
12029 return QualType();
12030 }
12031 }
12032
12034 LHS.get(), RHS.get()))
12035 return QualType();
12036
12037 // For pointer subtraction, if the address spaces differ but overlap,
12038 // convert both pointers to the composite (superset) address space.
12039 // This is needed because address spaces may use different
12040 // representations, such as a private offset vs a flat address.
12041 LangAS LAddrSpace = lpointee.getAddressSpace();
12042 LangAS RAddrSpace = rpointee.getAddressSpace();
12043 if (LAddrSpace != RAddrSpace) {
12044 Qualifiers LQual = lpointee.getQualifiers();
12045 Qualifiers RQual = rpointee.getQualifiers();
12046 LangAS ResultAddrSpace = LQual.isAddressSpaceSupersetOf(RQual, Context)
12047 ? LAddrSpace
12048 : RAddrSpace;
12049
12050 if (LAddrSpace != ResultAddrSpace) {
12051 QualType NewPteTy = Context.getAddrSpaceQualType(
12052 lpointee.getUnqualifiedType(), ResultAddrSpace);
12053 QualType NewPtrTy = Context.getPointerType(NewPteTy);
12054 LHS =
12055 ImpCastExprToType(LHS.get(), NewPtrTy, CK_AddressSpaceConversion);
12056 }
12057 if (RAddrSpace != ResultAddrSpace) {
12058 QualType NewPteTy = Context.getAddrSpaceQualType(
12059 rpointee.getUnqualifiedType(), ResultAddrSpace);
12060 QualType NewPtrTy = Context.getPointerType(NewPteTy);
12061 RHS =
12062 ImpCastExprToType(RHS.get(), NewPtrTy, CK_AddressSpaceConversion);
12063 }
12064 }
12065
12066 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12068 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12070
12071 // Subtracting nullptr or from nullptr is suspect
12072 if (LHSIsNullPtr)
12073 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
12074 if (RHSIsNullPtr)
12075 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
12076
12077 // The pointee type may have zero size. As an extension, a structure or
12078 // union may have zero size or an array may have zero length. In this
12079 // case subtraction does not make sense. For a variably modified type,
12080 // warn only when the size is provably zero.
12081 if (!rpointee->isVoidType() && !rpointee->isFunctionType() &&
12082 isProvablyZeroSize(Context, rpointee))
12083 Diag(Loc, diag::warn_sub_ptr_zero_size_types)
12084 << rpointee.getUnqualifiedType() << LHS.get()->getSourceRange()
12085 << RHS.get()->getSourceRange();
12086
12087 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12088 return Context.getPointerDiffType();
12089 }
12090 }
12091
12092 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12093 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12094 return ResultTy;
12095}
12096
12098 if (const EnumType *ET = T->getAsCanonical<EnumType>())
12099 return ET->getDecl()->isScoped();
12100 return false;
12101}
12102
12105 QualType LHSType) {
12106 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
12107 // so skip remaining warnings as we don't want to modify values within Sema.
12108 if (S.getLangOpts().OpenCL)
12109 return;
12110
12111 if (Opc == BO_Shr &&
12113 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
12114
12115 // Check right/shifter operand
12116 Expr::EvalResult RHSResult;
12117 if (RHS.get()->isValueDependent() ||
12118 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
12119 return;
12120 llvm::APSInt Right = RHSResult.Val.getInt();
12121
12122 if (Right.isNegative()) {
12123 S.DiagRuntimeBehavior(Loc, RHS.get(),
12124 S.PDiag(diag::warn_shift_negative)
12125 << RHS.get()->getSourceRange());
12126 return;
12127 }
12128
12129 QualType LHSExprType = LHS.get()->getType();
12130 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
12131 if (LHSExprType->isBitIntType())
12132 LeftSize = S.Context.getIntWidth(LHSExprType);
12133 else if (LHSExprType->isFixedPointType()) {
12134 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
12135 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
12136 }
12137 if (Right.uge(LeftSize)) {
12138 S.DiagRuntimeBehavior(Loc, RHS.get(),
12139 S.PDiag(diag::warn_shift_gt_typewidth)
12140 << RHS.get()->getSourceRange());
12141 return;
12142 }
12143
12144 // FIXME: We probably need to handle fixed point types specially here.
12145 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12146 return;
12147
12148 // When left shifting an ICE which is signed, we can check for overflow which
12149 // according to C++ standards prior to C++2a has undefined behavior
12150 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12151 // more than the maximum value representable in the result type, so never
12152 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12153 // expression is still probably a bug.)
12154 Expr::EvalResult LHSResult;
12155 if (LHS.get()->isValueDependent() ||
12157 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
12158 return;
12159 llvm::APSInt Left = LHSResult.Val.getInt();
12160
12161 // Don't warn if signed overflow is defined, then all the rest of the
12162 // diagnostics will not be triggered because the behavior is defined.
12163 // Also don't warn in C++20 mode (and newer), as signed left shifts
12164 // always wrap and never overflow.
12165 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12166 return;
12167
12168 // If LHS does not have a non-negative value then, the
12169 // behavior is undefined before C++2a. Warn about it.
12170 if (Left.isNegative()) {
12171 S.DiagRuntimeBehavior(Loc, LHS.get(),
12172 S.PDiag(diag::warn_shift_lhs_negative)
12173 << LHS.get()->getSourceRange());
12174 return;
12175 }
12176
12177 llvm::APInt ResultBits =
12178 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12179 if (ResultBits.ule(LeftSize))
12180 return;
12181 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
12182 Result = Result.shl(Right);
12183
12184 // Print the bit representation of the signed integer as an unsigned
12185 // hexadecimal number.
12186 SmallString<40> HexResult;
12187 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
12188
12189 // If we are only missing a sign bit, this is less likely to result in actual
12190 // bugs -- if the result is cast back to an unsigned type, it will have the
12191 // expected value. Thus we place this behind a different warning that can be
12192 // turned off separately if needed.
12193 if (ResultBits - 1 == LeftSize) {
12194 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
12195 << HexResult << LHSType
12196 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12197 return;
12198 }
12199
12200 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
12201 << HexResult.str() << Result.getSignificantBits() << LHSType
12202 << Left.getBitWidth() << LHS.get()->getSourceRange()
12203 << RHS.get()->getSourceRange();
12204}
12205
12206/// Return the resulting type when a vector is shifted
12207/// by a scalar or vector shift amount.
12209 SourceLocation Loc, bool IsCompAssign) {
12210 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12211 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12212 !LHS.get()->getType()->isVectorType()) {
12213 S.Diag(Loc, diag::err_shift_rhs_only_vector)
12214 << RHS.get()->getType() << LHS.get()->getType()
12215 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12216 return QualType();
12217 }
12218
12219 if (!IsCompAssign) {
12220 LHS = S.UsualUnaryConversions(LHS.get());
12221 if (LHS.isInvalid()) return QualType();
12222 }
12223
12224 RHS = S.UsualUnaryConversions(RHS.get());
12225 if (RHS.isInvalid()) return QualType();
12226
12227 QualType LHSType = LHS.get()->getType();
12228 // Note that LHS might be a scalar because the routine calls not only in
12229 // OpenCL case.
12230 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12231 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12232
12233 // Note that RHS might not be a vector.
12234 QualType RHSType = RHS.get()->getType();
12235 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12236 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12237
12238 // Do not allow shifts for boolean vectors.
12239 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12240 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12241 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12242 << LHS.get()->getType() << RHS.get()->getType()
12243 << LHS.get()->getSourceRange();
12244 return QualType();
12245 }
12246
12247 // The operands need to be integers.
12248 if (!LHSEleType->isIntegerType()) {
12249 S.Diag(Loc, diag::err_typecheck_expect_int)
12250 << LHS.get()->getType() << LHS.get()->getSourceRange();
12251 return QualType();
12252 }
12253
12254 if (!RHSEleType->isIntegerType()) {
12255 S.Diag(Loc, diag::err_typecheck_expect_int)
12256 << RHS.get()->getType() << RHS.get()->getSourceRange();
12257 return QualType();
12258 }
12259
12260 if (!LHSVecTy) {
12261 assert(RHSVecTy);
12262 if (IsCompAssign)
12263 return RHSType;
12264 if (LHSEleType != RHSEleType) {
12265 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
12266 LHSEleType = RHSEleType;
12267 }
12268 QualType VecTy =
12269 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
12270 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
12271 LHSType = VecTy;
12272 } else if (RHSVecTy) {
12273 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12274 // are applied component-wise. So if RHS is a vector, then ensure
12275 // that the number of elements is the same as LHS...
12276 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12277 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12278 << LHS.get()->getType() << RHS.get()->getType()
12279 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12280 return QualType();
12281 }
12282 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12283 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12284 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12285 if (LHSBT != RHSBT &&
12286 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12287 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12288 << LHS.get()->getType() << RHS.get()->getType()
12289 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12290 }
12291 }
12292 } else {
12293 // ...else expand RHS to match the number of elements in LHS.
12294 QualType VecTy =
12295 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12296 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12297 }
12298
12299 return LHSType;
12300}
12301
12303 ExprResult &RHS, SourceLocation Loc,
12304 bool IsCompAssign) {
12305 if (!IsCompAssign) {
12306 LHS = S.UsualUnaryConversions(LHS.get());
12307 if (LHS.isInvalid())
12308 return QualType();
12309 }
12310
12311 RHS = S.UsualUnaryConversions(RHS.get());
12312 if (RHS.isInvalid())
12313 return QualType();
12314
12315 QualType LHSType = LHS.get()->getType();
12316 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12317 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12318 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12319 : LHSType;
12320
12321 // Note that RHS might not be a vector
12322 QualType RHSType = RHS.get()->getType();
12323 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12324 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12325 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12326 : RHSType;
12327
12328 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12329 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12330 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12331 << LHSType << RHSType << LHS.get()->getSourceRange();
12332 return QualType();
12333 }
12334
12335 if (!LHSEleType->isIntegerType()) {
12336 S.Diag(Loc, diag::err_typecheck_expect_int)
12337 << LHS.get()->getType() << LHS.get()->getSourceRange();
12338 return QualType();
12339 }
12340
12341 if (!RHSEleType->isIntegerType()) {
12342 S.Diag(Loc, diag::err_typecheck_expect_int)
12343 << RHS.get()->getType() << RHS.get()->getSourceRange();
12344 return QualType();
12345 }
12346
12347 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12348 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12349 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12350 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12351 << LHSType << RHSType << LHS.get()->getSourceRange()
12352 << RHS.get()->getSourceRange();
12353 return QualType();
12354 }
12355
12356 if (!LHSType->isSveVLSBuiltinType()) {
12357 assert(RHSType->isSveVLSBuiltinType());
12358 if (IsCompAssign)
12359 return RHSType;
12360 if (LHSEleType != RHSEleType) {
12361 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12362 LHSEleType = RHSEleType;
12363 }
12364 const llvm::ElementCount VecSize =
12365 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12366 QualType VecTy =
12367 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12368 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12369 LHSType = VecTy;
12370 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12371 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12372 S.Context.getTypeSize(LHSBuiltinTy)) {
12373 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12374 << LHSType << RHSType << LHS.get()->getSourceRange()
12375 << RHS.get()->getSourceRange();
12376 return QualType();
12377 }
12378 } else {
12379 const llvm::ElementCount VecSize =
12380 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12381 if (LHSEleType != RHSEleType) {
12382 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12383 RHSEleType = LHSEleType;
12384 }
12385 QualType VecTy =
12386 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12387 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12388 }
12389
12390 return LHSType;
12391}
12392
12393// C99 6.5.7
12396 bool IsCompAssign) {
12397 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12398
12399 // Vector shifts promote their scalar inputs to vector type.
12400 if (LHS.get()->getType()->isVectorType() ||
12401 RHS.get()->getType()->isVectorType()) {
12402 if (LangOpts.ZVector) {
12403 // The shift operators for the z vector extensions work basically
12404 // like general shifts, except that neither the LHS nor the RHS is
12405 // allowed to be a "vector bool".
12406 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12407 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12408 return InvalidOperands(Loc, LHS, RHS);
12409 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12410 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12411 return InvalidOperands(Loc, LHS, RHS);
12412 }
12413 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12414 }
12415
12416 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12417 RHS.get()->getType()->isSveVLSBuiltinType())
12418 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12419
12420 // Shifts don't perform usual arithmetic conversions, they just do integer
12421 // promotions on each operand. C99 6.5.7p3
12422
12423 // For the LHS, do usual unary conversions, but then reset them away
12424 // if this is a compound assignment.
12425 ExprResult OldLHS = LHS;
12426 LHS = UsualUnaryConversions(LHS.get());
12427 if (LHS.isInvalid())
12428 return QualType();
12429 QualType LHSType = LHS.get()->getType();
12430 if (IsCompAssign) LHS = OldLHS;
12431
12432 // The RHS is simpler.
12433 RHS = UsualUnaryConversions(RHS.get());
12434 if (RHS.isInvalid())
12435 return QualType();
12436 QualType RHSType = RHS.get()->getType();
12437
12438 // C99 6.5.7p2: Each of the operands shall have integer type.
12439 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12440 if ((!LHSType->isFixedPointOrIntegerType() &&
12441 !LHSType->hasIntegerRepresentation()) ||
12442 !RHSType->hasIntegerRepresentation()) {
12443 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12444 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12445 return ResultTy;
12446 }
12447
12448 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12449
12450 // "The type of the result is that of the promoted left operand."
12451 return LHSType;
12452}
12453
12454/// Diagnose bad pointer comparisons.
12456 ExprResult &LHS, ExprResult &RHS,
12457 bool IsError) {
12458 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12459 : diag::ext_typecheck_comparison_of_distinct_pointers)
12460 << LHS.get()->getType() << RHS.get()->getType()
12461 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12462}
12463
12464/// Returns false if the pointers are converted to a composite type,
12465/// true otherwise.
12467 ExprResult &LHS, ExprResult &RHS) {
12468 // C++ [expr.rel]p2:
12469 // [...] Pointer conversions (4.10) and qualification
12470 // conversions (4.4) are performed on pointer operands (or on
12471 // a pointer operand and a null pointer constant) to bring
12472 // them to their composite pointer type. [...]
12473 //
12474 // C++ [expr.eq]p1 uses the same notion for (in)equality
12475 // comparisons of pointers.
12476
12477 QualType LHSType = LHS.get()->getType();
12478 QualType RHSType = RHS.get()->getType();
12479 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12480 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12481
12482 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12483 if (T.isNull()) {
12484 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12485 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12486 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12487 else
12488 S.InvalidOperands(Loc, LHS, RHS);
12489 return true;
12490 }
12491
12492 return false;
12493}
12494
12496 ExprResult &LHS,
12497 ExprResult &RHS,
12498 bool IsError) {
12499 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12500 : diag::ext_typecheck_comparison_of_fptr_to_void)
12501 << LHS.get()->getType() << RHS.get()->getType()
12502 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12503}
12504
12506 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12507 case Stmt::ObjCArrayLiteralClass:
12508 case Stmt::ObjCDictionaryLiteralClass:
12509 case Stmt::ObjCStringLiteralClass:
12510 case Stmt::ObjCBoxedExprClass:
12511 return true;
12512 default:
12513 // Note that ObjCBoolLiteral is NOT an object literal!
12514 return false;
12515 }
12516}
12517
12518static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12521
12522 // If this is not actually an Objective-C object, bail out.
12523 if (!Type)
12524 return false;
12525
12526 // Get the LHS object's interface type.
12527 QualType InterfaceType = Type->getPointeeType();
12528
12529 // If the RHS isn't an Objective-C object, bail out.
12530 if (!RHS->getType()->isObjCObjectPointerType())
12531 return false;
12532
12533 // Try to find the -isEqual: method.
12534 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12535 ObjCMethodDecl *Method =
12536 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
12537 /*IsInstance=*/true);
12538 if (!Method) {
12539 if (Type->isObjCIdType()) {
12540 // For 'id', just check the global pool.
12541 Method =
12543 /*receiverId=*/true);
12544 } else {
12545 // Check protocols.
12546 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
12547 /*IsInstance=*/true);
12548 }
12549 }
12550
12551 if (!Method)
12552 return false;
12553
12554 QualType T = Method->parameters()[0]->getType();
12555 if (!T->isObjCObjectPointerType())
12556 return false;
12557
12558 QualType R = Method->getReturnType();
12559 if (!R->isScalarType())
12560 return false;
12561
12562 return true;
12563}
12564
12566 ExprResult &LHS, ExprResult &RHS,
12568 Expr *Literal;
12569 Expr *Other;
12570 if (isObjCObjectLiteral(LHS)) {
12571 Literal = LHS.get();
12572 Other = RHS.get();
12573 } else {
12574 Literal = RHS.get();
12575 Other = LHS.get();
12576 }
12577
12578 // Don't warn on comparisons against nil.
12579 Other = Other->IgnoreParenCasts();
12580 if (Other->isNullPointerConstant(S.getASTContext(),
12582 return;
12583
12584 // This should be kept in sync with warn_objc_literal_comparison.
12585 // LK_String should always be after the other literals, since it has its own
12586 // warning flag.
12587 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12588 assert(LiteralKind != SemaObjC::LK_Block);
12589 if (LiteralKind == SemaObjC::LK_None) {
12590 llvm_unreachable("Unknown Objective-C object literal kind");
12591 }
12592
12593 if (LiteralKind == SemaObjC::LK_String)
12594 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12595 << Literal->getSourceRange();
12596 else
12597 S.Diag(Loc, diag::warn_objc_literal_comparison)
12598 << LiteralKind << Literal->getSourceRange();
12599
12601 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12602 SourceLocation Start = LHS.get()->getBeginLoc();
12604 CharSourceRange OpRange =
12606
12607 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12608 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12609 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12610 << FixItHint::CreateInsertion(End, "]");
12611 }
12612}
12613
12614/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12616 ExprResult &RHS, SourceLocation Loc,
12617 BinaryOperatorKind Opc) {
12618 // Check that left hand side is !something.
12619 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12620 if (!UO || UO->getOpcode() != UO_LNot) return;
12621
12622 // Only check if the right hand side is non-bool arithmetic type.
12623 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12624
12625 // Make sure that the something in !something is not bool.
12626 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12627 if (SubExpr->isKnownToHaveBooleanValue()) return;
12628
12629 // Emit warning.
12630 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12631 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12632 << Loc << IsBitwiseOp;
12633
12634 // First note suggest !(x < y)
12635 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12636 SourceLocation FirstClose = RHS.get()->getEndLoc();
12637 FirstClose = S.getLocForEndOfToken(FirstClose);
12638 if (FirstClose.isInvalid())
12639 FirstOpen = SourceLocation();
12640 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12641 << IsBitwiseOp
12642 << FixItHint::CreateInsertion(FirstOpen, "(")
12643 << FixItHint::CreateInsertion(FirstClose, ")");
12644
12645 // Second note suggests (!x) < y
12646 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12647 SourceLocation SecondClose = LHS.get()->getEndLoc();
12648 SecondClose = S.getLocForEndOfToken(SecondClose);
12649 if (SecondClose.isInvalid())
12650 SecondOpen = SourceLocation();
12651 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12652 << FixItHint::CreateInsertion(SecondOpen, "(")
12653 << FixItHint::CreateInsertion(SecondClose, ")");
12654}
12655
12656// Returns true if E refers to a non-weak array.
12657static bool checkForArray(const Expr *E) {
12658 const ValueDecl *D = nullptr;
12659 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12660 D = DR->getDecl();
12661 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12662 if (Mem->isImplicitAccess())
12663 D = Mem->getMemberDecl();
12664 }
12665 if (!D)
12666 return false;
12667 return D->getType()->isArrayType() && !D->isWeak();
12668}
12669
12670/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12671/// pointer and size is an unsigned integer. Return whether the result is
12672/// always true/false.
12673static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12674 const Expr *RHS,
12675 BinaryOperatorKind Opc) {
12676 if (!LHS->getType()->isPointerType() ||
12677 S.getLangOpts().PointerOverflowDefined)
12678 return std::nullopt;
12679
12680 // Canonicalize to >= or < predicate.
12681 switch (Opc) {
12682 case BO_GE:
12683 case BO_LT:
12684 break;
12685 case BO_GT:
12686 std::swap(LHS, RHS);
12687 Opc = BO_LT;
12688 break;
12689 case BO_LE:
12690 std::swap(LHS, RHS);
12691 Opc = BO_GE;
12692 break;
12693 default:
12694 return std::nullopt;
12695 }
12696
12697 auto *BO = dyn_cast<BinaryOperator>(LHS);
12698 if (!BO || BO->getOpcode() != BO_Add)
12699 return std::nullopt;
12700
12701 Expr *Other;
12702 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12703 Other = BO->getRHS();
12704 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12705 Other = BO->getLHS();
12706 else
12707 return std::nullopt;
12708
12709 if (!Other->getType()->isUnsignedIntegerType())
12710 return std::nullopt;
12711
12712 return Opc == BO_GE;
12713}
12714
12715/// Diagnose some forms of syntactically-obvious tautological comparison.
12717 Expr *LHS, Expr *RHS,
12718 BinaryOperatorKind Opc) {
12719 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12720 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12721
12722 QualType LHSType = LHS->getType();
12723 QualType RHSType = RHS->getType();
12724 if (LHSType->hasFloatingRepresentation() ||
12725 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12727 return;
12728
12729 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12730 // Tautological diagnostics.
12731 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12732 return;
12733
12734 // Comparisons between two array types are ill-formed for operator<=>, so
12735 // we shouldn't emit any additional warnings about it.
12736 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12737 return;
12738
12739 // For non-floating point types, check for self-comparisons of the form
12740 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12741 // often indicate logic errors in the program.
12742 //
12743 // NOTE: Don't warn about comparison expressions resulting from macro
12744 // expansion. Also don't warn about comparisons which are only self
12745 // comparisons within a template instantiation. The warnings should catch
12746 // obvious cases in the definition of the template anyways. The idea is to
12747 // warn when the typed comparison operator will always evaluate to the same
12748 // result.
12749
12750 // Used for indexing into %select in warn_comparison_always
12751 enum {
12752 AlwaysConstant,
12753 AlwaysTrue,
12754 AlwaysFalse,
12755 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12756 };
12757
12758 // C++1a [array.comp]:
12759 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12760 // operands of array type.
12761 // C++2a [depr.array.comp]:
12762 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12763 // operands of array type are deprecated.
12764 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12765 RHSStripped->getType()->isArrayType()) {
12766 auto IsDeprArrayComparionIgnored =
12767 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12768 auto DiagID = S.getLangOpts().CPlusPlus26
12769 ? diag::warn_array_comparison_cxx26
12770 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12771 ? diag::warn_array_comparison
12772 : diag::warn_depr_array_comparison;
12773 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12774 << LHSStripped->getType() << RHSStripped->getType();
12775 // Carry on to produce the tautological comparison warning, if this
12776 // expression is potentially-evaluated, we can resolve the array to a
12777 // non-weak declaration, and so on.
12778 }
12779
12780 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12781 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12782 unsigned Result;
12783 switch (Opc) {
12784 case BO_EQ:
12785 case BO_LE:
12786 case BO_GE:
12787 Result = AlwaysTrue;
12788 break;
12789 case BO_NE:
12790 case BO_LT:
12791 case BO_GT:
12792 Result = AlwaysFalse;
12793 break;
12794 case BO_Cmp:
12795 Result = AlwaysEqual;
12796 break;
12797 default:
12798 Result = AlwaysConstant;
12799 break;
12800 }
12801 S.DiagRuntimeBehavior(Loc, nullptr,
12802 S.PDiag(diag::warn_comparison_always)
12803 << 0 /*self-comparison*/
12804 << Result);
12805 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12806 // What is it always going to evaluate to?
12807 unsigned Result;
12808 switch (Opc) {
12809 case BO_EQ: // e.g. array1 == array2
12810 Result = AlwaysFalse;
12811 break;
12812 case BO_NE: // e.g. array1 != array2
12813 Result = AlwaysTrue;
12814 break;
12815 default: // e.g. array1 <= array2
12816 // The best we can say is 'a constant'
12817 Result = AlwaysConstant;
12818 break;
12819 }
12820 S.DiagRuntimeBehavior(Loc, nullptr,
12821 S.PDiag(diag::warn_comparison_always)
12822 << 1 /*array comparison*/
12823 << Result);
12824 } else if (std::optional<bool> Res =
12825 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12826 S.DiagRuntimeBehavior(Loc, nullptr,
12827 S.PDiag(diag::warn_comparison_always)
12828 << 2 /*pointer comparison*/
12829 << (*Res ? AlwaysTrue : AlwaysFalse));
12830 }
12831 }
12832
12833 if (isa<CastExpr>(LHSStripped))
12834 LHSStripped = LHSStripped->IgnoreParenCasts();
12835 if (isa<CastExpr>(RHSStripped))
12836 RHSStripped = RHSStripped->IgnoreParenCasts();
12837
12838 // Warn about comparisons against a string constant (unless the other
12839 // operand is null); the user probably wants string comparison function.
12840 Expr *LiteralString = nullptr;
12841 Expr *LiteralStringStripped = nullptr;
12842 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12843 !RHSStripped->isNullPointerConstant(S.Context,
12845 LiteralString = LHS;
12846 LiteralStringStripped = LHSStripped;
12847 } else if ((isa<StringLiteral>(RHSStripped) ||
12848 isa<ObjCEncodeExpr>(RHSStripped)) &&
12849 !LHSStripped->isNullPointerConstant(S.Context,
12851 LiteralString = RHS;
12852 LiteralStringStripped = RHSStripped;
12853 }
12854
12855 if (LiteralString) {
12856 S.DiagRuntimeBehavior(Loc, nullptr,
12857 S.PDiag(diag::warn_stringcompare)
12858 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12859 << LiteralString->getSourceRange());
12860 }
12861}
12862
12864 switch (CK) {
12865 default: {
12866#ifndef NDEBUG
12867 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12868 << "\n";
12869#endif
12870 llvm_unreachable("unhandled cast kind");
12871 }
12872 case CK_UserDefinedConversion:
12873 return ICK_Identity;
12874 case CK_LValueToRValue:
12875 return ICK_Lvalue_To_Rvalue;
12876 case CK_ArrayToPointerDecay:
12877 return ICK_Array_To_Pointer;
12878 case CK_FunctionToPointerDecay:
12880 case CK_IntegralCast:
12882 case CK_FloatingCast:
12884 case CK_IntegralToFloating:
12885 case CK_FloatingToIntegral:
12886 return ICK_Floating_Integral;
12887 case CK_IntegralComplexCast:
12888 case CK_FloatingComplexCast:
12889 case CK_FloatingComplexToIntegralComplex:
12890 case CK_IntegralComplexToFloatingComplex:
12892 case CK_FloatingComplexToReal:
12893 case CK_FloatingRealToComplex:
12894 case CK_IntegralComplexToReal:
12895 case CK_IntegralRealToComplex:
12896 return ICK_Complex_Real;
12897 case CK_HLSLArrayRValue:
12898 return ICK_HLSL_Array_RValue;
12899 }
12900}
12901
12903 QualType FromType,
12904 SourceLocation Loc) {
12905 // Check for a narrowing implicit conversion.
12908 SCS.setToType(0, FromType);
12909 SCS.setToType(1, ToType);
12910 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12911 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12912
12913 APValue PreNarrowingValue;
12914 QualType PreNarrowingType;
12915 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12916 PreNarrowingType,
12917 /*IgnoreFloatToIntegralConversion*/ true)) {
12919 // Implicit conversion to a narrower type, but the expression is
12920 // value-dependent so we can't tell whether it's actually narrowing.
12921 case NK_Not_Narrowing:
12922 return false;
12923
12925 // Implicit conversion to a narrower type, and the value is not a constant
12926 // expression.
12927 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12928 << /*Constant*/ 1
12929 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12930 return true;
12931
12933 // Implicit conversion to a narrower type, and the value is not a constant
12934 // expression.
12935 case NK_Type_Narrowing:
12936 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12937 << /*Constant*/ 0 << FromType << ToType;
12938 // TODO: It's not a constant expression, but what if the user intended it
12939 // to be? Can we produce notes to help them figure out why it isn't?
12940 return true;
12941 }
12942 llvm_unreachable("unhandled case in switch");
12943}
12944
12946 ExprResult &LHS,
12947 ExprResult &RHS,
12948 SourceLocation Loc) {
12949 QualType LHSType = LHS.get()->getType();
12950 QualType RHSType = RHS.get()->getType();
12951 // Dig out the original argument type and expression before implicit casts
12952 // were applied. These are the types/expressions we need to check the
12953 // [expr.spaceship] requirements against.
12954 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12955 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12956 QualType LHSStrippedType = LHSStripped.get()->getType();
12957 QualType RHSStrippedType = RHSStripped.get()->getType();
12958
12959 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12960 // other is not, the program is ill-formed.
12961 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12962 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12963 return QualType();
12964 }
12965
12966 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12967 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12968 RHSStrippedType->isEnumeralType();
12969 if (NumEnumArgs == 1) {
12970 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12971 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12972 if (OtherTy->hasFloatingRepresentation()) {
12973 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12974 return QualType();
12975 }
12976 }
12977 if (NumEnumArgs == 2) {
12978 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12979 // type E, the operator yields the result of converting the operands
12980 // to the underlying type of E and applying <=> to the converted operands.
12981 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12982 S.InvalidOperands(Loc, LHS, RHS);
12983 return QualType();
12984 }
12985 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12986 assert(IntType->isArithmeticType());
12987
12988 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12989 // promote the boolean type, and all other promotable integer types, to
12990 // avoid this.
12991 if (S.Context.isPromotableIntegerType(IntType))
12992 IntType = S.Context.getPromotedIntegerType(IntType);
12993
12994 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12995 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12996 LHSType = RHSType = IntType;
12997 }
12998
12999 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
13000 // usual arithmetic conversions are applied to the operands.
13001 QualType Type =
13003 if (LHS.isInvalid() || RHS.isInvalid())
13004 return QualType();
13005 if (Type.isNull()) {
13006 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13007 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
13008 return ResultTy;
13009 }
13010
13011 std::optional<ComparisonCategoryType> CCT =
13013 if (!CCT)
13014 return S.InvalidOperands(Loc, LHS, RHS);
13015
13016 bool HasNarrowing = checkThreeWayNarrowingConversion(
13017 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
13018 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
13019 RHS.get()->getBeginLoc());
13020 if (HasNarrowing)
13021 return QualType();
13022
13023 assert(!Type.isNull() && "composite type for <=> has not been set");
13024
13027}
13028
13030 ExprResult &RHS,
13031 SourceLocation Loc,
13032 BinaryOperatorKind Opc) {
13033 if (Opc == BO_Cmp)
13034 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
13035
13036 // C99 6.5.8p3 / C99 6.5.9p4
13037 QualType Type =
13039 if (LHS.isInvalid() || RHS.isInvalid())
13040 return QualType();
13041 if (Type.isNull()) {
13042 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
13043 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
13044 return ResultTy;
13045 }
13046 assert(Type->isArithmeticType() || Type->isEnumeralType());
13047
13049 return S.InvalidOperands(Loc, LHS, RHS);
13050
13051 // Check for comparisons of floating point operands using != and ==.
13053 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13054
13055 // The result of comparisons is 'bool' in C++, 'int' in C.
13057}
13058
13060 if (!NullE.get()->getType()->isAnyPointerType())
13061 return;
13062 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
13063 if (!E.get()->getType()->isAnyPointerType() &&
13067 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
13068 if (CL->getValue() == 0)
13069 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13070 << NullValue
13072 NullValue ? "NULL" : "(void *)0");
13073 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
13074 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
13075 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
13076 if (T == Context.CharTy)
13077 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13078 << NullValue
13080 NullValue ? "NULL" : "(void *)0");
13081 }
13082 }
13083}
13084
13085// C99 6.5.8, C++ [expr.rel]
13087 SourceLocation Loc,
13088 BinaryOperatorKind Opc) {
13089 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
13090 bool IsThreeWay = Opc == BO_Cmp;
13091 bool IsOrdered = IsRelational || IsThreeWay;
13092 auto IsAnyPointerType = [](ExprResult E) {
13093 QualType Ty = E.get()->getType();
13094 return Ty->isPointerType() || Ty->isMemberPointerType();
13095 };
13096
13097 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
13098 // type, array-to-pointer, ..., conversions are performed on both operands to
13099 // bring them to their composite type.
13100 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
13101 // any type-related checks.
13102 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
13104 if (LHS.isInvalid())
13105 return QualType();
13107 if (RHS.isInvalid())
13108 return QualType();
13109 } else {
13110 LHS = DefaultLvalueConversion(LHS.get());
13111 if (LHS.isInvalid())
13112 return QualType();
13113 RHS = DefaultLvalueConversion(RHS.get());
13114 if (RHS.isInvalid())
13115 return QualType();
13116 }
13117
13118 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
13122 }
13123
13124 if (getLangOpts().HLSL && (LHS.get()->getType()->isConstantMatrixType() ||
13125 RHS.get()->getType()->isConstantMatrixType()))
13126 return CheckMatrixCompareOperands(LHS, RHS, Loc, Opc);
13127
13128 // Handle vector comparisons separately.
13129 if (LHS.get()->getType()->isVectorType() ||
13130 RHS.get()->getType()->isVectorType())
13131 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
13132
13133 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13134 RHS.get()->getType()->isSveVLSBuiltinType())
13135 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
13136
13137 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13138 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13139
13140 QualType LHSType = LHS.get()->getType();
13141 QualType RHSType = RHS.get()->getType();
13142 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
13143 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13144 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
13145
13146 if ((LHSType->isPointerType() &&
13148 (RHSType->isPointerType() &&
13150 return InvalidOperands(Loc, LHS, RHS);
13151
13152 const Expr::NullPointerConstantKind LHSNullKind =
13154 const Expr::NullPointerConstantKind RHSNullKind =
13156 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13157 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13158
13159 auto computeResultTy = [&]() {
13160 if (Opc != BO_Cmp)
13161 return QualType(Context.getLogicalOperationType());
13162 assert(getLangOpts().CPlusPlus);
13163 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13164
13165 QualType CompositeTy = LHS.get()->getType();
13166 assert(!CompositeTy->isReferenceType());
13167
13168 std::optional<ComparisonCategoryType> CCT =
13170 if (!CCT)
13171 return InvalidOperands(Loc, LHS, RHS);
13172
13173 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13174 // P0946R0: Comparisons between a null pointer constant and an object
13175 // pointer result in std::strong_equality, which is ill-formed under
13176 // P1959R0.
13177 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13178 << (LHSIsNull ? LHS.get()->getSourceRange()
13179 : RHS.get()->getSourceRange());
13180 return QualType();
13181 }
13182
13185 };
13186
13187 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13188 bool IsEquality = Opc == BO_EQ;
13189 if (RHSIsNull)
13190 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
13191 RHS.get()->getSourceRange());
13192 else
13193 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
13194 LHS.get()->getSourceRange());
13195 }
13196
13197 if (IsOrdered && LHSType->isFunctionPointerType() &&
13198 RHSType->isFunctionPointerType()) {
13199 // Valid unless a relational comparison of function pointers
13200 bool IsError = Opc == BO_Cmp;
13201 auto DiagID =
13202 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13203 : getLangOpts().CPlusPlus
13204 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13205 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13206 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13207 << RHS.get()->getSourceRange();
13208 if (IsError)
13209 return QualType();
13210 }
13211
13212 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13213 (RHSType->isIntegerType() && !RHSIsNull)) {
13214 // Skip normal pointer conversion checks in this case; we have better
13215 // diagnostics for this below.
13216 } else if (getLangOpts().CPlusPlus) {
13217 // Equality comparison of a function pointer to a void pointer is invalid,
13218 // but we allow it as an extension.
13219 // FIXME: If we really want to allow this, should it be part of composite
13220 // pointer type computation so it works in conditionals too?
13221 if (!IsOrdered &&
13222 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13223 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13224 // This is a gcc extension compatibility comparison.
13225 // In a SFINAE context, we treat this as a hard error to maintain
13226 // conformance with the C++ standard.
13227 bool IsError = isSFINAEContext();
13228 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError);
13229
13230 if (IsError)
13231 return QualType();
13232
13233 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13234 return computeResultTy();
13235 }
13236
13237 // C++ [expr.eq]p2:
13238 // If at least one operand is a pointer [...] bring them to their
13239 // composite pointer type.
13240 // C++ [expr.spaceship]p6
13241 // If at least one of the operands is of pointer type, [...] bring them
13242 // to their composite pointer type.
13243 // C++ [expr.rel]p2:
13244 // If both operands are pointers, [...] bring them to their composite
13245 // pointer type.
13246 // For <=>, the only valid non-pointer types are arrays and functions, and
13247 // we already decayed those, so this is really the same as the relational
13248 // comparison rule.
13249 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13250 (IsOrdered ? 2 : 1) &&
13251 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13252 RHSType->isObjCObjectPointerType()))) {
13253 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13254 return QualType();
13255 return computeResultTy();
13256 }
13257 } else if (LHSType->isPointerType() &&
13258 RHSType->isPointerType()) { // C99 6.5.8p2
13259 // All of the following pointer-related warnings are GCC extensions, except
13260 // when handling null pointer constants.
13261 QualType LCanPointeeTy =
13263 QualType RCanPointeeTy =
13265
13266 // C99 6.5.9p2 and C99 6.5.8p2
13267 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
13268 RCanPointeeTy.getUnqualifiedType())) {
13269 if (IsRelational) {
13270 // Pointers both need to point to complete or incomplete types
13271 if ((LCanPointeeTy->isIncompleteType() !=
13272 RCanPointeeTy->isIncompleteType()) &&
13273 !getLangOpts().C11) {
13274 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13275 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13276 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13277 << RCanPointeeTy->isIncompleteType();
13278 }
13279 }
13280 } else if (!IsRelational &&
13281 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13282 // Valid unless comparison between non-null pointer and function pointer
13283 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13284 && !LHSIsNull && !RHSIsNull)
13285 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13286 /*isError*/false);
13287 } else {
13288 // Invalid
13289 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13290 }
13291 if (LCanPointeeTy != RCanPointeeTy) {
13292 // Treat NULL constant as a special case in OpenCL.
13293 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13294 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
13295 getASTContext())) {
13296 Diag(Loc,
13297 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13298 << LHSType << RHSType << 0 /* comparison */
13299 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13300 }
13301 }
13302 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13303 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13304 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13305 : CK_BitCast;
13306
13307 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13308 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13309 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13310 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13311 bool ChangingCFIUncheckedCallee =
13312 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13313
13314 if (LHSIsNull && !RHSIsNull)
13315 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13316 else if (!ChangingCFIUncheckedCallee)
13317 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13318 }
13319 return computeResultTy();
13320 }
13321
13322
13323 // C++ [expr.eq]p4:
13324 // Two operands of type std::nullptr_t or one operand of type
13325 // std::nullptr_t and the other a null pointer constant compare
13326 // equal.
13327 // C23 6.5.9p5:
13328 // If both operands have type nullptr_t or one operand has type nullptr_t
13329 // and the other is a null pointer constant, they compare equal if the
13330 // former is a null pointer.
13331 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13332 if (LHSType->isNullPtrType()) {
13333 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13334 return computeResultTy();
13335 }
13336 if (RHSType->isNullPtrType()) {
13337 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13338 return computeResultTy();
13339 }
13340 }
13341
13342 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13343 // C23 6.5.9p6:
13344 // Otherwise, at least one operand is a pointer. If one is a pointer and
13345 // the other is a null pointer constant or has type nullptr_t, they
13346 // compare equal
13347 if (LHSIsNull && RHSType->isPointerType()) {
13348 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13349 return computeResultTy();
13350 }
13351 if (RHSIsNull && LHSType->isPointerType()) {
13352 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13353 return computeResultTy();
13354 }
13355 }
13356
13357 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13358 // These aren't covered by the composite pointer type rules.
13359 if (!IsOrdered && RHSType->isNullPtrType() &&
13360 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13361 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13362 return computeResultTy();
13363 }
13364 if (!IsOrdered && LHSType->isNullPtrType() &&
13365 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13366 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13367 return computeResultTy();
13368 }
13369
13370 if (getLangOpts().CPlusPlus) {
13371 if (IsRelational &&
13372 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13373 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13374 // HACK: Relational comparison of nullptr_t against a pointer type is
13375 // invalid per DR583, but we allow it within std::less<> and friends,
13376 // since otherwise common uses of it break.
13377 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13378 // friends to have std::nullptr_t overload candidates.
13379 DeclContext *DC = CurContext;
13380 if (isa<FunctionDecl>(DC))
13381 DC = DC->getParent();
13382 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13383 if (CTSD->isInStdNamespace() &&
13384 llvm::StringSwitch<bool>(CTSD->getName())
13385 .Cases({"less", "less_equal", "greater", "greater_equal"}, true)
13386 .Default(false)) {
13387 if (RHSType->isNullPtrType())
13388 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13389 else
13390 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13391 return computeResultTy();
13392 }
13393 }
13394 }
13395
13396 // C++ [expr.eq]p2:
13397 // If at least one operand is a pointer to member, [...] bring them to
13398 // their composite pointer type.
13399 if (!IsOrdered &&
13400 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13401 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13402 return QualType();
13403 else
13404 return computeResultTy();
13405 }
13406 }
13407
13408 // Handle block pointer types.
13409 if (!IsOrdered && LHSType->isBlockPointerType() &&
13410 RHSType->isBlockPointerType()) {
13411 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13412 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13413
13414 if (!LHSIsNull && !RHSIsNull &&
13415 !Context.typesAreCompatible(lpointee, rpointee)) {
13416 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13417 << LHSType << RHSType << LHS.get()->getSourceRange()
13418 << RHS.get()->getSourceRange();
13419 }
13420 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13421 return computeResultTy();
13422 }
13423
13424 // Allow block pointers to be compared with null pointer constants.
13425 if (!IsOrdered
13426 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13427 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13428 if (!LHSIsNull && !RHSIsNull) {
13429 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13431 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13432 ->getPointeeType()->isVoidType())))
13433 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13434 << LHSType << RHSType << LHS.get()->getSourceRange()
13435 << RHS.get()->getSourceRange();
13436 }
13437 if (LHSIsNull && !RHSIsNull)
13438 LHS = ImpCastExprToType(LHS.get(), RHSType,
13439 RHSType->isPointerType() ? CK_BitCast
13440 : CK_AnyPointerToBlockPointerCast);
13441 else
13442 RHS = ImpCastExprToType(RHS.get(), LHSType,
13443 LHSType->isPointerType() ? CK_BitCast
13444 : CK_AnyPointerToBlockPointerCast);
13445 return computeResultTy();
13446 }
13447
13448 if (LHSType->isObjCObjectPointerType() ||
13449 RHSType->isObjCObjectPointerType()) {
13450 const PointerType *LPT = LHSType->getAs<PointerType>();
13451 const PointerType *RPT = RHSType->getAs<PointerType>();
13452 if (LPT || RPT) {
13453 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13454 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13455
13456 if (!LPtrToVoid && !RPtrToVoid &&
13457 !Context.typesAreCompatible(LHSType, RHSType)) {
13458 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13459 /*isError*/false);
13460 }
13461 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13462 // the RHS, but we have test coverage for this behavior.
13463 // FIXME: Consider using convertPointersToCompositeType in C++.
13464 if (LHSIsNull && !RHSIsNull) {
13465 Expr *E = LHS.get();
13466 if (getLangOpts().ObjCAutoRefCount)
13467 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
13469 LHS = ImpCastExprToType(E, RHSType,
13470 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13471 }
13472 else {
13473 Expr *E = RHS.get();
13474 if (getLangOpts().ObjCAutoRefCount)
13475 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
13477 /*Diagnose=*/true,
13478 /*DiagnoseCFAudited=*/false, Opc);
13479 RHS = ImpCastExprToType(E, LHSType,
13480 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13481 }
13482 return computeResultTy();
13483 }
13484 if (LHSType->isObjCObjectPointerType() &&
13485 RHSType->isObjCObjectPointerType()) {
13486 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13487 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13488 /*isError*/false);
13490 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13491
13492 if (LHSIsNull && !RHSIsNull)
13493 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13494 else
13495 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13496 return computeResultTy();
13497 }
13498
13499 if (!IsOrdered && LHSType->isBlockPointerType() &&
13501 LHS = ImpCastExprToType(LHS.get(), RHSType,
13502 CK_BlockPointerToObjCPointerCast);
13503 return computeResultTy();
13504 } else if (!IsOrdered &&
13506 RHSType->isBlockPointerType()) {
13507 RHS = ImpCastExprToType(RHS.get(), LHSType,
13508 CK_BlockPointerToObjCPointerCast);
13509 return computeResultTy();
13510 }
13511 }
13512 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13513 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13514 unsigned DiagID = 0;
13515 bool isError = false;
13516 if (LangOpts.DebuggerSupport) {
13517 // Under a debugger, allow the comparison of pointers to integers,
13518 // since users tend to want to compare addresses.
13519 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13520 (RHSIsNull && RHSType->isIntegerType())) {
13521 if (IsOrdered) {
13522 isError = getLangOpts().CPlusPlus;
13523 DiagID =
13524 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13525 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13526 }
13527 } else if (getLangOpts().CPlusPlus) {
13528 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13529 isError = true;
13530 } else if (IsOrdered)
13531 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13532 else
13533 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13534
13535 if (DiagID) {
13536 Diag(Loc, DiagID)
13537 << LHSType << RHSType << LHS.get()->getSourceRange()
13538 << RHS.get()->getSourceRange();
13539 if (isError)
13540 return QualType();
13541 }
13542
13543 if (LHSType->isIntegerType())
13544 LHS = ImpCastExprToType(LHS.get(), RHSType,
13545 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13546 else
13547 RHS = ImpCastExprToType(RHS.get(), LHSType,
13548 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13549 return computeResultTy();
13550 }
13551
13552 // Handle block pointers.
13553 if (!IsOrdered && RHSIsNull
13554 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13555 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13556 return computeResultTy();
13557 }
13558 if (!IsOrdered && LHSIsNull
13559 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13560 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13561 return computeResultTy();
13562 }
13563
13564 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13565 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13566 return computeResultTy();
13567 }
13568
13569 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13570 return computeResultTy();
13571 }
13572
13573 if (LHSIsNull && RHSType->isQueueT()) {
13574 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13575 return computeResultTy();
13576 }
13577
13578 if (LHSType->isQueueT() && RHSIsNull) {
13579 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13580 return computeResultTy();
13581 }
13582 }
13583
13584 return InvalidOperands(Loc, LHS, RHS);
13585}
13586
13588 const VectorType *VTy = V->castAs<VectorType>();
13589 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13590
13591 if (isa<ExtVectorType>(VTy)) {
13592 if (VTy->isExtVectorBoolType())
13593 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13594 if (TypeSize == Context.getTypeSize(Context.CharTy))
13595 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13596 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13597 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13598 if (TypeSize == Context.getTypeSize(Context.IntTy))
13599 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13600 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13601 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13602 if (TypeSize == Context.getTypeSize(Context.LongTy))
13603 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13604 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13605 "Unhandled vector element size in vector compare");
13606 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13607 }
13608
13609 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13610 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13612 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13613 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13615 if (TypeSize == Context.getTypeSize(Context.LongTy))
13616 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13618 if (TypeSize == Context.getTypeSize(Context.IntTy))
13619 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13621 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13622 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13624 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13625 "Unhandled vector element size in vector compare");
13626 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13628}
13629
13631 const BuiltinType *VTy = V->castAs<BuiltinType>();
13632 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13633
13634 const QualType ETy = V->getSveEltType(Context);
13635 const auto TypeSize = Context.getTypeSize(ETy);
13636
13637 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13638 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13639 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13640}
13641
13643 SourceLocation Loc,
13644 BinaryOperatorKind Opc) {
13645 if (Opc == BO_Cmp) {
13646 Diag(Loc, diag::err_three_way_vector_comparison);
13647 return QualType();
13648 }
13649
13650 // Check to make sure we're operating on vectors of the same type and width,
13651 // Allowing one side to be a scalar of element type.
13652 QualType vType =
13653 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13654 /*AllowBothBool*/ true,
13655 /*AllowBoolConversions*/ getLangOpts().ZVector,
13656 /*AllowBooleanOperation*/ true,
13657 /*ReportInvalid*/ true);
13658 if (vType.isNull())
13659 return vType;
13660
13661 QualType LHSType = LHS.get()->getType();
13662
13663 // Determine the return type of a vector compare. By default clang will return
13664 // a scalar for all vector compares except vector bool and vector pixel.
13665 // With the gcc compiler we will always return a vector type and with the xl
13666 // compiler we will always return a scalar type. This switch allows choosing
13667 // which behavior is prefered.
13668 if (getLangOpts().AltiVec) {
13669 switch (getLangOpts().getAltivecSrcCompat()) {
13671 // If AltiVec, the comparison results in a numeric type, i.e.
13672 // bool for C++, int for C
13673 if (vType->castAs<VectorType>()->getVectorKind() ==
13675 return Context.getLogicalOperationType();
13676 else
13677 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13678 break;
13680 // For GCC we always return the vector type.
13681 break;
13683 return Context.getLogicalOperationType();
13684 break;
13685 }
13686 }
13687
13688 // For non-floating point types, check for self-comparisons of the form
13689 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13690 // often indicate logic errors in the program.
13691 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13692
13693 // Check for comparisons of floating point operands using != and ==.
13694 if (LHSType->hasFloatingRepresentation()) {
13695 assert(RHS.get()->getType()->hasFloatingRepresentation());
13696 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13697 }
13698
13699 // Return a signed type for the vector.
13700 return GetSignedVectorType(vType);
13701}
13702
13704 SourceLocation Loc,
13705 BinaryOperatorKind Opc) {
13706 assert(getLangOpts().HLSL && "matrix comparisons are only supported in HLSL");
13707 assert(Opc != BO_Cmp && "three-way comparisons are not supported in HLSL");
13708
13709 QualType MatrixTy =
13710 CheckMatrixElementwiseOperands(LHS, RHS, Loc, /*IsCompAssign=*/false);
13711 if (MatrixTy.isNull())
13712 return QualType();
13713
13714 if (!LHS.get()->getType()->isMatrixType()) {
13715 LHS = prepareMatrixSplat(MatrixTy, LHS.get());
13716 if (LHS.isInvalid())
13717 return QualType();
13718 LHS = ImpCastExprToType(LHS.get(), MatrixTy, CK_HLSLAggregateSplatCast);
13719 }
13720 if (!RHS.get()->getType()->isMatrixType()) {
13721 RHS = prepareMatrixSplat(MatrixTy, RHS.get());
13722 if (RHS.isInvalid())
13723 return QualType();
13724 RHS = ImpCastExprToType(RHS.get(), MatrixTy, CK_HLSLAggregateSplatCast);
13725 }
13726
13727 const auto *MT = MatrixTy->castAs<ConstantMatrixType>();
13728 return Context.getConstantMatrixType(Context.BoolTy, MT->getNumRows(),
13729 MT->getNumColumns());
13730}
13731
13733 ExprResult &RHS,
13734 SourceLocation Loc,
13735 BinaryOperatorKind Opc) {
13736 if (Opc == BO_Cmp) {
13737 Diag(Loc, diag::err_three_way_vector_comparison);
13738 return QualType();
13739 }
13740
13741 // Check to make sure we're operating on vectors of the same type and width,
13742 // Allowing one side to be a scalar of element type.
13744 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13745
13746 if (vType.isNull())
13747 return vType;
13748
13749 QualType LHSType = LHS.get()->getType();
13750
13751 // For non-floating point types, check for self-comparisons of the form
13752 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13753 // often indicate logic errors in the program.
13754 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13755
13756 // Check for comparisons of floating point operands using != and ==.
13757 if (LHSType->hasFloatingRepresentation()) {
13758 assert(RHS.get()->getType()->hasFloatingRepresentation());
13759 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13760 }
13761
13762 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13763 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13764
13765 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13766 RHSBuiltinTy->isSVEBool())
13767 return LHSType;
13768
13769 // Return a signed type for the vector.
13770 return GetSignedSizelessVectorType(vType);
13771}
13772
13773static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13774 const ExprResult &XorRHS,
13775 const SourceLocation Loc) {
13776 // Do not diagnose macros.
13777 if (Loc.isMacroID())
13778 return;
13779
13780 // Do not diagnose if both LHS and RHS are macros.
13781 if (XorLHS.get()->getExprLoc().isMacroID() &&
13782 XorRHS.get()->getExprLoc().isMacroID())
13783 return;
13784
13785 bool Negative = false;
13786 bool ExplicitPlus = false;
13787 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13788 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13789
13790 if (!LHSInt)
13791 return;
13792 if (!RHSInt) {
13793 // Check negative literals.
13794 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13795 UnaryOperatorKind Opc = UO->getOpcode();
13796 if (Opc != UO_Minus && Opc != UO_Plus)
13797 return;
13798 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13799 if (!RHSInt)
13800 return;
13801 Negative = (Opc == UO_Minus);
13802 ExplicitPlus = !Negative;
13803 } else {
13804 return;
13805 }
13806 }
13807
13808 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13809 llvm::APInt RightSideValue = RHSInt->getValue();
13810 if (LeftSideValue != 2 && LeftSideValue != 10)
13811 return;
13812
13813 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13814 return;
13815
13817 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13818 llvm::StringRef ExprStr =
13820
13821 CharSourceRange XorRange =
13823 llvm::StringRef XorStr =
13825 // Do not diagnose if xor keyword/macro is used.
13826 if (XorStr == "xor")
13827 return;
13828
13829 std::string LHSStr = std::string(Lexer::getSourceText(
13830 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13831 S.getSourceManager(), S.getLangOpts()));
13832 std::string RHSStr = std::string(Lexer::getSourceText(
13833 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13834 S.getSourceManager(), S.getLangOpts()));
13835
13836 if (Negative) {
13837 RightSideValue = -RightSideValue;
13838 RHSStr = "-" + RHSStr;
13839 } else if (ExplicitPlus) {
13840 RHSStr = "+" + RHSStr;
13841 }
13842
13843 StringRef LHSStrRef = LHSStr;
13844 StringRef RHSStrRef = RHSStr;
13845 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13846 // literals.
13847 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13848 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13849 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13850 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13851 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13852 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13853 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13854 return;
13855
13856 bool SuggestXor =
13857 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13858 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13859 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13860 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13861 std::string SuggestedExpr = "1 << " + RHSStr;
13862 bool Overflow = false;
13863 llvm::APInt One = (LeftSideValue - 1);
13864 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13865 if (Overflow) {
13866 if (RightSideIntValue < 64)
13867 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13868 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13869 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13870 else if (RightSideIntValue == 64)
13871 S.Diag(Loc, diag::warn_xor_used_as_pow)
13872 << ExprStr << toString(XorValue, 10, true);
13873 else
13874 return;
13875 } else {
13876 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13877 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13878 << toString(PowValue, 10, true)
13880 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13881 }
13882
13883 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13884 << ("0x2 ^ " + RHSStr) << SuggestXor;
13885 } else if (LeftSideValue == 10) {
13886 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13887 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13888 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13889 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13890 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13891 << ("0xA ^ " + RHSStr) << SuggestXor;
13892 }
13893}
13894
13896 SourceLocation Loc,
13897 BinaryOperatorKind Opc) {
13898 // Ensure that either both operands are of the same vector type, or
13899 // one operand is of a vector type and the other is of its element type.
13900 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13901 /*AllowBothBool*/ true,
13902 /*AllowBoolConversions*/ false,
13903 /*AllowBooleanOperation*/ false,
13904 /*ReportInvalid*/ false);
13905 if (vType.isNull())
13906 return InvalidOperands(Loc, LHS, RHS);
13907 if (getLangOpts().OpenCL &&
13908 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13910 return InvalidOperands(Loc, LHS, RHS);
13911 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13912 // usage of the logical operators && and || with vectors in C. This
13913 // check could be notionally dropped.
13914 if (!getLangOpts().CPlusPlus &&
13915 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13916 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13917 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13918 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13919 // `select` functions.
13920 if (getLangOpts().HLSL &&
13921 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13922 (void)InvalidOperands(Loc, LHS, RHS);
13923 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13924 return QualType();
13925 }
13926
13927 return GetSignedVectorType(LHS.get()->getType());
13928}
13929
13931 SourceLocation Loc,
13932 BinaryOperatorKind Opc) {
13933
13934 if (!getLangOpts().HLSL) {
13935 SemaRef.Diag(Loc, diag::err_matrix_logical_operations_supported_for_hlsl);
13936 return QualType();
13937 }
13938
13939 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13940 (void)InvalidOperands(Loc, LHS, RHS);
13941 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13942 return QualType();
13943 }
13944 SemaRef.Diag(LHS.get()->getBeginLoc(), diag::err_hlsl_langstd_unimplemented)
13945 << getLangOpts().getHLSLVersion();
13946 return QualType();
13947}
13948
13950 SourceLocation Loc,
13951 bool IsCompAssign) {
13952 if (!IsCompAssign) {
13954 if (LHS.isInvalid())
13955 return QualType();
13956 }
13958 if (RHS.isInvalid())
13959 return QualType();
13960
13961 // For conversion purposes, we ignore any qualifiers.
13962 // For example, "const float" and "float" are equivalent.
13963 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13964 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13965
13966 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13967 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13968 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13969
13970 if (Context.hasSameType(LHSType, RHSType))
13971 return Context.getCommonSugaredType(LHSType, RHSType);
13972
13973 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13974 // case we have to return InvalidOperands.
13975 ExprResult OriginalLHS = LHS;
13976 ExprResult OriginalRHS = RHS;
13977 if (LHSMatType && !RHSMatType) {
13978 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13979 if (!RHS.isInvalid())
13980 return LHSType;
13981
13982 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13983 }
13984
13985 if (!LHSMatType && RHSMatType) {
13986 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13987 if (!LHS.isInvalid())
13988 return RHSType;
13989 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13990 }
13991
13992 return InvalidOperands(Loc, LHS, RHS);
13993}
13994
13996 SourceLocation Loc,
13997 bool IsCompAssign) {
13998 if (!IsCompAssign) {
14000 if (LHS.isInvalid())
14001 return QualType();
14002 }
14004 if (RHS.isInvalid())
14005 return QualType();
14006
14007 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
14008 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
14009 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
14010
14011 if (LHSMatType && RHSMatType) {
14012 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
14013 return InvalidOperands(Loc, LHS, RHS);
14014
14015 if (Context.hasSameType(LHSMatType, RHSMatType))
14016 return Context.getCommonSugaredType(
14017 LHS.get()->getType().getUnqualifiedType(),
14018 RHS.get()->getType().getUnqualifiedType());
14019
14020 QualType LHSELTy = LHSMatType->getElementType(),
14021 RHSELTy = RHSMatType->getElementType();
14022 if (!Context.hasSameType(LHSELTy, RHSELTy))
14023 return InvalidOperands(Loc, LHS, RHS);
14024
14025 return Context.getConstantMatrixType(
14026 Context.getCommonSugaredType(LHSELTy, RHSELTy),
14027 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
14028 }
14029 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
14030}
14031
14033 switch (Opc) {
14034 default:
14035 return false;
14036 case BO_And:
14037 case BO_AndAssign:
14038 case BO_Or:
14039 case BO_OrAssign:
14040 case BO_Xor:
14041 case BO_XorAssign:
14042 return true;
14043 }
14044}
14045
14047 SourceLocation Loc,
14048 BinaryOperatorKind Opc) {
14049 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
14050
14051 bool IsCompAssign =
14052 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
14053
14054 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
14055
14056 if (LHS.get()->getType()->isVectorType() ||
14057 RHS.get()->getType()->isVectorType()) {
14058 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14060 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
14061 /*AllowBothBool*/ true,
14062 /*AllowBoolConversions*/ getLangOpts().ZVector,
14063 /*AllowBooleanOperation*/ LegalBoolVecOperator,
14064 /*ReportInvalid*/ true);
14065 return InvalidOperands(Loc, LHS, RHS);
14066 }
14067
14068 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14069 RHS.get()->getType()->isSveVLSBuiltinType()) {
14070 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14072 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14074 return InvalidOperands(Loc, LHS, RHS);
14075 }
14076
14077 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14078 RHS.get()->getType()->isSveVLSBuiltinType()) {
14079 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14081 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14083 return InvalidOperands(Loc, LHS, RHS);
14084 }
14085
14086 if (Opc == BO_And)
14087 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
14088
14089 if (LHS.get()->getType()->hasFloatingRepresentation() ||
14091 return InvalidOperands(Loc, LHS, RHS);
14092
14093 ExprResult LHSResult = LHS, RHSResult = RHS;
14095 LHSResult, RHSResult, Loc,
14097 if (LHSResult.isInvalid() || RHSResult.isInvalid())
14098 return QualType();
14099 LHS = LHSResult.get();
14100 RHS = RHSResult.get();
14101
14102 if (Opc == BO_Xor)
14103 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
14104
14105 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
14106 return compType;
14107 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14108 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14109 return ResultTy;
14110}
14111
14112// C99 6.5.[13,14]
14114 SourceLocation Loc,
14115 BinaryOperatorKind Opc) {
14116 // Check vector operands differently.
14117 if (LHS.get()->getType()->isVectorType() ||
14118 RHS.get()->getType()->isVectorType())
14119 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
14120
14121 if (LHS.get()->getType()->isConstantMatrixType() ||
14122 RHS.get()->getType()->isConstantMatrixType())
14123 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
14124
14125 bool EnumConstantInBoolContext = false;
14126 for (const ExprResult &HS : {LHS, RHS}) {
14127 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
14128 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
14129 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
14130 EnumConstantInBoolContext = true;
14131 }
14132 }
14133
14134 if (EnumConstantInBoolContext)
14135 Diag(Loc, diag::warn_enum_constant_in_bool_context);
14136
14137 // WebAssembly tables can't be used with logical operators.
14138 QualType LHSTy = LHS.get()->getType();
14139 QualType RHSTy = RHS.get()->getType();
14140 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
14141 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
14142 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
14143 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
14144 return InvalidOperands(Loc, LHS, RHS);
14145 }
14146
14147 // Diagnose cases where the user write a logical and/or but probably meant a
14148 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
14149 // is a constant.
14150 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
14151 !LHS.get()->getType()->isBooleanType() &&
14152 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
14153 // Don't warn in macros or template instantiations.
14154 !Loc.isMacroID() && !inTemplateInstantiation()) {
14155 // If the RHS can be constant folded, and if it constant folds to something
14156 // that isn't 0 or 1 (which indicate a potential logical operation that
14157 // happened to fold to true/false) then warn.
14158 // Parens on the RHS are ignored.
14159 Expr::EvalResult EVResult;
14160 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
14161 llvm::APSInt Result = EVResult.Val.getInt();
14162 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
14163 !RHS.get()->getExprLoc().isMacroID()) ||
14164 (Result != 0 && Result != 1)) {
14165 Diag(Loc, diag::warn_logical_instead_of_bitwise)
14166 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
14167 // Suggest replacing the logical operator with the bitwise version
14168 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
14169 << (Opc == BO_LAnd ? "&" : "|")
14172 Opc == BO_LAnd ? "&" : "|");
14173 if (Opc == BO_LAnd)
14174 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14175 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
14178 RHS.get()->getEndLoc()));
14179 }
14180 }
14181 }
14182
14183 if (!Context.getLangOpts().CPlusPlus) {
14184 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14185 // not operate on the built-in scalar and vector float types.
14186 if (Context.getLangOpts().OpenCL &&
14187 Context.getLangOpts().OpenCLVersion < 120) {
14188 if (LHS.get()->getType()->isFloatingType() ||
14189 RHS.get()->getType()->isFloatingType())
14190 return InvalidOperands(Loc, LHS, RHS);
14191 }
14192
14193 LHS = UsualUnaryConversions(LHS.get());
14194 if (LHS.isInvalid())
14195 return QualType();
14196
14197 RHS = UsualUnaryConversions(RHS.get());
14198 if (RHS.isInvalid())
14199 return QualType();
14200
14201 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14203 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14205
14206 if (!LHS.get()->getType()->isScalarType() ||
14207 !RHS.get()->getType()->isScalarType())
14208 return InvalidOperands(Loc, LHS, RHS);
14209
14210 return Context.IntTy;
14211 }
14212
14213 // The following is safe because we only use this method for
14214 // non-overloadable operands.
14215
14216 // C++ [expr.log.and]p1
14217 // C++ [expr.log.or]p1
14218 // The operands are both contextually converted to type bool.
14220 if (LHSRes.isInvalid()) {
14221 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14222 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14223 return ResultTy;
14224 }
14225 LHS = LHSRes;
14226
14228 if (RHSRes.isInvalid()) {
14229 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14230 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14231 return ResultTy;
14232 }
14233 RHS = RHSRes;
14234
14235 // C++ [expr.log.and]p2
14236 // C++ [expr.log.or]p2
14237 // The result is a bool.
14238 return Context.BoolTy;
14239}
14240
14241static bool IsReadonlyMessage(Expr *E, Sema &S) {
14242 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14243 if (!ME) return false;
14244 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
14245 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14247 if (!Base) return false;
14248 return Base->getMethodDecl() != nullptr;
14249}
14250
14251/// Is the given expression (which must be 'const') a reference to a
14252/// variable which was originally non-const, but which has become
14253/// 'const' due to being captured within a block?
14256 assert(E->isLValue() && E->getType().isConstQualified());
14257 E = E->IgnoreParens();
14258
14259 // Must be a reference to a declaration from an enclosing scope.
14260 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14261 if (!DRE) return NCCK_None;
14263
14264 ValueDecl *Value = DRE->getDecl();
14265
14266 // The declaration must be a value which is not declared 'const'.
14268 return NCCK_None;
14269
14270 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
14271 if (Binding) {
14272 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14273 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14274 return NCCK_Lambda;
14275 }
14276
14277 VarDecl *Var = dyn_cast<VarDecl>(Value);
14278 if (!Var)
14279 return NCCK_None;
14280 if (Var->getType()->isReferenceType())
14281 return NCCK_None;
14282
14283 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14284
14285 // Decide whether the first capture was for a block or a lambda.
14286 DeclContext *DC = S.CurContext, *Prev = nullptr;
14287 // Decide whether the first capture was for a block or a lambda.
14288 while (DC) {
14289 // For init-capture, it is possible that the variable belongs to the
14290 // template pattern of the current context.
14291 if (auto *FD = dyn_cast<FunctionDecl>(DC))
14292 if (Var->isInitCapture() &&
14293 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14294 break;
14295 if (DC == Var->getDeclContext())
14296 break;
14297 Prev = DC;
14298 DC = DC->getParent();
14299 }
14300 // Unless we have an init-capture, we've gone one step too far.
14301 if (!Var->isInitCapture())
14302 DC = Prev;
14303 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
14304}
14305
14306static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14307 Ty = Ty.getNonReferenceType();
14308 if (IsDereference && Ty->isPointerType())
14309 Ty = Ty->getPointeeType();
14310 return !Ty.isConstQualified();
14311}
14312
14313// Update err_typecheck_assign_const and note_typecheck_assign_const
14314// when this enum is changed.
14315enum {
14320 ConstUnknown, // Keep as last element
14321};
14322
14323/// Emit the "read-only variable not assignable" error and print notes to give
14324/// more information about why the variable is not assignable, such as pointing
14325/// to the declaration of a const variable, showing that a method is const, or
14326/// that the function is returning a const reference.
14327static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14328 SourceLocation Loc) {
14329 SourceRange ExprRange = E->getSourceRange();
14330
14331 // Only emit one error on the first const found. All other consts will emit
14332 // a note to the error.
14333 bool DiagnosticEmitted = false;
14334
14335 // Track if the current expression is the result of a dereference, and if the
14336 // next checked expression is the result of a dereference.
14337 bool IsDereference = false;
14338 bool NextIsDereference = false;
14339
14340 // Loop to process MemberExpr chains.
14341 while (true) {
14342 IsDereference = NextIsDereference;
14343
14345 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14346 NextIsDereference = ME->isArrow();
14347 const ValueDecl *VD = ME->getMemberDecl();
14348 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14349 // Mutable fields can be modified even if the class is const.
14350 if (Field->isMutable()) {
14351 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14352 break;
14353 }
14354
14355 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14356 if (!DiagnosticEmitted) {
14357 S.Diag(Loc, diag::err_typecheck_assign_const)
14358 << ExprRange << ConstMember << false /*static*/ << Field
14359 << Field->getType();
14360 DiagnosticEmitted = true;
14361 }
14362 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14363 << ConstMember << false /*static*/ << Field << Field->getType()
14364 << Field->getSourceRange();
14365 }
14366 E = ME->getBase();
14367 continue;
14368 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14369 if (VDecl->getType().isConstQualified()) {
14370 if (!DiagnosticEmitted) {
14371 S.Diag(Loc, diag::err_typecheck_assign_const)
14372 << ExprRange << ConstMember << true /*static*/ << VDecl
14373 << VDecl->getType();
14374 DiagnosticEmitted = true;
14375 }
14376 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14377 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14378 << VDecl->getSourceRange();
14379 }
14380 // Static fields do not inherit constness from parents.
14381 break;
14382 }
14383 break; // End MemberExpr
14384 } else if (const ArraySubscriptExpr *ASE =
14385 dyn_cast<ArraySubscriptExpr>(E)) {
14386 E = ASE->getBase()->IgnoreParenImpCasts();
14387 continue;
14388 } else if (const ExtVectorElementExpr *EVE =
14389 dyn_cast<ExtVectorElementExpr>(E)) {
14390 E = EVE->getBase()->IgnoreParenImpCasts();
14391 continue;
14392 }
14393 break;
14394 }
14395
14396 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14397 // Function calls
14398 const FunctionDecl *FD = CE->getDirectCallee();
14399 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14400 if (!DiagnosticEmitted) {
14401 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14402 << ConstFunction << FD;
14403 DiagnosticEmitted = true;
14404 }
14406 diag::note_typecheck_assign_const)
14407 << ConstFunction << FD << FD->getReturnType()
14408 << FD->getReturnTypeSourceRange();
14409 }
14410 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14411 // Point to variable declaration.
14412 if (const ValueDecl *VD = DRE->getDecl()) {
14413 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14414 if (!DiagnosticEmitted) {
14415 S.Diag(Loc, diag::err_typecheck_assign_const)
14416 << ExprRange << ConstVariable << VD << VD->getType();
14417 DiagnosticEmitted = true;
14418 }
14419 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14420 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14421 }
14422 }
14423 } else if (isa<CXXThisExpr>(E)) {
14424 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14425 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14426 if (MD->isConst()) {
14427 if (!DiagnosticEmitted) {
14428 S.Diag(Loc, diag::err_typecheck_assign_const_method)
14429 << ExprRange << MD;
14430 DiagnosticEmitted = true;
14431 }
14432 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const_method)
14433 << MD << MD->getSourceRange();
14434 }
14435 }
14436 }
14437 }
14438
14439 if (DiagnosticEmitted)
14440 return;
14441
14442 // Can't determine a more specific message, so display the generic error.
14443 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14444}
14445
14451
14453 const RecordType *Ty,
14454 SourceLocation Loc, SourceRange Range,
14455 OriginalExprKind OEK,
14456 bool &DiagnosticEmitted) {
14457 std::vector<const RecordType *> RecordTypeList;
14458 RecordTypeList.push_back(Ty);
14459 unsigned NextToCheckIndex = 0;
14460 // We walk the record hierarchy breadth-first to ensure that we print
14461 // diagnostics in field nesting order.
14462 while (RecordTypeList.size() > NextToCheckIndex) {
14463 bool IsNested = NextToCheckIndex > 0;
14464 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14465 ->getDecl()
14466 ->getDefinitionOrSelf()
14467 ->fields()) {
14468 // First, check every field for constness.
14469 QualType FieldTy = Field->getType();
14470 if (FieldTy.isConstQualified()) {
14471 if (!DiagnosticEmitted) {
14472 S.Diag(Loc, diag::err_typecheck_assign_const)
14473 << Range << NestedConstMember << OEK << VD
14474 << IsNested << Field;
14475 DiagnosticEmitted = true;
14476 }
14477 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14478 << NestedConstMember << IsNested << Field
14479 << FieldTy << Field->getSourceRange();
14480 }
14481
14482 // Then we append it to the list to check next in order.
14483 FieldTy = FieldTy.getCanonicalType();
14484 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14485 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14486 RecordTypeList.push_back(FieldRecTy);
14487 }
14488 }
14489 ++NextToCheckIndex;
14490 }
14491}
14492
14493/// Emit an error for the case where a record we are trying to assign to has a
14494/// const-qualified field somewhere in its hierarchy.
14495static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14496 SourceLocation Loc) {
14497 QualType Ty = E->getType();
14498 assert(Ty->isRecordType() && "lvalue was not record?");
14499 SourceRange Range = E->getSourceRange();
14500 const auto *RTy = Ty->getAsCanonical<RecordType>();
14501 bool DiagEmitted = false;
14502
14503 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14504 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14505 Range, OEK_Member, DiagEmitted);
14506 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14507 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14508 Range, OEK_Variable, DiagEmitted);
14509 else
14510 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14511 Range, OEK_LValue, DiagEmitted);
14512 if (!DiagEmitted)
14513 DiagnoseConstAssignment(S, E, Loc);
14514}
14515
14516/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14517/// emit an error and return true. If so, return false.
14519 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14520
14522
14523 SourceLocation OrigLoc = Loc;
14525 &Loc);
14526 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14528 if (IsLV == Expr::MLV_Valid)
14529 return false;
14530
14531 unsigned DiagID = 0;
14532 bool NeedType = false;
14533 switch (IsLV) { // C99 6.5.16p2
14535 // Use a specialized diagnostic when we're assigning to an object
14536 // from an enclosing function or block.
14538 if (NCCK == NCCK_Block)
14539 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14540 else
14541 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14542 break;
14543 }
14544
14545 // In ARC, use some specialized diagnostics for occasions where we
14546 // infer 'const'. These are always pseudo-strong variables.
14547 if (S.getLangOpts().ObjCAutoRefCount) {
14548 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14549 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14550 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14551
14552 // Use the normal diagnostic if it's pseudo-__strong but the
14553 // user actually wrote 'const'.
14554 if (var->isARCPseudoStrong() &&
14555 (!var->getTypeSourceInfo() ||
14556 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14557 // There are three pseudo-strong cases:
14558 // - self
14559 ObjCMethodDecl *method = S.getCurMethodDecl();
14560 if (method && var == method->getSelfDecl()) {
14561 DiagID = method->isClassMethod()
14562 ? diag::err_typecheck_arc_assign_self_class_method
14563 : diag::err_typecheck_arc_assign_self;
14564
14565 // - Objective-C externally_retained attribute.
14566 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14567 isa<ParmVarDecl>(var)) {
14568 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14569
14570 // - fast enumeration variables
14571 } else {
14572 DiagID = diag::err_typecheck_arr_assign_enumeration;
14573 }
14574
14575 SourceRange Assign;
14576 if (Loc != OrigLoc)
14577 Assign = SourceRange(OrigLoc, OrigLoc);
14578 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14579 // We need to preserve the AST regardless, so migration tool
14580 // can do its job.
14581 return false;
14582 }
14583 }
14584 }
14585
14586 // If none of the special cases above are triggered, then this is a
14587 // simple const assignment.
14588 if (DiagID == 0) {
14589 DiagnoseConstAssignment(S, E, Loc);
14590 return true;
14591 }
14592
14593 break;
14595 DiagnoseConstAssignment(S, E, Loc);
14596 return true;
14599 return true;
14602 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14603 NeedType = true;
14604 break;
14606 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14607 NeedType = true;
14608 break;
14610 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14611 break;
14612 case Expr::MLV_Valid:
14613 llvm_unreachable("did not take early return for MLV_Valid");
14617 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E)) {
14618 const Expr *Op = UnaryOp->getSubExpr()->IgnoreParens();
14619 if (UnaryOp->getOpcode() == UO_Imag &&
14620 !Op->getType()->isAnyComplexType()) {
14621 DiagID = diag::err_typecheck_lvalue_imag_not_modifiable_lvalue;
14622 NeedType = true;
14623 break;
14624 }
14625 }
14626
14627 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14628 break;
14629 }
14632 return S.RequireCompleteType(Loc, E->getType(),
14633 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14635 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14636 break;
14638 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14639 break;
14641 llvm_unreachable("readonly properties should be processed differently");
14643 DiagID = diag::err_readonly_message_assignment;
14644 break;
14646 DiagID = diag::err_no_subobject_property_setting;
14647 break;
14648 }
14649
14650 SourceRange Assign;
14651 if (Loc != OrigLoc)
14652 Assign = SourceRange(OrigLoc, OrigLoc);
14653 if (NeedType)
14654 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14655 else
14656 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14657 return true;
14658}
14659
14660static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14661 SourceLocation Loc,
14662 Sema &Sema) {
14664 return;
14666 return;
14667 if (Loc.isInvalid() || Loc.isMacroID())
14668 return;
14669 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14670 return;
14671
14672 // C / C++ fields
14673 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14674 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14675 if (ML && MR) {
14676 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14677 return;
14678 const ValueDecl *LHSDecl =
14680 const ValueDecl *RHSDecl =
14682 if (LHSDecl != RHSDecl)
14683 return;
14684 if (LHSDecl->getType().isVolatileQualified())
14685 return;
14686 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14687 if (RefTy->getPointeeType().isVolatileQualified())
14688 return;
14689
14690 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14691 }
14692
14693 // Objective-C instance variables
14694 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14695 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14696 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14697 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14698 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14699 if (RL && RR && RL->getDecl() == RR->getDecl())
14700 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14701 }
14702}
14703
14704// C99 6.5.16.1
14706 SourceLocation Loc,
14707 QualType CompoundType,
14708 BinaryOperatorKind Opc) {
14709 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14710
14711 // Verify that LHS is a modifiable lvalue, and emit error if not.
14712 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14713 return QualType();
14714
14715 QualType LHSType = LHSExpr->getType();
14716 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14717 CompoundType;
14718
14719 if (RHS.isUsable()) {
14720 // Even if this check fails don't return early to allow the best
14721 // possible error recovery and to allow any subsequent diagnostics to
14722 // work.
14723 const ValueDecl *Assignee = nullptr;
14724 bool ShowFullyQualifiedAssigneeName = false;
14725 // In simple cases describe what is being assigned to
14726 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14727 Assignee = DR->getDecl();
14728 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14729 Assignee = ME->getMemberDecl();
14730 ShowFullyQualifiedAssigneeName = true;
14731 }
14732
14734 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14735 ShowFullyQualifiedAssigneeName);
14736 }
14737
14738 // OpenCL v1.2 s6.1.1.1 p2:
14739 // The half data type can only be used to declare a pointer to a buffer that
14740 // contains half values
14741 if (getLangOpts().OpenCL &&
14742 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14743 LHSType->isHalfType()) {
14744 Diag(Loc, diag::err_opencl_half_load_store) << 1
14745 << LHSType.getUnqualifiedType();
14746 return QualType();
14747 }
14748
14749 // WebAssembly tables can't be used on RHS of an assignment expression.
14750 if (RHSType->isWebAssemblyTableType()) {
14751 Diag(Loc, diag::err_wasm_table_art) << 0;
14752 return QualType();
14753 }
14754
14755 AssignConvertType ConvTy;
14756 if (CompoundType.isNull()) {
14757 Expr *RHSCheck = RHS.get();
14758
14759 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14760
14761 QualType LHSTy(LHSType);
14762 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14763 if (RHS.isInvalid())
14764 return QualType();
14765 // Special case of NSObject attributes on c-style pointer types.
14767 ((Context.isObjCNSObjectType(LHSType) &&
14768 RHSType->isObjCObjectPointerType()) ||
14769 (Context.isObjCNSObjectType(RHSType) &&
14770 LHSType->isObjCObjectPointerType())))
14772
14773 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14774 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14775
14776 // If the RHS is a unary plus or minus, check to see if they = and + are
14777 // right next to each other. If so, the user may have typo'd "x =+ 4"
14778 // instead of "x += 4".
14779 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14780 RHSCheck = ICE->getSubExpr();
14781 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14782 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14783 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14784 // Only if the two operators are exactly adjacent.
14785 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14786 // And there is a space or other character before the subexpr of the
14787 // unary +/-. We don't want to warn on "x=-1".
14788 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14789 UO->getSubExpr()->getBeginLoc().isFileID()) {
14790 Diag(Loc, diag::warn_not_compound_assign)
14791 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14792 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14793 }
14794 }
14795
14796 if (IsAssignConvertCompatible(ConvTy)) {
14797 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14798 // Warn about retain cycles where a block captures the LHS, but
14799 // not if the LHS is a simple variable into which the block is
14800 // being stored...unless that variable can be captured by reference!
14801 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14802 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14803 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14804 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14805 }
14806
14807 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14809 // It is safe to assign a weak reference into a strong variable.
14810 // Although this code can still have problems:
14811 // id x = self.weakProp;
14812 // id y = self.weakProp;
14813 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14814 // paths through the function. This should be revisited if
14815 // -Wrepeated-use-of-weak is made flow-sensitive.
14816 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14817 // variable, which will be valid for the current autorelease scope.
14818 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14819 RHS.get()->getBeginLoc()))
14821
14822 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14823 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14824 }
14825 }
14826 } else {
14827 // Compound assignment "x += y"
14828 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14829 }
14830
14831 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14833 return QualType();
14834
14835 CheckForNullPointerDereference(*this, LHSExpr);
14836
14837 AssignedEntity AE{LHSExpr};
14838 checkAssignmentLifetime(*this, AE, RHS.get());
14839
14840 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14841 if (CompoundType.isNull()) {
14842 // C++2a [expr.ass]p5:
14843 // A simple-assignment whose left operand is of a volatile-qualified
14844 // type is deprecated unless the assignment is either a discarded-value
14845 // expression or an unevaluated operand
14846 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14847 }
14848 }
14849
14850 // C11 6.5.16p3: The type of an assignment expression is the type of the
14851 // left operand would have after lvalue conversion.
14852 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14853 // qualified type, the value has the unqualified version of the type of the
14854 // lvalue; additionally, if the lvalue has atomic type, the value has the
14855 // non-atomic version of the type of the lvalue.
14856 // C++ 5.17p1: the type of the assignment expression is that of its left
14857 // operand.
14858 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14859}
14860
14861// Scenarios to ignore if expression E is:
14862// 1. an explicit cast expression into void
14863// 2. a function call expression that returns void
14864static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14865 E = E->IgnoreParens();
14866
14867 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14868 if (CE->getCastKind() == CK_ToVoid) {
14869 return true;
14870 }
14871
14872 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14873 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14874 CE->getSubExpr()->getType()->isDependentType()) {
14875 return true;
14876 }
14877 }
14878
14879 if (const auto *CE = dyn_cast<CallExpr>(E))
14880 return CE->getCallReturnType(Context)->isVoidType();
14881 return false;
14882}
14883
14885 // No warnings in macros
14886 if (Loc.isMacroID())
14887 return;
14888
14889 // Don't warn in template instantiations.
14891 return;
14892
14893 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14894 // instead, skip more than needed, then call back into here with the
14895 // CommaVisitor in SemaStmt.cpp.
14896 // The listed locations are the initialization and increment portions
14897 // of a for loop. The additional checks are on the condition of
14898 // if statements, do/while loops, and for loops.
14899 if (getCurScope()->isControlScope())
14900 return;
14901
14902 // If there are multiple comma operators used together, get the RHS of the
14903 // of the comma operator as the LHS.
14904 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14905 if (BO->getOpcode() != BO_Comma)
14906 break;
14907 LHS = BO->getRHS();
14908 }
14909
14910 // Only allow some expressions on LHS to not warn.
14911 if (IgnoreCommaOperand(LHS, Context))
14912 return;
14913
14914 Diag(Loc, diag::warn_comma_operator);
14915 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14916 << LHS->getSourceRange()
14918 LangOpts.CPlusPlus ? "static_cast<void>("
14919 : "(void)(")
14920 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14921 ")");
14922}
14923
14924// C99 6.5.17
14926 SourceLocation Loc) {
14927 LHS = S.CheckPlaceholderExpr(LHS.get());
14928 RHS = S.CheckPlaceholderExpr(RHS.get());
14929 if (LHS.isInvalid() || RHS.isInvalid())
14930 return QualType();
14931
14932 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14933 // operands, but not unary promotions.
14934 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14935
14936 // So we treat the LHS as a ignored value, and in C++ we allow the
14937 // containing site to determine what should be done with the RHS.
14938 LHS = S.IgnoredValueConversions(LHS.get());
14939 if (LHS.isInvalid())
14940 return QualType();
14941
14942 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14943
14944 if (!S.getLangOpts().CPlusPlus) {
14946 if (RHS.isInvalid())
14947 return QualType();
14948 if (!RHS.get()->getType()->isVoidType())
14949 S.RequireCompleteType(Loc, RHS.get()->getType(),
14950 diag::err_incomplete_type);
14951 }
14952
14953 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14954 S.DiagnoseCommaOperator(LHS.get(), Loc);
14955
14956 return RHS.get()->getType();
14957}
14958
14959/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14960/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14963 ExprObjectKind &OK,
14964 SourceLocation OpLoc, bool IsInc,
14965 bool IsPrefix) {
14966 QualType ResType = Op->getType();
14967 // Atomic types can be used for increment / decrement where the non-atomic
14968 // versions can, so ignore the _Atomic() specifier for the purpose of
14969 // checking.
14970 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14971 ResType = ResAtomicType->getValueType();
14972
14973 assert(!ResType.isNull() && "no type for increment/decrement expression");
14974
14975 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14976 // Decrement of bool is not allowed.
14977 if (!IsInc) {
14978 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14979 return QualType();
14980 }
14981 // Increment of bool sets it to true, but is deprecated.
14982 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14983 : diag::warn_increment_bool)
14984 << Op->getSourceRange();
14985 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14986 // Error on enum increments and decrements in C++ mode
14987 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14988 return QualType();
14989 } else if (ResType->isRealType()) {
14990 // OK!
14991 } else if (ResType->isPointerType()) {
14992 // C99 6.5.2.4p2, 6.5.6p2
14993 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14994 return QualType();
14995 } else if (ResType->isOverflowBehaviorType()) {
14996 // OK!
14997 } else if (ResType->isObjCObjectPointerType()) {
14998 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14999 // Otherwise, we just need a complete type.
15000 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
15001 checkArithmeticOnObjCPointer(S, OpLoc, Op))
15002 return QualType();
15003 } else if (ResType->isAnyComplexType()) {
15004 // C99 does not support ++/-- on complex types, we allow as an extension.
15005 S.DiagCompat(OpLoc, diag_compat::increment_complex)
15006 << IsInc << Op->getSourceRange();
15007 } else if (ResType->isPlaceholderType()) {
15009 if (PR.isInvalid()) return QualType();
15010 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
15011 IsInc, IsPrefix);
15012 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
15013 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
15014 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
15015 (ResType->castAs<VectorType>()->getVectorKind() !=
15017 // The z vector extensions allow ++ and -- for non-bool vectors.
15018 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
15019 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
15020 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
15021 } else {
15022 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
15023 << ResType << int(IsInc) << Op->getSourceRange();
15024 return QualType();
15025 }
15026 // At this point, we know we have a real, complex or pointer type.
15027 // Now make sure the operand is a modifiable lvalue.
15028 if (CheckForModifiableLvalue(Op, OpLoc, S))
15029 return QualType();
15030 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
15031 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
15032 // An operand with volatile-qualified type is deprecated
15033 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
15034 << IsInc << ResType;
15035 }
15036 // In C++, a prefix increment is the same type as the operand. Otherwise
15037 // (in C or with postfix), the increment is the unqualified type of the
15038 // operand.
15039 if (IsPrefix && S.getLangOpts().CPlusPlus) {
15040 VK = VK_LValue;
15041 OK = Op->getObjectKind();
15042 return ResType;
15043 } else {
15044 VK = VK_PRValue;
15045 return ResType.getUnqualifiedType();
15046 }
15047}
15048
15049/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
15050/// This routine allows us to typecheck complex/recursive expressions
15051/// where the declaration is needed for type checking. We only need to
15052/// handle cases when the expression references a function designator
15053/// or is an lvalue. Here are some examples:
15054/// - &(x) => x
15055/// - &*****f => f for f a function designator.
15056/// - &s.xx => s
15057/// - &s.zz[1].yy -> s, if zz is an array
15058/// - *(x + 1) -> x, if x is an array
15059/// - &"123"[2] -> 0
15060/// - & __real__ x -> x
15061///
15062/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
15063/// members.
15065 switch (E->getStmtClass()) {
15066 case Stmt::DeclRefExprClass:
15067 return cast<DeclRefExpr>(E)->getDecl();
15068 case Stmt::MemberExprClass:
15069 // If this is an arrow operator, the address is an offset from
15070 // the base's value, so the object the base refers to is
15071 // irrelevant.
15072 if (cast<MemberExpr>(E)->isArrow())
15073 return nullptr;
15074 // Otherwise, the expression refers to a part of the base
15075 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
15076 case Stmt::ArraySubscriptExprClass: {
15077 // FIXME: This code shouldn't be necessary! We should catch the implicit
15078 // promotion of register arrays earlier.
15079 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
15080 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
15081 if (ICE->getSubExpr()->getType()->isArrayType())
15082 return getPrimaryDecl(ICE->getSubExpr());
15083 }
15084 return nullptr;
15085 }
15086 case Stmt::UnaryOperatorClass: {
15088
15089 switch(UO->getOpcode()) {
15090 case UO_Real:
15091 case UO_Imag:
15092 case UO_Extension:
15093 return getPrimaryDecl(UO->getSubExpr());
15094 default:
15095 return nullptr;
15096 }
15097 }
15098 case Stmt::ParenExprClass:
15099 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
15100 case Stmt::ImplicitCastExprClass:
15101 // If the result of an implicit cast is an l-value, we care about
15102 // the sub-expression; otherwise, the result here doesn't matter.
15103 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
15104 case Stmt::CXXUuidofExprClass:
15105 return cast<CXXUuidofExpr>(E)->getGuidDecl();
15106 default:
15107 return nullptr;
15108 }
15109}
15110
15111namespace {
15112enum {
15113 AO_Bit_Field = 0,
15114 AO_Vector_Element = 1,
15115 AO_Property_Expansion = 2,
15116 AO_Register_Variable = 3,
15117 AO_Matrix_Element = 4,
15118 AO_No_Error = 5
15119};
15120}
15121/// Diagnose invalid operand for address of operations.
15122///
15123/// \param Type The type of operand which cannot have its address taken.
15125 Expr *E, unsigned Type) {
15126 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
15127}
15128
15130 const Expr *Op,
15131 const CXXMethodDecl *MD) {
15132 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
15133
15134 if (Op != DRE)
15135 return Diag(OpLoc, diag::err_parens_pointer_member_function)
15136 << Op->getSourceRange();
15137
15138 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
15139 if (isa<CXXDestructorDecl>(MD))
15140 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
15141 << DRE->getSourceRange();
15142
15143 if (DRE->getQualifier())
15144 return false;
15145
15146 if (MD->getParent()->getName().empty())
15147 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15148 << DRE->getSourceRange();
15149
15150 SmallString<32> Str;
15151 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
15152 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15153 << DRE->getSourceRange()
15154 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
15155}
15156
15158 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
15159 if (PTy->getKind() == BuiltinType::Overload) {
15160 Expr *E = OrigOp.get()->IgnoreParens();
15161 if (!isa<OverloadExpr>(E)) {
15162 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
15163 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
15164 << OrigOp.get()->getSourceRange();
15165 return QualType();
15166 }
15167
15171 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15172 << OrigOp.get()->getSourceRange();
15173 return QualType();
15174 }
15175
15176 return Context.OverloadTy;
15177 }
15178
15179 if (PTy->getKind() == BuiltinType::UnknownAny)
15180 return Context.UnknownAnyTy;
15181
15182 if (PTy->getKind() == BuiltinType::BoundMember) {
15183 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15184 << OrigOp.get()->getSourceRange();
15185 return QualType();
15186 }
15187
15188 OrigOp = CheckPlaceholderExpr(OrigOp.get());
15189 if (OrigOp.isInvalid()) return QualType();
15190 }
15191
15192 if (OrigOp.get()->isTypeDependent())
15193 return Context.DependentTy;
15194
15195 assert(!OrigOp.get()->hasPlaceholderType());
15196
15197 // Make sure to ignore parentheses in subsequent checks
15198 Expr *op = OrigOp.get()->IgnoreParens();
15199
15200 // In OpenCL captures for blocks called as lambda functions
15201 // are located in the private address space. Blocks used in
15202 // enqueue_kernel can be located in a different address space
15203 // depending on a vendor implementation. Thus preventing
15204 // taking an address of the capture to avoid invalid AS casts.
15205 if (LangOpts.OpenCL) {
15206 auto* VarRef = dyn_cast<DeclRefExpr>(op);
15207 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15208 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
15209 return QualType();
15210 }
15211 }
15212
15213 if (getLangOpts().C99) {
15214 // Implement C99-only parts of addressof rules.
15215 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
15216 if (uOp->getOpcode() == UO_Deref)
15217 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15218 // (assuming the deref expression is valid).
15219 return uOp->getSubExpr()->getType();
15220 }
15221 // Technically, there should be a check for array subscript
15222 // expressions here, but the result of one is always an lvalue anyway.
15223 }
15224 ValueDecl *dcl = getPrimaryDecl(op);
15225
15226 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
15227 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15228 op->getBeginLoc()))
15229 return QualType();
15230
15232 unsigned AddressOfError = AO_No_Error;
15233
15234 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15235 bool IsError = isSFINAEContext();
15236 Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary
15237 : diag::ext_typecheck_addrof_temporary)
15238 << op->getType() << op->getSourceRange();
15239 if (IsError)
15240 return QualType();
15241 // Materialize the temporary as an lvalue so that we can take its address.
15242 OrigOp = op =
15243 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
15244 } else if (isa<ObjCSelectorExpr>(op)) {
15245 return Context.getPointerType(op->getType());
15246 } else if (lval == Expr::LV_MemberFunction) {
15247 // If it's an instance method, make a member pointer.
15248 // The expression must have exactly the form &A::foo.
15249
15250 // If the underlying expression isn't a decl ref, give up.
15251 if (!isa<DeclRefExpr>(op)) {
15252 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15253 << OrigOp.get()->getSourceRange();
15254 return QualType();
15255 }
15256 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
15258
15259 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15260 QualType MPTy = Context.getMemberPointerType(
15261 op->getType(), DRE->getQualifier(), MD->getParent());
15262
15263 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15264 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15265 // When pointer authentication is enabled, argument and return types of
15266 // vitual member functions must be complete. This is because vitrual
15267 // member function pointers are implemented using virtual dispatch
15268 // thunks and the thunks cannot be emitted if the argument or return
15269 // types are incomplete.
15270 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15271 SourceLocation DeclRefLoc,
15272 SourceLocation RetArgTypeLoc) {
15273 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
15274 Diag(DeclRefLoc,
15275 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15276 Diag(RetArgTypeLoc,
15277 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15278 << T;
15279 return true;
15280 }
15281 return false;
15282 };
15283 QualType RetTy = MD->getReturnType();
15284 bool IsIncomplete =
15285 !RetTy->isVoidType() &&
15286 ReturnOrParamTypeIsIncomplete(
15287 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15288 for (auto *PVD : MD->parameters())
15289 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15290 PVD->getBeginLoc());
15291 if (IsIncomplete)
15292 return QualType();
15293 }
15294
15295 // Under the MS ABI, lock down the inheritance model now.
15296 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15297 (void)isCompleteType(OpLoc, MPTy);
15298 return MPTy;
15299 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15300 // C99 6.5.3.2p1
15301 // The operand must be either an l-value or a function designator
15302 if (!op->getType()->isFunctionType()) {
15303 // Use a special diagnostic for loads from property references.
15304 if (isa<PseudoObjectExpr>(op)) {
15305 AddressOfError = AO_Property_Expansion;
15306 } else {
15307 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15308 << op->getType() << op->getSourceRange();
15309 return QualType();
15310 }
15311 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
15312 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
15313 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15314 }
15315
15316 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15317 // The operand cannot be a bit-field
15318 AddressOfError = AO_Bit_Field;
15319 } else if (op->getObjectKind() == OK_VectorComponent) {
15320 // The operand cannot be an element of a vector
15321 AddressOfError = AO_Vector_Element;
15322 } else if (op->getObjectKind() == OK_MatrixComponent) {
15323 // The operand cannot be an element of a matrix.
15324 AddressOfError = AO_Matrix_Element;
15325 } else if (dcl) { // C99 6.5.3.2p1
15326 // We have an lvalue with a decl. Make sure the decl is not declared
15327 // with the register storage-class specifier.
15328 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15329 // in C++ it is not error to take address of a register
15330 // variable (c++03 7.1.1P3)
15331 if (vd->getStorageClass() == SC_Register &&
15333 AddressOfError = AO_Register_Variable;
15334 }
15335 } else if (isa<MSPropertyDecl>(dcl)) {
15336 AddressOfError = AO_Property_Expansion;
15337 } else if (isa<FunctionTemplateDecl>(dcl)) {
15338 return Context.OverloadTy;
15339 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15340 // Okay: we can take the address of a field.
15341 // Could be a pointer to member, though, if there is an explicit
15342 // scope qualifier for the class.
15343
15344 // [C++26] [expr.prim.id.general]
15345 // If an id-expression E denotes a non-static non-type member
15346 // of some class C [...] and if E is a qualified-id, E is
15347 // not the un-parenthesized operand of the unary & operator [...]
15348 // the id-expression is transformed into a class member access expression.
15349 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
15350 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
15351 DeclContext *Ctx = dcl->getDeclContext();
15352 if (Ctx && Ctx->isRecord()) {
15353 if (dcl->getType()->isReferenceType()) {
15354 Diag(OpLoc,
15355 diag::err_cannot_form_pointer_to_member_of_reference_type)
15356 << dcl->getDeclName() << dcl->getType();
15357 return QualType();
15358 }
15359
15360 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15361 Ctx = Ctx->getParent();
15362
15363 QualType MPTy = Context.getMemberPointerType(
15364 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
15365 // Under the MS ABI, lock down the inheritance model now.
15366 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15367 (void)isCompleteType(OpLoc, MPTy);
15368 return MPTy;
15369 }
15370 }
15374 llvm_unreachable("Unknown/unexpected decl type");
15375 }
15376
15377 if (AddressOfError != AO_No_Error) {
15378 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15379 return QualType();
15380 }
15381
15382 if (lval == Expr::LV_IncompleteVoidType) {
15383 // Taking the address of a void variable is technically illegal, but we
15384 // allow it in cases which are otherwise valid.
15385 // Example: "extern void x; void* y = &x;".
15386 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15387 }
15388
15389 // If the operand has type "type", the result has type "pointer to type".
15390 if (op->getType()->isObjCObjectType())
15391 return Context.getObjCObjectPointerType(op->getType());
15392
15393 // Cannot take the address of WebAssembly references or tables.
15394 if (Context.getTargetInfo().getTriple().isWasm()) {
15395 QualType OpTy = op->getType();
15396 if (OpTy.isWebAssemblyReferenceType()) {
15397 Diag(OpLoc, diag::err_wasm_ca_reference)
15398 << 1 << OrigOp.get()->getSourceRange();
15399 return QualType();
15400 }
15401 if (OpTy->isWebAssemblyTableType()) {
15402 Diag(OpLoc, diag::err_wasm_table_pr)
15403 << 1 << OrigOp.get()->getSourceRange();
15404 return QualType();
15405 }
15406 }
15407
15408 CheckAddressOfPackedMember(op);
15409
15410 return Context.getPointerType(op->getType());
15411}
15412
15413static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15414 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15415 if (!DRE)
15416 return;
15417 const Decl *D = DRE->getDecl();
15418 if (!D)
15419 return;
15420 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15421 if (!Param)
15422 return;
15423 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15424 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15425 return;
15426 if (FunctionScopeInfo *FD = S.getCurFunction())
15427 FD->ModifiedNonNullParams.insert(Param);
15428}
15429
15430/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15432 SourceLocation OpLoc,
15433 bool IsAfterAmp = false) {
15434 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15435 if (ConvResult.isInvalid())
15436 return QualType();
15437 Op = ConvResult.get();
15438 QualType OpTy = Op->getType();
15440
15442 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15443 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15444 Op->getSourceRange());
15445 }
15446
15447 if (const PointerType *PT = OpTy->getAs<PointerType>())
15448 {
15449 Result = PT->getPointeeType();
15450 }
15451 else if (const ObjCObjectPointerType *OPT =
15453 Result = OPT->getPointeeType();
15454 else {
15456 if (PR.isInvalid()) return QualType();
15457 if (PR.get() != Op)
15458 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15459 }
15460
15461 if (Result.isNull()) {
15462 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15463 << OpTy << Op->getSourceRange();
15464 return QualType();
15465 }
15466
15467 if (Result->isVoidType()) {
15468 // C++ [expr.unary.op]p1:
15469 // [...] the expression to which [the unary * operator] is applied shall
15470 // be a pointer to an object type, or a pointer to a function type
15471 LangOptions LO = S.getLangOpts();
15472 if (LO.CPlusPlus)
15473 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15474 << OpTy << Op->getSourceRange();
15475 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15476 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15477 << OpTy << Op->getSourceRange();
15478 }
15479
15480 // Dereferences are usually l-values...
15481 VK = VK_LValue;
15482
15483 // ...except that certain expressions are never l-values in C.
15484 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15485 VK = VK_PRValue;
15486
15487 return Result;
15488}
15489
15490BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15492 switch (Kind) {
15493 default: llvm_unreachable("Unknown binop!");
15494 case tok::periodstar: Opc = BO_PtrMemD; break;
15495 case tok::arrowstar: Opc = BO_PtrMemI; break;
15496 case tok::star: Opc = BO_Mul; break;
15497 case tok::slash: Opc = BO_Div; break;
15498 case tok::percent: Opc = BO_Rem; break;
15499 case tok::plus: Opc = BO_Add; break;
15500 case tok::minus: Opc = BO_Sub; break;
15501 case tok::lessless: Opc = BO_Shl; break;
15502 case tok::greatergreater: Opc = BO_Shr; break;
15503 case tok::lessequal: Opc = BO_LE; break;
15504 case tok::less: Opc = BO_LT; break;
15505 case tok::greaterequal: Opc = BO_GE; break;
15506 case tok::greater: Opc = BO_GT; break;
15507 case tok::exclaimequal: Opc = BO_NE; break;
15508 case tok::equalequal: Opc = BO_EQ; break;
15509 case tok::spaceship: Opc = BO_Cmp; break;
15510 case tok::amp: Opc = BO_And; break;
15511 case tok::caret: Opc = BO_Xor; break;
15512 case tok::pipe: Opc = BO_Or; break;
15513 case tok::ampamp: Opc = BO_LAnd; break;
15514 case tok::pipepipe: Opc = BO_LOr; break;
15515 case tok::equal: Opc = BO_Assign; break;
15516 case tok::starequal: Opc = BO_MulAssign; break;
15517 case tok::slashequal: Opc = BO_DivAssign; break;
15518 case tok::percentequal: Opc = BO_RemAssign; break;
15519 case tok::plusequal: Opc = BO_AddAssign; break;
15520 case tok::minusequal: Opc = BO_SubAssign; break;
15521 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15522 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15523 case tok::ampequal: Opc = BO_AndAssign; break;
15524 case tok::caretequal: Opc = BO_XorAssign; break;
15525 case tok::pipeequal: Opc = BO_OrAssign; break;
15526 case tok::comma: Opc = BO_Comma; break;
15527 }
15528 return Opc;
15529}
15530
15532 tok::TokenKind Kind) {
15534 switch (Kind) {
15535 default: llvm_unreachable("Unknown unary op!");
15536 case tok::plusplus: Opc = UO_PreInc; break;
15537 case tok::minusminus: Opc = UO_PreDec; break;
15538 case tok::amp: Opc = UO_AddrOf; break;
15539 case tok::star: Opc = UO_Deref; break;
15540 case tok::plus: Opc = UO_Plus; break;
15541 case tok::minus: Opc = UO_Minus; break;
15542 case tok::tilde: Opc = UO_Not; break;
15543 case tok::exclaim: Opc = UO_LNot; break;
15544 case tok::kw___real: Opc = UO_Real; break;
15545 case tok::kw___imag: Opc = UO_Imag; break;
15546 case tok::kw___extension__: Opc = UO_Extension; break;
15547 }
15548 return Opc;
15549}
15550
15551const FieldDecl *
15553 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15554 // common for setters.
15555 // struct A {
15556 // int X;
15557 // -void setX(int X) { X = X; }
15558 // +void setX(int X) { this->X = X; }
15559 // };
15560
15561 // Only consider parameters for self assignment fixes.
15562 if (!isa<ParmVarDecl>(SelfAssigned))
15563 return nullptr;
15564 const auto *Method =
15565 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15566 if (!Method)
15567 return nullptr;
15568
15569 const CXXRecordDecl *Parent = Method->getParent();
15570 // In theory this is fixable if the lambda explicitly captures this, but
15571 // that's added complexity that's rarely going to be used.
15572 if (Parent->isLambda())
15573 return nullptr;
15574
15575 // FIXME: Use an actual Lookup operation instead of just traversing fields
15576 // in order to get base class fields.
15577 auto Field =
15578 llvm::find_if(Parent->fields(),
15579 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15580 return F->getDeclName() == Name;
15581 });
15582 return (Field != Parent->field_end()) ? *Field : nullptr;
15583}
15584
15585/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15586/// This warning suppressed in the event of macro expansions.
15587static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15588 SourceLocation OpLoc, bool IsBuiltin) {
15590 return;
15591 if (S.isUnevaluatedContext())
15592 return;
15593 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15594 return;
15595 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15596 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15597 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15598 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15599 if (!LHSDeclRef || !RHSDeclRef ||
15600 LHSDeclRef->getLocation().isMacroID() ||
15601 RHSDeclRef->getLocation().isMacroID())
15602 return;
15603 const ValueDecl *LHSDecl =
15604 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15605 const ValueDecl *RHSDecl =
15606 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15607 if (LHSDecl != RHSDecl)
15608 return;
15609 if (LHSDecl->getType().isVolatileQualified())
15610 return;
15611 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15612 if (RefTy->getPointeeType().isVolatileQualified())
15613 return;
15614
15615 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15616 : diag::warn_self_assignment_overloaded)
15617 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15618 << RHSExpr->getSourceRange();
15619 if (const FieldDecl *SelfAssignField =
15621 Diag << 1 << SelfAssignField
15622 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15623 else
15624 Diag << 0;
15625}
15626
15627/// Check if a bitwise-& is performed on an Objective-C pointer. This
15628/// is usually indicative of introspection within the Objective-C pointer.
15630 SourceLocation OpLoc) {
15631 if (!S.getLangOpts().ObjC)
15632 return;
15633
15634 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15635 const Expr *LHS = L.get();
15636 const Expr *RHS = R.get();
15637
15639 ObjCPointerExpr = LHS;
15640 OtherExpr = RHS;
15641 }
15642 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15643 ObjCPointerExpr = RHS;
15644 OtherExpr = LHS;
15645 }
15646
15647 // This warning is deliberately made very specific to reduce false
15648 // positives with logic that uses '&' for hashing. This logic mainly
15649 // looks for code trying to introspect into tagged pointers, which
15650 // code should generally never do.
15651 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15652 unsigned Diag = diag::warn_objc_pointer_masking;
15653 // Determine if we are introspecting the result of performSelectorXXX.
15654 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15655 // Special case messages to -performSelector and friends, which
15656 // can return non-pointer values boxed in a pointer value.
15657 // Some clients may wish to silence warnings in this subcase.
15658 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15659 Selector S = ME->getSelector();
15660 StringRef SelArg0 = S.getNameForSlot(0);
15661 if (SelArg0.starts_with("performSelector"))
15662 Diag = diag::warn_objc_pointer_masking_performSelector;
15663 }
15664
15665 S.Diag(OpLoc, Diag)
15666 << ObjCPointerExpr->getSourceRange();
15667 }
15668}
15669
15670// This helper function promotes a binary operator's operands (which are of a
15671// half vector type) to a vector of floats and then truncates the result to
15672// a vector of either half or short.
15674 BinaryOperatorKind Opc, QualType ResultTy,
15676 bool IsCompAssign, SourceLocation OpLoc,
15677 FPOptionsOverride FPFeatures) {
15678 auto &Context = S.getASTContext();
15679 assert((isVector(ResultTy, Context.HalfTy) ||
15680 isVector(ResultTy, Context.ShortTy)) &&
15681 "Result must be a vector of half or short");
15682 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15683 isVector(RHS.get()->getType(), Context.HalfTy) &&
15684 "both operands expected to be a half vector");
15685
15686 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15687 QualType BinOpResTy = RHS.get()->getType();
15688
15689 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15690 // change BinOpResTy to a vector of ints.
15691 if (isVector(ResultTy, Context.ShortTy))
15692 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15693
15694 if (IsCompAssign)
15695 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15696 ResultTy, VK, OK, OpLoc, FPFeatures,
15697 BinOpResTy, BinOpResTy);
15698
15699 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15700 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15701 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15702 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15703}
15704
15705/// Returns true if conversion between vectors of halfs and vectors of floats
15706/// is needed.
15707static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15708 QualType ResultTy, Expr *E0,
15709 Expr *E1 = nullptr) {
15710 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType)
15711 return false;
15712
15713 // The conversion truncates the result to a half/short vector, so it shouldn't
15714 // apply when the result is not that type (e.g. HLSL comparisons).
15715 if (ResultTy->isVectorType() && !isVector(ResultTy, Ctx.HalfTy) &&
15716 !isVector(ResultTy, Ctx.ShortTy))
15717 return false;
15718
15719 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15720 QualType Ty = E->IgnoreImplicit()->getType();
15721
15722 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15723 // to vectors of floats. Although the element type of the vectors is __fp16,
15724 // the vectors shouldn't be treated as storage-only types. See the
15725 // discussion here: https://reviews.llvm.org/rG825235c140e7
15726 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15727 if (VT->getVectorKind() == VectorKind::Neon)
15728 return false;
15729 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15730 }
15731 return false;
15732 };
15733
15734 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15735}
15736
15738 BinaryOperatorKind Opc, Expr *LHSExpr,
15739 Expr *RHSExpr, bool ForFoldExpression) {
15740 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15741 // The syntax only allows initializer lists on the RHS of assignment,
15742 // so we don't need to worry about accepting invalid code for
15743 // non-assignment operators.
15744 // C++11 5.17p9:
15745 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15746 // of x = {} is x = T().
15748 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15749 InitializedEntity Entity =
15751 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15752 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15753 if (Init.isInvalid())
15754 return Init;
15755 RHSExpr = Init.get();
15756 }
15757
15758 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15759 QualType ResultTy; // Result type of the binary operator.
15760 // The following two variables are used for compound assignment operators
15761 QualType CompLHSTy; // Type of LHS after promotions for computation
15762 QualType CompResultTy; // Type of computation result
15765 bool ConvertHalfVec = false;
15766
15767 if (!LHS.isUsable() || !RHS.isUsable())
15768 return ExprError();
15769
15770 if (getLangOpts().OpenCL) {
15771 QualType LHSTy = LHSExpr->getType();
15772 QualType RHSTy = RHSExpr->getType();
15773 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15774 // the ATOMIC_VAR_INIT macro.
15775 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15776 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15777 if (BO_Assign == Opc)
15778 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15779 else
15780 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15781 return ExprError();
15782 }
15783
15784 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15785 // only with a builtin functions and therefore should be disallowed here.
15786 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15787 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15788 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15789 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15790 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15791 return ExprError();
15792 }
15793 }
15794
15795 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15796 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15797
15798 switch (Opc) {
15799 case BO_Assign:
15800 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15801 if (getLangOpts().CPlusPlus &&
15802 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15803 VK = LHS.get()->getValueKind();
15804 OK = LHS.get()->getObjectKind();
15805 }
15806 if (!ResultTy.isNull()) {
15807 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15808 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15809
15810 // Avoid copying a block to the heap if the block is assigned to a local
15811 // auto variable that is declared in the same scope as the block. This
15812 // optimization is unsafe if the local variable is declared in an outer
15813 // scope. For example:
15814 //
15815 // BlockTy b;
15816 // {
15817 // b = ^{...};
15818 // }
15819 // // It is unsafe to invoke the block here if it wasn't copied to the
15820 // // heap.
15821 // b();
15822
15823 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15824 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15825 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15826 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15827 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15828
15830 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15832 }
15833 RecordModifiableNonNullParam(*this, LHS.get());
15834 break;
15835 case BO_PtrMemD:
15836 case BO_PtrMemI:
15837 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15838 Opc == BO_PtrMemI);
15839 break;
15840 case BO_Mul:
15841 case BO_Div:
15842 ConvertHalfVec = true;
15843 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15844 break;
15845 case BO_Rem:
15846 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15847 break;
15848 case BO_Add:
15849 ConvertHalfVec = true;
15850 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15851 break;
15852 case BO_Sub:
15853 ConvertHalfVec = true;
15854 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15855 break;
15856 case BO_Shl:
15857 case BO_Shr:
15858 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15859 break;
15860 case BO_LE:
15861 case BO_LT:
15862 case BO_GE:
15863 case BO_GT:
15864 ConvertHalfVec = true;
15865 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15866
15867 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15868 !ForFoldExpression && BI && BI->isComparisonOp())
15869 Diag(OpLoc, diag::warn_consecutive_comparison)
15870 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15871
15872 break;
15873 case BO_EQ:
15874 case BO_NE:
15875 ConvertHalfVec = true;
15876 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15877 break;
15878 case BO_Cmp:
15879 ConvertHalfVec = true;
15880 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15881 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15882 break;
15883 case BO_And:
15884 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15885 [[fallthrough]];
15886 case BO_Xor:
15887 case BO_Or:
15888 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15889 break;
15890 case BO_LAnd:
15891 case BO_LOr:
15892 ConvertHalfVec = true;
15893 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15894 break;
15895 case BO_MulAssign:
15896 case BO_DivAssign:
15897 ConvertHalfVec = true;
15898 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15899 CompLHSTy = CompResultTy;
15900 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15901 ResultTy =
15902 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15903 break;
15904 case BO_RemAssign:
15905 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15906 CompLHSTy = CompResultTy;
15907 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15908 ResultTy =
15909 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15910 break;
15911 case BO_AddAssign:
15912 ConvertHalfVec = true;
15913 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15914 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15915 ResultTy =
15916 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15917 break;
15918 case BO_SubAssign:
15919 ConvertHalfVec = true;
15920 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15921 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15922 ResultTy =
15923 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15924 break;
15925 case BO_ShlAssign:
15926 case BO_ShrAssign:
15927 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15928 CompLHSTy = CompResultTy;
15929 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15930 ResultTy =
15931 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15932 break;
15933 case BO_AndAssign:
15934 case BO_OrAssign: // fallthrough
15935 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15936 [[fallthrough]];
15937 case BO_XorAssign:
15938 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15939 CompLHSTy = CompResultTy;
15940 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15941 ResultTy =
15942 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15943 break;
15944 case BO_Comma:
15945 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15946 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15947 VK = RHS.get()->getValueKind();
15948 OK = RHS.get()->getObjectKind();
15949 }
15950 break;
15951 }
15952 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15953 return ExprError();
15954
15955 // Some of the binary operations require promoting operands of half vector to
15956 // float vectors and truncating the result back to half vector. For now, we do
15957 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15958 // arm64).
15959 assert(
15960 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15961 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15962 "both sides are half vectors or neither sides are");
15963 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, ResultTy,
15964 LHS.get(), RHS.get());
15965
15966 // Check for array bounds violations for both sides of the BinaryOperator
15967 CheckArrayAccess(LHS.get());
15968 CheckArrayAccess(RHS.get());
15969
15970 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15971 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15972 &Context.Idents.get("object_setClass"),
15974 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15975 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15976 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15978 "object_setClass(")
15979 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15980 ",")
15981 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15982 }
15983 else
15984 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15985 }
15986 else if (const ObjCIvarRefExpr *OIRE =
15987 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15988 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15989
15990 // Opc is not a compound assignment if CompResultTy is null.
15991 if (CompResultTy.isNull()) {
15992 if (ConvertHalfVec)
15993 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15994 OpLoc, CurFPFeatureOverrides());
15995 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15996 VK, OK, OpLoc, CurFPFeatureOverrides());
15997 }
15998
15999 // Handle compound assignments.
16000 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
16002 VK = VK_LValue;
16003 OK = LHS.get()->getObjectKind();
16004 }
16005
16006 // The LHS is not converted to the result type for fixed-point compound
16007 // assignment as the common type is computed on demand. Reset the CompLHSTy
16008 // to the LHS type we would have gotten after unary conversions.
16009 if (CompResultTy->isFixedPointType())
16010 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
16011
16012 if (ConvertHalfVec)
16013 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
16014 OpLoc, CurFPFeatureOverrides());
16015
16017 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
16018 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
16019}
16020
16021/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
16022/// operators are mixed in a way that suggests that the programmer forgot that
16023/// comparison operators have higher precedence. The most typical example of
16024/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
16026 SourceLocation OpLoc, Expr *LHSExpr,
16027 Expr *RHSExpr) {
16028 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
16029 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
16030
16031 // Check that one of the sides is a comparison operator and the other isn't.
16032 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
16033 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
16034 if (isLeftComp == isRightComp)
16035 return;
16036
16037 // Bitwise operations are sometimes used as eager logical ops.
16038 // Don't diagnose this.
16039 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
16040 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
16041 if (isLeftBitwise || isRightBitwise)
16042 return;
16043
16044 SourceRange DiagRange = isLeftComp
16045 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
16046 : SourceRange(OpLoc, RHSExpr->getEndLoc());
16047 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
16048 SourceRange ParensRange =
16049 isLeftComp
16050 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
16051 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
16052
16053 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
16054 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
16055 SuggestParentheses(Self, OpLoc,
16056 Self.PDiag(diag::note_precedence_silence) << OpStr,
16057 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
16058 SuggestParentheses(Self, OpLoc,
16059 Self.PDiag(diag::note_precedence_bitwise_first)
16061 ParensRange);
16062}
16063
16064/// It accepts a '&&' expr that is inside a '||' one.
16065/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
16066/// in parentheses.
16067static void
16069 BinaryOperator *Bop) {
16070 assert(Bop->getOpcode() == BO_LAnd);
16071 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
16072 << Bop->getSourceRange() << OpLoc;
16074 Self.PDiag(diag::note_precedence_silence)
16075 << Bop->getOpcodeStr(),
16076 Bop->getSourceRange());
16077}
16078
16079/// Look for '&&' in the left hand of a '||' expr.
16081 Expr *LHSExpr, Expr *RHSExpr) {
16082 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
16083 if (Bop->getOpcode() == BO_LAnd) {
16084 // If it's "string_literal && a || b" don't warn since the precedence
16085 // doesn't matter.
16086 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
16087 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
16088 } else if (Bop->getOpcode() == BO_LOr) {
16089 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
16090 // If it's "a || b && string_literal || c" we didn't warn earlier for
16091 // "a || b && string_literal", but warn now.
16092 if (RBop->getOpcode() == BO_LAnd &&
16093 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
16094 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
16095 }
16096 }
16097 }
16098}
16099
16100/// Look for '&&' in the right hand of a '||' expr.
16102 Expr *LHSExpr, Expr *RHSExpr) {
16103 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
16104 if (Bop->getOpcode() == BO_LAnd) {
16105 // If it's "a || b && string_literal" don't warn since the precedence
16106 // doesn't matter.
16107 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
16108 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
16109 }
16110 }
16111}
16112
16113/// Look for bitwise op in the left or right hand of a bitwise op with
16114/// lower precedence and emit a diagnostic together with a fixit hint that wraps
16115/// the '&' expression in parentheses.
16117 SourceLocation OpLoc, Expr *SubExpr) {
16118 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
16119 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
16120 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
16121 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
16122 << Bop->getSourceRange() << OpLoc;
16123 SuggestParentheses(S, Bop->getOperatorLoc(),
16124 S.PDiag(diag::note_precedence_silence)
16125 << Bop->getOpcodeStr(),
16126 Bop->getSourceRange());
16127 }
16128 }
16129}
16130
16132 Expr *SubExpr, StringRef Shift) {
16133 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
16134 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
16135 StringRef Op = Bop->getOpcodeStr();
16136 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
16137 << Bop->getSourceRange() << OpLoc << Shift << Op;
16138 SuggestParentheses(S, Bop->getOperatorLoc(),
16139 S.PDiag(diag::note_precedence_silence) << Op,
16140 Bop->getSourceRange());
16141 }
16142 }
16143}
16144
16146 Expr *LHSExpr, Expr *RHSExpr) {
16147 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
16148 if (!OCE)
16149 return;
16150
16151 FunctionDecl *FD = OCE->getDirectCallee();
16152 if (!FD || !FD->isOverloadedOperator())
16153 return;
16154
16156 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
16157 return;
16158
16159 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
16160 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
16161 << (Kind == OO_LessLess);
16163 S.PDiag(diag::note_precedence_silence)
16164 << (Kind == OO_LessLess ? "<<" : ">>"),
16165 OCE->getSourceRange());
16167 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
16168 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
16169}
16170
16171/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
16172/// precedence.
16174 SourceLocation OpLoc, Expr *LHSExpr,
16175 Expr *RHSExpr){
16176 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
16178 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
16179
16180 // Diagnose "arg1 & arg2 | arg3"
16181 if ((Opc == BO_Or || Opc == BO_Xor) &&
16182 !OpLoc.isMacroID()/* Don't warn in macros. */) {
16183 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
16184 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
16185 }
16186
16187 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16188 // We don't warn for 'assert(a || b && "bad")' since this is safe.
16189 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
16190 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
16191 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
16192 }
16193
16194 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
16195 || Opc == BO_Shr) {
16196 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
16197 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
16198 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
16199 }
16200
16201 // Warn on overloaded shift operators and comparisons, such as:
16202 // cout << 5 == 4;
16204 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
16205}
16206
16208 tok::TokenKind Kind,
16209 Expr *LHSExpr, Expr *RHSExpr) {
16210 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16211 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16212 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16213
16214 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16215 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
16216
16220
16221 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
16222 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
16223
16224 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
16225}
16226
16228 UnresolvedSetImpl &Functions) {
16230 if (OverOp != OO_None && OverOp != OO_Equal)
16231 LookupOverloadedOperatorName(OverOp, S, Functions);
16232
16233 // In C++20 onwards, we may have a second operator to look up.
16234 if (getLangOpts().CPlusPlus20) {
16236 LookupOverloadedOperatorName(ExtraOp, S, Functions);
16237 }
16238}
16239
16240/// Build an overloaded binary operator expression in the given scope.
16243 Expr *LHS, Expr *RHS) {
16244 switch (Opc) {
16245 case BO_Assign:
16246 // In the non-overloaded case, we warn about self-assignment (x = x) for
16247 // both simple assignment and certain compound assignments where algebra
16248 // tells us the operation yields a constant result. When the operator is
16249 // overloaded, we can't do the latter because we don't want to assume that
16250 // those algebraic identities still apply; for example, a path-building
16251 // library might use operator/= to append paths. But it's still reasonable
16252 // to assume that simple assignment is just moving/copying values around
16253 // and so self-assignment is likely a bug.
16254 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
16255 [[fallthrough]];
16256 case BO_DivAssign:
16257 case BO_RemAssign:
16258 case BO_SubAssign:
16259 case BO_AndAssign:
16260 case BO_OrAssign:
16261 case BO_XorAssign:
16262 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
16263 break;
16264 default:
16265 break;
16266 }
16267
16268 // Find all of the overloaded operators visible from this point.
16269 UnresolvedSet<16> Functions;
16270 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
16271
16272 // Build the (potentially-overloaded, potentially-dependent)
16273 // binary operation.
16274 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16275}
16276
16278 BinaryOperatorKind Opc, Expr *LHSExpr,
16279 Expr *RHSExpr, bool ForFoldExpression) {
16280 if (!LHSExpr || !RHSExpr)
16281 return ExprError();
16282
16283 // We want to end up calling one of SemaPseudoObject::checkAssignment
16284 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16285 // both expressions are overloadable or either is type-dependent),
16286 // or CreateBuiltinBinOp (in any other case). We also want to get
16287 // any placeholder types out of the way.
16288
16289 // Handle pseudo-objects in the LHS.
16290 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16291 // Assignments with a pseudo-object l-value need special analysis.
16292 if (pty->getKind() == BuiltinType::PseudoObject &&
16294 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16295
16296 // Don't resolve overloads if the other type is overloadable.
16297 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16298 // We can't actually test that if we still have a placeholder,
16299 // though. Fortunately, none of the exceptions we see in that
16300 // code below are valid when the LHS is an overload set. Note
16301 // that an overload set can be dependently-typed, but it never
16302 // instantiates to having an overloadable type.
16303 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16304 if (resolvedRHS.isInvalid()) return ExprError();
16305 RHSExpr = resolvedRHS.get();
16306
16307 if (RHSExpr->isTypeDependent() ||
16308 RHSExpr->getType()->isOverloadableType())
16309 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16310 }
16311
16312 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16313 // template, diagnose the missing 'template' keyword instead of diagnosing
16314 // an invalid use of a bound member function.
16315 //
16316 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16317 // to C++1z [over.over]/1.4, but we already checked for that case above.
16318 if (Opc == BO_LT && inTemplateInstantiation() &&
16319 (pty->getKind() == BuiltinType::BoundMember ||
16320 pty->getKind() == BuiltinType::Overload)) {
16321 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16322 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16323 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16324 return isa<FunctionTemplateDecl>(ND);
16325 })) {
16326 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16327 : OE->getNameLoc(),
16328 diag::err_template_kw_missing)
16329 << OE->getName().getAsIdentifierInfo();
16330 return ExprError();
16331 }
16332 }
16333
16334 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16335 if (LHS.isInvalid()) return ExprError();
16336 LHSExpr = LHS.get();
16337 }
16338
16339 // Handle pseudo-objects in the RHS.
16340 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16341 // An overload in the RHS can potentially be resolved by the type
16342 // being assigned to.
16343 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16344 if (getLangOpts().CPlusPlus &&
16345 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16346 LHSExpr->getType()->isOverloadableType()))
16347 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16348
16349 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16350 ForFoldExpression);
16351 }
16352
16353 // Don't resolve overloads if the other type is overloadable.
16354 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16355 LHSExpr->getType()->isOverloadableType())
16356 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16357
16358 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16359 if (!resolvedRHS.isUsable()) return ExprError();
16360 RHSExpr = resolvedRHS.get();
16361 }
16362
16363 if (getLangOpts().HLSL) {
16364 if (LHSExpr->getType()->isHLSLResourceRecord() ||
16365 LHSExpr->getType()->isHLSLResourceRecordArray()) {
16366 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
16367 return ExprError();
16368 } else if (RHSExpr->getType()->isHLSLResourceRecord()) {
16369 std::optional<ExprResult> ConvRHS =
16371 if (ConvRHS && Context.hasSameUnqualifiedType(
16372 LHSExpr->getType(), ConvRHS->get()->getType())) {
16373 assert(!ConvRHS->isInvalid());
16374 RHSExpr = ConvRHS->get();
16375 }
16376 }
16377 }
16378
16379 if (getLangOpts().CPlusPlus) {
16380 bool CanOverloadBinOp =
16381 !getLangOpts().HLSL ||
16382 HLSL().canHaveOverloadedBinOp(LHSExpr->getType(), Opc) ||
16383 HLSL().canHaveOverloadedBinOp(RHSExpr->getType(), Opc);
16384 bool TypeDependent =
16385 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16386 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16387 RHSExpr->getType()->isOverloadableType();
16388 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16389 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16390 }
16391
16392 if (getLangOpts().RecoveryAST &&
16393 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16394 assert(!getLangOpts().CPlusPlus);
16395 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16396 "Should only occur in error-recovery path.");
16398 // C [6.15.16] p3:
16399 // An assignment expression has the value of the left operand after the
16400 // assignment, but is not an lvalue.
16402 Context, LHSExpr, RHSExpr, Opc,
16404 OpLoc, CurFPFeatureOverrides());
16405 QualType ResultType;
16406 switch (Opc) {
16407 case BO_Assign:
16408 ResultType = LHSExpr->getType().getUnqualifiedType();
16409 break;
16410 case BO_LT:
16411 case BO_GT:
16412 case BO_LE:
16413 case BO_GE:
16414 case BO_EQ:
16415 case BO_NE:
16416 case BO_LAnd:
16417 case BO_LOr:
16418 // These operators have a fixed result type regardless of operands.
16419 ResultType = Context.IntTy;
16420 break;
16421 case BO_Comma:
16422 ResultType = RHSExpr->getType();
16423 break;
16424 default:
16425 ResultType = Context.DependentTy;
16426 break;
16427 }
16428 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16429 VK_PRValue, OK_Ordinary, OpLoc,
16431 }
16432
16433 // Build a built-in binary operation.
16434 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16435}
16436
16438 if (T.isNull() || T->isDependentType())
16439 return false;
16440
16441 if (!Ctx.isPromotableIntegerType(T))
16442 return true;
16443
16444 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16445}
16446
16448 UnaryOperatorKind Opc, Expr *InputExpr,
16449 bool IsAfterAmp) {
16450 ExprResult Input = InputExpr;
16453 QualType resultType;
16454 bool CanOverflow = false;
16455
16456 bool ConvertHalfVec = false;
16457 if (getLangOpts().OpenCL) {
16458 QualType Ty = InputExpr->getType();
16459 // The only legal unary operation for atomics is '&'.
16460 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16461 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16462 // only with a builtin functions and therefore should be disallowed here.
16463 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16464 || Ty->isBlockPointerType())) {
16465 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16466 << InputExpr->getType()
16467 << Input.get()->getSourceRange());
16468 }
16469 }
16470
16471 if (getLangOpts().HLSL && OpLoc.isValid()) {
16472 if (Opc == UO_AddrOf)
16473 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16474 if (Opc == UO_Deref)
16475 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16476 }
16477
16478 if (InputExpr->isTypeDependent() &&
16479 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
16480 resultType = Context.DependentTy;
16481 } else {
16482 switch (Opc) {
16483 case UO_PreInc:
16484 case UO_PreDec:
16485 case UO_PostInc:
16486 case UO_PostDec:
16487 resultType =
16488 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
16489 Opc == UO_PreInc || Opc == UO_PostInc,
16490 Opc == UO_PreInc || Opc == UO_PreDec);
16491 CanOverflow = isOverflowingIntegerType(Context, resultType);
16492 break;
16493 case UO_AddrOf:
16494 resultType = CheckAddressOfOperand(Input, OpLoc);
16495 CheckAddressOfNoDeref(InputExpr);
16496 RecordModifiableNonNullParam(*this, InputExpr);
16497 break;
16498 case UO_Deref: {
16500 if (Input.isInvalid())
16501 return ExprError();
16502 resultType =
16503 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16504 break;
16505 }
16506 case UO_Plus:
16507 case UO_Minus:
16508 CanOverflow = Opc == UO_Minus &&
16510 Input = UsualUnaryConversions(Input.get());
16511 if (Input.isInvalid())
16512 return ExprError();
16513 // Unary plus and minus require promoting an operand of half vector to a
16514 // float vector and truncating the result back to a half vector. For now,
16515 // we do this only when HalfArgsAndReturns is set (that is, when the
16516 // target is arm or arm64).
16517 ConvertHalfVec = needsConversionOfHalfVec(
16518 true, Context, Input.get()->getType(), Input.get());
16519
16520 // If the operand is a half vector, promote it to a float vector.
16521 if (ConvertHalfVec)
16522 Input = convertVector(Input.get(), Context.FloatTy, *this);
16523 resultType = Input.get()->getType();
16524 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16525 break;
16526 else if (resultType->isVectorType() &&
16527 // The z vector extensions don't allow + or - with bool vectors.
16528 (!Context.getLangOpts().ZVector ||
16529 resultType->castAs<VectorType>()->getVectorKind() !=
16531 break;
16532 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16533 break;
16534 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16535 Opc == UO_Plus && resultType->isPointerType())
16536 break;
16537
16538 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16539 << resultType << Input.get()->getSourceRange());
16540
16541 case UO_Not: // bitwise complement
16542 Input = UsualUnaryConversions(Input.get());
16543 if (Input.isInvalid())
16544 return ExprError();
16545 resultType = Input.get()->getType();
16546 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16547 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16548 // C99 does not support '~' for complex conjugation.
16549 Diag(OpLoc, diag::ext_integer_complement_complex)
16550 << resultType << Input.get()->getSourceRange();
16551 else if (resultType->hasIntegerRepresentation())
16552 break;
16553 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16554 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16555 // on vector float types.
16556 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16557 if (!T->isIntegerType())
16558 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16559 << resultType << Input.get()->getSourceRange());
16560 } else {
16561 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16562 << resultType << Input.get()->getSourceRange());
16563 }
16564 break;
16565
16566 case UO_LNot: // logical negation
16567 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16569 if (Input.isInvalid())
16570 return ExprError();
16571 resultType = Input.get()->getType();
16572
16573 // Though we still have to promote half FP to float...
16574 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16575 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16576 .get();
16577 resultType = Context.FloatTy;
16578 }
16579
16580 // WebAsembly tables can't be used in unary expressions.
16581 if (resultType->isPointerType() &&
16583 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16584 << resultType << Input.get()->getSourceRange());
16585 }
16586
16587 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16588 // C99 6.5.3.3p1: ok, fallthrough;
16589 if (Context.getLangOpts().CPlusPlus) {
16590 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16591 // operand contextually converted to bool.
16592 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16593 ScalarTypeToBooleanCastKind(resultType));
16594 } else if (Context.getLangOpts().OpenCL &&
16595 Context.getLangOpts().OpenCLVersion < 120) {
16596 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16597 // operate on scalar float types.
16598 if (!resultType->isIntegerType() && !resultType->isPointerType())
16599 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16600 << resultType << Input.get()->getSourceRange());
16601 }
16602 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16603 !resultType->hasBooleanRepresentation()) {
16604 // HLSL unary logical 'not' behaves like C++, which states that the
16605 // operand is converted to bool and the result is bool, however HLSL
16606 // extends this property to vectors.
16607 const VectorType *VTy = resultType->castAs<VectorType>();
16608 resultType =
16609 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16610
16611 Input = ImpCastExprToType(
16612 Input.get(), resultType,
16614 .get();
16615 break;
16616 } else if (resultType->isExtVectorType()) {
16617 if (Context.getLangOpts().OpenCL &&
16618 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16619 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16620 // operate on vector float types.
16621 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16622 if (!T->isIntegerType())
16623 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16624 << resultType << Input.get()->getSourceRange());
16625 }
16626 // Vector logical not returns the signed variant of the operand type.
16627 resultType = GetSignedVectorType(resultType);
16628 break;
16629 } else if (Context.getLangOpts().CPlusPlus &&
16630 resultType->isVectorType()) {
16631 const VectorType *VTy = resultType->castAs<VectorType>();
16632 if (VTy->getVectorKind() != VectorKind::Generic)
16633 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16634 << resultType << Input.get()->getSourceRange());
16635
16636 // Vector logical not returns the signed variant of the operand type.
16637 resultType = GetSignedVectorType(resultType);
16638 break;
16639 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16640 resultType = Context.getLogicalOperationType();
16641 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(InputExpr);
16642 break;
16643 } else {
16644 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16645 << resultType << Input.get()->getSourceRange());
16646 }
16647
16648 // LNot always has type int. C99 6.5.3.3p5.
16649 // In C++, it's bool. C++ 5.3.1p8
16650 resultType = Context.getLogicalOperationType();
16651 break;
16652 case UO_Real:
16653 case UO_Imag:
16654 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16655 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16656 // ordinary complex l-values to ordinary l-values and all other values to
16657 // r-values.
16658 if (Input.isInvalid())
16659 return ExprError();
16660 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16661 if (Input.get()->isGLValue() &&
16662 Input.get()->getObjectKind() == OK_Ordinary)
16663 VK = Input.get()->getValueKind();
16664 } else if (!getLangOpts().CPlusPlus) {
16665 // In C, a volatile scalar is read by __imag. In C++, it is not.
16666 Input = DefaultLvalueConversion(Input.get());
16667 }
16668 break;
16669 case UO_Extension:
16670 resultType = Input.get()->getType();
16671 VK = Input.get()->getValueKind();
16672 OK = Input.get()->getObjectKind();
16673 break;
16674 case UO_Coawait:
16675 // It's unnecessary to represent the pass-through operator co_await in the
16676 // AST; just return the input expression instead.
16677 assert(!Input.get()->getType()->isDependentType() &&
16678 "the co_await expression must be non-dependant before "
16679 "building operator co_await");
16680 return Input;
16681 }
16682 }
16683 if (resultType.isNull() || Input.isInvalid())
16684 return ExprError();
16685
16686 // Check for array bounds violations in the operand of the UnaryOperator,
16687 // except for the '*' and '&' operators that have to be handled specially
16688 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16689 // that are explicitly defined as valid by the standard).
16690 if (Opc != UO_AddrOf && Opc != UO_Deref)
16691 CheckArrayAccess(Input.get());
16692
16693 auto *UO =
16694 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16695 OpLoc, CanOverflow, CurFPFeatureOverrides());
16696
16697 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16698 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16700 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16701
16702 // Convert the result back to a half vector.
16703 if (ConvertHalfVec)
16704 return convertVector(UO, Context.HalfTy, *this);
16705 return UO;
16706}
16707
16709 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16710 if (!DRE->getQualifier())
16711 return false;
16712
16713 ValueDecl *VD = DRE->getDecl();
16714 if (!VD->isCXXClassMember())
16715 return false;
16716
16718 return true;
16719 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16720 return Method->isImplicitObjectMemberFunction();
16721
16722 return false;
16723 }
16724
16725 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16726 if (!ULE->getQualifier())
16727 return false;
16728
16729 for (NamedDecl *D : ULE->decls()) {
16730 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16731 if (Method->isImplicitObjectMemberFunction())
16732 return true;
16733 } else {
16734 // Overload set does not contain methods.
16735 break;
16736 }
16737 }
16738
16739 return false;
16740 }
16741
16742 return false;
16743}
16744
16746 UnaryOperatorKind Opc, Expr *Input,
16747 bool IsAfterAmp) {
16748 // First things first: handle placeholders so that the
16749 // overloaded-operator check considers the right type.
16750 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16751 // Increment and decrement of pseudo-object references.
16752 if (pty->getKind() == BuiltinType::PseudoObject &&
16754 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16755
16756 // extension is always a builtin operator.
16757 if (Opc == UO_Extension)
16758 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16759
16760 // & gets special logic for several kinds of placeholder.
16761 // The builtin code knows what to do.
16762 if (Opc == UO_AddrOf &&
16763 (pty->getKind() == BuiltinType::Overload ||
16764 pty->getKind() == BuiltinType::UnknownAny ||
16765 pty->getKind() == BuiltinType::BoundMember))
16766 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16767
16768 // Anything else needs to be handled now.
16770 if (Result.isInvalid()) return ExprError();
16771 Input = Result.get();
16772 }
16773
16774 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16776 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16777 // Find all of the overloaded operators visible from this point.
16778 UnresolvedSet<16> Functions;
16780 if (S && OverOp != OO_None)
16781 LookupOverloadedOperatorName(OverOp, S, Functions);
16782
16783 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16784 }
16785
16786 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16787}
16788
16790 Expr *Input, bool IsAfterAmp) {
16791 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16792 IsAfterAmp);
16793}
16794
16796 LabelDecl *TheDecl) {
16797 TheDecl->markUsed(Context);
16798 // Create the AST node. The address of a label always has type 'void*'.
16799 auto *Res = new (Context) AddrLabelExpr(
16800 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16801
16802 if (getCurFunction())
16803 getCurFunction()->AddrLabels.push_back(Res);
16804
16805 return Res;
16806}
16807
16810 // Make sure we diagnose jumping into a statement expression.
16812}
16813
16815 // Note that function is also called by TreeTransform when leaving a
16816 // StmtExpr scope without rebuilding anything.
16817
16820}
16821
16823 SourceLocation RPLoc) {
16824 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16825}
16826
16828 SourceLocation RPLoc, unsigned TemplateDepth) {
16829 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16830 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16831
16834 assert(!Cleanup.exprNeedsCleanups() &&
16835 "cleanups within StmtExpr not correctly bound!");
16837
16838 // FIXME: there are a variety of strange constraints to enforce here, for
16839 // example, it is not possible to goto into a stmt expression apparently.
16840 // More semantic analysis is needed.
16841
16842 // If there are sub-stmts in the compound stmt, take the type of the last one
16843 // as the type of the stmtexpr.
16844 QualType Ty = Context.VoidTy;
16845 bool StmtExprMayBindToTemp = false;
16846 if (!Compound->body_empty()) {
16847 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16848 if (const Expr *Value = LastStmt->getExprStmt()) {
16849 StmtExprMayBindToTemp = true;
16850 Ty = Value->getType();
16851 }
16852 }
16853 }
16854
16855 // FIXME: Check that expression type is complete/non-abstract; statement
16856 // expressions are not lvalues.
16857 Expr *ResStmtExpr =
16858 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16859 if (StmtExprMayBindToTemp)
16860 return MaybeBindToTemporary(ResStmtExpr);
16861 return ResStmtExpr;
16862}
16863
16865 if (ER.isInvalid())
16866 return ExprError();
16867
16868 // Do function/array conversion on the last expression, but not
16869 // lvalue-to-rvalue. However, initialize an unqualified type.
16871 if (ER.isInvalid())
16872 return ExprError();
16873 Expr *E = ER.get();
16874
16875 if (E->isTypeDependent())
16876 return E;
16877
16878 // In ARC, if the final expression ends in a consume, splice
16879 // the consume out and bind it later. In the alternate case
16880 // (when dealing with a retainable type), the result
16881 // initialization will create a produce. In both cases the
16882 // result will be +1, and we'll need to balance that out with
16883 // a bind.
16884 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16885 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16886 return Cast->getSubExpr();
16887
16888 // FIXME: Provide a better location for the initialization.
16892 SourceLocation(), E);
16893}
16894
16896 TypeSourceInfo *TInfo,
16897 const Designation &Desig,
16898 SourceLocation RParenLoc) {
16899 QualType ArgTy = TInfo->getType();
16900 bool Dependent = ArgTy->isDependentType();
16901 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16902
16903 // We must have at least one component that refers to the type, and the first
16904 // one is known to be a field designator. Verify that the ArgTy represents
16905 // a struct/union/class.
16906 if (!Dependent && !ArgTy->isRecordType())
16907 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16908 << ArgTy << TypeRange);
16909
16910 // Type must be complete per C99 7.17p3 because a declaring a variable
16911 // with an incomplete type would be ill-formed.
16912 if (!Dependent
16913 && RequireCompleteType(BuiltinLoc, ArgTy,
16914 diag::err_offsetof_incomplete_type, TypeRange))
16915 return ExprError();
16916
16917 bool DidWarnAboutNonPOD = false;
16918 QualType CurrentType = ArgTy;
16921 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
16922 const Designator &D = Desig.getDesignator(I);
16923 assert(!D.isArrayRangeDesignator());
16924 if (D.isArrayDesignator()) {
16925 // Offset of an array sub-field. TODO: Should we allow vector elements?
16926 if (!CurrentType->isDependentType()) {
16927 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16928 if(!AT)
16929 return ExprError(Diag(D.getEndLoc(), diag::err_offsetof_array_type)
16930 << CurrentType);
16931 CurrentType = AT->getElementType();
16932 } else
16933 CurrentType = Context.DependentTy;
16934
16936 if (IdxRval.isInvalid())
16937 return ExprError();
16938 Expr *Idx = IdxRval.get();
16939
16940 // The expression must be an integral expression.
16941 // FIXME: An integral constant expression?
16942 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16943 !Idx->getType()->isIntegerType())
16944 return ExprError(
16945 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16946 << Idx->getSourceRange());
16947
16948 // Record this array index.
16949 Comps.push_back(
16950 OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
16951 Exprs.push_back(Idx);
16952 continue;
16953 }
16954
16955 assert(D.isFieldDesignator());
16956 const IdentifierInfo *Name = D.getFieldDecl();
16957
16958 // Offset of a field.
16959 if (CurrentType->isDependentType()) {
16960 // We have the offset of a field, but we can't look into the dependent
16961 // type. Just record the identifier of the field.
16962 Comps.push_back(OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
16963 CurrentType = Context.DependentTy;
16964 continue;
16965 }
16966
16967 // We need to have a complete type to look into.
16968 if (RequireCompleteType(D.getBeginLoc(), CurrentType,
16969 diag::err_offsetof_incomplete_type))
16970 return ExprError();
16971
16972 // Look for the designated field.
16973 auto *RD = CurrentType->getAsRecordDecl();
16974 if (!RD)
16975 return ExprError(Diag(D.getEndLoc(), diag::err_offsetof_record_type)
16976 << CurrentType);
16977
16978 // C++ [lib.support.types]p5:
16979 // The macro offsetof accepts a restricted set of type arguments in this
16980 // International Standard. type shall be a POD structure or a POD union
16981 // (clause 9).
16982 // C++11 [support.types]p4:
16983 // If type is not a standard-layout class (Clause 9), the results are
16984 // undefined.
16985 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16986 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16987 unsigned DiagID =
16988 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16989 : diag::ext_offsetof_non_pod_type;
16990
16991 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16992 Diag(BuiltinLoc, DiagID)
16994 << CurrentType;
16995 DidWarnAboutNonPOD = true;
16996 }
16997 }
16998
16999 // Look for the field.
17000 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
17001 LookupQualifiedName(R, RD);
17002 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
17003 IndirectFieldDecl *IndirectMemberDecl = nullptr;
17004 if (!MemberDecl) {
17005 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
17006 MemberDecl = IndirectMemberDecl->getAnonField();
17007 }
17008
17009 if (!MemberDecl) {
17010 // Lookup could be ambiguous when looking up a placeholder variable
17011 // __builtin_offsetof(S, _).
17012 // In that case we would already have emitted a diagnostic
17013 if (!R.isAmbiguous())
17014 Diag(BuiltinLoc, diag::err_no_member)
17015 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
17016 return ExprError();
17017 }
17018
17019 // C99 7.17p3:
17020 // (If the specified member is a bit-field, the behavior is undefined.)
17021 //
17022 // We diagnose this as an error.
17023 if (MemberDecl->isBitField()) {
17024 Diag(D.getEndLoc(), diag::err_offsetof_bitfield)
17025 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17026 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
17027 return ExprError();
17028 }
17029
17030 RecordDecl *Parent = MemberDecl->getParent();
17031 if (IndirectMemberDecl)
17032 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
17033
17034 // If the member was found in a base class, introduce OffsetOfNodes for
17035 // the base class indirections.
17036 CXXBasePaths Paths;
17037 if (IsDerivedFrom(D.getBeginLoc(), CurrentType,
17038 Context.getCanonicalTagType(Parent), Paths)) {
17039 if (Paths.getDetectedVirtual()) {
17040 Diag(D.getEndLoc(), diag::err_offsetof_field_of_virtual_base)
17041 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
17042 return ExprError();
17043 }
17044
17045 CXXBasePath &Path = Paths.front();
17046 for (const CXXBasePathElement &B : Path)
17047 Comps.push_back(OffsetOfNode(B.Base));
17048 }
17049
17050 if (IndirectMemberDecl) {
17051 for (auto *FI : IndirectMemberDecl->chain()) {
17052 assert(isa<FieldDecl>(FI));
17053 Comps.push_back(
17055 }
17056 } else
17057 Comps.push_back(OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
17058
17059 CurrentType = MemberDecl->getType().getNonReferenceType();
17060 }
17061
17062 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
17063 Comps, Exprs, RParenLoc);
17064}
17065
17068 ParsedType ParsedArgTy,
17069 const Designation &Desig,
17070 SourceLocation RParenLoc) {
17071
17072 TypeSourceInfo *ArgTInfo;
17073 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
17074 if (ArgTy.isNull())
17075 return ExprError();
17076
17077 if (!ArgTInfo)
17078 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
17079
17080 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Desig, RParenLoc);
17081}
17082
17084 Expr *CondExpr,
17085 Expr *LHSExpr, Expr *RHSExpr,
17086 SourceLocation RPLoc) {
17087 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
17088
17091 QualType resType;
17092 bool CondIsTrue = false;
17093 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
17094 resType = Context.DependentTy;
17095 } else {
17096 // The conditional expression is required to be a constant expression.
17097 llvm::APSInt condEval(32);
17099 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
17100 if (CondICE.isInvalid())
17101 return ExprError();
17102 CondExpr = CondICE.get();
17103 CondIsTrue = condEval.getZExtValue();
17104
17105 // If the condition is > zero, then the AST type is the same as the LHSExpr.
17106 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
17107
17108 resType = ActiveExpr->getType();
17109 VK = ActiveExpr->getValueKind();
17110 OK = ActiveExpr->getObjectKind();
17111 }
17112
17113 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
17114 resType, VK, OK, RPLoc, CondIsTrue);
17115}
17116
17117//===----------------------------------------------------------------------===//
17118// Clang Extensions.
17119//===----------------------------------------------------------------------===//
17120
17121void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
17123
17124 if (LangOpts.CPlusPlus) {
17126 Decl *ManglingContextDecl;
17127 std::tie(MCtx, ManglingContextDecl) =
17128 getCurrentMangleNumberContext(Block->getDeclContext());
17129 if (MCtx) {
17130 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
17131 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
17132 }
17133 }
17134
17135 PushBlockScope(CurScope, Block);
17136 CurContext->addDecl(Block);
17137 if (CurScope)
17138 PushDeclContext(CurScope, Block);
17139 else
17140 CurContext = Block;
17141
17143
17144 // Enter a new evaluation context to insulate the block from any
17145 // cleanups from the enclosing full-expression.
17148}
17149
17151 Scope *CurScope) {
17152 assert(ParamInfo.getIdentifier() == nullptr &&
17153 "block-id should have no identifier!");
17154 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
17155 BlockScopeInfo *CurBlock = getCurBlock();
17156
17157 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
17158 QualType T = Sig->getType();
17160
17161 // GetTypeForDeclarator always produces a function type for a block
17162 // literal signature. Furthermore, it is always a FunctionProtoType
17163 // unless the function was written with a typedef.
17164 assert(T->isFunctionType() &&
17165 "GetTypeForDeclarator made a non-function block signature");
17166
17167 // Look for an explicit signature in that function type.
17168 FunctionProtoTypeLoc ExplicitSignature;
17169
17170 if ((ExplicitSignature = Sig->getTypeLoc()
17172
17173 // Check whether that explicit signature was synthesized by
17174 // GetTypeForDeclarator. If so, don't save that as part of the
17175 // written signature.
17176 if (ExplicitSignature.getLocalRangeBegin() ==
17177 ExplicitSignature.getLocalRangeEnd()) {
17178 // This would be much cheaper if we stored TypeLocs instead of
17179 // TypeSourceInfos.
17180 TypeLoc Result = ExplicitSignature.getReturnLoc();
17181 unsigned Size = Result.getFullDataSize();
17182 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
17183 Sig->getTypeLoc().initializeFullCopy(Result, Size);
17184
17185 ExplicitSignature = FunctionProtoTypeLoc();
17186 }
17187 }
17188
17189 CurBlock->TheDecl->setSignatureAsWritten(Sig);
17190 CurBlock->FunctionType = T;
17191
17192 const auto *Fn = T->castAs<FunctionType>();
17193 QualType RetTy = Fn->getReturnType();
17194 bool isVariadic =
17195 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
17196
17197 CurBlock->TheDecl->setIsVariadic(isVariadic);
17198
17199 // Context.DependentTy is used as a placeholder for a missing block
17200 // return type. TODO: what should we do with declarators like:
17201 // ^ * { ... }
17202 // If the answer is "apply template argument deduction"....
17203 if (RetTy != Context.DependentTy) {
17204 CurBlock->ReturnType = RetTy;
17205 CurBlock->TheDecl->setBlockMissingReturnType(false);
17206 CurBlock->HasImplicitReturnType = false;
17207 }
17208
17209 // Push block parameters from the declarator if we had them.
17211 if (ExplicitSignature) {
17212 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17213 ParmVarDecl *Param = ExplicitSignature.getParam(I);
17214 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17215 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17216 // Diagnose this as an extension in C17 and earlier.
17217 if (!getLangOpts().C23)
17218 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
17219 }
17220 Params.push_back(Param);
17221 }
17222
17223 // Fake up parameter variables if we have a typedef, like
17224 // ^ fntype { ... }
17225 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17226 for (const auto &I : Fn->param_types()) {
17228 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
17229 Params.push_back(Param);
17230 }
17231 }
17232
17233 // Set the parameters on the block decl.
17234 if (!Params.empty()) {
17235 CurBlock->TheDecl->setParams(Params);
17237 /*CheckParameterNames=*/false);
17238 }
17239
17240 // Finally we can process decl attributes.
17241 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
17242
17243 // Put the parameter variables in scope.
17244 for (auto *AI : CurBlock->TheDecl->parameters()) {
17245 AI->setOwningFunction(CurBlock->TheDecl);
17246
17247 // If this has an identifier, add it to the scope stack.
17248 if (AI->getIdentifier()) {
17249 CheckShadow(CurBlock->TheScope, AI);
17250
17251 PushOnScopeChains(AI, CurBlock->TheScope);
17252 }
17253
17254 if (AI->isInvalidDecl())
17255 CurBlock->TheDecl->setInvalidDecl();
17256 }
17257}
17258
17259void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17260 // Leave the expression-evaluation context.
17263
17264 // Pop off CurBlock, handle nested blocks.
17267}
17268
17270 Stmt *Body, Scope *CurScope) {
17271 // If blocks are disabled, emit an error.
17272 if (!LangOpts.Blocks)
17273 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
17274
17275 // Leave the expression-evaluation context.
17278 assert(!Cleanup.exprNeedsCleanups() &&
17279 "cleanups within block not correctly bound!");
17281
17283 BlockDecl *BD = BSI->TheDecl;
17284
17286
17287 if (BSI->HasImplicitReturnType)
17289
17290 QualType RetTy = Context.VoidTy;
17291 if (!BSI->ReturnType.isNull())
17292 RetTy = BSI->ReturnType;
17293
17294 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17295 QualType BlockTy;
17296
17297 // If the user wrote a function type in some form, try to use that.
17298 if (!BSI->FunctionType.isNull()) {
17299 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17300
17301 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17302 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17303
17304 // Turn protoless block types into nullary block types.
17305 if (isa<FunctionNoProtoType>(FTy)) {
17307 EPI.ExtInfo = Ext;
17308 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17309
17310 // Otherwise, if we don't need to change anything about the function type,
17311 // preserve its sugar structure.
17312 } else if (FTy->getReturnType() == RetTy &&
17313 (!NoReturn || FTy->getNoReturnAttr())) {
17314 BlockTy = BSI->FunctionType;
17315
17316 // Otherwise, make the minimal modifications to the function type.
17317 } else {
17320 EPI.TypeQuals = Qualifiers();
17321 EPI.ExtInfo = Ext;
17322 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17323 }
17324
17325 // If we don't have a function type, just build one from nothing.
17326 } else {
17328 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17329 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17330 }
17331
17333 BlockTy = Context.getBlockPointerType(BlockTy);
17334
17335 // If needed, diagnose invalid gotos and switches in the block.
17336 if (getCurFunction()->NeedsScopeChecking() &&
17337 !PP.isCodeCompletionEnabled())
17339
17340 BD->setBody(cast<CompoundStmt>(Body));
17341
17342 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17344
17345 // Try to apply the named return value optimization. We have to check again
17346 // if we can do this, though, because blocks keep return statements around
17347 // to deduce an implicit return type.
17348 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17349 !BD->isDependentContext())
17350 computeNRVO(Body, BSI);
17351
17357
17359
17360 // Set the captured variables on the block.
17362 for (Capture &Cap : BSI->Captures) {
17363 if (Cap.isInvalid() || Cap.isThisCapture())
17364 continue;
17365 // Cap.getVariable() is always a VarDecl because
17366 // blocks cannot capture structured bindings or other ValueDecl kinds.
17367 auto *Var = cast<VarDecl>(Cap.getVariable());
17368 Expr *CopyExpr = nullptr;
17369 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17370 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17371 // The capture logic needs the destructor, so make sure we mark it.
17372 // Usually this is unnecessary because most local variables have
17373 // their destructors marked at declaration time, but parameters are
17374 // an exception because it's technically only the call site that
17375 // actually requires the destructor.
17376 if (isa<ParmVarDecl>(Var))
17378
17379 // Enter a separate potentially-evaluated context while building block
17380 // initializers to isolate their cleanups from those of the block
17381 // itself.
17382 // FIXME: Is this appropriate even when the block itself occurs in an
17383 // unevaluated operand?
17386
17387 SourceLocation Loc = Cap.getLocation();
17388
17390 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17391
17392 // According to the blocks spec, the capture of a variable from
17393 // the stack requires a const copy constructor. This is not true
17394 // of the copy/move done to move a __block variable to the heap.
17395 if (!Result.isInvalid() &&
17396 !Result.get()->getType().isConstQualified()) {
17398 Result.get()->getType().withConst(),
17399 CK_NoOp, VK_LValue);
17400 }
17401
17402 if (!Result.isInvalid()) {
17404 InitializedEntity::InitializeBlock(Var->getLocation(),
17405 Cap.getCaptureType()),
17406 Loc, Result.get());
17407 }
17408
17409 // Build a full-expression copy expression if initialization
17410 // succeeded and used a non-trivial constructor. Recover from
17411 // errors by pretending that the copy isn't necessary.
17412 if (!Result.isInvalid() &&
17413 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17414 ->isTrivial()) {
17416 CopyExpr = Result.get();
17417 }
17418 }
17419 }
17420
17421 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17422 CopyExpr);
17423 Captures.push_back(NewCap);
17424 }
17425 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17426
17427 // Pop the block scope now but keep it alive to the end of this function.
17429 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
17430 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17431
17432 BlockExpr *Result = new (Context)
17433 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17434
17435 // If the block isn't obviously global, i.e. it captures anything at
17436 // all, then we need to do a few things in the surrounding context:
17437 if (Result->getBlockDecl()->hasCaptures()) {
17438 // First, this expression has a new cleanup object.
17439 ExprCleanupObjects.push_back(Result->getBlockDecl());
17440 Cleanup.setExprNeedsCleanups(true);
17441
17442 // It also gets a branch-protected scope if any of the captured
17443 // variables needs destruction.
17444 for (const auto &CI : Result->getBlockDecl()->captures()) {
17445 const VarDecl *var = CI.getVariable();
17446 if (var->getType().isDestructedType() != QualType::DK_none) {
17448 break;
17449 }
17450 }
17451 }
17452
17453 if (getCurFunction())
17454 getCurFunction()->addBlock(BD);
17455
17456 // This can happen if the block's return type is deduced, but
17457 // the return expression is invalid.
17458 if (BD->isInvalidDecl())
17459 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17460 {Result}, Result->getType());
17461 return Result;
17462}
17463
17465 SourceLocation RPLoc) {
17466 TypeSourceInfo *TInfo;
17467 GetTypeFromParser(Ty, &TInfo);
17468 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17469}
17470
17472 Expr *E, TypeSourceInfo *TInfo,
17473 SourceLocation RPLoc) {
17474 Expr *OrigExpr = E;
17476
17477 // CUDA device global function does not support varargs.
17478 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17479 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17482 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17483 }
17484 }
17485
17486 // NVPTX does not support va_arg expression.
17487 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17488 Context.getTargetInfo().getTriple().isNVPTX())
17489 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17490
17491 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17492 // as Microsoft ABI on an actual Microsoft platform, where
17493 // __builtin_ms_va_list and __builtin_va_list are the same.)
17494 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17495 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17496 QualType MSVaListType = Context.getBuiltinMSVaListType();
17497 if (Context.hasSameType(MSVaListType, E->getType())) {
17498 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17499 return ExprError();
17500 VAKind = VAArgExpr::VA_MS;
17501 }
17502 }
17503
17504 // Get the va_list type
17505 QualType VaListType = Context.getBuiltinVaListType();
17506
17507 // It might be a __builtin_zos_va_list!
17508 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinZOSVaList()) {
17509 // E->getType() can be:
17510 // - va_list: equal to array (char*)[2] (inside function)
17511 // - char **: decayed array (va_list passed as parameter)
17512 // We need to check for both cases.
17513 QualType ZOSVaListType = Context.getBuiltinZOSVaListType();
17514 assert(ZOSVaListType->isArrayType() &&
17515 "__builtin_zos_va_list must be an array type");
17516 QualType DecayedType = Context.getArrayDecayedType(ZOSVaListType);
17517 if (Context.hasSameType(ZOSVaListType, E->getType()) ||
17518 Context.hasSameType(DecayedType, E->getType())) {
17519 VAKind = VAArgExpr::VA_ZOS;
17520 VaListType = ZOSVaListType;
17521 }
17522 }
17523
17524 if (VAKind != VAArgExpr::VA_MS) {
17525 if (VaListType->isArrayType()) {
17526 // Deal with implicit array decay; for example, on x86-64,
17527 // va_list is an array, but it's supposed to decay to
17528 // a pointer for va_arg.
17529 VaListType = Context.getArrayDecayedType(VaListType);
17530 // Make sure the input expression also decays appropriately.
17532 if (Result.isInvalid())
17533 return ExprError();
17534 E = Result.get();
17535 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17536 // If va_list is a record type and we are compiling in C++ mode,
17537 // check the argument using reference binding.
17539 Context, Context.getLValueReferenceType(VaListType), false);
17541 if (Init.isInvalid())
17542 return ExprError();
17543 E = Init.getAs<Expr>();
17544 } else {
17545 // Otherwise, the va_list argument must be an l-value because
17546 // it is modified by va_arg.
17547 if (!E->isTypeDependent() &&
17548 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17549 return ExprError();
17550 }
17551 }
17552
17553 if ((VAKind != VAArgExpr::VA_MS) && !E->isTypeDependent() &&
17554 !Context.hasSameType(VaListType, E->getType()))
17555 return ExprError(
17556 Diag(E->getBeginLoc(),
17557 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17558 << OrigExpr->getType() << E->getSourceRange());
17559
17560 if (!TInfo->getType()->isDependentType()) {
17561 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17562 diag::err_second_parameter_to_va_arg_incomplete,
17563 TInfo->getTypeLoc()))
17564 return ExprError();
17565
17567 TInfo->getType(),
17568 diag::err_second_parameter_to_va_arg_abstract,
17569 TInfo->getTypeLoc()))
17570 return ExprError();
17571
17572 if (!TInfo->getType().isPODType(Context)) {
17573 Diag(TInfo->getTypeLoc().getBeginLoc(),
17574 TInfo->getType()->isObjCLifetimeType()
17575 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17576 : diag::warn_second_parameter_to_va_arg_not_pod)
17577 << TInfo->getType()
17578 << TInfo->getTypeLoc().getSourceRange();
17579 }
17580
17581 if (TInfo->getType()->isArrayType()) {
17583 PDiag(diag::warn_second_parameter_to_va_arg_array)
17584 << TInfo->getType()
17585 << TInfo->getTypeLoc().getSourceRange());
17586 }
17587
17588 // Check for va_arg where arguments of the given type will be promoted
17589 // (i.e. this va_arg is guaranteed to have undefined behavior).
17590 QualType PromoteType;
17591 if (Context.isPromotableIntegerType(TInfo->getType())) {
17592 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17593 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17594 // and C23 7.16.1.1p2 says, in part:
17595 // If type is not compatible with the type of the actual next argument
17596 // (as promoted according to the default argument promotions), the
17597 // behavior is undefined, except for the following cases:
17598 // - both types are pointers to qualified or unqualified versions of
17599 // compatible types;
17600 // - one type is compatible with a signed integer type, the other
17601 // type is compatible with the corresponding unsigned integer type,
17602 // and the value is representable in both types;
17603 // - one type is pointer to qualified or unqualified void and the
17604 // other is a pointer to a qualified or unqualified character type;
17605 // - or, the type of the next argument is nullptr_t and type is a
17606 // pointer type that has the same representation and alignment
17607 // requirements as a pointer to a character type.
17608 // Given that type compatibility is the primary requirement (ignoring
17609 // qualifications), you would think we could call typesAreCompatible()
17610 // directly to test this. However, in C++, that checks for *same type*,
17611 // which causes false positives when passing an enumeration type to
17612 // va_arg. Instead, get the underlying type of the enumeration and pass
17613 // that.
17614 QualType UnderlyingType = TInfo->getType();
17615 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17616 UnderlyingType = ED->getIntegerType();
17617 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17618 /*CompareUnqualified*/ true))
17619 PromoteType = QualType();
17620
17621 // If the types are still not compatible, we need to test whether the
17622 // promoted type and the underlying type are the same except for
17623 // signedness. Ask the AST for the correctly corresponding type and see
17624 // if that's compatible.
17625 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17626 PromoteType->isUnsignedIntegerType() !=
17627 UnderlyingType->isUnsignedIntegerType()) {
17628 UnderlyingType =
17629 UnderlyingType->isUnsignedIntegerType()
17630 ? Context.getCorrespondingSignedType(UnderlyingType)
17631 : Context.getCorrespondingUnsignedType(UnderlyingType);
17632 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17633 /*CompareUnqualified*/ true))
17634 PromoteType = QualType();
17635 }
17636 }
17637 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17638 PromoteType = Context.DoubleTy;
17639 if (!PromoteType.isNull())
17641 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17642 << TInfo->getType()
17643 << PromoteType
17644 << TInfo->getTypeLoc().getSourceRange());
17645 }
17646
17648 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, VAKind);
17649}
17650
17652 // The type of __null will be int or long, depending on the size of
17653 // pointers on the target.
17654 QualType Ty;
17655 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17656 if (pw == Context.getTargetInfo().getIntWidth())
17657 Ty = Context.IntTy;
17658 else if (pw == Context.getTargetInfo().getLongWidth())
17659 Ty = Context.LongTy;
17660 else if (pw == Context.getTargetInfo().getLongLongWidth())
17661 Ty = Context.LongLongTy;
17662 else {
17663 llvm_unreachable("I don't know size of pointer!");
17664 }
17665
17666 return new (Context) GNUNullExpr(Ty, TokenLoc);
17667}
17668
17670 CXXRecordDecl *ImplDecl = nullptr;
17671
17672 // Fetch the std::source_location::__impl decl.
17673 if (NamespaceDecl *Std = S.getStdNamespace()) {
17674 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17676 if (S.LookupQualifiedName(ResultSL, Std)) {
17677 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17678 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17680 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17681 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17682 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17683 }
17684 }
17685 }
17686 }
17687
17688 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17689 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17690 return nullptr;
17691 }
17692
17693 // Verify that __impl is a trivial struct type, with no base classes, and with
17694 // only the four expected fields.
17695 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17696 ImplDecl->getNumBases() != 0) {
17697 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17698 return nullptr;
17699 }
17700
17701 unsigned Count = 0;
17702 for (FieldDecl *F : ImplDecl->fields()) {
17703 StringRef Name = F->getName();
17704
17705 if (Name == "_M_file_name") {
17706 if (F->getType() !=
17708 break;
17709 Count++;
17710 } else if (Name == "_M_function_name") {
17711 if (F->getType() !=
17713 break;
17714 Count++;
17715 } else if (Name == "_M_line") {
17716 if (!F->getType()->isIntegerType())
17717 break;
17718 Count++;
17719 } else if (Name == "_M_column") {
17720 if (!F->getType()->isIntegerType())
17721 break;
17722 Count++;
17723 } else {
17724 Count = 100; // invalid
17725 break;
17726 }
17727 }
17728 if (Count != 4) {
17729 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17730 return nullptr;
17731 }
17732
17733 return ImplDecl;
17734}
17735
17737 SourceLocation BuiltinLoc,
17738 SourceLocation RPLoc) {
17739 QualType ResultTy;
17740 switch (Kind) {
17745 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17746 ResultTy =
17747 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17748 break;
17749 }
17752 ResultTy = Context.UnsignedIntTy;
17753 break;
17757 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17759 return ExprError();
17760 }
17761 ResultTy = Context.getPointerType(
17762 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17763 break;
17764 }
17765
17766 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17767}
17768
17770 SourceLocation BuiltinLoc,
17771 SourceLocation RPLoc,
17772 DeclContext *ParentContext) {
17773 return new (Context)
17774 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17775}
17776
17778 StringLiteral *BinaryData, StringRef FileName) {
17780 Data->BinaryData = BinaryData;
17781 Data->FileName = FileName;
17782 return new (Context)
17783 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17784 Data->getDataElementCount());
17785}
17786
17788 const Expr *SrcExpr) {
17789 if (!DstType->isFunctionPointerType() ||
17790 !SrcExpr->getType()->isFunctionType())
17791 return false;
17792
17793 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17794 if (!DRE)
17795 return false;
17796
17797 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17798 if (!FD)
17799 return false;
17800
17802 /*Complain=*/true,
17803 SrcExpr->getBeginLoc());
17804}
17805
17807 SourceLocation Loc,
17808 QualType DstType, QualType SrcType,
17809 Expr *SrcExpr, AssignmentAction Action,
17810 bool *Complained) {
17811 if (Complained)
17812 *Complained = false;
17813
17814 // Decode the result (notice that AST's are still created for extensions).
17815 bool CheckInferredResultType = false;
17816 bool isInvalid = false;
17817 unsigned DiagKind = 0;
17818 ConversionFixItGenerator ConvHints;
17819 bool MayHaveConvFixit = false;
17820 bool MayHaveFunctionDiff = false;
17821 const ObjCInterfaceDecl *IFace = nullptr;
17822 const ObjCProtocolDecl *PDecl = nullptr;
17823
17824 switch (ConvTy) {
17826 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17827 return false;
17829 // Still a valid conversion, but we may want to diagnose for C++
17830 // compatibility reasons.
17831 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17832 break;
17834 if (getLangOpts().CPlusPlus) {
17835 DiagKind = diag::err_typecheck_convert_pointer_int;
17836 isInvalid = true;
17837 } else {
17838 DiagKind = diag::ext_typecheck_convert_pointer_int;
17839 }
17840 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17841 MayHaveConvFixit = true;
17842 break;
17844 if (getLangOpts().CPlusPlus) {
17845 DiagKind = diag::err_typecheck_convert_int_pointer;
17846 isInvalid = true;
17847 } else {
17848 DiagKind = diag::ext_typecheck_convert_int_pointer;
17849 }
17850 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17851 MayHaveConvFixit = true;
17852 break;
17854 DiagKind =
17855 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17856 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17857 MayHaveConvFixit = true;
17858 break;
17860 if (getLangOpts().CPlusPlus) {
17861 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17862 isInvalid = true;
17863 } else {
17864 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17865 }
17866 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17867 MayHaveConvFixit = true;
17868 break;
17871 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17872 } else if (getLangOpts().CPlusPlus) {
17873 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17874 isInvalid = true;
17875 } else {
17876 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17877 }
17878 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17879 SrcType->isObjCObjectPointerType();
17880 if (CheckInferredResultType) {
17881 SrcType = SrcType.getUnqualifiedType();
17882 DstType = DstType.getUnqualifiedType();
17883 } else {
17884 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17885 }
17886 MayHaveConvFixit = true;
17887 break;
17889 if (getLangOpts().CPlusPlus) {
17890 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17891 isInvalid = true;
17892 } else {
17893 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17894 }
17895 break;
17897 if (getLangOpts().CPlusPlus) {
17898 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17899 isInvalid = true;
17900 } else {
17901 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17902 }
17903 break;
17905 // Perform decay if necessary.
17906 if (SrcType->canDecayToPointerType())
17907 SrcType = Context.getDecayedType(SrcType);
17908
17909 isInvalid = true;
17910
17911 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17912 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17913 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17914 DiagKind = diag::err_typecheck_incompatible_address_space;
17915 break;
17916 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17917 DiagKind = diag::err_typecheck_incompatible_ownership;
17918 break;
17919 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17920 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17921 break;
17922 }
17923
17924 llvm_unreachable("unknown error case for discarding qualifiers!");
17925 // fallthrough
17926 }
17928 if (SrcType->isArrayType())
17929 SrcType = Context.getArrayDecayedType(SrcType);
17930
17931 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17932 break;
17934 // If the qualifiers lost were because we were applying the
17935 // (deprecated) C++ conversion from a string literal to a char*
17936 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17937 // Ideally, this check would be performed in
17938 // checkPointerTypesForAssignment. However, that would require a
17939 // bit of refactoring (so that the second argument is an
17940 // expression, rather than a type), which should be done as part
17941 // of a larger effort to fix checkPointerTypesForAssignment for
17942 // C++ semantics.
17943 if (getLangOpts().CPlusPlus &&
17945 return false;
17946 if (getLangOpts().CPlusPlus) {
17947 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17948 isInvalid = true;
17949 } else {
17950 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17951 }
17952
17953 break;
17955 if (getLangOpts().CPlusPlus) {
17956 isInvalid = true;
17957 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17958 } else {
17959 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17960 }
17961 break;
17963 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17964 isInvalid = true;
17965 break;
17967 DiagKind = diag::err_int_to_block_pointer;
17968 isInvalid = true;
17969 break;
17971 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17972 isInvalid = true;
17973 break;
17975 if (SrcType->isObjCQualifiedIdType()) {
17976 const ObjCObjectPointerType *srcOPT =
17977 SrcType->castAs<ObjCObjectPointerType>();
17978 for (auto *srcProto : srcOPT->quals()) {
17979 PDecl = srcProto;
17980 break;
17981 }
17982 if (const ObjCInterfaceType *IFaceT =
17984 IFace = IFaceT->getDecl();
17985 }
17986 else if (DstType->isObjCQualifiedIdType()) {
17987 const ObjCObjectPointerType *dstOPT =
17988 DstType->castAs<ObjCObjectPointerType>();
17989 for (auto *dstProto : dstOPT->quals()) {
17990 PDecl = dstProto;
17991 break;
17992 }
17993 if (const ObjCInterfaceType *IFaceT =
17995 IFace = IFaceT->getDecl();
17996 }
17997 if (getLangOpts().CPlusPlus) {
17998 DiagKind = diag::err_incompatible_qualified_id;
17999 isInvalid = true;
18000 } else {
18001 DiagKind = diag::warn_incompatible_qualified_id;
18002 }
18003 break;
18004 }
18006 if (getLangOpts().CPlusPlus) {
18007 DiagKind = diag::err_incompatible_vectors;
18008 isInvalid = true;
18009 } else {
18010 DiagKind = diag::warn_incompatible_vectors;
18011 }
18012 break;
18014 DiagKind = diag::err_arc_weak_unavailable_assign;
18015 isInvalid = true;
18016 break;
18018 return false;
18020 assert(!SrcType->isFunctionType() &&
18021 "Unexpected function type found in IncompatibleOBTKinds assignment");
18022 if (SrcType->canDecayToPointerType())
18023 SrcType = Context.getDecayedType(SrcType);
18024
18025 auto getOBTKindName = [](QualType Ty) -> StringRef {
18026 if (Ty->isPointerType())
18027 Ty = Ty->getPointeeType();
18028 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
18029 return OBT->getBehaviorKind() ==
18030 OverflowBehaviorType::OverflowBehaviorKind::Trap
18031 ? "__ob_trap"
18032 : "__ob_wrap";
18033 }
18034 llvm_unreachable("OBT kind unhandled");
18035 };
18036
18037 Diag(Loc, diag::err_incompatible_obt_kinds_assignment)
18038 << DstType << SrcType << getOBTKindName(DstType)
18039 << getOBTKindName(SrcType);
18040 isInvalid = true;
18041 return true;
18042 }
18044 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
18045 if (Complained)
18046 *Complained = true;
18047 return true;
18048 }
18049
18050 DiagKind = diag::err_typecheck_convert_incompatible;
18051 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
18052 MayHaveConvFixit = true;
18053 isInvalid = true;
18054 MayHaveFunctionDiff = true;
18055 break;
18056 }
18057
18058 QualType FirstType, SecondType;
18059 switch (Action) {
18062 // The destination type comes first.
18063 FirstType = DstType;
18064 SecondType = SrcType;
18065 break;
18066
18073 // The source type comes first.
18074 FirstType = SrcType;
18075 SecondType = DstType;
18076 break;
18077 }
18078
18079 PartialDiagnostic FDiag = PDiag(DiagKind);
18080 AssignmentAction ActionForDiag = Action;
18082 ActionForDiag = AssignmentAction::Passing;
18083
18084 FDiag << FirstType << SecondType << ActionForDiag
18085 << SrcExpr->getSourceRange();
18086
18087 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
18088 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
18089 auto isPlainChar = [](const clang::Type *Type) {
18090 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
18091 Type->isSpecificBuiltinType(BuiltinType::Char_U);
18092 };
18093 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
18094 isPlainChar(SecondType->getPointeeOrArrayElementType()));
18095 }
18096
18097 // If we can fix the conversion, suggest the FixIts.
18098 if (!ConvHints.isNull()) {
18099 for (FixItHint &H : ConvHints.Hints)
18100 FDiag << H;
18101 }
18102
18103 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
18104
18105 if (MayHaveFunctionDiff)
18106 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
18107
18108 Diag(Loc, FDiag);
18109 if ((DiagKind == diag::warn_incompatible_qualified_id ||
18110 DiagKind == diag::err_incompatible_qualified_id) &&
18111 PDecl && IFace && !IFace->hasDefinition())
18112 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
18113 << IFace << PDecl;
18114
18115 if (SecondType == Context.OverloadTy)
18117 FirstType, /*TakingAddress=*/true);
18118
18119 if (CheckInferredResultType)
18121
18122 if (Action == AssignmentAction::Returning &&
18125
18126 if (Complained)
18127 *Complained = true;
18128 return isInvalid;
18129}
18130
18132 llvm::APSInt *Result,
18133 AllowFoldKind CanFold) {
18134 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
18135 public:
18136 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
18137 QualType T) override {
18138 return S.Diag(Loc, diag::err_ice_not_integral)
18139 << T << S.LangOpts.CPlusPlus;
18140 }
18141 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18142 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
18143 }
18144 } Diagnoser;
18145
18146 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18147}
18148
18150 llvm::APSInt *Result,
18151 unsigned DiagID,
18152 AllowFoldKind CanFold) {
18153 class IDDiagnoser : public VerifyICEDiagnoser {
18154 unsigned DiagID;
18155
18156 public:
18157 IDDiagnoser(unsigned DiagID)
18158 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
18159
18160 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
18161 return S.Diag(Loc, DiagID);
18162 }
18163 } Diagnoser(DiagID);
18164
18165 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
18166}
18167
18173
18176 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
18177}
18178
18181 VerifyICEDiagnoser &Diagnoser,
18182 AllowFoldKind CanFold) {
18183 SourceLocation DiagLoc = E->getBeginLoc();
18184
18185 if (getLangOpts().CPlusPlus11) {
18186 // C++11 [expr.const]p5:
18187 // If an expression of literal class type is used in a context where an
18188 // integral constant expression is required, then that class type shall
18189 // have a single non-explicit conversion function to an integral or
18190 // unscoped enumeration type
18191 ExprResult Converted;
18192 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
18193 VerifyICEDiagnoser &BaseDiagnoser;
18194 public:
18195 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
18196 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18197 BaseDiagnoser.Suppress, true),
18198 BaseDiagnoser(BaseDiagnoser) {}
18199
18200 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18201 QualType T) override {
18202 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18203 }
18204
18205 SemaDiagnosticBuilder diagnoseIncomplete(
18206 Sema &S, SourceLocation Loc, QualType T) override {
18207 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
18208 }
18209
18210 SemaDiagnosticBuilder diagnoseExplicitConv(
18211 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18212 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
18213 }
18214
18215 SemaDiagnosticBuilder noteExplicitConv(
18216 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18217 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18218 << ConvTy->isEnumeralType() << ConvTy;
18219 }
18220
18221 SemaDiagnosticBuilder diagnoseAmbiguous(
18222 Sema &S, SourceLocation Loc, QualType T) override {
18223 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
18224 }
18225
18226 SemaDiagnosticBuilder noteAmbiguous(
18227 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18228 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18229 << ConvTy->isEnumeralType() << ConvTy;
18230 }
18231
18232 SemaDiagnosticBuilder diagnoseConversion(
18233 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18234 llvm_unreachable("conversion functions are permitted");
18235 }
18236 } ConvertDiagnoser(Diagnoser);
18237
18238 Converted = PerformContextualImplicitConversion(DiagLoc, E,
18239 ConvertDiagnoser);
18240 if (Converted.isInvalid())
18241 return Converted;
18242 E = Converted.get();
18243 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
18244 // don't try to evaluate it later. We also don't want to return the
18245 // RecoveryExpr here, as it results in this call succeeding, thus callers of
18246 // this function will attempt to use 'Value'.
18247 if (isa<RecoveryExpr>(E))
18248 return ExprError();
18250 return ExprError();
18251 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18252 // An ICE must be of integral or unscoped enumeration type.
18253 if (!Diagnoser.Suppress)
18254 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
18255 << E->getSourceRange();
18256 return ExprError();
18257 }
18258
18259 ExprResult RValueExpr = DefaultLvalueConversion(E);
18260 if (RValueExpr.isInvalid())
18261 return ExprError();
18262
18263 E = RValueExpr.get();
18264
18265 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18266 // in the non-ICE case.
18269 if (Result)
18271 if (!isa<ConstantExpr>(E))
18274
18275 if (Notes.empty())
18276 return E;
18277
18278 // If our only note is the usual "invalid subexpression" note, just point
18279 // the caret at its location rather than producing an essentially
18280 // redundant note.
18281 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18282 diag::note_invalid_subexpr_in_const_expr) {
18283 DiagLoc = Notes[0].first;
18284 Notes.clear();
18285 }
18286
18287 if (getLangOpts().CPlusPlus) {
18288 if (!Diagnoser.Suppress) {
18289 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18290 for (const PartialDiagnosticAt &Note : Notes)
18291 Diag(Note.first, Note.second);
18292 }
18293 return ExprError();
18294 }
18295
18296 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18297 for (const PartialDiagnosticAt &Note : Notes)
18298 Diag(Note.first, Note.second);
18299
18300 return E;
18301 }
18302
18303 Expr::EvalResult EvalResult;
18306 EvalResult.Diag = &Notes;
18307 EvalResult.ExtendedDiag = &MSWarning;
18308
18309 // Try to evaluate the expression, and produce diagnostics explaining why it's
18310 // not a constant expression as a side-effect.
18311 bool Folded =
18312 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
18313 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18314 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18315
18316 if (!isa<ConstantExpr>(E))
18317 E = ConstantExpr::Create(Context, E, EvalResult.Val);
18318
18319 // For -fms-compatibility mode we relax some requirements
18320 // for constant folding in non-SFINAE contexts
18321 if (!MSWarning.empty()) {
18322 if (isSFINAEContext()) {
18323 Folded = false;
18324 } else {
18325 for (auto &Info : MSWarning)
18326 Diag(Info.first, Info.second);
18327 }
18328 }
18329
18330 // In C++11, we can rely on diagnostics being produced for any expression
18331 // which is not a constant expression. If no diagnostics were produced, then
18332 // this is a constant expression.
18333 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18334 if (Result)
18335 *Result = EvalResult.Val.getInt();
18336 return E;
18337 }
18338
18339 // If our only note is the usual "invalid subexpression" note, just point
18340 // the caret at its location rather than producing an essentially
18341 // redundant note.
18342 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18343 diag::note_invalid_subexpr_in_const_expr) {
18344 DiagLoc = Notes[0].first;
18345 Notes.clear();
18346 }
18347
18348 if (!Folded || CanFold == AllowFoldKind::No) {
18349 if (!Diagnoser.Suppress) {
18350 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18351 for (const PartialDiagnosticAt &Note : Notes)
18352 Diag(Note.first, Note.second);
18353 }
18354
18355 return ExprError();
18356 }
18357
18358 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18359 for (const PartialDiagnosticAt &Note : Notes)
18360 Diag(Note.first, Note.second);
18361
18362 if (Result)
18363 *Result = EvalResult.Val.getInt();
18364 return E;
18365}
18366
18367namespace {
18368 // Handle the case where we conclude a expression which we speculatively
18369 // considered to be unevaluated is actually evaluated.
18370 class TransformToPE : public TreeTransform<TransformToPE> {
18371 typedef TreeTransform<TransformToPE> BaseTransform;
18372
18373 public:
18374 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18375
18376 // Make sure we redo semantic analysis
18377 bool AlwaysRebuild() { return true; }
18378 bool ReplacingOriginal() { return true; }
18379
18380 // We need to special-case DeclRefExprs referring to FieldDecls which
18381 // are not part of a member pointer formation; normal TreeTransforming
18382 // doesn't catch this case because of the way we represent them in the AST.
18383 // FIXME: This is a bit ugly; is it really the best way to handle this
18384 // case?
18385 //
18386 // Error on DeclRefExprs referring to FieldDecls.
18387 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18388 if (isa<FieldDecl>(E->getDecl()) &&
18389 !SemaRef.isUnevaluatedContext())
18390 return SemaRef.Diag(E->getLocation(),
18391 diag::err_invalid_non_static_member_use)
18392 << E->getDecl() << E->getSourceRange();
18393
18394 return BaseTransform::TransformDeclRefExpr(E);
18395 }
18396
18397 // Exception: filter out member pointer formation
18398 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18399 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18400 return E;
18401
18402 return BaseTransform::TransformUnaryOperator(E);
18403 }
18404
18405 // The body of a lambda-expression is in a separate expression evaluation
18406 // context so never needs to be transformed.
18407 // FIXME: Ideally we wouldn't transform the closure type either, and would
18408 // just recreate the capture expressions and lambda expression.
18409 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18410 return SkipLambdaBody(E, Body);
18411 }
18412 };
18413}
18414
18416 assert(isUnevaluatedContext() &&
18417 "Should only transform unevaluated expressions");
18418 ExprEvalContexts.back().Context =
18419 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18421 return E;
18422 return TransformToPE(*this).TransformExpr(E);
18423}
18424
18426 assert(isUnevaluatedContext() &&
18427 "Should only transform unevaluated expressions");
18430 return TInfo;
18431 return TransformToPE(*this).TransformType(TInfo);
18432}
18433
18434void
18436 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18438 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18439 LambdaContextDecl, ExprContext);
18440
18441 // Discarded statements and immediate contexts nested in other
18442 // discarded statements or immediate context are themselves
18443 // a discarded statement or an immediate context, respectively.
18444 ExprEvalContexts.back().InDiscardedStatement =
18446
18447 // C++23 [expr.const]/p15
18448 // An expression or conversion is in an immediate function context if [...]
18449 // it is a subexpression of a manifestly constant-evaluated expression or
18450 // conversion.
18451 const auto &Prev = parentEvaluationContext();
18452 ExprEvalContexts.back().InImmediateFunctionContext =
18453 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18454
18455 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18456 Prev.InImmediateEscalatingFunctionContext;
18457
18458 Cleanup.reset();
18459 if (!MaybeODRUseExprs.empty())
18460 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18461}
18462
18463void
18467 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18468 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18469}
18470
18472 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18473 // [expr.const]/p14.1
18474 // An expression or conversion is in an immediate function context if it is
18475 // potentially evaluated and either: its innermost enclosing non-block scope
18476 // is a function parameter scope of an immediate function.
18478 FD && FD->isConsteval()
18480 : NewContext);
18484
18485 Current.InDiscardedStatement = false;
18486
18487 if (FD) {
18488
18489 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18490 // context is nested in an immediate function context, so smaller contexts
18491 // that appear inside immediate functions (like variable initializers) are
18492 // considered to be inside an immediate function context even though by
18493 // themselves they are not immediate function contexts. But when a new
18494 // function is entered, we need to reset this tracking, since the entered
18495 // function might be not an immediate function.
18496
18498 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18499
18500 if (isLambdaMethod(FD))
18502 FD->isConsteval() ||
18503 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
18504 Parent.isImmediateFunctionContext()));
18505 else
18507 }
18508}
18509
18511 TypeSourceInfo *TSI) {
18512 return BuildCXXReflectExpr(CaretCaretLoc, TSI);
18513}
18514
18516 TypeSourceInfo *TSI) {
18517 return CXXReflectExpr::Create(Context, CaretCaretLoc, TSI);
18518}
18519
18520namespace {
18521
18522const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18523 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18524 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18525 if (E->getOpcode() == UO_Deref)
18526 return CheckPossibleDeref(S, E->getSubExpr());
18527 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18528 return CheckPossibleDeref(S, E->getBase());
18529 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18530 return CheckPossibleDeref(S, E->getBase());
18531 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18532 QualType Inner;
18533 QualType Ty = E->getType();
18534 if (const auto *Ptr = Ty->getAs<PointerType>())
18535 Inner = Ptr->getPointeeType();
18536 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18537 Inner = Arr->getElementType();
18538 else
18539 return nullptr;
18540
18541 if (Inner->hasAttr(attr::NoDeref))
18542 return E;
18543 }
18544 return nullptr;
18545}
18546
18547} // namespace
18548
18550 for (const Expr *E : Rec.PossibleDerefs) {
18551 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18552 if (DeclRef) {
18553 const ValueDecl *Decl = DeclRef->getDecl();
18554 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18555 << Decl->getName() << E->getSourceRange();
18556 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18557 } else {
18558 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18559 << E->getSourceRange();
18560 }
18561 }
18562 Rec.PossibleDerefs.clear();
18563}
18564
18567 return;
18568
18569 // Note: ignoring parens here is not justified by the standard rules, but
18570 // ignoring parentheses seems like a more reasonable approach, and this only
18571 // drives a deprecation warning so doesn't affect conformance.
18572 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18573 if (BO->getOpcode() == BO_Assign) {
18574 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18575 llvm::erase(LHSs, BO->getLHS());
18576 }
18577 }
18578}
18579
18581 assert(getLangOpts().CPlusPlus20 &&
18582 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18583 "Cannot mark an immediate escalating expression outside of an "
18584 "immediate escalating context");
18585 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18586 Call && Call->getCallee()) {
18587 if (auto *DeclRef =
18588 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18589 DeclRef->setIsImmediateEscalating(true);
18590 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18591 Ctr->setIsImmediateEscalating(true);
18592 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18593 DeclRef->setIsImmediateEscalating(true);
18594 } else {
18595 assert(false && "expected an immediately escalating expression");
18596 }
18598 FI->FoundImmediateEscalatingExpression = true;
18599}
18600
18602 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18603 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18606 return E;
18607
18608 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18609 /// It's OK if this fails; we'll also remove this in
18610 /// HandleImmediateInvocations, but catching it here allows us to avoid
18611 /// walking the AST looking for it in simple cases.
18612 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18613 if (auto *DeclRef =
18614 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18615 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18616
18617 // C++23 [expr.const]/p16
18618 // An expression or conversion is immediate-escalating if it is not initially
18619 // in an immediate function context and it is [...] an immediate invocation
18620 // that is not a constant expression and is not a subexpression of an
18621 // immediate invocation.
18622 APValue Cached;
18623 auto CheckConstantExpressionAndKeepResult = [&]() {
18624 Expr::EvalResult Eval;
18625 bool Res = E.get()->EvaluateAsConstantExpr(
18626 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18627 if (Res && !Eval.DiagEmitted) {
18628 Cached = std::move(Eval.Val);
18629 return true;
18630 }
18631 return false;
18632 };
18633
18634 if (!E.get()->isValueDependent() &&
18635 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18636 !CheckConstantExpressionAndKeepResult()) {
18638 return E;
18639 }
18640
18641 if (Cleanup.exprNeedsCleanups()) {
18642 // Since an immediate invocation is a full expression itself - it requires
18643 // an additional ExprWithCleanups node, but it can participate to a bigger
18644 // full expression which actually requires cleanups to be run after so
18645 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18646 // may discard cleanups for outer expression too early.
18647
18648 // Note that ExprWithCleanups created here must always have empty cleanup
18649 // objects:
18650 // - compound literals do not create cleanup objects in C++ and immediate
18651 // invocations are C++-only.
18652 // - blocks are not allowed inside constant expressions and compiler will
18653 // issue an error if they appear there.
18654 //
18655 // Hence, in correct code any cleanup objects created inside current
18656 // evaluation context must be outside the immediate invocation.
18658 Cleanup.cleanupsHaveSideEffects(), {});
18659 }
18660
18662 getASTContext(), E.get(),
18663 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18664 getASTContext()),
18665 /*IsImmediateInvocation*/ true);
18666 if (Cached.hasValue())
18667 Res->MoveIntoResult(Cached, getASTContext());
18668 /// Value-dependent constant expressions should not be immediately
18669 /// evaluated until they are instantiated.
18670 if (!Res->isValueDependent())
18671 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18672 return Res;
18673}
18674
18678 Expr::EvalResult Eval;
18679 Eval.Diag = &Notes;
18680 ConstantExpr *CE = Candidate.getPointer();
18681 bool Result = CE->EvaluateAsConstantExpr(
18682 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18683 if (!Result || !Notes.empty()) {
18685 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18686 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18687 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18688 FunctionDecl *FD = nullptr;
18689 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18690 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18691 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18692 FD = Call->getConstructor();
18693 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18694 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18695
18696 assert(FD && FD->isImmediateFunction() &&
18697 "could not find an immediate function in this expression");
18698 if (FD->isInvalidDecl())
18699 return;
18700 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18701 << FD << FD->isConsteval();
18702 if (auto Context =
18704 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18705 << Context->Decl;
18706 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18707 }
18708 if (!FD->isConsteval())
18710 for (auto &Note : Notes)
18711 SemaRef.Diag(Note.first, Note.second);
18712 return;
18713 }
18715}
18716
18720 struct ComplexRemove : TreeTransform<ComplexRemove> {
18722 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18725 CurrentII;
18726 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18729 4>::reverse_iterator Current)
18730 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18731 void RemoveImmediateInvocation(ConstantExpr* E) {
18732 auto It = std::find_if(CurrentII, IISet.rend(),
18734 return Elem.getPointer() == E;
18735 });
18736 // It is possible that some subexpression of the current immediate
18737 // invocation was handled from another expression evaluation context. Do
18738 // not handle the current immediate invocation if some of its
18739 // subexpressions failed before.
18740 if (It == IISet.rend()) {
18741 if (SemaRef.FailedImmediateInvocations.contains(E))
18742 CurrentII->setInt(1);
18743 } else {
18744 It->setInt(1); // Mark as deleted
18745 }
18746 }
18747 ExprResult TransformConstantExpr(ConstantExpr *E) {
18748 if (!E->isImmediateInvocation())
18749 return Base::TransformConstantExpr(E);
18750 RemoveImmediateInvocation(E);
18751 return Base::TransformExpr(E->getSubExpr());
18752 }
18753 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18754 /// we need to remove its DeclRefExpr from the DRSet.
18755 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18756 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18757 return Base::TransformCXXOperatorCallExpr(E);
18758 }
18759 /// Base::TransformUserDefinedLiteral doesn't preserve the
18760 /// UserDefinedLiteral node.
18761 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18762 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18763 /// here.
18764 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18765 if (!Init)
18766 return Init;
18767
18768 // We cannot use IgnoreImpCasts because we need to preserve
18769 // full expressions.
18770 while (true) {
18771 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18772 Init = ICE->getSubExpr();
18773 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18774 Init = ICE->getSubExpr();
18775 else
18776 break;
18777 }
18778 /// ConstantExprs are the first layer of implicit node to be removed so if
18779 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18780 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18781 CE && CE->isImmediateInvocation())
18782 RemoveImmediateInvocation(CE);
18783 return Base::TransformInitializer(Init, NotCopyInit);
18784 }
18785 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18786 DRSet.erase(E);
18787 return E;
18788 }
18789 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18790 // Do not rebuild lambdas to avoid creating a new type.
18791 // Lambdas have already been processed inside their eval contexts.
18792 return E;
18793 }
18794
18795 // We do not have enough information to transform opaque expressions and
18796 // assume they do not contain immediate subexpressions.
18797 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18798
18799 bool AlwaysRebuild() { return false; }
18800 bool ReplacingOriginal() { return true; }
18801 bool AllowSkippingCXXConstructExpr() {
18802 bool Res = AllowSkippingFirstCXXConstructExpr;
18803 AllowSkippingFirstCXXConstructExpr = true;
18804 return Res;
18805 }
18806 bool AllowSkippingFirstCXXConstructExpr = true;
18807 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18809
18810 /// CXXConstructExpr with a single argument are getting skipped by
18811 /// TreeTransform in some situtation because they could be implicit. This
18812 /// can only occur for the top-level CXXConstructExpr because it is used
18813 /// nowhere in the expression being transformed therefore will not be rebuilt.
18814 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18815 /// skipping the first CXXConstructExpr.
18816 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18817 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18818
18819 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18820 // The result may not be usable in case of previous compilation errors.
18821 // In this case evaluation of the expression may result in crash so just
18822 // don't do anything further with the result.
18823 if (Res.isUsable()) {
18825 It->getPointer()->setSubExpr(Res.get());
18826 }
18827}
18828
18829static void
18832 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18833 Rec.ReferenceToConsteval.size() == 0) ||
18835 return;
18836
18837 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18838 // [...]
18839 // - the initializer of a variable that is usable in constant expressions or
18840 // has constant initialization.
18841 if (SemaRef.getLangOpts().CPlusPlus23 &&
18842 Rec.ExprContext ==
18844 auto *VD = dyn_cast<VarDecl>(Rec.ManglingContextDecl);
18845 if (VD && (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18846 VD->hasConstantInitialization())) {
18847 // An expression or conversion is in an 'immediate function context' if it
18848 // is potentially evaluated and either:
18849 // [...]
18850 // - it is a subexpression of a manifestly constant-evaluated expression
18851 // or conversion.
18852 return;
18853 }
18854 }
18855
18856 /// When we have more than 1 ImmediateInvocationCandidates or previously
18857 /// failed immediate invocations, we need to check for nested
18858 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18859 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18860 /// invocation.
18861 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18863
18864 /// Prevent sema calls during the tree transform from adding pointers that
18865 /// are already in the sets.
18866 llvm::SaveAndRestore DisableIITracking(
18868
18869 /// Prevent diagnostic during tree transfrom as they are duplicates
18871
18872 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18873 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18874 if (!It->getInt())
18876 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18877 Rec.ReferenceToConsteval.size()) {
18878 struct SimpleRemove : DynamicRecursiveASTVisitor {
18879 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18880 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18881 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18882 DRSet.erase(E);
18883 return DRSet.size();
18884 }
18885 } Visitor(Rec.ReferenceToConsteval);
18886 Visitor.TraverseStmt(
18887 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18888 }
18889 for (auto CE : Rec.ImmediateInvocationCandidates)
18890 if (!CE.getInt())
18892 for (auto *DR : Rec.ReferenceToConsteval) {
18893 // If the expression is immediate escalating, it is not an error;
18894 // The outer context itself becomes immediate and further errors,
18895 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18896 if (DR->isImmediateEscalating())
18897 continue;
18898 auto *FD = cast<FunctionDecl>(DR->getDecl());
18899 const NamedDecl *ND = FD;
18900 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18901 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18902 ND = MD->getParent();
18903
18904 // C++23 [expr.const]/p16
18905 // An expression or conversion is immediate-escalating if it is not
18906 // initially in an immediate function context and it is [...] a
18907 // potentially-evaluated id-expression that denotes an immediate function
18908 // that is not a subexpression of an immediate invocation.
18909 bool ImmediateEscalating = false;
18910 bool IsPotentiallyEvaluated =
18911 Rec.Context ==
18913 Rec.Context ==
18915 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18916 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18917
18919 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18920 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18921 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18922 if (!FD->getBuiltinID())
18923 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18924 if (auto Context =
18926 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18927 << Context->Decl;
18928 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18929 }
18930 if (FD->isImmediateEscalating() && !FD->isConsteval())
18932
18933 } else {
18935 }
18936 }
18937}
18938
18941 if (!Rec.Lambdas.empty()) {
18943 if (!getLangOpts().CPlusPlus20 &&
18944 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18945 Rec.isUnevaluated() ||
18947 unsigned D;
18948 if (Rec.isUnevaluated()) {
18949 // C++11 [expr.prim.lambda]p2:
18950 // A lambda-expression shall not appear in an unevaluated operand
18951 // (Clause 5).
18952 D = diag::err_lambda_unevaluated_operand;
18953 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18954 // C++1y [expr.const]p2:
18955 // A conditional-expression e is a core constant expression unless the
18956 // evaluation of e, following the rules of the abstract machine, would
18957 // evaluate [...] a lambda-expression.
18958 D = diag::err_lambda_in_constant_expression;
18959 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18960 // C++17 [expr.prim.lamda]p2:
18961 // A lambda-expression shall not appear [...] in a template-argument.
18962 D = diag::err_lambda_in_invalid_context;
18963 } else
18964 llvm_unreachable("Couldn't infer lambda error message.");
18965
18966 for (const auto *L : Rec.Lambdas)
18967 Diag(L->getBeginLoc(), D);
18968 }
18969 }
18970
18971 // Append the collected materialized temporaries into previous context before
18972 // exit if the previous also is a lifetime extending context.
18974 parentEvaluationContext().InLifetimeExtendingContext &&
18975 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18978 }
18979
18981 HandleImmediateInvocations(*this, Rec);
18982
18983 // Warn on any volatile-qualified simple-assignments that are not discarded-
18984 // value expressions nor unevaluated operands (those cases get removed from
18985 // this list by CheckUnusedVolatileAssignment).
18986 for (auto *BO : Rec.VolatileAssignmentLHSs)
18987 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18988 << BO->getType();
18989
18990 // When are coming out of an unevaluated context, clear out any
18991 // temporaries that we may have created as part of the evaluation of
18992 // the expression in that context: they aren't relevant because they
18993 // will never be constructed.
18994 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18996 ExprCleanupObjects.end());
18997 Cleanup = Rec.ParentCleanup;
19000 // Otherwise, merge the contexts together.
19001 } else {
19002 Cleanup.mergeFrom(Rec.ParentCleanup);
19003 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
19004 }
19005
19007
19008 // Pop the current expression evaluation context off the stack.
19009 ExprEvalContexts.pop_back();
19010}
19011
19013 ExprCleanupObjects.erase(
19014 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
19015 ExprCleanupObjects.end());
19016 Cleanup.reset();
19017 MaybeODRUseExprs.clear();
19018}
19019
19022 if (Result.isInvalid())
19023 return ExprError();
19024 E = Result.get();
19025 if (!E->getType()->isVariablyModifiedType())
19026 return E;
19028}
19029
19030/// Are we in a context that is potentially constant evaluated per C++20
19031/// [expr.const]p12?
19033 /// C++2a [expr.const]p12:
19034 // An expression or conversion is potentially constant evaluated if it is
19035 switch (SemaRef.ExprEvalContexts.back().Context) {
19038
19039 // -- a manifestly constant-evaluated expression,
19043 // -- a potentially-evaluated expression,
19045 // -- an immediate subexpression of a braced-init-list,
19046
19047 // -- [FIXME] an expression of the form & cast-expression that occurs
19048 // within a templated entity
19049 // -- a subexpression of one of the above that is not a subexpression of
19050 // a nested unevaluated operand.
19051 return true;
19052
19055 // Expressions in this context are never evaluated.
19056 return false;
19057 }
19058 llvm_unreachable("Invalid context");
19059}
19060
19061/// Return true if this function has a calling convention that requires mangling
19062/// in the size of the parameter pack.
19064 // These manglings are only applicable for targets whcih use Microsoft
19065 // mangling scheme for C.
19067 return false;
19068
19069 // If this is C++ and this isn't an extern "C" function, parameters do not
19070 // need to be complete. In this case, C++ mangling will apply, which doesn't
19071 // use the size of the parameters.
19072 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
19073 return false;
19074
19075 // Stdcall, fastcall, and vectorcall need this special treatment.
19076 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19077 switch (CC) {
19078 case CC_X86StdCall:
19079 case CC_X86FastCall:
19080 case CC_X86VectorCall:
19081 return true;
19082 default:
19083 break;
19084 }
19085 return false;
19086}
19087
19088/// Require that all of the parameter types of function be complete. Normally,
19089/// parameter types are only required to be complete when a function is called
19090/// or defined, but to mangle functions with certain calling conventions, the
19091/// mangler needs to know the size of the parameter list. In this situation,
19092/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
19093/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
19094/// result in a linker error. Clang doesn't implement this behavior, and instead
19095/// attempts to error at compile time.
19097 SourceLocation Loc) {
19098 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
19099 FunctionDecl *FD;
19100 ParmVarDecl *Param;
19101
19102 public:
19103 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
19104 : FD(FD), Param(Param) {}
19105
19106 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19107 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
19108 StringRef CCName;
19109 switch (CC) {
19110 case CC_X86StdCall:
19111 CCName = "stdcall";
19112 break;
19113 case CC_X86FastCall:
19114 CCName = "fastcall";
19115 break;
19116 case CC_X86VectorCall:
19117 CCName = "vectorcall";
19118 break;
19119 default:
19120 llvm_unreachable("CC does not need mangling");
19121 }
19122
19123 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
19124 << Param->getDeclName() << FD->getDeclName() << CCName;
19125 }
19126 };
19127
19128 for (ParmVarDecl *Param : FD->parameters()) {
19129 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
19130 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
19131 }
19132}
19133
19134namespace {
19135enum class OdrUseContext {
19136 /// Declarations in this context are not odr-used.
19137 None,
19138 /// Declarations in this context are formally odr-used, but this is a
19139 /// dependent context.
19140 Dependent,
19141 /// Declarations in this context are odr-used but not actually used (yet).
19142 FormallyOdrUsed,
19143 /// Declarations in this context are used.
19144 Used
19145};
19146}
19147
19148/// Are we within a context in which references to resolved functions or to
19149/// variables result in odr-use?
19150static OdrUseContext isOdrUseContext(Sema &SemaRef) {
19153
19154 if (Context.isUnevaluated())
19155 return OdrUseContext::None;
19156
19158 return OdrUseContext::Dependent;
19159
19160 if (Context.isDiscardedStatementContext())
19161 return OdrUseContext::FormallyOdrUsed;
19162
19163 else if (Context.Context ==
19165 return OdrUseContext::FormallyOdrUsed;
19166
19167 return OdrUseContext::Used;
19168}
19169
19171 if (!Func->isConstexpr())
19172 return false;
19173
19174 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
19175 return true;
19176
19177 // Lambda conversion operators are never user provided.
19178 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
19179 return isLambdaConversionOperator(Conv);
19180
19181 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
19182 return CCD && CCD->getInheritedConstructor();
19183}
19184
19186 bool MightBeOdrUse) {
19187 assert(Func && "No function?");
19188
19189 Func->setReferenced();
19190
19191 // Recursive functions aren't really used until they're used from some other
19192 // context.
19193 bool IsRecursiveCall = CurContext == Func;
19194
19195 // C++11 [basic.def.odr]p3:
19196 // A function whose name appears as a potentially-evaluated expression is
19197 // odr-used if it is the unique lookup result or the selected member of a
19198 // set of overloaded functions [...].
19199 //
19200 // We (incorrectly) mark overload resolution as an unevaluated context, so we
19201 // can just check that here.
19202 OdrUseContext OdrUse =
19203 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
19204 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
19205 OdrUse = OdrUseContext::FormallyOdrUsed;
19206
19207 // Trivial default constructors and destructors are never actually used.
19208 // FIXME: What about other special members?
19209 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
19210 OdrUse == OdrUseContext::Used) {
19211 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
19212 if (Constructor->isDefaultConstructor())
19213 OdrUse = OdrUseContext::FormallyOdrUsed;
19215 OdrUse = OdrUseContext::FormallyOdrUsed;
19216 }
19217
19218 // C++20 [expr.const]p12:
19219 // A function [...] is needed for constant evaluation if it is [...] a
19220 // constexpr function that is named by an expression that is potentially
19221 // constant evaluated
19222 bool NeededForConstantEvaluation =
19225
19226 // Determine whether we require a function definition to exist, per
19227 // C++11 [temp.inst]p3:
19228 // Unless a function template specialization has been explicitly
19229 // instantiated or explicitly specialized, the function template
19230 // specialization is implicitly instantiated when the specialization is
19231 // referenced in a context that requires a function definition to exist.
19232 // C++20 [temp.inst]p7:
19233 // The existence of a definition of a [...] function is considered to
19234 // affect the semantics of the program if the [...] function is needed for
19235 // constant evaluation by an expression
19236 // C++20 [basic.def.odr]p10:
19237 // Every program shall contain exactly one definition of every non-inline
19238 // function or variable that is odr-used in that program outside of a
19239 // discarded statement
19240 // C++20 [special]p1:
19241 // The implementation will implicitly define [defaulted special members]
19242 // if they are odr-used or needed for constant evaluation.
19243 //
19244 // Note that we skip the implicit instantiation of templates that are only
19245 // used in unused default arguments or by recursive calls to themselves.
19246 // This is formally non-conforming, but seems reasonable in practice.
19247 bool NeedDefinition =
19248 !IsRecursiveCall &&
19249 (OdrUse == OdrUseContext::Used ||
19250 (NeededForConstantEvaluation && !Func->isPureVirtual()));
19251
19252 // C++14 [temp.expl.spec]p6:
19253 // If a template [...] is explicitly specialized then that specialization
19254 // shall be declared before the first use of that specialization that would
19255 // cause an implicit instantiation to take place, in every translation unit
19256 // in which such a use occurs
19257 if (NeedDefinition &&
19258 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
19259 Func->getMemberSpecializationInfo()))
19261
19262 if (getLangOpts().CUDA)
19263 CUDA().CheckCall(Loc, Func);
19264
19265 // If we need a definition, try to create one.
19266 if (NeedDefinition && !Func->getBody()) {
19269 dyn_cast<CXXConstructorDecl>(Func)) {
19271 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19272 if (Constructor->isDefaultConstructor()) {
19273 if (Constructor->isTrivial() &&
19274 !Constructor->hasAttr<DLLExportAttr>())
19275 return;
19277 } else if (Constructor->isCopyConstructor()) {
19279 } else if (Constructor->isMoveConstructor()) {
19281 }
19282 } else if (Constructor->getInheritedConstructor()) {
19284 }
19285 } else if (CXXDestructorDecl *Destructor =
19286 dyn_cast<CXXDestructorDecl>(Func)) {
19288 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19289 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19290 return;
19292 }
19293 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19294 MarkVTableUsed(Loc, Destructor->getParent());
19295 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
19296 if (MethodDecl->isOverloadedOperator() &&
19297 MethodDecl->getOverloadedOperator() == OO_Equal) {
19298 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
19299 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19300 if (MethodDecl->isCopyAssignmentOperator())
19301 DefineImplicitCopyAssignment(Loc, MethodDecl);
19302 else if (MethodDecl->isMoveAssignmentOperator())
19303 DefineImplicitMoveAssignment(Loc, MethodDecl);
19304 }
19305 } else if (isa<CXXConversionDecl>(MethodDecl) &&
19306 MethodDecl->getParent()->isLambda()) {
19307 CXXConversionDecl *Conversion =
19308 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
19309 if (Conversion->isLambdaToBlockPointerConversion())
19311 else
19313 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19314 MarkVTableUsed(Loc, MethodDecl->getParent());
19315 }
19316
19317 if (Func->isDefaulted() && !Func->isDeleted()) {
19318 DefaultedComparisonKind DCK = Func->getDefaultedComparisonKind();
19321 }
19322
19323 // Implicit instantiation of function templates and member functions of
19324 // class templates.
19325 if (Func->isImplicitlyInstantiable()) {
19327 Func->getTemplateSpecializationKindForInstantiation();
19328 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19329 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19330 if (FirstInstantiation) {
19331 PointOfInstantiation = Loc;
19332 if (auto *MSI = Func->getMemberSpecializationInfo())
19333 MSI->setPointOfInstantiation(Loc);
19334 // FIXME: Notify listener.
19335 else
19336 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19337 } else if (TSK != TSK_ImplicitInstantiation) {
19338 // Use the point of use as the point of instantiation, instead of the
19339 // point of explicit instantiation (which we track as the actual point
19340 // of instantiation). This gives better backtraces in diagnostics.
19341 PointOfInstantiation = Loc;
19342 }
19343
19344 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19345 Func->isConstexpr()) {
19346 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19347 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19348 CodeSynthesisContexts.size())
19350 std::make_pair(Func, PointOfInstantiation));
19351 else if (Func->isConstexpr())
19352 // Do not defer instantiations of constexpr functions, to avoid the
19353 // expression evaluator needing to call back into Sema if it sees a
19354 // call to such a function.
19355 InstantiateFunctionDefinition(PointOfInstantiation, Func);
19356 else {
19357 Func->setInstantiationIsPending(true);
19358 PendingInstantiations.push_back(
19359 std::make_pair(Func, PointOfInstantiation));
19360 if (llvm::isTimeTraceVerbose()) {
19361 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
19362 std::string Name;
19363 llvm::raw_string_ostream OS(Name);
19364 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
19365 /*Qualified=*/true);
19366 return Name;
19367 });
19368 }
19369 // Notify the consumer that a function was implicitly instantiated.
19370 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
19371 }
19372 }
19373 } else {
19374 // Walk redefinitions, as some of them may be instantiable.
19375 for (auto *i : Func->redecls()) {
19376 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19377 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19378 }
19379 }
19380 });
19381 }
19382
19383 // If a constructor was defined in the context of a default parameter
19384 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19385 // context), its initializers may not be referenced yet.
19386 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19388 *this,
19389 Constructor->isImmediateFunction()
19392 Constructor);
19393 for (CXXCtorInitializer *Init : Constructor->inits()) {
19394 if (Init->isInClassMemberInitializer())
19395 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19396 MarkDeclarationsReferencedInExpr(Init->getInit());
19397 });
19398 }
19399 }
19400
19401 // C++14 [except.spec]p17:
19402 // An exception-specification is considered to be needed when:
19403 // - the function is odr-used or, if it appears in an unevaluated operand,
19404 // would be odr-used if the expression were potentially-evaluated;
19405 //
19406 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19407 // function is a pure virtual function we're calling, and in that case the
19408 // function was selected by overload resolution and we need to resolve its
19409 // exception specification for a different reason.
19410 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19412 ResolveExceptionSpec(Loc, FPT);
19413
19414 // A callee could be called by a host function then by a device function.
19415 // If we only try recording once, we will miss recording the use on device
19416 // side. Therefore keep trying until it is recorded.
19417 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19418 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19420
19421 // If this is the first "real" use, act on that.
19422 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19423 // Keep track of used but undefined functions.
19424 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19425 if (mightHaveNonExternalLinkage(Func))
19426 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19427 else if (Func->getMostRecentDecl()->isInlined() &&
19428 !LangOpts.GNUInline &&
19429 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19430 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19432 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19433 }
19434
19435 // Some x86 Windows calling conventions mangle the size of the parameter
19436 // pack into the name. Computing the size of the parameters requires the
19437 // parameter types to be complete. Check that now.
19440
19441 // In the MS C++ ABI, the compiler emits destructor variants where they are
19442 // used. If the destructor is used here but defined elsewhere, mark the
19443 // virtual base destructors referenced. If those virtual base destructors
19444 // are inline, this will ensure they are defined when emitting the complete
19445 // destructor variant. This checking may be redundant if the destructor is
19446 // provided later in this TU.
19447 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19448 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19449 CXXRecordDecl *Parent = Dtor->getParent();
19450 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19452 }
19453 }
19454
19455 Func->markUsed(Context);
19456 }
19457}
19458
19459/// Directly mark a variable odr-used. Given a choice, prefer to use
19460/// MarkVariableReferenced since it does additional checks and then
19461/// calls MarkVarDeclODRUsed.
19462/// If the variable must be captured:
19463/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19464/// - else capture it in the DeclContext that maps to the
19465/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19466static void
19468 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19469 // Keep track of used but undefined variables.
19470 // FIXME: We shouldn't suppress this warning for static data members.
19471 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19472 assert(Var && "expected a capturable variable");
19473
19475 (!Var->isExternallyVisible() || Var->isInline() ||
19477 !(Var->isStaticDataMember() && Var->hasInit())) {
19479 if (old.isInvalid())
19480 old = Loc;
19481 }
19482 QualType CaptureType, DeclRefType;
19483 if (SemaRef.LangOpts.OpenMP)
19486 /*EllipsisLoc*/ SourceLocation(),
19487 /*BuildAndDiagnose*/ true, CaptureType,
19488 DeclRefType, FunctionScopeIndexToStopAt);
19489
19490 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19491 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19492 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
19493 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
19494 if (VarTarget == SemaCUDA::CVT_Host &&
19495 (UserTarget == CUDAFunctionTarget::Device ||
19496 UserTarget == CUDAFunctionTarget::HostDevice ||
19497 UserTarget == CUDAFunctionTarget::Global)) {
19498 // Diagnose ODR-use of host global variables in device functions.
19499 // Reference of device global variables in host functions is allowed
19500 // through shadow variables therefore it is not diagnosed.
19501 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19502 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19503 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19505 Var->getType().isConstQualified()
19506 ? diag::note_cuda_const_var_unpromoted
19507 : diag::note_cuda_host_var);
19508 }
19509 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19510 // Also capture __device__ const variables, which are classified
19511 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19512 // an explicit CUDADeviceAttr to distinguish them from plain
19513 // const variables (no __device__), which also get CVT_Both but
19514 // only have an implicit CUDADeviceAttr.
19515 (VarTarget == SemaCUDA::CVT_Both &&
19516 Var->hasAttr<CUDADeviceAttr>() &&
19517 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19518 !Var->hasAttr<CUDASharedAttr>() &&
19519 (UserTarget == CUDAFunctionTarget::Host ||
19520 UserTarget == CUDAFunctionTarget::HostDevice)) {
19521 // Record a CUDA/HIP device side variable if it is ODR-used
19522 // by host code. This is done conservatively, when the variable is
19523 // referenced in any of the following contexts:
19524 // - a non-function context
19525 // - a host function
19526 // - a host device function
19527 // This makes the ODR-use of the device side variable by host code to
19528 // be visible in the device compilation for the compiler to be able to
19529 // emit template variables instantiated by host code only and to
19530 // externalize the static device side variable ODR-used by host code.
19531 if (!Var->hasExternalStorage())
19533 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19534 (!FD || (!FD->getDescribedFunctionTemplate() &&
19538 }
19539 }
19540
19541 V->markUsed(SemaRef.Context);
19542}
19543
19545 SourceLocation Loc,
19546 unsigned CapturingScopeIndex) {
19547 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19548}
19549
19551 SourceLocation loc,
19552 ValueDecl *var) {
19553 DeclContext *VarDC =
19554 var->getDeclContext()->getEnclosingNonExpansionStatementContext();
19555
19556 // If the parameter still belongs to the translation unit, then
19557 // we're actually just using one parameter in the declaration of
19558 // the next.
19559 if (isa<ParmVarDecl>(var) &&
19561 return;
19562
19563 // For C code, don't diagnose about capture if we're not actually in code
19564 // right now; it's impossible to write a non-constant expression outside of
19565 // function context, so we'll get other (more useful) diagnostics later.
19566 //
19567 // For C++, things get a bit more nasty... it would be nice to suppress this
19568 // diagnostic for certain cases like using a local variable in an array bound
19569 // for a member of a local class, but the correct predicate is not obvious.
19570 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19571 return;
19572
19573 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19574 unsigned ContextKind = 3; // unknown
19575 if (isa<CXXMethodDecl>(VarDC) &&
19576 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19577 ContextKind = 2;
19578 } else if (isa<FunctionDecl>(VarDC)) {
19579 ContextKind = 0;
19580 } else if (isa<BlockDecl>(VarDC)) {
19581 ContextKind = 1;
19582 }
19583
19584 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19585 << var << ValueKind << ContextKind << VarDC;
19586 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19587 << var;
19588
19589 // FIXME: Add additional diagnostic info about class etc. which prevents
19590 // capture.
19591}
19592
19594 ValueDecl *Var,
19595 bool &SubCapturesAreNested,
19596 QualType &CaptureType,
19597 QualType &DeclRefType) {
19598 // Check whether we've already captured it.
19599 if (CSI->CaptureMap.count(Var)) {
19600 // If we found a capture, any subcaptures are nested.
19601 SubCapturesAreNested = true;
19602
19603 // Retrieve the capture type for this variable.
19604 CaptureType = CSI->getCapture(Var).getCaptureType();
19605
19606 // Compute the type of an expression that refers to this variable.
19607 DeclRefType = CaptureType.getNonReferenceType();
19608
19609 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19610 // are mutable in the sense that user can change their value - they are
19611 // private instances of the captured declarations.
19612 const Capture &Cap = CSI->getCapture(Var);
19613 // C++ [expr.prim.lambda]p10:
19614 // The type of such a data member is [...] an lvalue reference to the
19615 // referenced function type if the entity is a reference to a function.
19616 // [...]
19617 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19618 !(isa<LambdaScopeInfo>(CSI) &&
19619 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19621 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19622 DeclRefType.addConst();
19623 return true;
19624 }
19625 return false;
19626}
19627
19628// Only block literals, captured statements, and lambda expressions can
19629// capture; other scopes don't work.
19631 ValueDecl *Var,
19632 SourceLocation Loc,
19633 const bool Diagnose,
19634 Sema &S) {
19637
19638 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19639 if (Underlying) {
19640 if (Underlying->hasLocalStorage() && Diagnose)
19642 }
19643 return nullptr;
19644}
19645
19646// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19647// certain types of variables (unnamed, variably modified types etc.)
19648// so check for eligibility.
19650 SourceLocation Loc, const bool Diagnose,
19651 Sema &S) {
19652
19653 assert((isa<VarDecl, BindingDecl>(Var)) &&
19654 "Only variables and structured bindings can be captured");
19655
19656 bool IsBlock = isa<BlockScopeInfo>(CSI);
19657 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19658
19659 // Lambdas are not allowed to capture unnamed variables
19660 // (e.g. anonymous unions).
19661 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19662 // assuming that's the intent.
19663 if (IsLambda && !Var->getDeclName()) {
19664 if (Diagnose) {
19665 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19666 S.Diag(Var->getLocation(), diag::note_declared_at);
19667 }
19668 return false;
19669 }
19670
19671 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19672 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19673 if (Diagnose) {
19674 S.Diag(Loc, diag::err_ref_vm_type);
19675 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19676 }
19677 return false;
19678 }
19679 // Prohibit structs with flexible array members too.
19680 // We cannot capture what is in the tail end of the struct.
19681 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19682 VTD && VTD->hasFlexibleArrayMember()) {
19683 if (Diagnose) {
19684 if (IsBlock)
19685 S.Diag(Loc, diag::err_ref_flexarray_type);
19686 else
19687 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19688 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19689 }
19690 return false;
19691 }
19692 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19693 // Lambdas and captured statements are not allowed to capture __block
19694 // variables; they don't support the expected semantics.
19695 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19696 if (Diagnose) {
19697 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19698 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19699 }
19700 return false;
19701 }
19702 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19703 if (S.getLangOpts().OpenCL && IsBlock &&
19704 Var->getType()->isBlockPointerType()) {
19705 if (Diagnose)
19706 S.Diag(Loc, diag::err_opencl_block_ref_block);
19707 return false;
19708 }
19709
19710 if (isa<BindingDecl>(Var)) {
19711 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19712 if (Diagnose)
19714 return false;
19715 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19716 S.DiagCompat(Loc, diag_compat::capture_binding) << Var;
19717 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19718 }
19719 }
19720
19721 return true;
19722}
19723
19724// Returns true if the capture by block was successful.
19726 SourceLocation Loc, const bool BuildAndDiagnose,
19727 QualType &CaptureType, QualType &DeclRefType,
19728 const bool Nested, Sema &S, bool Invalid) {
19729 bool ByRef = false;
19730
19731 // Blocks are not allowed to capture arrays, excepting OpenCL.
19732 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19733 // (decayed to pointers).
19734 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19735 if (BuildAndDiagnose) {
19736 S.Diag(Loc, diag::err_ref_array_type);
19737 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19738 Invalid = true;
19739 } else {
19740 return false;
19741 }
19742 }
19743
19744 // Forbid the block-capture of autoreleasing variables.
19745 if (!Invalid &&
19747 if (BuildAndDiagnose) {
19748 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19749 << /*block*/ 0;
19750 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19751 Invalid = true;
19752 } else {
19753 return false;
19754 }
19755 }
19756
19757 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19758 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19759 QualType PointeeTy = PT->getPointeeType();
19760
19761 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19763 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19764 if (BuildAndDiagnose) {
19765 SourceLocation VarLoc = Var->getLocation();
19766 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19767 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19768 }
19769 }
19770 }
19771
19772 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19773 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19774 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19775 // Block capture by reference does not change the capture or
19776 // declaration reference types.
19777 ByRef = true;
19778 } else {
19779 // Block capture by copy introduces 'const'.
19780 CaptureType = CaptureType.getNonReferenceType().withConst();
19781 DeclRefType = CaptureType;
19782 }
19783
19784 // Actually capture the variable.
19785 if (BuildAndDiagnose)
19786 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19787 CaptureType, Invalid);
19788
19789 return !Invalid;
19790}
19791
19792/// Capture the given variable in the captured region.
19795 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19796 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19797 Sema &S, bool Invalid) {
19798 // By default, capture variables by reference.
19799 bool ByRef = true;
19800 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19801 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19802 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19803 // Using an LValue reference type is consistent with Lambdas (see below).
19804 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19805 bool HasConst = DeclRefType.isConstQualified();
19806 DeclRefType = DeclRefType.getUnqualifiedType();
19807 // Don't lose diagnostics about assignments to const.
19808 if (HasConst)
19809 DeclRefType.addConst();
19810 }
19811 // Do not capture firstprivates in tasks.
19812 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19813 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19814 return true;
19815 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19816 RSI->OpenMPCaptureLevel);
19817 }
19818
19819 if (ByRef)
19820 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19821 else
19822 CaptureType = DeclRefType;
19823
19824 // Actually capture the variable.
19825 if (BuildAndDiagnose)
19826 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19827 Loc, SourceLocation(), CaptureType, Invalid);
19828
19829 return !Invalid;
19830}
19831
19832/// Capture the given variable in the lambda.
19834 SourceLocation Loc, const bool BuildAndDiagnose,
19835 QualType &CaptureType, QualType &DeclRefType,
19836 const bool RefersToCapturedVariable,
19837 const TryCaptureKind Kind,
19838 SourceLocation EllipsisLoc, const bool IsTopScope,
19839 Sema &S, bool Invalid) {
19840 // Determine whether we are capturing by reference or by value.
19841 bool ByRef = false;
19842 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19843 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19844 } else {
19845 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19846 }
19847
19848 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19850 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19851 Invalid = true;
19852 }
19853
19854 // Compute the type of the field that will capture this variable.
19855 if (ByRef) {
19856 // C++11 [expr.prim.lambda]p15:
19857 // An entity is captured by reference if it is implicitly or
19858 // explicitly captured but not captured by copy. It is
19859 // unspecified whether additional unnamed non-static data
19860 // members are declared in the closure type for entities
19861 // captured by reference.
19862 //
19863 // FIXME: It is not clear whether we want to build an lvalue reference
19864 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19865 // to do the former, while EDG does the latter. Core issue 1249 will
19866 // clarify, but for now we follow GCC because it's a more permissive and
19867 // easily defensible position.
19868 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19869 } else {
19870 // C++11 [expr.prim.lambda]p14:
19871 // For each entity captured by copy, an unnamed non-static
19872 // data member is declared in the closure type. The
19873 // declaration order of these members is unspecified. The type
19874 // of such a data member is the type of the corresponding
19875 // captured entity if the entity is not a reference to an
19876 // object, or the referenced type otherwise. [Note: If the
19877 // captured entity is a reference to a function, the
19878 // corresponding data member is also a reference to a
19879 // function. - end note ]
19880 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19881 if (!RefType->getPointeeType()->isFunctionType())
19882 CaptureType = RefType->getPointeeType();
19883 }
19884
19885 // Forbid the lambda copy-capture of autoreleasing variables.
19886 if (!Invalid &&
19888 if (BuildAndDiagnose) {
19889 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19890 S.Diag(Var->getLocation(), diag::note_previous_decl)
19891 << Var->getDeclName();
19892 Invalid = true;
19893 } else {
19894 return false;
19895 }
19896 }
19897
19898 // Make sure that by-copy captures are of a complete and non-abstract type.
19899 if (!Invalid && BuildAndDiagnose) {
19900 if (!CaptureType->isDependentType() &&
19902 Loc, CaptureType,
19903 diag::err_capture_of_incomplete_or_sizeless_type,
19904 Var->getDeclName()))
19905 Invalid = true;
19906 else if (S.RequireNonAbstractType(Loc, CaptureType,
19907 diag::err_capture_of_abstract_type))
19908 Invalid = true;
19909 }
19910 }
19911
19912 // Compute the type of a reference to this captured variable.
19913 if (ByRef)
19914 DeclRefType = CaptureType.getNonReferenceType();
19915 else {
19916 // C++ [expr.prim.lambda]p5:
19917 // The closure type for a lambda-expression has a public inline
19918 // function call operator [...]. This function call operator is
19919 // declared const (9.3.1) if and only if the lambda-expression's
19920 // parameter-declaration-clause is not followed by mutable.
19921 DeclRefType = CaptureType.getNonReferenceType();
19922 bool Const = LSI->lambdaCaptureShouldBeConst();
19923 // C++ [expr.prim.lambda]p10:
19924 // The type of such a data member is [...] an lvalue reference to the
19925 // referenced function type if the entity is a reference to a function.
19926 // [...]
19927 if (Const && !CaptureType->isReferenceType() &&
19928 !DeclRefType->isFunctionType())
19929 DeclRefType.addConst();
19930 }
19931
19932 // Add the capture.
19933 if (BuildAndDiagnose)
19934 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19935 Loc, EllipsisLoc, CaptureType, Invalid);
19936
19937 return !Invalid;
19938}
19939
19941 const ASTContext &Context) {
19942 // Offer a Copy fix even if the type is dependent.
19943 if (Var->getType()->isDependentType())
19944 return true;
19946 if (T.isTriviallyCopyableType(Context))
19947 return true;
19948 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19949
19950 if (!(RD = RD->getDefinition()))
19951 return false;
19952 if (RD->hasSimpleCopyConstructor())
19953 return true;
19954 if (RD->hasUserDeclaredCopyConstructor())
19955 for (CXXConstructorDecl *Ctor : RD->ctors())
19956 if (Ctor->isCopyConstructor())
19957 return !Ctor->isDeleted();
19958 }
19959 return false;
19960}
19961
19962/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19963/// default capture. Fixes may be omitted if they aren't allowed by the
19964/// standard, for example we can't emit a default copy capture fix-it if we
19965/// already explicitly copy capture capture another variable.
19967 ValueDecl *Var) {
19969 // Don't offer Capture by copy of default capture by copy fixes if Var is
19970 // known not to be copy constructible.
19971 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19972
19973 SmallString<32> FixBuffer;
19974 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19975 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19976 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19977 if (ShouldOfferCopyFix) {
19978 // Offer fixes to insert an explicit capture for the variable.
19979 // [] -> [VarName]
19980 // [OtherCapture] -> [OtherCapture, VarName]
19981 FixBuffer.assign({Separator, Var->getName()});
19982 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19983 << Var << /*value*/ 0
19984 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19985 }
19986 // As above but capture by reference.
19987 FixBuffer.assign({Separator, "&", Var->getName()});
19988 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19989 << Var << /*reference*/ 1
19990 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19991 }
19992
19993 // Only try to offer default capture if there are no captures excluding this
19994 // and init captures.
19995 // [this]: OK.
19996 // [X = Y]: OK.
19997 // [&A, &B]: Don't offer.
19998 // [A, B]: Don't offer.
19999 if (llvm::any_of(LSI->Captures, [](Capture &C) {
20000 return !C.isThisCapture() && !C.isInitCapture();
20001 }))
20002 return;
20003
20004 // The default capture specifiers, '=' or '&', must appear first in the
20005 // capture body.
20006 SourceLocation DefaultInsertLoc =
20008
20009 if (ShouldOfferCopyFix) {
20010 bool CanDefaultCopyCapture = true;
20011 // [=, *this] OK since c++17
20012 // [=, this] OK since c++20
20013 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
20014 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
20016 : false;
20017 // We can't use default capture by copy if any captures already specified
20018 // capture by copy.
20019 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
20020 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
20021 })) {
20022 FixBuffer.assign({"=", Separator});
20023 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
20024 << /*value*/ 0
20025 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
20026 }
20027 }
20028
20029 // We can't use default capture by reference if any captures already specified
20030 // capture by reference.
20031 if (llvm::none_of(LSI->Captures, [](Capture &C) {
20032 return !C.isInitCapture() && C.isReferenceCapture() &&
20033 !C.isThisCapture();
20034 })) {
20035 FixBuffer.assign({"&", Separator});
20036 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
20037 << /*reference*/ 1
20038 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
20039 }
20040}
20041
20043 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
20044 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
20045 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
20046 // An init-capture is notionally from the context surrounding its
20047 // declaration, but its parent DC is the lambda class.
20048 DeclContext *VarDC =
20050 DeclContext *DC = CurContext;
20051
20052 // Skip past RequiresExprBodys because they don't constitute function scopes.
20053 while (DC->isRequiresExprBody() || DC->isExpansionStmt())
20054 DC = DC->getParent();
20055
20056 // tryCaptureVariable is called every time a DeclRef is formed,
20057 // it can therefore have non-negigible impact on performances.
20058 // For local variables and when there is no capturing scope,
20059 // we can bailout early.
20060 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
20061 return true;
20062
20063 // Exception: Function parameters are not tied to the function's DeclContext
20064 // until we enter the function definition. Capturing them anyway would result
20065 // in an out-of-bounds error while traversing DC and its parents.
20066 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
20067 return true;
20068
20069 const auto *VD = dyn_cast<VarDecl>(Var);
20070 if (VD) {
20071 if (VD->isInitCapture())
20072 VarDC = VarDC->getParent();
20073 } else {
20075 }
20076 assert(VD && "Cannot capture a null variable");
20077
20078 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
20079 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
20080 // We need to sync up the Declaration Context with the
20081 // FunctionScopeIndexToStopAt
20082 if (FunctionScopeIndexToStopAt) {
20083 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
20084 unsigned FSIndex = FunctionScopes.size() - 1;
20085 // When we're parsing the lambda parameter list, the current DeclContext is
20086 // NOT the lambda but its parent. So move away the current LSI before
20087 // aligning DC and FunctionScopeIndexToStopAt.
20088 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
20089 FSIndex && LSI && !LSI->AfterParameterList)
20090 --FSIndex;
20091 assert(MaxFunctionScopesIndex <= FSIndex &&
20092 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
20093 "FunctionScopes.");
20094 while (FSIndex != MaxFunctionScopesIndex) {
20096 --FSIndex;
20097 }
20098 }
20099
20100 // Capture global variables if it is required to use private copy of this
20101 // variable.
20102 bool IsGlobal = !VD->hasLocalStorage();
20103 if (IsGlobal && !(LangOpts.OpenMP &&
20104 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
20105 MaxFunctionScopesIndex)))
20106 return true;
20107
20108 if (isa<VarDecl>(Var))
20109 Var = cast<VarDecl>(Var->getCanonicalDecl());
20110
20111 // Walk up the stack to determine whether we can capture the variable,
20112 // performing the "simple" checks that don't depend on type. We stop when
20113 // we've either hit the declared scope of the variable or find an existing
20114 // capture of that variable. We start from the innermost capturing-entity
20115 // (the DC) and ensure that all intervening capturing-entities
20116 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
20117 // declcontext can either capture the variable or have already captured
20118 // the variable.
20119 CaptureType = Var->getType();
20120 DeclRefType = CaptureType.getNonReferenceType();
20121 bool Nested = false;
20122 bool Explicit = (Kind != TryCaptureKind::Implicit);
20123 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
20124 do {
20125
20126 LambdaScopeInfo *LSI = nullptr;
20127 if (!FunctionScopes.empty())
20128 LSI = dyn_cast_or_null<LambdaScopeInfo>(
20129 FunctionScopes[FunctionScopesIndex]);
20130
20131 bool IsInScopeDeclarationContext =
20132 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
20133
20134 if (LSI && !LSI->AfterParameterList) {
20135 // This allows capturing parameters from a default value which does not
20136 // seems correct
20137 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
20138 return true;
20139 }
20140 // If the variable is declared in the current context, there is no need to
20141 // capture it.
20142 if (IsInScopeDeclarationContext &&
20143 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
20144 return true;
20145
20146 // Only block literals, captured statements, and lambda expressions can
20147 // capture; other scopes don't work.
20148 DeclContext *ParentDC =
20149 !IsInScopeDeclarationContext
20150 ? DC->getParent()
20151 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
20152 BuildAndDiagnose, *this);
20153 // We need to check for the parent *first* because, if we *have*
20154 // private-captured a global variable, we need to recursively capture it in
20155 // intermediate blocks, lambdas, etc.
20156 if (!ParentDC) {
20157 if (IsGlobal) {
20158 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
20159 break;
20160 }
20161 return true;
20162 }
20163
20164 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
20166
20167 // Check whether we've already captured it.
20168 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
20169 DeclRefType)) {
20170 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
20171 break;
20172 }
20173
20174 // When evaluating some attributes (like enable_if) we might refer to a
20175 // function parameter appertaining to the same declaration as that
20176 // attribute.
20177 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
20178 Parm && Parm->getDeclContext() == DC)
20179 return true;
20180
20181 // If we are instantiating a generic lambda call operator body,
20182 // we do not want to capture new variables. What was captured
20183 // during either a lambdas transformation or initial parsing
20184 // should be used.
20186 if (BuildAndDiagnose) {
20189 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
20190 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
20191 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
20192 buildLambdaCaptureFixit(*this, LSI, Var);
20193 } else
20195 }
20196 return true;
20197 }
20198
20199 // Try to capture variable-length arrays types.
20200 if (Var->getType()->isVariablyModifiedType()) {
20201 // We're going to walk down into the type and look for VLA
20202 // expressions.
20203 QualType QTy = Var->getType();
20204 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
20205 QTy = PVD->getOriginalType();
20207 }
20208
20209 if (getLangOpts().OpenMP) {
20210 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20211 // OpenMP private variables should not be captured in outer scope, so
20212 // just break here. Similarly, global variables that are captured in a
20213 // target region should not be captured outside the scope of the region.
20214 if (RSI->CapRegionKind == CR_OpenMP) {
20215 // FIXME: We should support capturing structured bindings in OpenMP.
20216 if (isa<BindingDecl>(Var)) {
20217 if (BuildAndDiagnose) {
20218 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
20219 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
20220 }
20221 return true;
20222 }
20223 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
20224 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
20225 // If the variable is private (i.e. not captured) and has variably
20226 // modified type, we still need to capture the type for correct
20227 // codegen in all regions, associated with the construct. Currently,
20228 // it is captured in the innermost captured region only.
20229 if (IsOpenMPPrivateDecl != OMPC_unknown &&
20230 Var->getType()->isVariablyModifiedType()) {
20231 QualType QTy = Var->getType();
20232 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
20233 QTy = PVD->getOriginalType();
20234 for (int I = 1,
20235 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
20236 I < E; ++I) {
20237 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
20238 FunctionScopes[FunctionScopesIndex - I]);
20239 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
20240 "Wrong number of captured regions associated with the "
20241 "OpenMP construct.");
20242 captureVariablyModifiedType(Context, QTy, OuterRSI);
20243 }
20244 }
20245 bool IsTargetCap =
20246 IsOpenMPPrivateDecl != OMPC_private &&
20247 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
20248 RSI->OpenMPCaptureLevel);
20249 // Do not capture global if it is not privatized in outer regions.
20250 bool IsGlobalCap =
20251 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
20252 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
20253
20254 // When we detect target captures we are looking from inside the
20255 // target region, therefore we need to propagate the capture from the
20256 // enclosing region. Therefore, the capture is not initially nested.
20257 if (IsTargetCap)
20258 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
20259 RSI->OpenMPLevel);
20260
20261 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
20262 (IsGlobal && !IsGlobalCap)) {
20263 Nested = !IsTargetCap;
20264 bool HasConst = DeclRefType.isConstQualified();
20265 DeclRefType = DeclRefType.getUnqualifiedType();
20266 // Don't lose diagnostics about assignments to const.
20267 if (HasConst)
20268 DeclRefType.addConst();
20269 CaptureType = Context.getLValueReferenceType(DeclRefType);
20270 break;
20271 }
20272 }
20273 }
20274 }
20276 // No capture-default, and this is not an explicit capture
20277 // so cannot capture this variable.
20278 if (BuildAndDiagnose) {
20279 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
20280 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
20281 auto *LSI = cast<LambdaScopeInfo>(CSI);
20282 if (LSI->Lambda) {
20283 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
20284 buildLambdaCaptureFixit(*this, LSI, Var);
20285 }
20286 // FIXME: If we error out because an outer lambda can not implicitly
20287 // capture a variable that an inner lambda explicitly captures, we
20288 // should have the inner lambda do the explicit capture - because
20289 // it makes for cleaner diagnostics later. This would purely be done
20290 // so that the diagnostic does not misleadingly claim that a variable
20291 // can not be captured by a lambda implicitly even though it is captured
20292 // explicitly. Suggestion:
20293 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20294 // at the function head
20295 // - cache the StartingDeclContext - this must be a lambda
20296 // - captureInLambda in the innermost lambda the variable.
20297 }
20298 return true;
20299 }
20300 Explicit = false;
20301 FunctionScopesIndex--;
20302 if (IsInScopeDeclarationContext)
20303 DC = ParentDC;
20304 } while (!VarDC->Equals(DC));
20305
20306 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20307 // computing the type of the capture at each step, checking type-specific
20308 // requirements, and adding captures if requested.
20309 // If the variable had already been captured previously, we start capturing
20310 // at the lambda nested within that one.
20311 bool Invalid = false;
20312 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20313 ++I) {
20315
20316 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20317 // certain types of variables (unnamed, variably modified types etc.)
20318 // so check for eligibility.
20319 if (!Invalid)
20320 Invalid =
20321 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
20322
20323 // After encountering an error, if we're actually supposed to capture, keep
20324 // capturing in nested contexts to suppress any follow-on diagnostics.
20325 if (Invalid && !BuildAndDiagnose)
20326 return true;
20327
20328 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
20329 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20330 DeclRefType, Nested, *this, Invalid);
20331 Nested = true;
20332 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20334 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
20335 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
20336 Nested = true;
20337 } else {
20339 Invalid =
20340 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20341 DeclRefType, Nested, Kind, EllipsisLoc,
20342 /*IsTopScope*/ I == N - 1, *this, Invalid);
20343 Nested = true;
20344 }
20345
20346 if (Invalid && !BuildAndDiagnose)
20347 return true;
20348 }
20349 return Invalid;
20350}
20351
20353 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20354 QualType CaptureType;
20355 QualType DeclRefType;
20356 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
20357 /*BuildAndDiagnose=*/true, CaptureType,
20358 DeclRefType, nullptr);
20359}
20360
20362 QualType CaptureType;
20363 QualType DeclRefType;
20364 return !tryCaptureVariable(
20366 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
20367}
20368
20370 assert(Var && "Null value cannot be captured");
20371
20372 QualType CaptureType;
20373 QualType DeclRefType;
20374
20375 // Determine whether we can capture this variable.
20377 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20378 nullptr))
20379 return QualType();
20380
20381 return DeclRefType;
20382}
20383
20384namespace {
20385// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20386// The produced TemplateArgumentListInfo* points to data stored within this
20387// object, so should only be used in contexts where the pointer will not be
20388// used after the CopiedTemplateArgs object is destroyed.
20389class CopiedTemplateArgs {
20390 bool HasArgs;
20391 TemplateArgumentListInfo TemplateArgStorage;
20392public:
20393 template<typename RefExpr>
20394 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20395 if (HasArgs)
20396 E->copyTemplateArgumentsInto(TemplateArgStorage);
20397 }
20398 operator TemplateArgumentListInfo*()
20399#ifdef __has_cpp_attribute
20400#if __has_cpp_attribute(clang::lifetimebound)
20401 [[clang::lifetimebound]]
20402#endif
20403#endif
20404 {
20405 return HasArgs ? &TemplateArgStorage : nullptr;
20406 }
20407};
20408}
20409
20410/// Walk the set of potential results of an expression and mark them all as
20411/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20412///
20413/// \return A new expression if we found any potential results, ExprEmpty() if
20414/// not, and ExprError() if we diagnosed an error.
20416 NonOdrUseReason NOUR) {
20417 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20418 // an object that satisfies the requirements for appearing in a
20419 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20420 // is immediately applied." This function handles the lvalue-to-rvalue
20421 // conversion part.
20422 //
20423 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20424 // transform it into the relevant kind of non-odr-use node and rebuild the
20425 // tree of nodes leading to it.
20426 //
20427 // This is a mini-TreeTransform that only transforms a restricted subset of
20428 // nodes (and only certain operands of them).
20429
20430 // Rebuild a subexpression.
20431 auto Rebuild = [&](Expr *Sub) {
20432 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20433 };
20434
20435 // Check whether a potential result satisfies the requirements of NOUR.
20436 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20437 // Any entity other than a VarDecl is always odr-used whenever it's named
20438 // in a potentially-evaluated expression.
20439 auto *VD = dyn_cast<VarDecl>(D);
20440 if (!VD)
20441 return true;
20442
20443 // C++2a [basic.def.odr]p4:
20444 // A variable x whose name appears as a potentially-evalauted expression
20445 // e is odr-used by e unless
20446 // -- x is a reference that is usable in constant expressions, or
20447 // -- x is a variable of non-reference type that is usable in constant
20448 // expressions and has no mutable subobjects, and e is an element of
20449 // the set of potential results of an expression of
20450 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20451 // conversion is applied, or
20452 // -- x is a variable of non-reference type, and e is an element of the
20453 // set of potential results of a discarded-value expression to which
20454 // the lvalue-to-rvalue conversion is not applied
20455 //
20456 // We check the first bullet and the "potentially-evaluated" condition in
20457 // BuildDeclRefExpr. We check the type requirements in the second bullet
20458 // in CheckLValueToRValueConversionOperand below.
20459 switch (NOUR) {
20460 case NOUR_None:
20461 case NOUR_Unevaluated:
20462 llvm_unreachable("unexpected non-odr-use-reason");
20463
20464 case NOUR_Constant:
20465 // Constant references were handled when they were built.
20466 if (VD->getType()->isReferenceType())
20467 return true;
20468 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20469 if (RD->hasDefinition() && RD->hasMutableFields())
20470 return true;
20471 if (!VD->isUsableInConstantExpressions(S.Context))
20472 return true;
20473 break;
20474
20475 case NOUR_Discarded:
20476 if (VD->getType()->isReferenceType())
20477 return true;
20478 break;
20479 }
20480 return false;
20481 };
20482
20483 // Check whether this expression may be odr-used in CUDA/HIP.
20484 auto MaybeCUDAODRUsed = [&]() -> bool {
20485 if (!S.LangOpts.CUDA)
20486 return false;
20487 LambdaScopeInfo *LSI = S.getCurLambda();
20488 if (!LSI)
20489 return false;
20490 auto *DRE = dyn_cast<DeclRefExpr>(E);
20491 if (!DRE)
20492 return false;
20493 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
20494 if (!VD)
20495 return false;
20496 return LSI->CUDAPotentialODRUsedVars.count(VD);
20497 };
20498
20499 // Mark that this expression does not constitute an odr-use.
20500 auto MarkNotOdrUsed = [&] {
20501 if (!MaybeCUDAODRUsed()) {
20502 S.MaybeODRUseExprs.remove(E);
20503 if (LambdaScopeInfo *LSI = S.getCurLambda())
20504 LSI->markVariableExprAsNonODRUsed(E);
20505 }
20506 };
20507
20508 // C++2a [basic.def.odr]p2:
20509 // The set of potential results of an expression e is defined as follows:
20510 switch (E->getStmtClass()) {
20511 // -- If e is an id-expression, ...
20512 case Expr::DeclRefExprClass: {
20513 auto *DRE = cast<DeclRefExpr>(E);
20514 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20515 break;
20516
20517 // Rebuild as a non-odr-use DeclRefExpr.
20518 MarkNotOdrUsed();
20519 return DeclRefExpr::Create(
20520 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20521 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20522 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20523 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20524 }
20525
20526 case Expr::FunctionParmPackExprClass: {
20527 auto *FPPE = cast<FunctionParmPackExpr>(E);
20528 // If any of the declarations in the pack is odr-used, then the expression
20529 // as a whole constitutes an odr-use.
20530 for (ValueDecl *D : *FPPE)
20531 if (IsPotentialResultOdrUsed(D))
20532 return ExprEmpty();
20533
20534 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20535 // nothing cares about whether we marked this as an odr-use, but it might
20536 // be useful for non-compiler tools.
20537 MarkNotOdrUsed();
20538 break;
20539 }
20540
20541 // -- If e is a subscripting operation with an array operand...
20542 case Expr::ArraySubscriptExprClass: {
20543 auto *ASE = cast<ArraySubscriptExpr>(E);
20544 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20545 if (!OldBase->getType()->isArrayType())
20546 break;
20547 ExprResult Base = Rebuild(OldBase);
20548 if (!Base.isUsable())
20549 return Base;
20550 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20551 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20552 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20553 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20554 ASE->getRBracketLoc());
20555 }
20556
20557 case Expr::MemberExprClass: {
20558 auto *ME = cast<MemberExpr>(E);
20559 // -- If e is a class member access expression [...] naming a non-static
20560 // data member...
20561 if (isa<FieldDecl>(ME->getMemberDecl())) {
20562 ExprResult Base = Rebuild(ME->getBase());
20563 if (!Base.isUsable())
20564 return Base;
20565 return MemberExpr::Create(
20566 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20567 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20568 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20569 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20570 ME->getObjectKind(), ME->isNonOdrUse());
20571 }
20572
20573 if (ME->getMemberDecl()->isCXXInstanceMember())
20574 break;
20575
20576 // -- If e is a class member access expression naming a static data member,
20577 // ...
20578 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20579 break;
20580
20581 // Rebuild as a non-odr-use MemberExpr.
20582 MarkNotOdrUsed();
20583 return MemberExpr::Create(
20584 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20585 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20586 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20587 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20588 }
20589
20590 case Expr::BinaryOperatorClass: {
20591 auto *BO = cast<BinaryOperator>(E);
20592 Expr *LHS = BO->getLHS();
20593 Expr *RHS = BO->getRHS();
20594 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20595 if (BO->getOpcode() == BO_PtrMemD) {
20596 ExprResult Sub = Rebuild(LHS);
20597 if (!Sub.isUsable())
20598 return Sub;
20599 BO->setLHS(Sub.get());
20600 // -- If e is a comma expression, ...
20601 } else if (BO->getOpcode() == BO_Comma) {
20602 ExprResult Sub = Rebuild(RHS);
20603 if (!Sub.isUsable())
20604 return Sub;
20605 BO->setRHS(Sub.get());
20606 } else {
20607 break;
20608 }
20609 return ExprResult(BO);
20610 }
20611
20612 // -- If e has the form (e1)...
20613 case Expr::ParenExprClass: {
20614 auto *PE = cast<ParenExpr>(E);
20615 ExprResult Sub = Rebuild(PE->getSubExpr());
20616 if (!Sub.isUsable())
20617 return Sub;
20618 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20619 }
20620
20621 // -- If e is a glvalue conditional expression, ...
20622 // We don't apply this to a binary conditional operator. FIXME: Should we?
20623 case Expr::ConditionalOperatorClass: {
20624 auto *CO = cast<ConditionalOperator>(E);
20625 ExprResult LHS = Rebuild(CO->getLHS());
20626 if (LHS.isInvalid())
20627 return ExprError();
20628 ExprResult RHS = Rebuild(CO->getRHS());
20629 if (RHS.isInvalid())
20630 return ExprError();
20631 if (!LHS.isUsable() && !RHS.isUsable())
20632 return ExprEmpty();
20633 if (!LHS.isUsable())
20634 LHS = CO->getLHS();
20635 if (!RHS.isUsable())
20636 RHS = CO->getRHS();
20637 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20638 CO->getCond(), LHS.get(), RHS.get());
20639 }
20640
20641 // [Clang extension]
20642 // -- If e has the form __extension__ e1...
20643 case Expr::UnaryOperatorClass: {
20644 auto *UO = cast<UnaryOperator>(E);
20645 if (UO->getOpcode() != UO_Extension)
20646 break;
20647 ExprResult Sub = Rebuild(UO->getSubExpr());
20648 if (!Sub.isUsable())
20649 return Sub;
20650 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20651 Sub.get());
20652 }
20653
20654 // [Clang extension]
20655 // -- If e has the form _Generic(...), the set of potential results is the
20656 // union of the sets of potential results of the associated expressions.
20657 case Expr::GenericSelectionExprClass: {
20658 auto *GSE = cast<GenericSelectionExpr>(E);
20659
20660 SmallVector<Expr *, 4> AssocExprs;
20661 bool AnyChanged = false;
20662 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20663 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20664 if (AssocExpr.isInvalid())
20665 return ExprError();
20666 if (AssocExpr.isUsable()) {
20667 AssocExprs.push_back(AssocExpr.get());
20668 AnyChanged = true;
20669 } else {
20670 AssocExprs.push_back(OrigAssocExpr);
20671 }
20672 }
20673
20674 void *ExOrTy = nullptr;
20675 bool IsExpr = GSE->isExprPredicate();
20676 if (IsExpr)
20677 ExOrTy = GSE->getControllingExpr();
20678 else
20679 ExOrTy = GSE->getControllingType();
20680 return AnyChanged ? S.CreateGenericSelectionExpr(
20681 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20682 GSE->getRParenLoc(), IsExpr, ExOrTy,
20683 GSE->getAssocTypeSourceInfos(), AssocExprs)
20684 : ExprEmpty();
20685 }
20686
20687 // [Clang extension]
20688 // -- If e has the form __builtin_choose_expr(...), the set of potential
20689 // results is the union of the sets of potential results of the
20690 // second and third subexpressions.
20691 case Expr::ChooseExprClass: {
20692 auto *CE = cast<ChooseExpr>(E);
20693
20694 ExprResult LHS = Rebuild(CE->getLHS());
20695 if (LHS.isInvalid())
20696 return ExprError();
20697
20698 ExprResult RHS = Rebuild(CE->getLHS());
20699 if (RHS.isInvalid())
20700 return ExprError();
20701
20702 if (!LHS.get() && !RHS.get())
20703 return ExprEmpty();
20704 if (!LHS.isUsable())
20705 LHS = CE->getLHS();
20706 if (!RHS.isUsable())
20707 RHS = CE->getRHS();
20708
20709 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20710 RHS.get(), CE->getRParenLoc());
20711 }
20712
20713 // Step through non-syntactic nodes.
20714 case Expr::ConstantExprClass: {
20715 auto *CE = cast<ConstantExpr>(E);
20716 ExprResult Sub = Rebuild(CE->getSubExpr());
20717 if (!Sub.isUsable())
20718 return Sub;
20719 return ConstantExpr::Create(S.Context, Sub.get());
20720 }
20721
20722 // We could mostly rely on the recursive rebuilding to rebuild implicit
20723 // casts, but not at the top level, so rebuild them here.
20724 case Expr::ImplicitCastExprClass: {
20725 auto *ICE = cast<ImplicitCastExpr>(E);
20726 // Only step through the narrow set of cast kinds we expect to encounter.
20727 // Anything else suggests we've left the region in which potential results
20728 // can be found.
20729 switch (ICE->getCastKind()) {
20730 case CK_NoOp:
20731 case CK_DerivedToBase:
20732 case CK_UncheckedDerivedToBase: {
20733 ExprResult Sub = Rebuild(ICE->getSubExpr());
20734 if (!Sub.isUsable())
20735 return Sub;
20736 CXXCastPath Path(ICE->path());
20737 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20738 ICE->getValueKind(), &Path);
20739 }
20740
20741 default:
20742 break;
20743 }
20744 break;
20745 }
20746
20747 default:
20748 break;
20749 }
20750
20751 // Can't traverse through this node. Nothing to do.
20752 return ExprEmpty();
20753}
20754
20756 // Check whether the operand is or contains an object of non-trivial C union
20757 // type.
20758 if (E->getType().isVolatileQualified() &&
20764
20765 // C++2a [basic.def.odr]p4:
20766 // [...] an expression of non-volatile-qualified non-class type to which
20767 // the lvalue-to-rvalue conversion is applied [...]
20768 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20769 return E;
20770
20773 if (Result.isInvalid())
20774 return ExprError();
20775 return Result.get() ? Result : E;
20776}
20777
20779 if (!Res.isUsable())
20780 return Res;
20781
20782 // If a constant-expression is a reference to a variable where we delay
20783 // deciding whether it is an odr-use, just assume we will apply the
20784 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20785 // (a non-type template argument), we have special handling anyway.
20787}
20788
20790 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20791 // call.
20792 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20793 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20794
20795 for (Expr *E : LocalMaybeODRUseExprs) {
20796 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20797 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20798 DRE->getLocation(), *this);
20799 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20800 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20801 *this);
20802 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20803 for (ValueDecl *VD : *FP)
20804 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20805 } else {
20806 llvm_unreachable("Unexpected expression");
20807 }
20808 }
20809
20810 assert(MaybeODRUseExprs.empty() &&
20811 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20812}
20813
20815 ValueDecl *Var, Expr *E) {
20817 if (!VD)
20818 return;
20819
20820 const bool RefersToEnclosingScope =
20821 (SemaRef.CurContext != VD->getDeclContext() &&
20823 if (RefersToEnclosingScope) {
20824 LambdaScopeInfo *const LSI =
20825 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20826 if (LSI && (!LSI->CallOperator ||
20827 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20828 // If a variable could potentially be odr-used, defer marking it so
20829 // until we finish analyzing the full expression for any
20830 // lvalue-to-rvalue
20831 // or discarded value conversions that would obviate odr-use.
20832 // Add it to the list of potential captures that will be analyzed
20833 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20834 // unless the variable is a reference that was initialized by a constant
20835 // expression (this will never need to be captured or odr-used).
20836 //
20837 // FIXME: We can simplify this a lot after implementing P0588R1.
20838 assert(E && "Capture variable should be used in an expression.");
20839 if (!Var->getType()->isReferenceType() ||
20842 }
20843 }
20844}
20845
20847 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20848 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20849 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20851 "Invalid Expr argument to DoMarkVarDeclReferenced");
20852 Var->setReferenced();
20853
20854 if (Var->isInvalidDecl())
20855 return;
20856
20857 auto *MSI = Var->getMemberSpecializationInfo();
20858 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20860
20861 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20862 bool UsableInConstantExpr =
20864
20865 // Only track variables with internal linkage or local scope.
20866 // Use canonical decl so in-class declarations and out-of-class definitions
20867 // of static data members in anonymous namespaces are tracked as a single
20868 // entry.
20869 const VarDecl *CanonVar = Var->getCanonicalDecl();
20870 if ((CanonVar->isLocalVarDeclOrParm() ||
20871 CanonVar->isInternalLinkageFileVar()) &&
20872 !CanonVar->hasExternalStorage()) {
20873 RefsMinusAssignments.insert({CanonVar, 0}).first->getSecond()++;
20874 }
20875
20876 // C++20 [expr.const]p12:
20877 // A variable [...] is needed for constant evaluation if it is [...] a
20878 // variable whose name appears as a potentially constant evaluated
20879 // expression that is either a contexpr variable or is of non-volatile
20880 // const-qualified integral type or of reference type
20881 bool NeededForConstantEvaluation =
20882 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20883
20884 bool NeedDefinition =
20885 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20886 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20887 Var->getType()->isUndeducedType());
20888
20890 "Can't instantiate a partial template specialization.");
20891
20892 // If this might be a member specialization of a static data member, check
20893 // the specialization is visible. We already did the checks for variable
20894 // template specializations when we created them.
20895 if (NeedDefinition && TSK != TSK_Undeclared &&
20898
20899 // Perform implicit instantiation of static data members, static data member
20900 // templates of class templates, and variable template specializations. Delay
20901 // instantiations of variable templates, except for those that could be used
20902 // in a constant expression.
20903 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20904 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20905 // instantiation declaration if a variable is usable in a constant
20906 // expression (among other cases).
20907 bool TryInstantiating =
20909 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20910
20911 if (TryInstantiating) {
20912 SourceLocation PointOfInstantiation =
20913 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20914 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20915 if (FirstInstantiation) {
20916 PointOfInstantiation = Loc;
20917 if (MSI)
20918 MSI->setPointOfInstantiation(PointOfInstantiation);
20919 // FIXME: Notify listener.
20920 else
20921 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20922 }
20923
20924 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20925 // Do not defer instantiations of variables that could be used in a
20926 // constant expression.
20927 // The type deduction also needs a complete initializer.
20928 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20929 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20930 });
20931
20932 // The size of an incomplete array type can be updated by
20933 // instantiating the initializer. The DeclRefExpr's type should be
20934 // updated accordingly too, or users of it would be confused!
20935 if (E)
20937
20938 // Re-set the member to trigger a recomputation of the dependence bits
20939 // for the expression.
20940 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20941 DRE->setDecl(DRE->getDecl());
20942 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20943 ME->setMemberDecl(ME->getMemberDecl());
20944 } else if (FirstInstantiation) {
20946 .push_back(std::make_pair(Var, PointOfInstantiation));
20947 } else {
20948 bool Inserted = false;
20949 for (auto &I : SemaRef.SavedPendingInstantiations) {
20950 auto Iter = llvm::find_if(
20951 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20952 return P.first == Var;
20953 });
20954 if (Iter != I.end()) {
20955 SemaRef.PendingInstantiations.push_back(*Iter);
20956 I.erase(Iter);
20957 Inserted = true;
20958 break;
20959 }
20960 }
20961
20962 // FIXME: For a specialization of a variable template, we don't
20963 // distinguish between "declaration and type implicitly instantiated"
20964 // and "implicit instantiation of definition requested", so we have
20965 // no direct way to avoid enqueueing the pending instantiation
20966 // multiple times.
20967 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20969 .push_back(std::make_pair(Var, PointOfInstantiation));
20970 }
20971 }
20972 }
20973
20974 // C++2a [basic.def.odr]p4:
20975 // A variable x whose name appears as a potentially-evaluated expression e
20976 // is odr-used by e unless
20977 // -- x is a reference that is usable in constant expressions
20978 // -- x is a variable of non-reference type that is usable in constant
20979 // expressions and has no mutable subobjects [FIXME], and e is an
20980 // element of the set of potential results of an expression of
20981 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20982 // conversion is applied
20983 // -- x is a variable of non-reference type, and e is an element of the set
20984 // of potential results of a discarded-value expression to which the
20985 // lvalue-to-rvalue conversion is not applied [FIXME]
20986 //
20987 // We check the first part of the second bullet here, and
20988 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20989 // FIXME: To get the third bullet right, we need to delay this even for
20990 // variables that are not usable in constant expressions.
20991
20992 // If we already know this isn't an odr-use, there's nothing more to do.
20993 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20994 if (DRE->isNonOdrUse())
20995 return;
20996 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20997 if (ME->isNonOdrUse())
20998 return;
20999
21000 switch (OdrUse) {
21001 case OdrUseContext::None:
21002 // In some cases, a variable may not have been marked unevaluated, if it
21003 // appears in a defaukt initializer.
21004 assert((!E || isa<FunctionParmPackExpr>(E) ||
21006 "missing non-odr-use marking for unevaluated decl ref");
21007 break;
21008
21009 case OdrUseContext::FormallyOdrUsed:
21010 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
21011 // behavior.
21012 break;
21013
21014 case OdrUseContext::Used:
21015 // If we might later find that this expression isn't actually an odr-use,
21016 // delay the marking.
21018 SemaRef.MaybeODRUseExprs.insert(E);
21019 else
21020 MarkVarDeclODRUsed(Var, Loc, SemaRef);
21021 break;
21022
21023 case OdrUseContext::Dependent:
21024 // If this is a dependent context, we don't need to mark variables as
21025 // odr-used, but we may still need to track them for lambda capture.
21026 // FIXME: Do we also need to do this inside dependent typeid expressions
21027 // (which are modeled as unevaluated at this point)?
21028 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
21029 break;
21030 }
21031}
21032
21034 BindingDecl *BD, Expr *E) {
21035 BD->setReferenced();
21036
21037 if (BD->isInvalidDecl())
21038 return;
21039
21040 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
21041 if (OdrUse == OdrUseContext::Used) {
21042 QualType CaptureType, DeclRefType;
21044 /*EllipsisLoc*/ SourceLocation(),
21045 /*BuildAndDiagnose*/ true, CaptureType,
21046 DeclRefType,
21047 /*FunctionScopeIndexToStopAt*/ nullptr);
21048 } else if (OdrUse == OdrUseContext::Dependent) {
21049 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
21050 }
21051}
21052
21054 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
21055}
21056
21057// C++ [temp.dep.expr]p3:
21058// An id-expression is type-dependent if it contains:
21059// - an identifier associated by name lookup with an entity captured by copy
21060// in a lambda-expression that has an explicit object parameter whose type
21061// is dependent ([dcl.fct]),
21063 Sema &SemaRef, ValueDecl *D, Expr *E) {
21064 auto *ID = dyn_cast<DeclRefExpr>(E);
21065 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
21066 return;
21067
21068 // If any enclosing lambda with a dependent explicit object parameter either
21069 // explicitly captures the variable by value, or has a capture default of '='
21070 // and does not capture the variable by reference, then the type of the DRE
21071 // is dependent on the type of that lambda's explicit object parameter.
21072 auto IsDependent = [&]() {
21073 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
21074 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
21075 if (!LSI)
21076 continue;
21077
21078 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
21079 LSI->AfterParameterList)
21080 return false;
21081
21082 const auto *MD = LSI->CallOperator;
21083 if (MD->getType().isNull())
21084 continue;
21085
21086 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
21087 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
21088 !Ty->getParamType(0)->isDependentType())
21089 continue;
21090
21091 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
21092 if (C->isCopyCapture())
21093 return true;
21094 continue;
21095 }
21096
21097 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
21098 return true;
21099 }
21100 return false;
21101 }();
21102
21103 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
21104 IsDependent, SemaRef.getASTContext());
21105}
21106
21107static void
21109 bool MightBeOdrUse,
21110 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
21113
21114 if (SemaRef.getLangOpts().OpenACC)
21115 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
21116
21117 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
21119 if (SemaRef.getLangOpts().CPlusPlus)
21121 Var, E);
21122 return;
21123 }
21124
21125 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
21127 if (SemaRef.getLangOpts().CPlusPlus)
21129 Decl, E);
21130 return;
21131 }
21132 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
21133
21134 // If this is a call to a method via a cast, also mark the method in the
21135 // derived class used in case codegen can devirtualize the call.
21136 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
21137 if (!ME)
21138 return;
21139 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
21140 if (!MD)
21141 return;
21142 // Only attempt to devirtualize if this is truly a virtual call.
21143 bool IsVirtualCall = MD->isVirtual() &&
21145 if (!IsVirtualCall)
21146 return;
21147
21148 // If it's possible to devirtualize the call, mark the called function
21149 // referenced.
21151 ME->getBase(), SemaRef.getLangOpts().AppleKext);
21152 if (DM)
21153 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
21154}
21155
21157 // [basic.def.odr] (CWG 1614)
21158 // A function is named by an expression or conversion [...]
21159 // unless it is a pure virtual function and either the expression is not an
21160 // id-expression naming the function with an explicitly qualified name or
21161 // the expression forms a pointer to member
21162 bool OdrUse = true;
21163 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
21164 if (Method->isVirtual() &&
21165 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
21166 OdrUse = false;
21167
21168 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
21172 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
21173 !FD->isDependentContext())
21174 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
21175 }
21176 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
21178}
21179
21181 // C++11 [basic.def.odr]p2:
21182 // A non-overloaded function whose name appears as a potentially-evaluated
21183 // expression or a member of a set of candidate functions, if selected by
21184 // overload resolution when referred to from a potentially-evaluated
21185 // expression, is odr-used, unless it is a pure virtual function and its
21186 // name is not explicitly qualified.
21187 bool MightBeOdrUse = true;
21189 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
21190 if (Method->isPureVirtual())
21191 MightBeOdrUse = false;
21192 }
21193 SourceLocation Loc =
21194 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
21195 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
21197}
21198
21204
21205/// Perform marking for a reference to an arbitrary declaration. It
21206/// marks the declaration referenced, and performs odr-use checking for
21207/// functions and variables. This method should not be used when building a
21208/// normal expression which refers to a variable.
21210 bool MightBeOdrUse) {
21211 if (MightBeOdrUse) {
21212 if (auto *VD = dyn_cast<VarDecl>(D)) {
21213 MarkVariableReferenced(Loc, VD);
21214 return;
21215 }
21216 }
21217 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
21218 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
21219 return;
21220 }
21221 D->setReferenced();
21222}
21223
21224namespace {
21225 // Mark all of the declarations used by a type as referenced.
21226 // FIXME: Not fully implemented yet! We need to have a better understanding
21227 // of when we're entering a context we should not recurse into.
21228 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
21229 // TreeTransforms rebuilding the type in a new context. Rather than
21230 // duplicating the TreeTransform logic, we should consider reusing it here.
21231 // Currently that causes problems when rebuilding LambdaExprs.
21232class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
21233 Sema &S;
21234 SourceLocation Loc;
21235
21236public:
21237 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
21238
21239 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
21240};
21241}
21242
21243bool MarkReferencedDecls::TraverseTemplateArgument(
21244 const TemplateArgument &Arg) {
21245 {
21246 // A non-type template argument is a constant-evaluated context.
21247 EnterExpressionEvaluationContext Evaluated(
21250 if (Decl *D = Arg.getAsDecl())
21251 S.MarkAnyDeclReferenced(Loc, D, true);
21252 } else if (Arg.getKind() == TemplateArgument::Expression) {
21254 }
21255 }
21256
21258}
21259
21261 MarkReferencedDecls Marker(*this, Loc);
21262 Marker.TraverseType(T);
21263}
21264
21265namespace {
21266/// Helper class that marks all of the declarations referenced by
21267/// potentially-evaluated subexpressions as "referenced".
21268class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21269public:
21270 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21271 bool SkipLocalVariables;
21273
21274 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21276 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21277
21278 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21280 }
21281
21282 void Visit(Expr *E) {
21283 if (llvm::is_contained(StopAt, E))
21284 return;
21285 Inherited::Visit(E);
21286 }
21287
21288 void VisitConstantExpr(ConstantExpr *E) {
21289 // Don't mark declarations within a ConstantExpression, as this expression
21290 // will be evaluated and folded to a value.
21291 }
21292
21293 void VisitDeclRefExpr(DeclRefExpr *E) {
21294 // If we were asked not to visit local variables, don't.
21295 if (SkipLocalVariables) {
21296 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
21297 if (VD->hasLocalStorage())
21298 return;
21299 }
21300
21301 // FIXME: This can trigger the instantiation of the initializer of a
21302 // variable, which can cause the expression to become value-dependent
21303 // or error-dependent. Do we need to propagate the new dependence bits?
21305 }
21306
21307 void VisitMemberExpr(MemberExpr *E) {
21309 Visit(E->getBase());
21310 }
21311};
21312} // namespace
21313
21315 bool SkipLocalVariables,
21316 ArrayRef<const Expr*> StopAt) {
21317 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21318}
21319
21320/// Emit a diagnostic when statements are reachable.
21322 const PartialDiagnostic &PD) {
21323 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21324 // The initializer of a constexpr variable or of the first declaration of a
21325 // static data member is not syntactically a constant evaluated constant,
21326 // but nonetheless is always required to be a constant expression, so we
21327 // can skip diagnosing.
21328 if (Decl &&
21329 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21330 Decl->isFirstDecl() && !Decl->isInline())))
21331 return false;
21332
21333 if (Stmts.empty()) {
21334 Diag(Loc, PD);
21335 return true;
21336 }
21337
21338 if (getCurFunction()) {
21339 // This queue flushes after the function is analyzed, by which time an
21340 // ignore-all-warnings region live here is gone, so sample it now. A note
21341 // is not error-class either, so this also drops the notes that accompany a
21342 // skipped warning. They arrive on their own call, out of reach of the
21343 // engine's rule that drops a note whose warning was ignored.
21344 if (Diags.getIgnoreAllWarnings() &&
21345 Diags.getDiagnosticIDs()->isWarningOrExtension(PD.getDiagID()))
21346 return false;
21347 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21348 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21349 return true;
21350 }
21351
21352 // For non-constexpr file-scope variables with reachability context (non-empty
21353 // Stmts), build a CFG for the initializer and check whether the context in
21354 // question is reachable.
21355 if (Decl && Decl->isFileVarDecl()) {
21356 AnalysisWarnings.registerVarDeclWarning(
21357 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21358 return true;
21359 }
21360
21361 Diag(Loc, PD);
21362 return true;
21363}
21364
21365/// Emit a diagnostic that describes an effect on the run-time behavior
21366/// of the program being compiled.
21367///
21368/// This routine emits the given diagnostic when the code currently being
21369/// type-checked is "potentially evaluated", meaning that there is a
21370/// possibility that the code will actually be executable. Code in sizeof()
21371/// expressions, code used only during overload resolution, etc., are not
21372/// potentially evaluated. This routine will suppress such diagnostics or,
21373/// in the absolutely nutty case of potentially potentially evaluated
21374/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21375/// later.
21376///
21377/// This routine should be used for all diagnostics that describe the run-time
21378/// behavior of a program, such as passing a non-POD value through an ellipsis.
21379/// Failure to do so will likely result in spurious diagnostics or failures
21380/// during overload resolution or within sizeof/alignof/typeof/typeid.
21382 const PartialDiagnostic &PD) {
21383
21384 if (ExprEvalContexts.back().isDiscardedStatementContext())
21385 return false;
21386
21387 switch (ExprEvalContexts.back().Context) {
21392 // The argument will never be evaluated, so don't complain.
21393 break;
21394
21397 // Relevant diagnostics should be produced by constant evaluation.
21398 break;
21399
21402 return DiagIfReachable(Loc, Stmts, PD);
21403 }
21404
21405 return false;
21406}
21407
21409 const PartialDiagnostic &PD) {
21410 return DiagRuntimeBehavior(
21411 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21412 PD);
21413}
21414
21416 CallExpr *CE, FunctionDecl *FD) {
21417 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21418 return false;
21419
21420 // If we're inside a decltype's expression, don't check for a valid return
21421 // type or construct temporaries until we know whether this is the last call.
21422 if (ExprEvalContexts.back().ExprContext ==
21424 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21425 return false;
21426 }
21427
21428 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21429 FunctionDecl *FD;
21430 CallExpr *CE;
21431
21432 public:
21433 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21434 : FD(FD), CE(CE) { }
21435
21436 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21437 if (!FD) {
21438 S.Diag(Loc, diag::err_call_incomplete_return)
21439 << T << CE->getSourceRange();
21440 return;
21441 }
21442
21443 S.Diag(Loc, diag::err_call_function_incomplete_return)
21444 << CE->getSourceRange() << FD << T;
21445 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21446 << FD->getDeclName();
21447 }
21448 } Diagnoser(FD, CE);
21449
21450 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21451 return true;
21452
21453 return false;
21454}
21455
21456// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21457// will prevent this condition from triggering, which is what we want.
21459 SourceLocation Loc;
21460
21461 unsigned diagnostic = diag::warn_condition_is_assignment;
21462 bool IsOrAssign = false;
21463
21464 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21465 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21466 return;
21467
21468 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21469
21470 // Greylist some idioms by putting them into a warning subcategory.
21471 if (ObjCMessageExpr *ME
21472 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21473 Selector Sel = ME->getSelector();
21474
21475 // self = [<foo> init...]
21476 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21477 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21478
21479 // <foo> = [<bar> nextObject]
21480 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21481 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21482 }
21483
21484 Loc = Op->getOperatorLoc();
21485 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21486 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21487 return;
21488
21489 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21490 Loc = Op->getOperatorLoc();
21491 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21492 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21493 else {
21494 // Not an assignment.
21495 return;
21496 }
21497
21498 Diag(Loc, diagnostic) << E->getSourceRange();
21499
21502 Diag(Loc, diag::note_condition_assign_silence)
21504 << FixItHint::CreateInsertion(Close, ")");
21505
21506 if (IsOrAssign)
21507 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21508 << FixItHint::CreateReplacement(Loc, "!=");
21509 else
21510 Diag(Loc, diag::note_condition_assign_to_comparison)
21511 << FixItHint::CreateReplacement(Loc, "==");
21512}
21513
21515 // Don't warn if the parens came from a macro.
21516 SourceLocation parenLoc = ParenE->getBeginLoc();
21517 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21518 return;
21519 // Don't warn for dependent expressions.
21520 if (ParenE->isTypeDependent())
21521 return;
21522
21523 Expr *E = ParenE->IgnoreParens();
21524 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21525 return;
21526
21527 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21528 if (opE->getOpcode() == BO_EQ &&
21529 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21530 == Expr::MLV_Valid) {
21531 SourceLocation Loc = opE->getOperatorLoc();
21532
21533 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21534 SourceRange ParenERange = ParenE->getSourceRange();
21535 Diag(Loc, diag::note_equality_comparison_silence)
21536 << FixItHint::CreateRemoval(ParenERange.getBegin())
21537 << FixItHint::CreateRemoval(ParenERange.getEnd());
21538 Diag(Loc, diag::note_equality_comparison_to_assign)
21539 << FixItHint::CreateReplacement(Loc, "=");
21540 }
21541}
21542
21544 bool IsConstexpr) {
21546 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21548
21549 ExprResult result = CheckPlaceholderExpr(E);
21550 if (result.isInvalid()) return ExprError();
21551 E = result.get();
21552
21553 if (!E->isTypeDependent()) {
21554 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21556
21557 if (getLangOpts().CPlusPlus)
21558 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21559
21561 if (ERes.isInvalid())
21562 return ExprError();
21563 E = ERes.get();
21564
21565 QualType T = E->getType();
21566 if (!T->isScalarType()) { // C99 6.8.4.1p1
21567 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21568 << T << E->getSourceRange();
21569 return ExprError();
21570 }
21571 CheckBoolLikeConversion(E, Loc);
21572 }
21573
21574 return E;
21575}
21576
21578 Expr *SubExpr, ConditionKind CK,
21579 bool MissingOK) {
21580 // MissingOK indicates whether having no condition expression is valid
21581 // (for loop) or invalid (e.g. while loop).
21582 if (!SubExpr)
21583 return MissingOK ? ConditionResult() : ConditionError();
21584
21585 ExprResult Cond;
21586 switch (CK) {
21588 Cond = CheckBooleanCondition(Loc, SubExpr);
21589 break;
21590
21592 // Note: this might produce a FullExpr
21593 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21594 break;
21595
21597 Cond = CheckSwitchCondition(Loc, SubExpr);
21598 break;
21599 }
21600 if (Cond.isInvalid()) {
21601 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21602 {SubExpr}, PreferredConditionType(CK));
21603 if (!Cond.get())
21604 return ConditionError();
21605 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
21606 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
21607
21608 if (!Cond.isUsable())
21609 return ConditionError();
21610
21611 return ConditionResult(*this, nullptr, Cond,
21613}
21614
21615namespace {
21616 /// A visitor for rebuilding a call to an __unknown_any expression
21617 /// to have an appropriate type.
21618 struct RebuildUnknownAnyFunction
21619 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21620
21621 Sema &S;
21622
21623 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21624
21625 ExprResult VisitStmt(Stmt *S) {
21626 llvm_unreachable("unexpected statement!");
21627 }
21628
21629 ExprResult VisitExpr(Expr *E) {
21630 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21631 << E->getSourceRange();
21632 return ExprError();
21633 }
21634
21635 /// Rebuild an expression which simply semantically wraps another
21636 /// expression which it shares the type and value kind of.
21637 template <class T> ExprResult rebuildSugarExpr(T *E) {
21638 ExprResult SubResult = Visit(E->getSubExpr());
21639 if (SubResult.isInvalid()) return ExprError();
21640
21641 Expr *SubExpr = SubResult.get();
21642 E->setSubExpr(SubExpr);
21643 E->setType(SubExpr->getType());
21644 E->setValueKind(SubExpr->getValueKind());
21645 assert(E->getObjectKind() == OK_Ordinary);
21646 return E;
21647 }
21648
21649 ExprResult VisitParenExpr(ParenExpr *E) {
21650 return rebuildSugarExpr(E);
21651 }
21652
21653 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21654 return rebuildSugarExpr(E);
21655 }
21656
21657 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21658 ExprResult SubResult = Visit(E->getSubExpr());
21659 if (SubResult.isInvalid()) return ExprError();
21660
21661 Expr *SubExpr = SubResult.get();
21662 E->setSubExpr(SubExpr);
21663 E->setType(S.Context.getPointerType(SubExpr->getType()));
21664 assert(E->isPRValue());
21665 assert(E->getObjectKind() == OK_Ordinary);
21666 return E;
21667 }
21668
21669 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21670 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21671
21672 E->setType(VD->getType());
21673
21674 assert(E->isPRValue());
21675 if (S.getLangOpts().CPlusPlus &&
21676 !(isa<CXXMethodDecl>(VD) &&
21677 cast<CXXMethodDecl>(VD)->isInstance()))
21679
21680 return E;
21681 }
21682
21683 ExprResult VisitMemberExpr(MemberExpr *E) {
21684 return resolveDecl(E, E->getMemberDecl());
21685 }
21686
21687 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21688 return resolveDecl(E, E->getDecl());
21689 }
21690 };
21691}
21692
21693/// Given a function expression of unknown-any type, try to rebuild it
21694/// to have a function type.
21696 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21697 if (Result.isInvalid()) return ExprError();
21698 return S.DefaultFunctionArrayConversion(Result.get());
21699}
21700
21701namespace {
21702 /// A visitor for rebuilding an expression of type __unknown_anytype
21703 /// into one which resolves the type directly on the referring
21704 /// expression. Strict preservation of the original source
21705 /// structure is not a goal.
21706 struct RebuildUnknownAnyExpr
21707 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21708
21709 Sema &S;
21710
21711 /// The current destination type.
21712 QualType DestType;
21713
21714 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21715 : S(S), DestType(CastType) {}
21716
21717 ExprResult VisitStmt(Stmt *S) {
21718 llvm_unreachable("unexpected statement!");
21719 }
21720
21721 ExprResult VisitExpr(Expr *E) {
21722 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21723 << E->getSourceRange();
21724 return ExprError();
21725 }
21726
21727 ExprResult VisitCallExpr(CallExpr *E);
21728 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21729
21730 /// Rebuild an expression which simply semantically wraps another
21731 /// expression which it shares the type and value kind of.
21732 template <class T> ExprResult rebuildSugarExpr(T *E) {
21733 ExprResult SubResult = Visit(E->getSubExpr());
21734 if (SubResult.isInvalid()) return ExprError();
21735 Expr *SubExpr = SubResult.get();
21736 E->setSubExpr(SubExpr);
21737 E->setType(SubExpr->getType());
21738 E->setValueKind(SubExpr->getValueKind());
21739 assert(E->getObjectKind() == OK_Ordinary);
21740 return E;
21741 }
21742
21743 ExprResult VisitParenExpr(ParenExpr *E) {
21744 return rebuildSugarExpr(E);
21745 }
21746
21747 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21748 return rebuildSugarExpr(E);
21749 }
21750
21751 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21752 const PointerType *Ptr = DestType->getAs<PointerType>();
21753 if (!Ptr) {
21754 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21755 << E->getSourceRange();
21756 return ExprError();
21757 }
21758
21759 if (isa<CallExpr>(E->getSubExpr())) {
21760 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21761 << E->getSourceRange();
21762 return ExprError();
21763 }
21764
21765 assert(E->isPRValue());
21766 assert(E->getObjectKind() == OK_Ordinary);
21767 E->setType(DestType);
21768
21769 // Build the sub-expression as if it were an object of the pointee type.
21770 DestType = Ptr->getPointeeType();
21771 ExprResult SubResult = Visit(E->getSubExpr());
21772 if (SubResult.isInvalid()) return ExprError();
21773 E->setSubExpr(SubResult.get());
21774 return E;
21775 }
21776
21777 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21778
21779 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21780
21781 ExprResult VisitMemberExpr(MemberExpr *E) {
21782 return resolveDecl(E, E->getMemberDecl());
21783 }
21784
21785 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21786 return resolveDecl(E, E->getDecl());
21787 }
21788 };
21789}
21790
21791/// Rebuilds a call expression which yielded __unknown_anytype.
21792ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21793 Expr *CalleeExpr = E->getCallee();
21794
21795 enum FnKind {
21796 FK_MemberFunction,
21797 FK_FunctionPointer,
21798 FK_BlockPointer
21799 };
21800
21801 FnKind Kind;
21802 QualType CalleeType = CalleeExpr->getType();
21803 if (CalleeType == S.Context.BoundMemberTy) {
21805 Kind = FK_MemberFunction;
21806 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21807 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21808 CalleeType = Ptr->getPointeeType();
21809 Kind = FK_FunctionPointer;
21810 } else {
21811 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21812 Kind = FK_BlockPointer;
21813 }
21814 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21815
21816 // Verify that this is a legal result type of a function.
21817 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21818 DestType->isFunctionType()) {
21819 unsigned diagID = diag::err_func_returning_array_function;
21820 if (Kind == FK_BlockPointer)
21821 diagID = diag::err_block_returning_array_function;
21822
21823 S.Diag(E->getExprLoc(), diagID)
21824 << DestType->isFunctionType() << DestType;
21825 return ExprError();
21826 }
21827
21828 // Otherwise, go ahead and set DestType as the call's result.
21829 E->setType(DestType.getNonLValueExprType(S.Context));
21831 assert(E->getObjectKind() == OK_Ordinary);
21832
21833 // Rebuild the function type, replacing the result type with DestType.
21834 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21835 if (Proto) {
21836 // __unknown_anytype(...) is a special case used by the debugger when
21837 // it has no idea what a function's signature is.
21838 //
21839 // We want to build this call essentially under the K&R
21840 // unprototyped rules, but making a FunctionNoProtoType in C++
21841 // would foul up all sorts of assumptions. However, we cannot
21842 // simply pass all arguments as variadic arguments, nor can we
21843 // portably just call the function under a non-variadic type; see
21844 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21845 // However, it turns out that in practice it is generally safe to
21846 // call a function declared as "A foo(B,C,D);" under the prototype
21847 // "A foo(B,C,D,...);". The only known exception is with the
21848 // Windows ABI, where any variadic function is implicitly cdecl
21849 // regardless of its normal CC. Therefore we change the parameter
21850 // types to match the types of the arguments.
21851 //
21852 // This is a hack, but it is far superior to moving the
21853 // corresponding target-specific code from IR-gen to Sema/AST.
21854
21855 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21856 SmallVector<QualType, 8> ArgTypes;
21857 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21858 ArgTypes.reserve(E->getNumArgs());
21859 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21860 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21861 }
21862 ParamTypes = ArgTypes;
21863 }
21864 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21865 Proto->getExtProtoInfo());
21866 } else {
21867 DestType = S.Context.getFunctionNoProtoType(DestType,
21868 FnType->getExtInfo());
21869 }
21870
21871 // Rebuild the appropriate pointer-to-function type.
21872 switch (Kind) {
21873 case FK_MemberFunction:
21874 // Nothing to do.
21875 break;
21876
21877 case FK_FunctionPointer:
21878 DestType = S.Context.getPointerType(DestType);
21879 break;
21880
21881 case FK_BlockPointer:
21882 DestType = S.Context.getBlockPointerType(DestType);
21883 break;
21884 }
21885
21886 // Finally, we can recurse.
21887 ExprResult CalleeResult = Visit(CalleeExpr);
21888 if (!CalleeResult.isUsable()) return ExprError();
21889 E->setCallee(CalleeResult.get());
21890
21891 // Bind a temporary if necessary.
21892 return S.MaybeBindToTemporary(E);
21893}
21894
21895ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21896 // Verify that this is a legal result type of a call.
21897 if (DestType->isArrayType() || DestType->isFunctionType()) {
21898 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21899 << DestType->isFunctionType() << DestType;
21900 return ExprError();
21901 }
21902
21903 // Rewrite the method result type if available.
21904 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21905 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21906 Method->setReturnType(DestType);
21907 }
21908
21909 // Change the type of the message.
21910 E->setType(DestType.getNonReferenceType());
21912
21913 return S.MaybeBindToTemporary(E);
21914}
21915
21916ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21917 // The only case we should ever see here is a function-to-pointer decay.
21918 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21919 assert(E->isPRValue());
21920 assert(E->getObjectKind() == OK_Ordinary);
21921
21922 E->setType(DestType);
21923
21924 // Rebuild the sub-expression as the pointee (function) type.
21925 DestType = DestType->castAs<PointerType>()->getPointeeType();
21926
21927 ExprResult Result = Visit(E->getSubExpr());
21928 if (!Result.isUsable()) return ExprError();
21929
21930 E->setSubExpr(Result.get());
21931 return E;
21932 } else if (E->getCastKind() == CK_LValueToRValue) {
21933 assert(E->isPRValue());
21934 assert(E->getObjectKind() == OK_Ordinary);
21935
21936 assert(isa<BlockPointerType>(E->getType()));
21937
21938 E->setType(DestType);
21939
21940 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21941 DestType = S.Context.getLValueReferenceType(DestType);
21942
21943 ExprResult Result = Visit(E->getSubExpr());
21944 if (!Result.isUsable()) return ExprError();
21945
21946 E->setSubExpr(Result.get());
21947 return E;
21948 } else {
21949 llvm_unreachable("Unhandled cast type!");
21950 }
21951}
21952
21953ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21954 ExprValueKind ValueKind = VK_LValue;
21955 QualType Type = DestType;
21956
21957 // We know how to make this work for certain kinds of decls:
21958
21959 // - functions
21960 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21961 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21962 DestType = Ptr->getPointeeType();
21963 ExprResult Result = resolveDecl(E, VD);
21964 if (Result.isInvalid()) return ExprError();
21965 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21966 VK_PRValue);
21967 }
21968
21969 if (!Type->isFunctionType()) {
21970 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21971 << VD << E->getSourceRange();
21972 return ExprError();
21973 }
21974 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21975 // We must match the FunctionDecl's type to the hack introduced in
21976 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21977 // type. See the lengthy commentary in that routine.
21978 QualType FDT = FD->getType();
21979 const FunctionType *FnType = FDT->castAs<FunctionType>();
21980 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21981 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21982 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21983 SourceLocation Loc = FD->getLocation();
21984 FunctionDecl *NewFD = FunctionDecl::Create(
21985 S.Context, FD->getDeclContext(), Loc, Loc,
21986 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21988 false /*isInlineSpecified*/, FD->hasPrototype(),
21989 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21990
21991 if (FD->getQualifier())
21992 NewFD->setQualifierInfo(FD->getQualifierLoc());
21993
21994 SmallVector<ParmVarDecl*, 16> Params;
21995 for (const auto &AI : FT->param_types()) {
21996 ParmVarDecl *Param =
21997 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21998 Param->setScopeInfo(0, Params.size());
21999 Params.push_back(Param);
22000 }
22001 NewFD->setParams(Params);
22002 DRE->setDecl(NewFD);
22003 VD = DRE->getDecl();
22004 }
22005 }
22006
22007 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
22008 if (MD->isInstance()) {
22009 ValueKind = VK_PRValue;
22011 }
22012
22013 // Function references aren't l-values in C.
22014 if (!S.getLangOpts().CPlusPlus)
22015 ValueKind = VK_PRValue;
22016
22017 // - variables
22018 } else if (isa<VarDecl>(VD)) {
22019 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
22020 Type = RefTy->getPointeeType();
22021 } else if (Type->isFunctionType()) {
22022 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
22023 << VD << E->getSourceRange();
22024 return ExprError();
22025 }
22026
22027 // - nothing else
22028 } else {
22029 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
22030 << VD << E->getSourceRange();
22031 return ExprError();
22032 }
22033
22034 // Modifying the declaration like this is friendly to IR-gen but
22035 // also really dangerous.
22036 VD->setType(DestType);
22037 E->setType(Type);
22038 E->setValueKind(ValueKind);
22039 return E;
22040}
22041
22044 ExprValueKind &VK, CXXCastPath &Path) {
22045 // The type we're casting to must be either void or complete.
22046 if (!CastType->isVoidType() &&
22048 diag::err_typecheck_cast_to_incomplete))
22049 return ExprError();
22050
22051 // Rewrite the casted expression from scratch.
22052 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
22053 if (!result.isUsable()) return ExprError();
22054
22055 CastExpr = result.get();
22057 CastKind = CK_NoOp;
22058
22059 return CastExpr;
22060}
22061
22063 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
22064}
22065
22067 Expr *arg, QualType &paramType) {
22068 // If the syntactic form of the argument is not an explicit cast of
22069 // any sort, just do default argument promotion.
22070 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
22071 if (!castArg) {
22073 if (result.isInvalid()) return ExprError();
22074 paramType = result.get()->getType();
22075 return result;
22076 }
22077
22078 // Otherwise, use the type that was written in the explicit cast.
22079 assert(!arg->hasPlaceholderType());
22080 paramType = castArg->getTypeAsWritten();
22081
22082 // Copy-initialize a parameter of that type.
22083 InitializedEntity entity =
22085 /*consumed*/ false);
22086 return PerformCopyInitialization(entity, callLoc, arg);
22087}
22088
22090 Expr *orig = E;
22091 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
22092 while (true) {
22093 E = E->IgnoreParenImpCasts();
22094 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
22095 E = call->getCallee();
22096 diagID = diag::err_uncasted_call_of_unknown_any;
22097 } else {
22098 break;
22099 }
22100 }
22101
22102 SourceLocation loc;
22103 NamedDecl *d;
22104 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
22105 loc = ref->getLocation();
22106 d = ref->getDecl();
22107 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
22108 loc = mem->getMemberLoc();
22109 d = mem->getMemberDecl();
22110 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
22111 diagID = diag::err_uncasted_call_of_unknown_any;
22112 loc = msg->getSelectorStartLoc();
22113 d = msg->getMethodDecl();
22114 if (!d) {
22115 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
22116 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
22117 << orig->getSourceRange();
22118 return ExprError();
22119 }
22120 } else {
22121 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
22122 << E->getSourceRange();
22123 return ExprError();
22124 }
22125
22126 S.Diag(loc, diagID) << d << orig->getSourceRange();
22127
22128 // Never recoverable.
22129 return ExprError();
22130}
22131
22133 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
22134 if (!placeholderType) return E;
22135
22136 switch (placeholderType->getKind()) {
22137 case BuiltinType::UnresolvedTemplate: {
22138 auto *ULE = cast<UnresolvedLookupExpr>(E->IgnoreParens());
22139 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
22140 // There's only one FoundDecl for UnresolvedTemplate type. See
22141 // BuildTemplateIdExpr.
22142 NamedDecl *Temp = *ULE->decls_begin();
22143 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
22144
22145 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
22146 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
22147 // as it models only the unqualified-id case, where this case can clearly be
22148 // qualified. Thus we can't just qualify an assumed template.
22149 TemplateName TN;
22150 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
22151 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
22152 TemplateName(TD));
22153 else
22154 TN = Context.getAssumedTemplateName(NameInfo.getName());
22155
22156 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
22157 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
22158 Diag(Temp->getLocation(), diag::note_referenced_type_template)
22159 << IsTypeAliasTemplateDecl;
22160
22161 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
22162 bool HasAnyDependentTA = false;
22163 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
22164 HasAnyDependentTA |= Arg.getArgument().isDependent();
22165 TAL.addArgument(Arg);
22166 }
22167
22168 QualType TST;
22169 {
22170 SFINAETrap Trap(*this);
22171 TST = CheckTemplateIdType(
22172 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
22173 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
22174 }
22175 if (TST.isNull())
22176 TST = Context.getTemplateSpecializationType(
22177 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
22178 /*CanonicalArgs=*/{},
22179 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
22180 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
22181 TST);
22182 }
22183
22184 // Overloaded expressions.
22185 case BuiltinType::Overload: {
22186 // Try to resolve a single function template specialization.
22187 // This is obligatory.
22188 ExprResult Result = E;
22190 return Result;
22191
22192 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
22193 // leaves Result unchanged on failure.
22194 Result = E;
22196 return Result;
22197
22198 // If that failed, try to recover with a call.
22199 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
22200 /*complain*/ true);
22201 return Result;
22202 }
22203
22204 // Bound member functions.
22205 case BuiltinType::BoundMember: {
22206 ExprResult result = E;
22207 const Expr *BME = E->IgnoreParens();
22208 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
22209 // Try to give a nicer diagnostic if it is a bound member that we recognize.
22211 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
22212 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
22213 if (ME->getMemberNameInfo().getName().getNameKind() ==
22215 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
22216 }
22217 tryToRecoverWithCall(result, PD,
22218 /*complain*/ true);
22219 return result;
22220 }
22221
22222 // ARC unbridged casts.
22223 case BuiltinType::ARCUnbridgedCast: {
22224 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
22225 ObjC().diagnoseARCUnbridgedCast(realCast);
22226 return realCast;
22227 }
22228
22229 // Expressions of unknown type.
22230 case BuiltinType::UnknownAny:
22231 return diagnoseUnknownAnyExpr(*this, E);
22232
22233 // Pseudo-objects.
22234 case BuiltinType::PseudoObject:
22235 return PseudoObject().checkRValue(E);
22236
22237 case BuiltinType::BuiltinFn: {
22238 // Accept __noop without parens by implicitly converting it to a call expr.
22239 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
22240 if (DRE) {
22241 auto *FD = cast<FunctionDecl>(DRE->getDecl());
22242 unsigned BuiltinID = FD->getBuiltinID();
22243 if (BuiltinID == Builtin::BI__noop) {
22244 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
22245 CK_BuiltinFnToFnPtr)
22246 .get();
22247 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
22250 }
22251
22252 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
22253 // Any use of these other than a direct call is ill-formed as of C++20,
22254 // because they are not addressable functions. In earlier language
22255 // modes, warn and force an instantiation of the real body.
22256 Diag(E->getBeginLoc(),
22258 ? diag::err_use_of_unaddressable_function
22259 : diag::warn_cxx20_compat_use_of_unaddressable_function);
22260 if (FD->isImplicitlyInstantiable()) {
22261 // Require a definition here because a normal attempt at
22262 // instantiation for a builtin will be ignored, and we won't try
22263 // again later. We assume that the definition of the template
22264 // precedes this use.
22266 /*Recursive=*/false,
22267 /*DefinitionRequired=*/true,
22268 /*AtEndOfTU=*/false);
22269 }
22270 // Produce a properly-typed reference to the function.
22271 CXXScopeSpec SS;
22272 SS.Adopt(DRE->getQualifierLoc());
22273 TemplateArgumentListInfo TemplateArgs;
22274 DRE->copyTemplateArgumentsInto(TemplateArgs);
22275 return BuildDeclRefExpr(
22276 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
22277 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
22278 DRE->getTemplateKeywordLoc(),
22279 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22280 }
22281 }
22282
22283 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
22284 return ExprError();
22285 }
22286
22287 case BuiltinType::IncompleteMatrixIdx: {
22288 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
22289 // At this point, we know there was no second [] to complete the operator.
22290 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22291 if (getLangOpts().HLSL) {
22293 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
22294 }
22295 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
22296 return ExprError();
22297 }
22298
22299 // Expressions of unknown type.
22300 case BuiltinType::ArraySection:
22301 // If we've already diagnosed something on the array section type, we
22302 // shouldn't need to do any further diagnostic here.
22303 if (!E->containsErrors())
22304 Diag(E->getBeginLoc(), diag::err_array_section_use)
22305 << cast<ArraySectionExpr>(E->IgnoreParens())->isOMPArraySection();
22306 return ExprError();
22307
22308 // Expressions of unknown type.
22309 case BuiltinType::OMPArrayShaping:
22310 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
22311
22312 case BuiltinType::OMPIterator:
22313 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
22314
22315 // Everything else should be impossible.
22316#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22317 case BuiltinType::Id:
22318#include "clang/Basic/OpenCLImageTypes.def"
22319#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22320 case BuiltinType::Id:
22321#include "clang/Basic/OpenCLExtensionTypes.def"
22322#define SVE_TYPE(Name, Id, SingletonId) \
22323 case BuiltinType::Id:
22324#include "clang/Basic/AArch64ACLETypes.def"
22325#define PPC_VECTOR_TYPE(Name, Id, Size) \
22326 case BuiltinType::Id:
22327#include "clang/Basic/PPCTypes.def"
22328#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22329#include "clang/Basic/RISCVVTypes.def"
22330#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22331#include "clang/Basic/WebAssemblyReferenceTypes.def"
22332#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22333#include "clang/Basic/AMDGPUTypes.def"
22334#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22335#include "clang/Basic/HLSLIntangibleTypes.def"
22336#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22337#include "clang/Basic/SPIRVTypes.def"
22338#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22339#define PLACEHOLDER_TYPE(Id, SingletonId)
22340#include "clang/AST/BuiltinTypes.def"
22341 break;
22342 }
22343
22344 llvm_unreachable("invalid placeholder type!");
22345}
22346
22348 if (E->isTypeDependent())
22349 return true;
22351 return E->getType()->isIntegralOrEnumerationType();
22352 return false;
22353}
22354
22356 ArrayRef<Expr *> SubExprs, QualType T) {
22357 if (!Context.getLangOpts().RecoveryAST)
22358 return ExprError();
22359
22360 if (isSFINAEContext())
22361 return ExprError();
22362
22363 if (T.isNull() || T->isUndeducedType() ||
22364 !Context.getLangOpts().RecoveryASTType)
22365 // We don't know the concrete type, fallback to dependent type.
22366 T = Context.DependentTy;
22367
22368 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
22369}
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:122
APSInt & getInt()
Definition APValue.h:511
bool hasValue() const
Definition APValue.h:486
bool isInt() const
Definition APValue.h:488
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:991
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:850
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:846
const LangOptions & getLangOpts() const
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:968
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:965
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:3813
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3827
QualType getElementType() const
Definition TypeBase.h:3825
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:2211
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:2164
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:5131
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:2236
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:2173
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:4214
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:5511
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:5522
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5715
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6722
Pointer to a block type.
Definition TypeBase.h:3646
This class is used for builtin types like 'int'.
Definition TypeBase.h:3241
bool isSVEBool() const
Definition TypeBase.h:3321
Kind getKind() const
Definition TypeBase.h:3292
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:2009
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const RecordType * getDetectedVirtual() const
The virtual base discovered on the path (if we are merely detecting virtuals).
CXXBasePath & front()
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
Represents a C++ constructor within a class.
Definition DeclCXX.h:2641
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2976
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:2406
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition ExprCXX.cpp:1072
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1381
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext, Expr *RewrittenInitExpr)
Field is the non-static data member whose default initializer is used by this expression.
Definition ExprCXX.cpp:1126
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1138
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:1583
Represents a C++ destructor within a class.
Definition DeclCXX.h:2906
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2149
bool isVirtual() const
Definition DeclCXX.h:2204
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2292
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:85
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:156
SourceRange getSourceRange() const
Definition ExprCXX.h:168
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:2040
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2749
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1234
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:1027
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:2087
bool hasDefinition() const
Definition DeclCXX.h:561
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
static CXXReflectExpr * Create(ASTContext &C, SourceLocation OperatorLoc, TypeSourceInfo *TL)
Definition ExprCXX.cpp:1985
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Represents the this expression in C++.
Definition ExprCXX.h:1158
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h: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:1545
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
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1649
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4892
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3355
QualType getElementType() const
Definition TypeBase.h:3365
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:5153
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:3851
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3907
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3927
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:4478
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4497
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4494
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:3629
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:550
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:494
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:1952
DeclaratorContext getContext() const
Definition DeclSpec.h:2124
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
bool isInvalidType() const
Definition DeclSpec.h:2766
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:575
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:970
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:739
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:1497
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:3150
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:3079
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:3128
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:3123
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3111
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3132
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:3119
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:3372
@ 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:3722
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:3103
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:4104
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:4356
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:4358
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:1003
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1082
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:4894
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4923
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5398
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5902
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5705
bool isParamConsumed(unsigned I) const
Definition TypeBase.h:5916
unsigned getNumParams() const
Definition TypeBase.h:5676
QualType getParamType(unsigned i) const
Definition TypeBase.h:5678
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5802
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5687
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5683
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5838
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:4705
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4776
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4633
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4594
ExtInfo getExtInfo() const
Definition TypeBase.h:4950
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4942
bool getCFIUncheckedCalleeAttr() const
Determine whether this is a function prototype that includes the cfi_unchecked_callee attribute.
Definition Type.cpp:3826
QualType getReturnType() const
Definition TypeBase.h:4934
bool getCmseNSCallAttr() const
Definition TypeBase.h:4948
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4962
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:4752
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:2103
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:623
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:981
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:1972
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition ExprCXX.cpp:1437
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:4432
MS property subscript expression.
Definition ExprCXX.h:1010
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:4428
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4442
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:1780
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:1824
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:8013
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:8069
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:2007
qual_range quals() const
Definition TypeBase.h:8188
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:1683
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:1161
@ CSK_Normal
Normal lookup.
Definition Overload.h:1165
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1377
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:3142
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3203
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:5003
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:3396
QualType getPointeeType() const
Definition TypeBase.h:3406
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition Expr.cpp:639
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition Expr.cpp:679
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:8512
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8517
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:3810
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:3147
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:8428
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8554
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:8468
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:2924
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:8613
QualType getCanonicalType() const
Definition TypeBase.h:8480
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8522
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:3166
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:8620
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8501
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1837
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:8485
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:2912
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:8593
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8460
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:5497
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:3671
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:1787
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:379
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:8497
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12570
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12614
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7767
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:1446
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:8254
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13728
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1137
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:8300
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8222
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:970
bool isAttrContext() const
Definition Sema.h:6991
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:8293
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9391
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9430
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9399
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:1531
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:1247
SemaCUDA & CUDA()
Definition Sema.h:1471
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:7888
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7890
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7889
bool needsRebuildOfDefaultArgOrInit() const
Definition Sema.h:8242
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:8380
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1240
Preprocessor & getPreprocessor() const
Definition Sema.h:934
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6969
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2473
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:8369
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:6798
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit=nullptr)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal,...
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2079
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:1556
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:6981
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:1768
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:843
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:1304
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:8209
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:1516
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:2983
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:764
bool isImmediateFunctionContext() const
Definition Sema.h:8234
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:774
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:777
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition SemaExpr.cpp:893
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:1208
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1773
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:11533
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:8269
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:8363
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:277
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:14587
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:2604
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:1521
ReuseLambdaContextDecl_t
Definition Sema.h:7060
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:1303
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:2279
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:1302
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2719
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:962
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6542
SemaHLSL & HLSL()
Definition Sema.h:1481
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:15857
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:5343
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:7005
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6572
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:14132
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:884
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:1339
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:7002
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:2456
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:8105
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2674
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1444
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:12641
SemaOpenCL & OpenCL()
Definition Sema.h:1526
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:14141
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:8230
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1747
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:6801
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:14076
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:7514
@ NTCUK_Destruct
Definition Sema.h:4154
@ NTCUK_Copy
Definition Sema.h:4155
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8379
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:2504
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:6799
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:13819
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:15620
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:2659
bool isConstantEvaluatedContext() const
Definition Sema.h:2641
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:1305
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4720
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:7009
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:1344
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14124
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:6743
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6765
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6755
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6770
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6760
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6780
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6749
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6775
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6790
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:1263
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:8220
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:8366
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:1307
@ TemplateNameIsRequired
Definition Sema.h:11510
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:793
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:1306
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:929
FPOptions CurFPFeatures
Definition Sema.h:1300
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:1586
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:6576
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:646
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:2262
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:8028
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9444
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9450
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9442
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9447
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9458
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9454
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:6457
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:14120
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:7874
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:1541
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2650
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:8246
SemaARM & ARM()
Definition Sema.h:1451
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:11040
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:8710
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:298
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
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:396
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:1194
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:8399
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:8410
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:9105
bool isBlockPointerType() const
Definition TypeBase.h:8685
bool isVoidType() const
Definition TypeBase.h:9037
bool isBooleanType() const
Definition TypeBase.h:9174
bool isObjCBuiltinType() const
Definition TypeBase.h:8895
bool isMFloat8Type() const
Definition TypeBase.h:9062
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:2118
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9224
bool isIncompleteArrayType() const
Definition TypeBase.h:8772
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:9013
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:853
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2295
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:9204
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:2241
bool isVoidPointerType() const
Definition Type.cpp:841
const ComplexType * getAsComplexIntegerType() const
Definition Type.cpp:874
bool isArrayType() const
Definition TypeBase.h:8764
bool isCharType() const
Definition Type.cpp:2315
bool isFunctionPointerType() const
Definition TypeBase.h:8732
bool isArithmeticType() const
Definition Type.cpp:2546
bool isConstantMatrixType() const
Definition TypeBase.h:8832
bool isPointerType() const
Definition TypeBase.h:8665
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9081
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2791
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9331
bool isReferenceType() const
Definition TypeBase.h:8689
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:9125
bool isEnumeralType() const
Definition TypeBase.h:8796
bool isScalarType() const
Definition TypeBase.h:9143
bool isVariableArrayType() const
Definition TypeBase.h:8776
bool isSizelessBuiltinType() const
Definition Type.cpp:2747
bool isClkEventT() const
Definition TypeBase.h:8917
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2825
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2278
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8865
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:881
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9159
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2500
bool isExtVectorType() const
Definition TypeBase.h:8808
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2351
bool isExtVectorBoolType() const
Definition TypeBase.h:8812
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2864
bool isImageType() const
Definition TypeBase.h:8929
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition TypeBase.h:9031
bool isPipeType() const
Definition TypeBase.h:8936
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2867
bool isBitIntType() const
Definition TypeBase.h:8940
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9006
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8788
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool isAnyComplexType() const
Definition TypeBase.h:8800
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9097
bool isHalfType() const
Definition TypeBase.h:9041
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9113
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:2578
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9019
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2432
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2775
bool isQueueT() const
Definition TypeBase.h:8921
bool isMemberPointerType() const
Definition TypeBase.h:8746
bool isAtomicType() const
Definition TypeBase.h:8857
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9187
bool isObjCIdType() const
Definition TypeBase.h:8877
bool isMatrixType() const
Definition TypeBase.h:8828
bool isOverflowBehaviorType() const
Definition TypeBase.h:8836
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:2877
bool isComplexIntegerType() const
Definition Type.cpp:859
bool isUnscopedEnumerationType() const
Definition Type.cpp:2308
bool isObjCObjectType() const
Definition TypeBase.h:8848
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition Type.cpp:5509
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9317
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5598
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9180
bool isHLSLResourceRecord() const
Definition Type.cpp:5683
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isDoubleType() const
Definition TypeBase.h:9054
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2651
bool isFunctionType() const
Definition TypeBase.h:8661
bool isObjCObjectPointerType() const
Definition TypeBase.h:8844
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2521
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:9139
bool isVectorType() const
Definition TypeBase.h:8804
bool isObjCQualifiedClassType() const
Definition TypeBase.h:8871
bool isObjCClassType() const
Definition TypeBase.h:8883
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2529
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2812
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
@ STK_FloatingComplex
Definition TypeBase.h:2841
@ STK_ObjCObjectPointer
Definition TypeBase.h:2835
@ STK_IntegralComplex
Definition TypeBase.h:2840
@ STK_MemberPointer
Definition TypeBase.h:2836
bool isFloatingType() const
Definition Type.cpp:2513
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:2456
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:3005
bool isAnyPointerType() const
Definition TypeBase.h:8673
bool isRealType() const
Definition Type.cpp:2535
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isSubscriptableVectorType() const
Definition TypeBase.h:8824
bool isSamplerT() const
Definition TypeBase.h:8909
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9264
bool isNullPtrType() const
Definition TypeBase.h:9074
bool isRecordType() const
Definition TypeBase.h:8792
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5687
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition Type.cpp:864
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5298
bool isUnicodeCharacterType() const
Definition Type.cpp:2371
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2568
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:1458
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:5188
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4489
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1127
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1121
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1091
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3372
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:463
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4179
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition ExprCXX.cpp:1715
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:1677
A set of unresolved declarations.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:644
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h: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:5646
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:4057
Expr * getSizeExpr() const
Definition TypeBase.h:4071
Represents a GCC generic vector type.
Definition TypeBase.h:4266
unsigned getNumElements() const
Definition TypeBase.h:4281
VectorKind getVectorKind() const
Definition TypeBase.h:4286
QualType getElementType() const
Definition TypeBase.h:4280
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:213
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus26
@ CPlusPlus17
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ GVA_StrongExternal
Definition Linkage.h:76
VariadicCallType
Definition Sema.h: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:347
@ Nullable
Values of this type can be null.
Definition Specifiers.h:351
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:356
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:349
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:150
@ OK_VectorComponent
A vector component is an element or range of elements of a vector.
Definition Specifiers.h:158
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:162
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition Specifiers.h:155
@ OK_MatrixComponent
A matrix component is a single element or range of elements of a matrix.
Definition Specifiers.h:170
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1033
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1031
@ AS_none
Definition Specifiers.h:128
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ CR_OpenMP
@ SC_Extern
Definition Specifiers.h:252
@ SC_Register
Definition Specifiers.h:258
@ SC_None
Definition Specifiers.h:251
@ 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
@ Type
The name was classified as a type.
Definition Sema.h:558
@ 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:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
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:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
StringLiteralKind
Definition Expr.h:1783
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_X86VectorCall
Definition Specifiers.h:284
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4236
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4245
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4230
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4233
@ Neon
is ARM Neon vector
Definition TypeBase.h:4239
@ Generic
not a target-specific vector type
Definition TypeBase.h:4227
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4251
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4254
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4248
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:6017
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:363
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:174
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition Specifiers.h:184
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:178
@ NOUR_None
This is an odr-use.
Definition Specifiers.h:176
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition Specifiers.h:181
#define false
Definition stdbool.h:26
ExprResult TransformSourceLocExpr(SourceLocExpr *E)
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
ExprResult TransformBlockExpr(BlockExpr *E)
ExprResult TransformLambdaExpr(LambdaExpr *E)
bool VisitSourceLocExpr(SourceLocExpr *E) override
bool VisitCXXConstructExpr(CXXConstructExpr *E) override
bool VisitCallExpr(CallExpr *E) override
const ASTContext & Context
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override
bool VisitLambdaExpr(LambdaExpr *E) override
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override
ImmediateCallVisitor(const ASTContext &Ctx)
Represents an element in a path from a derived class to a base class.
The class facilities generation and storage of conversion FixIts.
OverloadFixItKind Kind
The type of fix applied.
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
Stores data related to a single embed directive.
Definition Expr.h: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:5483
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13247
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6805
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6840
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6891
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6825
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6845
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:6853
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6849
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6859
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:6820
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6867
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6810
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6807
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6814
Abstract class used to diagnose incomplete types.
Definition Sema.h:8307
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.